PageRenderTime 57ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/projects/compiere-330/ad/src/org/compiere/model/MSystem.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 612 lines | 432 code | 34 blank | 146 comment | 91 complexity | dd41c1e899d5128e19f422ad34c1cf25 MD5 | raw file
  1. /******************************************************************************
  2. * Product: Compiere ERP & CRM Smart Business Solution *
  3. * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
  4. * This program is free software, you can redistribute it and/or modify it *
  5. * under the terms version 2 of the GNU General Public License as published *
  6. * by the Free Software Foundation. This program is distributed in the hope *
  7. * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
  8. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
  9. * See the GNU General Public License for more details. *
  10. * You should have received a copy of the GNU General Public License along *
  11. * with this program, if not, write to the Free Software Foundation, Inc., *
  12. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
  13. * For the text or an alternative of this public license, you may reach us *
  14. * ComPiere, Inc., 3600 Bridge Parkway #102, Redwood City, CA 94065, USA *
  15. * or via info@compiere.org or http://www.compiere.org/license.html *
  16. *****************************************************************************/
  17. package org.compiere.model;
  18. import java.lang.management.*;
  19. import java.sql.*;
  20. import java.util.*;
  21. import java.util.logging.*;
  22. import org.compiere.common.constants.*;
  23. import org.compiere.db.*;
  24. import org.compiere.util.*;
  25. /**
  26. * System Record (just one)
  27. *
  28. * @author Jorg Janke
  29. * @version $Id: MSystem.java,v 1.3 2006/10/09 00:22:28 jjanke Exp $
  30. */
  31. public class MSystem extends X_AD_System
  32. {
  33. /**
  34. *
  35. */
  36. private static final long serialVersionUID = 1L;
  37. /**
  38. * Load System Record
  39. * @param ctx context
  40. * @return System
  41. */
  42. public static MSystem get (Ctx ctx)
  43. {
  44. if (s_system != null)
  45. return s_system;
  46. //
  47. String sql = "SELECT * FROM AD_System ORDER BY AD_System_ID"; // 0 first
  48. PreparedStatement pstmt = null;
  49. try
  50. {
  51. pstmt = DB.prepareStatement(sql, (Trx) null);
  52. ResultSet rs = pstmt.executeQuery();
  53. if (rs.next())
  54. s_system = new MSystem (ctx, rs, null);
  55. rs.close();
  56. pstmt.close();
  57. pstmt = null;
  58. }
  59. catch (SQLException ex)
  60. {
  61. String info = "No System - " + DB.getDatabaseInfo() + " - " + ex.getLocalizedMessage();
  62. System.err.println(info);
  63. }
  64. try
  65. {
  66. if (pstmt != null)
  67. pstmt.close();
  68. }
  69. catch (SQLException ex1)
  70. {
  71. }
  72. pstmt = null;
  73. if (s_system == null)
  74. return null;
  75. //
  76. if (!Ini.isClient() && s_system.setInfo())
  77. s_system.save();
  78. return s_system;
  79. } // get
  80. /** System - cached */
  81. private static MSystem s_system = null;
  82. /**************************************************************************
  83. * Default Constructor
  84. * @param ctx context
  85. * @param ignored id - if < 0 not loaded
  86. * @param mtrxName transaction
  87. */
  88. public MSystem (Ctx ctx, int ignored, Trx mtrxName)
  89. {
  90. super(ctx, 0, mtrxName);
  91. Trx trx = null;
  92. if (ignored >= 0)
  93. load(trx); // load ID=0
  94. if (s_system == null)
  95. s_system = this;
  96. } // MSystem
  97. /**
  98. * Load Constructor
  99. * @param ctx context
  100. * @param rs result set
  101. * @param trx transaction
  102. */
  103. public MSystem (Ctx ctx, ResultSet rs, Trx trx)
  104. {
  105. super (ctx, rs, trx);
  106. if (s_system == null)
  107. s_system = this;
  108. } // MSystem
  109. /**
  110. * Constructor
  111. */
  112. public MSystem ()
  113. {
  114. this (new Ctx(), 0, null);
  115. } // MSystem
  116. /**
  117. * Is LDAP Authentification defined
  118. * @return true if ldap defined
  119. */
  120. public boolean isLDAP()
  121. {
  122. String host = getLDAPHost();
  123. if (host == null || host.length() == 0)
  124. return false;
  125. String domain = getLDAPDomain();
  126. return domain != null
  127. && domain.length() > 0;
  128. } // isLDAP
  129. /**
  130. * LDAP Authentification. Assumes that LDAP is defined.
  131. * @param userName user name
  132. * @param password password
  133. * @return true if ldap authenticated
  134. */
  135. public boolean isLDAP (String userName, String password)
  136. {
  137. return LDAP.validate(getLDAPHost(), getLDAPDomain(), userName, password);
  138. } // isLDAP
  139. /**
  140. * Get DB Address
  141. * @return dbURL
  142. */
  143. public String getDBAddress (boolean actual)
  144. {
  145. String s = super.getDBAddress ();
  146. if (actual || s == null || s.length() == 0)
  147. {
  148. CConnection cc = CConnection.get();
  149. s = cc.getConnectionURL() + "#" + cc.getDbUid();
  150. s = s.toLowerCase();
  151. }
  152. return s;
  153. } // getDBAddress
  154. /**
  155. * Get Statistics Info
  156. * @param recalc recalculate
  157. * @return statistics
  158. */
  159. public String getStatisticsInfo (boolean recalc)
  160. {
  161. String s = super.getStatisticsInfo();
  162. if (s == null || recalc)
  163. {
  164. String count = DB.TO_CHAR("COUNT(*)", DisplayTypeConstants.Number, Env.getAD_Language(Env.getCtx()));
  165. String sql = "SELECT 'C'||(SELECT " + count + " FROM AD_Client)"
  166. + " ||'U'||(SELECT " + count + " FROM AD_User)"
  167. + " ||'B'||(SELECT " + count + " FROM C_BPartner)"
  168. + " ||'P'||(SELECT " + count + " FROM M_Product)"
  169. + " ||'I'||(SELECT " + count + " FROM C_Invoice)"
  170. + " ||'L'||(SELECT " + count + " FROM C_InvoiceLine)"
  171. + " ||'M'||(SELECT " + count + " FROM M_Transaction)"
  172. + " ||'c'||(SELECT " + count + " FROM AD_Column WHERE EntityType NOT IN ('C','D'))"
  173. + " ||'t'||(SELECT " + count + " FROM AD_Table WHERE EntityType NOT IN ('C','D'))"
  174. + " ||'f'||(SELECT " + count + " FROM AD_Field WHERE EntityType NOT IN ('C','D'))"
  175. + " FROM AD_System";
  176. PreparedStatement pstmt = null;
  177. try
  178. {
  179. pstmt = DB.prepareStatement(sql, (Trx) null);
  180. ResultSet rs = pstmt.executeQuery ();
  181. if (rs.next ())
  182. s = rs.getString(1);
  183. rs.close ();
  184. pstmt.close ();
  185. pstmt = null;
  186. //
  187. setStatisticsInfo(s);
  188. }
  189. catch (Exception e)
  190. {
  191. log.log (Level.SEVERE, sql, e);
  192. }
  193. try
  194. {
  195. if (pstmt != null)
  196. pstmt.close ();
  197. pstmt = null;
  198. }
  199. catch (Exception e)
  200. {
  201. pstmt = null;
  202. }
  203. }
  204. return s;
  205. } // getStatisticsInfo
  206. /**
  207. * Get Profile Info
  208. * @param recalc recalculate
  209. * @return profile
  210. */
  211. public String getProfileInfo (boolean recalc)
  212. {
  213. String s = super.getProfileInfo ();
  214. if (s == null || recalc)
  215. {
  216. String sql = "SELECT Value FROM AD_Client "
  217. + "WHERE IsActive='Y' ORDER BY AD_Client_ID DESC";
  218. PreparedStatement pstmt = null;
  219. StringBuffer sb = new StringBuffer();
  220. try
  221. {
  222. pstmt = DB.prepareStatement(sql, (Trx) null);
  223. ResultSet rs = pstmt.executeQuery ();
  224. while (rs.next ())
  225. sb.append(rs.getString(1)).append('|');
  226. rs.close ();
  227. pstmt.close ();
  228. pstmt = null;
  229. }
  230. catch (Exception e)
  231. {
  232. log.log (Level.SEVERE, sql, e);
  233. }
  234. try
  235. {
  236. if (pstmt != null)
  237. pstmt.close ();
  238. pstmt = null;
  239. }
  240. catch (Exception e)
  241. {
  242. pstmt = null;
  243. }
  244. s = sb.toString();
  245. }
  246. return s;
  247. } // getProfileInfo
  248. /**
  249. * Before Save
  250. * @param newRecord new
  251. * @return true/false
  252. */
  253. @Override
  254. protected boolean beforeSave (boolean newRecord)
  255. {
  256. // Mandatory Values
  257. if (get_Value("IsAutoErrorReport") == null)
  258. setIsAutoErrorReport (true);
  259. //
  260. boolean userChange = Ini.isClient() &&
  261. (is_ValueChanged("Name")
  262. || is_ValueChanged("UserName")
  263. || is_ValueChanged("Password")
  264. || is_ValueChanged("LDAPHost")
  265. || is_ValueChanged("LDAPDomain")
  266. || is_ValueChanged("CustomPrefix")
  267. );
  268. if (userChange)
  269. {
  270. String name = getName();
  271. if (name.equals("?") || name.length() < 2)
  272. {
  273. log.saveError("Error", "Define a unique System name (e.g. Company name) not " + name);
  274. return false;
  275. }
  276. if (getUserName().equals("?") || getUserName().length() < 2)
  277. {
  278. log.saveError("Error", "Use the same EMail address as in the Compiere Web Store");
  279. return false;
  280. }
  281. if (getPassword().equals("?") || getPassword().length() < 2)
  282. {
  283. log.saveError("Error", "Use the same Password as in the Compiere Web Store");
  284. return false;
  285. }
  286. }
  287. if (getSupportLevel() == null)
  288. setSupportLevel(SUPPORTLEVEL_Unsupported);
  289. //
  290. setInfo();
  291. s_system = this; // update singleton
  292. return true;
  293. } // beforeSave
  294. /**
  295. * Save Record (ID=0)
  296. * @return true if saved
  297. */
  298. @Override
  299. public boolean save()
  300. {
  301. if (!beforeSave(false))
  302. return false;
  303. return saveUpdate();
  304. } // save
  305. /**
  306. * String Representation
  307. * @return info
  308. */
  309. @Override
  310. public String toString()
  311. {
  312. return "MSystem[" + getName()
  313. + ",User=" + getUserName()
  314. + ",ReleaseNo=" + getReleaseNo()
  315. + "]";
  316. } // toString
  317. /**************************************************************************
  318. * Check valididity
  319. * @return true if valid
  320. */
  321. public boolean isValid()
  322. {
  323. if (getName() == null || getName().length() < 2)
  324. {
  325. log.log(Level.WARNING, "Name not valid: " + getName());
  326. return false;
  327. }
  328. if (getPassword() == null || getPassword().length() < 2)
  329. {
  330. log.log(Level.WARNING, "Password not valid: " + getPassword());
  331. return false;
  332. }
  333. if (getInfo() == null || getInfo().length() < 2)
  334. {
  335. log.log(Level.WARNING, "Need to run Migration once");
  336. return false;
  337. }
  338. return true;
  339. } // isValid
  340. /**
  341. * Is there a PDF License
  342. * @return true if there is a PDF License
  343. */
  344. public boolean isPDFLicense()
  345. {
  346. String key = getSummary();
  347. return key != null && key.length() > 25;
  348. } // isPDFLicense
  349. /**
  350. * Get SupportLevel
  351. * @return Support Level
  352. */
  353. @Override
  354. public String getSupportLevel()
  355. {
  356. String sl = null;
  357. if (get_ColumnIndex("SupportLevel") != -1)
  358. sl = super.getSupportLevel();
  359. if (sl == null)
  360. return SUPPORTLEVEL_Unsupported;
  361. return sl;
  362. } // getSupportLevel
  363. /**
  364. * Get Record_ID
  365. * @return record ID
  366. */
  367. @Override
  368. public int getRecord_ID()
  369. {
  370. if (get_ColumnIndex("Record_ID") == -1)
  371. return -1;
  372. return super.getRecord_ID ();
  373. } // getRecord_ID
  374. /**
  375. * Get SupportUnits
  376. * @return SupportUnits
  377. */
  378. @Override
  379. public int getSupportUnits()
  380. {
  381. if (get_ColumnIndex("SupportUnits") == -1)
  382. return 0;
  383. return super.getSupportUnits ();
  384. } // getSupportUnits
  385. /**
  386. * Get System Status
  387. * @return system status
  388. */
  389. @Override
  390. public String getSystemStatus()
  391. {
  392. String ss = null;
  393. if (get_ColumnIndex("SystemStatus") != -1)
  394. ss = super.getSystemStatus();
  395. if (ss == null)
  396. ss = SYSTEMSTATUS_Evaluation;
  397. return ss;
  398. } // getSystemStatus
  399. /**************************************************************************
  400. * Set/Derive Info if more then a day old
  401. * @return true if set
  402. */
  403. public boolean setInfo()
  404. {
  405. // log.severe("setInfo");
  406. if (!TimeUtil.getDay(getUpdated()).before(TimeUtil.getDay(null)))
  407. return false;
  408. try
  409. {
  410. setDBInfo();
  411. setInternalUsers();
  412. if (isAllowStatistics())
  413. {
  414. setStatisticsInfo(getStatisticsInfo(true));
  415. setProfileInfo(getProfileInfo(true));
  416. }
  417. }
  418. catch (Exception e)
  419. {
  420. setSupportUnits(9999);
  421. setInfo(e.getLocalizedMessage());
  422. log.log(Level.SEVERE, "", e);
  423. }
  424. return true;
  425. } // setInfo
  426. /**
  427. * Set Internal User Count
  428. */
  429. private void setInternalUsers()
  430. {
  431. String sql = "SELECT COUNT(DISTINCT (u.AD_User_ID)) AS iu "
  432. + "FROM AD_User u"
  433. + " INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID) "
  434. + "WHERE u.AD_Client_ID<>11" // no Demo
  435. + " AND u.AD_User_ID NOT IN (0,100)"; // no System/SuperUser
  436. PreparedStatement pstmt = null;
  437. try
  438. {
  439. pstmt = DB.prepareStatement(sql, (Trx) null);
  440. ResultSet rs = pstmt.executeQuery ();
  441. if (rs.next ())
  442. {
  443. int internalUsers = rs.getInt (1);
  444. setSupportUnits(internalUsers);
  445. }
  446. rs.close ();
  447. pstmt.close ();
  448. pstmt = null;
  449. }
  450. catch (Exception e)
  451. {
  452. log.log(Level.SEVERE, sql, e);
  453. }
  454. try
  455. {
  456. if (pstmt != null)
  457. pstmt.close ();
  458. pstmt = null;
  459. }
  460. catch (Exception e)
  461. {
  462. pstmt = null;
  463. }
  464. } // setInternalUsers
  465. /**
  466. * Set DB Info
  467. */
  468. private void setDBInfo()
  469. {
  470. if (!DB.isRemoteObjects())
  471. {
  472. String dbAddress = getDBAddress(true);
  473. setDBAddress(dbAddress);
  474. }
  475. //
  476. if (!Ini.isClient())
  477. {
  478. int noProcessors = Runtime.getRuntime().availableProcessors();
  479. setNoProcessors(noProcessors);
  480. }
  481. //
  482. try
  483. {
  484. Trx trx = Trx.get("getDatabaseMetaData");
  485. DatabaseMetaData md = trx.getConnection().getMetaData();
  486. String db1 = md.getDatabaseProductName();
  487. String db2 = md.getDatabaseProductVersion();
  488. if (db2.startsWith(db1))
  489. db1 = db2;
  490. else
  491. db1 += "-" + db2;
  492. int fieldLength = p_info.getFieldLength("DBInstance");
  493. if (db1.length() > fieldLength)
  494. {
  495. db1 = Util.replace (db1, "Database ", "");
  496. db1 = Util.replace (db1, "Version ", "");
  497. db1 = Util.replace (db1, "Edition ", "");
  498. db1 = Util.replace (db1, "Release ", "");
  499. }
  500. db1 = Util.removeCRLF(db1);
  501. if (db1.length() > fieldLength)
  502. db1 = db1.substring(0, fieldLength);
  503. setDBInstance(db1);
  504. trx.close();
  505. }
  506. catch (Exception e)
  507. {
  508. log.log (Level.SEVERE, "MetaData", e);
  509. }
  510. } // setDBInfo
  511. /**
  512. * Print info
  513. */
  514. public void info()
  515. {
  516. if (!CLogMgt.isLevelFine())
  517. return;
  518. // OS
  519. // OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
  520. // log.fine(os.getName() + " " + os.getVersion() + " " + os.getArch()
  521. // + " Processors=" + os.getAvailableProcessors());
  522. // Runtime
  523. RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
  524. log.fine(rt.getName() + " (" + rt.getVmVersion() + ") Up=" + TimeUtil.formatElapsed(rt.getUptime()));
  525. // Memory
  526. if (CLogMgt.isLevelFiner())
  527. {
  528. List<MemoryPoolMXBean> list = ManagementFactory.getMemoryPoolMXBeans();
  529. Iterator<MemoryPoolMXBean> it = list.iterator();
  530. while (it.hasNext())
  531. {
  532. MemoryPoolMXBean pool = it.next();
  533. log.finer(pool.getName() + " " + pool.getType()
  534. + ": " + new CMemoryUsage(pool.getUsage()));
  535. }
  536. }
  537. else
  538. {
  539. MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
  540. log.fine("VM: " + new CMemoryUsage(memory.getNonHeapMemoryUsage()));
  541. log.fine("Heap: " + new CMemoryUsage(memory.getHeapMemoryUsage()));
  542. }
  543. // Thread
  544. ThreadMXBean th = ManagementFactory.getThreadMXBean();
  545. log.fine("Threads=" + th.getThreadCount()
  546. + ", Peak=" + th.getPeakThreadCount()
  547. + ", Demons=" + th.getDaemonThreadCount()
  548. + ", Total=" + th.getTotalStartedThreadCount()
  549. );
  550. } // info
  551. /**
  552. * Test
  553. * @param args
  554. */
  555. public static void main (String[] args)
  556. {
  557. new MSystem();
  558. } // main
  559. /**
  560. * Only save the license
  561. * @return true if success; otherwise false
  562. */
  563. public boolean saveLicenseOnly()
  564. {
  565. // Create the update statement for license
  566. StringBuffer sql = new StringBuffer ("UPDATE ");
  567. sql.append(p_info.getTableName())
  568. .append(" SET Name=").append(DB.TO_STRING(getName()))
  569. .append(", UserName=").append(DB.TO_STRING(getUserName()))
  570. .append(", Password=").append(DB.TO_STRING(getPassword()))
  571. .append(", Summary=").append(DB.TO_STRING(getSummary()))
  572. .append(" WHERE AD_System_ID=").append(getAD_System_ID());
  573. log.fine(sql.toString());
  574. // Send to database
  575. int no = DB.executeUpdate(sql.toString(), (Trx) null);
  576. return no == 1;
  577. } // saveLicenseOnly()
  578. } // MSystem