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