From ee46d9e79242cd6c161d0f4df50de5e2ae7ae645 Mon Sep 17 00:00:00 2001 From: vpj-cd Date: Thu, 7 Dec 2006 03:21:41 +0000 Subject: [PATCH] Adempiere 3.1.2 --- dbPort/src/org/compiere/Adempiere.java | 4 +- dbPort/src/org/compiere/db/CConnection.java | 115 +- .../org/compiere/db/CConnectionDialog.java | 934 ++-- dbPort/src/org/compiere/db/DB_Fyracle.java | 6 + dbPort/src/org/compiere/db/DB_PostgreSQL.java | 25 +- dbPort/src/org/compiere/db/DerbyServer.java | 426 ++ dbPort/src/org/compiere/db/LDAP.java | 400 +- .../src/org/compiere/dbPort/JdbcTestPG.java | 24 +- .../compiere/dbPort/PostgresConvertTest.java | 24 +- .../compiere/model/AccessSqlParserTest.java | 426 +- .../src/org/compiere/model/MClientShare.java | 552 +-- .../src/org/compiere/model/MCostElement.java | 874 ++-- .../org/compiere/model/MLookupFactory.java | 1494 ++++--- dbPort/src/org/compiere/model/MOrg.java | 419 +- dbPort/src/org/compiere/model/MOrgInfo.java | 181 +- .../src/org/compiere/util/AmtInWords_IN.java | 308 +- dbPort/src/org/compiere/util/CLogger.java | 3 + .../org/compiere/util/CPreparedStatement.java | 107 + dbPort/src/org/compiere/util/CStatement.java | 10 + dbPort/src/org/compiere/util/DB.java | 3778 +++++++++-------- dbPort/src/org/compiere/util/Env.java | 2847 ++++++------- .../src/org/compiere/util/GenerateModel.java | 1660 ++++---- dbPort/src/org/compiere/util/Login.java | 2155 +++++----- dbPort/src/org/compiere/util/Msg.java | 1262 +++--- 24 files changed, 9257 insertions(+), 8777 deletions(-) create mode 100755 dbPort/src/org/compiere/db/DerbyServer.java diff --git a/dbPort/src/org/compiere/Adempiere.java b/dbPort/src/org/compiere/Adempiere.java index 5d3ccdc109..e15b04038f 100644 --- a/dbPort/src/org/compiere/Adempiere.java +++ b/dbPort/src/org/compiere/Adempiere.java @@ -42,7 +42,7 @@ public final class Adempiere /** Timestamp */ static public final String ID = "$Id: Adempiere.java,v 1.8 2006/08/11 02:58:14 jjanke Exp $"; /** Main Version String */ - static public final String MAIN_VERSION = "Release 3.1.1"; + static public final String MAIN_VERSION = "Release 3.1.2"; /** Detail Version as date Used for Client/Server */ static public final String DATE_VERSION = "2006-11-02"; /** Database Version as date Compared with AD_System */ @@ -72,7 +72,7 @@ public final class Adempiere static private String s_supportEmail = ""; /** Subtitle */ - static public final String SUB_TITLE = "The Open Source Profesional ERP,CRM and SCM "; + static public final String SUB_TITLE = "Smart Suite ERP,CRM and SCM "; /** Adempiere is a wordwide registered Trademark * - Don't modify this - Program will someday fail unexpectedly */ static public final String ADEMPIERE_R = "Adempiere\u00AE"; diff --git a/dbPort/src/org/compiere/db/CConnection.java b/dbPort/src/org/compiere/db/CConnection.java index 732815ec2b..c278ab9d1a 100644 --- a/dbPort/src/org/compiere/db/CConnection.java +++ b/dbPort/src/org/compiere/db/CConnection.java @@ -27,7 +27,7 @@ import org.compiere.interfaces.*; import org.compiere.util.*; /** - * Adempiere Connection Descriptor + * Compiere Connection Descriptor * * @author Jorg Janke * @author Marek Mosiewicz - support for RMI over HTTP @@ -138,7 +138,7 @@ public class CConnection implements Serializable /************************************************************************** - * Adempiere Connection + * Compiere Connection * @param host optional application/db host */ private CConnection (String host) @@ -182,9 +182,9 @@ public class CConnection implements Serializable private int m_fw_port = 0; /** DB User name */ - private String m_db_uid = "adempiere"; + private String m_db_uid = "compiere"; /** DB User password */ - private String m_db_pwd = "adempiere"; + private String m_db_pwd = "compiere"; /** Database */ private AdempiereDatabase m_db = null; @@ -209,9 +209,6 @@ public class CConnection implements Serializable private Server m_server = null; /** DB Info */ private String m_dbInfo = null; - - /** Had application server been query **/ - private boolean m_queryAppsServer = false; /************************************************************************* @@ -259,7 +256,6 @@ public class CConnection implements Serializable m_apps_host = apps_host; m_name = toString (); m_okApps = false; - m_queryAppsServer = false; } /** @@ -279,7 +275,6 @@ public class CConnection implements Serializable { m_apps_port = apps_port; m_okApps = false; - m_queryAppsServer = false; } /** @@ -308,11 +303,9 @@ public class CConnection implements Serializable */ public boolean isAppsServerOK (boolean tryContactAgain) { - if (!tryContactAgain && m_queryAppsServer) + if (!tryContactAgain) return m_okApps; - m_queryAppsServer = true; - // Get Context if (m_iContext == null) { @@ -347,9 +340,8 @@ public class CConnection implements Serializable */ public Exception testAppsServer () { - //if (queryAppsServerInfo ()) - // testDatabase (false); - queryAppsServerInfo (); + if (queryAppsServerInfo ()) + testDatabase (false); return getAppsServerException (); } // testAppsServer @@ -809,24 +801,11 @@ public class CConnection implements Serializable if (getDbPort () != DB_DB2.DEFAULT_PORT) setDbPort (DB_DB2.DEFAULT_PORT); } - else if (isDerby()) + /*else if (isDerby()) { -// if (getDbPort () != DB_Derby.DEFAULT_PORT) -// setDbPort (DB_Derby.DEFAULT_PORT); - } - // begin vpj-cd e-evolution 09 ene 2006 - // PostgreSQL - if (isPostgreSQL ()) - { - if (getDbPort () != DB_PostgreSQL.DEFAULT_PORT) - setDbPort (DB_PostgreSQL.DEFAULT_PORT); - } - //end vpj-cd e-evolution 09 ene 2006 - if (isFyracle()) - { - if (getDbPort () != DB_Fyracle.DEFAULT_PORT) - setDbPort (DB_Fyracle.DEFAULT_PORT); - } + if (getDbPort () != DB_Derby.DEFAULT_PORT) + setDbPort (DB_Derby.DEFAULT_PORT); + }*/ } // setType /** @@ -875,16 +854,7 @@ public class CConnection implements Serializable return Database.DB_MSSQLServer.equals (m_type); } // isMSSQLServer - //begin e-evolution vpj-cd 30 nov 2005 - /** - * Is PostgreSQL DB - * @return true if PostgreSQL - */ -// public boolean isEDB () -// { -// return Database.DB_EDB.equals (m_type); -// } // isPostgreSQL - /** + /** * Is PostgreSQL DB * @return true if PostgreSQL */ @@ -902,6 +872,7 @@ public class CConnection implements Serializable return Database.DB_FYRACLE.equals (m_type); } // isPostgreSQL //end + /** * Is Database Connection OK * @return true if database connection is OK @@ -987,9 +958,18 @@ public class CConnection implements Serializable Connection.TRANSACTION_READ_COMMITTED); if (conn != null) { - try + try { - readInfo(conn); + DatabaseMetaData dbmd = conn.getMetaData (); + m_info[0] = "Database=" + dbmd.getDatabaseProductName () + + " - " + dbmd.getDatabaseProductVersion (); + m_info[0] = m_info[0].replace ('\n', ' '); + m_info[1] = "Driver =" + dbmd.getDriverName () + + " - " + dbmd.getDriverVersion (); + if (isDataSource()) + m_info[1] += " - via DataSource"; + m_info[1] = m_info[1].replace ('\n', ' '); + log.config(m_info[0] + " - " + m_info[1]); conn.close (); } catch (Exception e) @@ -1000,19 +980,20 @@ public class CConnection implements Serializable } return m_dbException; // from opening } // testDatabase - - public void readInfo(Connection conn) throws SQLException { - DatabaseMetaData dbmd = conn.getMetaData (); - m_info[0] = "Database=" + dbmd.getDatabaseProductName () - + " - " + dbmd.getDatabaseProductVersion (); - m_info[0] = m_info[0].replace ('\n', ' '); + + public void readInfo(Connection conn) throws SQLException { + DatabaseMetaData dbmd = conn.getMetaData (); + m_info[0] = "Database=" + dbmd.getDatabaseProductName () + + " - " + dbmd.getDatabaseProductVersion (); + m_info[0] = m_info[0].replace ('\n', ' '); m_info[1] = "Driver =" + dbmd.getDriverName () - + " - " + dbmd.getDriverVersion (); - if (isDataSource()) - m_info[1] += " - via DataSource"; - m_info[1] = m_info[1].replace ('\n', ' '); - log.config(m_info[0] + " - " + m_info[1]); - } + + " - " + dbmd.getDriverVersion (); + if (isDataSource()) + m_info[1] += " - via DataSource"; + m_info[1] = m_info[1].replace ('\n', ' '); + log.config(m_info[0] + " - " + m_info[1]); + } + /************************************************************************* * Short String representation @@ -1224,7 +1205,15 @@ public class CConnection implements Serializable { try { - m_db = Database.getDatabase(m_type); + for (int i = 0; i < Database.DB_NAMES.length; i++) + { + if (Database.DB_NAMES[i].equals (m_type)) + { + m_db = (AdempiereDatabase)Database.DB_CLASSES[i]. + newInstance (); + break; + } + } } catch (Exception e) { @@ -1507,19 +1496,12 @@ public class CConnection implements Serializable log.finer(getAppsHost()); long start = System.currentTimeMillis(); m_okApps = false; - m_queryAppsServer = true; m_appsException = null; // getInitialContext (false); if (m_iContext == null) return m_okApps; // false - - // Carlos Ruiz - globalqss - speed up when jnp://MyAppsServer:1099 is set - if (getAppsHost().equalsIgnoreCase("MyAppsServer")) { - log.warning (getAppsHost() + " ignored"); - return m_okApps; // false - } - + // Prevent error trace // CLogMgtLog4J.enable(false); try @@ -1642,6 +1624,7 @@ public class CConnection implements Serializable return ""; } // getTransactionIsolationInfo + /************************************************************************** * Testing @@ -1664,7 +1647,7 @@ public class CConnection implements Serializable Adempiere.startup(true); // System.out.println ("Connection = "); - // CConnection[name=localhost{dev-dev1-adempiere},AppsHost=localhost,AppsPort=1099,type=Oracle,DBhost=dev,DBport=1521,DBname=dev1,BQ=false,FW=false,FWhost=,FWport=1630,UID=adempiere,PWD=adempiere] + // CConnection[name=localhost{dev-dev1-compiere},AppsHost=localhost,AppsPort=1099,type=Oracle,DBhost=dev,DBport=1521,DBname=dev1,BQ=false,FW=false,FWhost=,FWport=1630,UID=compiere,PWD=compiere] System.out.println (Ini.getProperty (Ini.P_CONNECTION)); CConnection cc = CConnection.get (); diff --git a/dbPort/src/org/compiere/db/CConnectionDialog.java b/dbPort/src/org/compiere/db/CConnectionDialog.java index ad0eb30cdd..c22e876783 100644 --- a/dbPort/src/org/compiere/db/CConnectionDialog.java +++ b/dbPort/src/org/compiere/db/CConnectionDialog.java @@ -3,21 +3,21 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.db; - -import java.awt.*; -import java.awt.event.*; + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.db; + +import java.awt.*; +import java.awt.event.*; import java.util.*; import java.util.logging.*; import javax.swing.*; @@ -26,23 +26,23 @@ import org.adempiere.plaf.AdempierePLAF; import org.compiere.plaf.*; import org.compiere.swing.*; import org.compiere.util.*; - -/** - * Connection Dialog. - * - * @author Jorg Janke - * @author Marek Mosiewicz - support for RMI over HTTP - * @version $Id: CConnectionDialog.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $ - */ -public class CConnectionDialog extends CDialog implements ActionListener -{ - /** - * Connection Dialog using current Connection - */ - public CConnectionDialog() - { - this (null); - } // CConnectionDialog + +/** + * Connection Dialog. + * + * @author Jorg Janke + * @author Marek Mosiewicz - support for RMI over HTTP + * @version $Id: CConnectionDialog.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $ + */ +public class CConnectionDialog extends CDialog implements ActionListener +{ + /** + * Connection Dialog using current Connection + */ + public CConnectionDialog() + { + this (null); + } // CConnectionDialog /** * Connection Dialog @@ -50,13 +50,13 @@ public class CConnectionDialog extends CDialog implements ActionListener */ public CConnectionDialog(CConnection cc) { - super((Frame)null, true); - try - { - jbInit(); - setConnection (cc); - } - catch(Exception e) + super((Frame)null, true); + try + { + jbInit(); + setConnection (cc); + } + catch(Exception e) { log.log(Level.SEVERE, "", e); } @@ -64,33 +64,33 @@ public class CConnectionDialog extends CDialog implements ActionListener } // CConnection /** Resources */ - private static ResourceBundle res = ResourceBundle.getBundle("org.compiere.db.DBRes"); - - static - { - /** Connection Profiles */ - CConnection.CONNECTIONProfiles = new ValueNamePair[]{ - new ValueNamePair("L", res.getString("LAN")), - new ValueNamePair("T", res.getString("TerminalServer")), - new ValueNamePair("V", res.getString("VPN")), - new ValueNamePair("W", res.getString("WAN")) - }; - } - - /** Default HTTP Port */ - public static final String APPS_PORT_HTTP = "80"; - /** Default RMI Port */ - public static final String APPS_PORT_JNP = "1099"; - /** Connection */ - private CConnection m_cc = null; - private CConnection m_ccResult = null; - private boolean m_updating = false; - private boolean m_saved = false; - - /** Logger */ - private static CLogger log = CLogger.getCLogger (CConnectionDialog.class); - - private CPanel mainPanel = new CPanel(); + private static ResourceBundle res = ResourceBundle.getBundle("org.compiere.db.DBRes"); + + static + { + /** Connection Profiles */ + CConnection.CONNECTIONProfiles = new ValueNamePair[]{ + new ValueNamePair("L", res.getString("LAN")), + new ValueNamePair("T", res.getString("TerminalServer")), + new ValueNamePair("V", res.getString("VPN")), + new ValueNamePair("W", res.getString("WAN")) + }; + } + + /** Default HTTP Port */ + public static final String APPS_PORT_HTTP = "80"; + /** Default RMI Port */ + public static final String APPS_PORT_JNP = "1099"; + /** Connection */ + private CConnection m_cc = null; + private CConnection m_ccResult = null; + private boolean m_updating = false; + private boolean m_saved = false; + + /** Logger */ + private static CLogger log = CLogger.getCLogger (CConnectionDialog.class); + + private CPanel mainPanel = new CPanel(); private BorderLayout mainLayout = new BorderLayout(); private CPanel centerPanel = new CPanel(); private CPanel southPanel = new CPanel(); @@ -99,156 +99,156 @@ public class CConnectionDialog extends CDialog implements ActionListener private FlowLayout southLayout = new FlowLayout(); private GridBagLayout centerLayout = new GridBagLayout(); private CLabel nameLabel = new CLabel(); - private CTextField nameField = new CTextField(); - private CLabel hostLabel = new CLabel(); - private CTextField hostField = new CTextField(); - private CLabel portLabel = new CLabel(); - private CTextField dbPortField = new CTextField(); - private CLabel sidLabel = new CLabel(); - private CTextField sidField = new CTextField(); - private CCheckBox cbFirewall = new CCheckBox(); - private CLabel fwHostLabel = new CLabel(); - private CTextField fwHostField = new CTextField(); - private CLabel fwPortLabel = new CLabel(); - private CTextField fwPortField = new CTextField(); - private CButton bTestDB = new CButton(); - private CLabel dbTypeLabel = new CLabel(); - private CComboBox dbTypeField = new CComboBox(Database.DB_NAMES); - private CCheckBox cbBequeath = new CCheckBox(); - private CLabel appsHostLabel = new CLabel(); - private CTextField appsHostField = new CTextField(); - private CLabel appsPortLabel = new CLabel(); - private CTextField appsPortField = new CTextField(); - private CButton bTestApps = new CButton(); - private CCheckBox cbOverwrite = new CCheckBox(); - private CLabel dbUidLabel = new CLabel(); - private CTextField dbUidField = new CTextField(); - private JPasswordField dbPwdField = new JPasswordField(); - private CLabel connectionProfileLabel = new CLabel(); - private CComboBox connectionProfileField = new CComboBox(CConnection.CONNECTIONProfiles); - - - /** - * Static Layout - * @throws Exception - */ - private void jbInit() throws Exception - { - this.setTitle(res.getString("CConnectionDialog")); - mainPanel.setLayout(mainLayout); - southPanel.setLayout(southLayout); - southLayout.setAlignment(FlowLayout.RIGHT); - centerPanel.setLayout(centerLayout); - nameLabel.setText(res.getString("Name")); - nameField.setColumns(30); - nameField.setReadWrite(false); - hostLabel.setText(res.getString("DBHost")); - hostField.setColumns(30); - portLabel.setText(res.getString("DBPort")); - dbPortField.setColumns(10); - sidLabel.setText(res.getString("DBName")); - cbFirewall.setToolTipText(""); - cbFirewall.setText(res.getString("ViaFirewall")); - fwHostLabel.setText(res.getString("FWHost")); - fwHostField.setColumns(30); - fwPortLabel.setText(res.getString("FWPort")); - bTestDB.setText(res.getString("TestConnection")); - bTestDB.setHorizontalAlignment(JLabel.LEFT); - dbTypeLabel.setText(res.getString("Type")); - sidField.setColumns(30); - fwPortField.setColumns(10); - cbBequeath.setText(res.getString("BequeathConnection")); - appsHostLabel.setText(res.getString("AppsHost")); - appsHostField.setColumns(30); - appsPortLabel.setText(res.getString("AppsPort")); - appsPortField.setColumns(10); - bTestApps.setText(res.getString("TestApps")); - bTestApps.setHorizontalAlignment(JLabel.LEFT); - cbOverwrite.setText(res.getString("Overwrite")); - dbUidLabel.setText(res.getString("DBUidPwd")); - dbUidField.setColumns(10); - connectionProfileLabel.setText(res.getString("ConnectionProfile")); - connectionProfileField.addActionListener(this); - this.getContentPane().add(mainPanel, BorderLayout.CENTER); - mainPanel.add(centerPanel, BorderLayout.CENTER); - mainPanel.add(southPanel, BorderLayout.SOUTH); - southPanel.add(bCancel, null); - southPanel.add(bOK, null); - // - centerPanel.add(nameLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); - centerPanel.add(nameField, new GridBagConstraints(1, 0, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 0, 5, 12), 0, 0)); - centerPanel.add(appsHostLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - centerPanel.add(appsHostField, new GridBagConstraints(1, 1, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - - centerPanel.add(appsPortLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(appsPortField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); - centerPanel.add(connectionProfileLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - centerPanel.add(connectionProfileField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0)); - // - centerPanel.add(bTestApps, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0 - ,GridBagConstraints.SOUTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 12, 0), 0, 0)); - centerPanel.add(cbOverwrite, new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 5, 0, 12), 0, 0)); - // DB - centerPanel.add(dbTypeLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - centerPanel.add(dbTypeField, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 0), 0, 0)); - centerPanel.add(cbBequeath, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 12), 0, 0)); - centerPanel.add(hostLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - centerPanel.add(hostField, new GridBagConstraints(1, 6, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - centerPanel.add(portLabel, new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(dbPortField, new GridBagConstraints(1, 7, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - centerPanel.add(sidLabel, new GridBagConstraints(0, 8, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(sidField, new GridBagConstraints(1, 8, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(dbUidLabel, new GridBagConstraints(0, 9, 1, 1, 0.0, 0.0 + private CTextField nameField = new CTextField(); + private CLabel hostLabel = new CLabel(); + private CTextField hostField = new CTextField(); + private CLabel portLabel = new CLabel(); + private CTextField dbPortField = new CTextField(); + private CLabel sidLabel = new CLabel(); + private CTextField sidField = new CTextField(); + private CCheckBox cbFirewall = new CCheckBox(); + private CLabel fwHostLabel = new CLabel(); + private CTextField fwHostField = new CTextField(); + private CLabel fwPortLabel = new CLabel(); + private CTextField fwPortField = new CTextField(); + private CButton bTestDB = new CButton(); + private CLabel dbTypeLabel = new CLabel(); + private CComboBox dbTypeField = new CComboBox(Database.DB_NAMES); + private CCheckBox cbBequeath = new CCheckBox(); + private CLabel appsHostLabel = new CLabel(); + private CTextField appsHostField = new CTextField(); + private CLabel appsPortLabel = new CLabel(); + private CTextField appsPortField = new CTextField(); + private CButton bTestApps = new CButton(); + private CCheckBox cbOverwrite = new CCheckBox(); + private CLabel dbUidLabel = new CLabel(); + private CTextField dbUidField = new CTextField(); + private JPasswordField dbPwdField = new JPasswordField(); + private CLabel connectionProfileLabel = new CLabel(); + private CComboBox connectionProfileField = new CComboBox(CConnection.CONNECTIONProfiles); + + + /** + * Static Layout + * @throws Exception + */ + private void jbInit() throws Exception + { + this.setTitle(res.getString("CConnectionDialog")); + mainPanel.setLayout(mainLayout); + southPanel.setLayout(southLayout); + southLayout.setAlignment(FlowLayout.RIGHT); + centerPanel.setLayout(centerLayout); + nameLabel.setText(res.getString("Name")); + nameField.setColumns(30); + nameField.setReadWrite(false); + hostLabel.setText(res.getString("DBHost")); + hostField.setColumns(30); + portLabel.setText(res.getString("DBPort")); + dbPortField.setColumns(10); + sidLabel.setText(res.getString("DBName")); + cbFirewall.setToolTipText(""); + cbFirewall.setText(res.getString("ViaFirewall")); + fwHostLabel.setText(res.getString("FWHost")); + fwHostField.setColumns(30); + fwPortLabel.setText(res.getString("FWPort")); + bTestDB.setText(res.getString("TestConnection")); + bTestDB.setHorizontalAlignment(JLabel.LEFT); + dbTypeLabel.setText(res.getString("Type")); + sidField.setColumns(30); + fwPortField.setColumns(10); + cbBequeath.setText(res.getString("BequeathConnection")); + appsHostLabel.setText(res.getString("AppsHost")); + appsHostField.setColumns(30); + appsPortLabel.setText(res.getString("AppsPort")); + appsPortField.setColumns(10); + bTestApps.setText(res.getString("TestApps")); + bTestApps.setHorizontalAlignment(JLabel.LEFT); + cbOverwrite.setText(res.getString("Overwrite")); + dbUidLabel.setText(res.getString("DBUidPwd")); + dbUidField.setColumns(10); + connectionProfileLabel.setText(res.getString("ConnectionProfile")); + connectionProfileField.addActionListener(this); + this.getContentPane().add(mainPanel, BorderLayout.CENTER); + mainPanel.add(centerPanel, BorderLayout.CENTER); + mainPanel.add(southPanel, BorderLayout.SOUTH); + southPanel.add(bCancel, null); + southPanel.add(bOK, null); + // + centerPanel.add(nameLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); + centerPanel.add(nameField, new GridBagConstraints(1, 0, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 0, 5, 12), 0, 0)); + centerPanel.add(appsHostLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + centerPanel.add(appsHostField, new GridBagConstraints(1, 1, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + + centerPanel.add(appsPortLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(appsPortField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); + centerPanel.add(connectionProfileLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + centerPanel.add(connectionProfileField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0)); + // + centerPanel.add(bTestApps, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0 + ,GridBagConstraints.SOUTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 12, 0), 0, 0)); + centerPanel.add(cbOverwrite, new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 5, 0, 12), 0, 0)); + // DB + centerPanel.add(dbTypeLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + centerPanel.add(dbTypeField, new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 0), 0, 0)); + centerPanel.add(cbBequeath, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 12), 0, 0)); + centerPanel.add(hostLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + centerPanel.add(hostField, new GridBagConstraints(1, 6, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + centerPanel.add(portLabel, new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(dbPortField, new GridBagConstraints(1, 7, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); + centerPanel.add(sidLabel, new GridBagConstraints(0, 8, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(sidField, new GridBagConstraints(1, 8, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(dbUidLabel, new GridBagConstraints(0, 9, 1, 1, 0.0, 0.0 ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); centerPanel.add(dbUidField, new GridBagConstraints(1, 9, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - centerPanel.add(dbPwdField, new GridBagConstraints(2, 9, 1, 1, 1.0, 0.0 + centerPanel.add(dbPwdField, new GridBagConstraints(2, 9, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 5, 12), 0, 0)); centerPanel.add(cbFirewall, new GridBagConstraints(1, 10, 2, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 12), 0, 0)); - centerPanel.add(fwHostLabel, new GridBagConstraints(0, 11, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fwHostField, new GridBagConstraints(1, 11, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(fwPortLabel, new GridBagConstraints(0, 12, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fwPortField, new GridBagConstraints(1, 12, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); - centerPanel.add(bTestDB, new GridBagConstraints(1, 13, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 12, 0), 0, 0)); - // - nameField.addActionListener(this); - appsHostField.addActionListener(this); - appsPortField.addActionListener(this); - cbOverwrite.addActionListener(this); - bTestApps.addActionListener(this); - // - dbTypeField.addActionListener(this); - hostField.addActionListener(this); - dbPortField.addActionListener(this); - sidField.addActionListener(this); - cbBequeath.addActionListener(this); - cbFirewall.addActionListener(this); - fwHostField.addActionListener(this); - fwPortField.addActionListener(this); + centerPanel.add(fwHostLabel, new GridBagConstraints(0, 11, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fwHostField, new GridBagConstraints(1, 11, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(fwPortLabel, new GridBagConstraints(0, 12, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fwPortField, new GridBagConstraints(1, 12, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0)); + centerPanel.add(bTestDB, new GridBagConstraints(1, 13, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 12, 0), 0, 0)); + // + nameField.addActionListener(this); + appsHostField.addActionListener(this); + appsPortField.addActionListener(this); + cbOverwrite.addActionListener(this); + bTestApps.addActionListener(this); + // + dbTypeField.addActionListener(this); + hostField.addActionListener(this); + dbPortField.addActionListener(this); + sidField.addActionListener(this); + cbBequeath.addActionListener(this); + cbFirewall.addActionListener(this); + fwHostField.addActionListener(this); + fwPortField.addActionListener(this); bTestDB.addActionListener(this); bOK.addActionListener(this); bCancel.addActionListener(this); @@ -256,260 +256,260 @@ public class CConnectionDialog extends CDialog implements ActionListener // Server if (!Ini.isClient()) { - appsHostLabel.setVisible(false); - appsHostField.setVisible(false); - appsPortLabel.setVisible(false); - appsPortField.setVisible(false); - bTestApps.setVisible(false); - connectionProfileLabel.setVisible(false); - connectionProfileField.setVisible(false); - } - else // Client - cbBequeath.setVisible(false); - } // jbInit - - /** - * Set Busy - lock UI - * @param busy busy - */ - private void setBusy (boolean busy) - { - if (busy) - this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - else - this.setCursor(Cursor.getDefaultCursor()); - m_updating = busy; - } // setBusy - - /** - * Set Connection - * @param cc - if null use current connection - */ - public void setConnection (CConnection cc) - { - m_cc = cc; - if (m_cc == null) - { - m_cc = CConnection.get(); - m_cc.setName(); - } - // Should copy values - m_ccResult = m_cc; - // - String type = m_cc.getType(); - if (type == null || type.length() == 0) - dbTypeField.setSelectedItem(null); - else - m_cc.setType(m_cc.getType()); // sets defaults - updateInfo(); - } // setConnection - - /** - * Get Connection - * @return CConnection - */ - public CConnection getConnection() - { - return m_ccResult; - } // getConnection; - - /** - * ActionListener - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - if (m_updating) - return; - Object src = e.getSource(); - - if (src == bOK) - { - m_cc.setName(); - m_ccResult = m_cc; - dispose(); - return; - } - else if (src == bCancel) - { - m_cc.setName(); - dispose(); - return; - } - else if (src == connectionProfileField) - { - ValueNamePair pp = (ValueNamePair)connectionProfileField.getSelectedItem(); - m_cc.setConnectionProfile(pp.getValue()); - if (m_cc.isRMIoverHTTP()) - appsPortField.setText(APPS_PORT_HTTP); - else - appsPortField.setText(APPS_PORT_JNP); - return; - } - else if (src == dbTypeField) - { - if (dbTypeField.getSelectedItem() == null) - return; - } - - - if (Ini.isClient()) - { - m_cc.setAppsHost(appsHostField.getText()); - m_cc.setAppsPort(appsPortField.getText()); - } - else - m_cc.setAppsHost("localhost"); - // - ValueNamePair pp = (ValueNamePair)connectionProfileField.getSelectedItem(); - m_cc.setConnectionProfile(pp.getValue()); - // - m_cc.setType((String)dbTypeField.getSelectedItem()); - m_cc.setDbHost(hostField.getText()); - m_cc.setDbPort(dbPortField.getText()); - m_cc.setDbName(sidField.getText()); - m_cc.setDbUid(dbUidField.getText()); - m_cc.setDbPwd(String.valueOf(dbPwdField.getPassword())); - m_cc.setBequeath(cbBequeath.isSelected()); - m_cc.setViaFirewall(cbFirewall.isSelected()); - m_cc.setFwHost(fwHostField.getText()); - m_cc.setFwPort(fwPortField.getText()); - // - if (src == bTestApps) - cmd_testApps(); - - // Database Selection Changed - else if (src == dbTypeField) - { - m_cc.setType((String)dbTypeField.getSelectedItem()); - dbPortField.setText(String.valueOf(m_cc.getDbPort())); - cbBequeath.setSelected(m_cc.isBequeath()); - fwPortField.setText(String.valueOf(m_cc.getFwPort())); - } - // - else if (src == bTestDB) - cmd_testDB(); - - // Name - if (src == nameField) - m_cc.setName(nameField.getText()); - - updateInfo(); - } // actionPerformed - - /** - * Update Fields from Connection - */ - private void updateInfo() - { - m_updating = true; - nameField.setText(m_cc.getName()); - appsHostField.setText(m_cc.getAppsHost()); - appsPortField.setText(String.valueOf(m_cc.getAppsPort())); - // - String cp = m_cc.getConnectionProfile(); - ValueNamePair cpPP = null; - for (int i = 0; i < CConnection.CONNECTIONProfiles.length; i++) - { - if (cp.equals(CConnection.CONNECTIONProfiles[i].getValue())) - { - cpPP = CConnection.CONNECTIONProfiles[i]; - break; - } - } - if (cpPP == null) // LAN - cpPP = CConnection.CONNECTIONProfiles[0]; - connectionProfileField.setSelectedItem(cpPP); - bTestApps.setIcon(getStatusIcon(m_cc.isAppsServerOK(false))); - // bTestApps.setToolTipText(m_cc.getRmiUri()); - - cbOverwrite.setVisible(m_cc.isAppsServerOK(false)); - boolean rw = cbOverwrite.isSelected() || !m_cc.isAppsServerOK(false); - // - dbTypeLabel.setReadWrite(rw); - dbTypeField.setReadWrite(rw); - dbTypeField.setSelectedItem(m_cc.getType()); - // - hostLabel.setReadWrite(rw); - hostField.setReadWrite(rw); - hostField.setText(m_cc.getDbHost()); - portLabel.setReadWrite(rw); - dbPortField.setReadWrite(rw); - dbPortField.setText(String.valueOf(m_cc.getDbPort())); - sidLabel.setReadWrite(rw); - sidField.setReadWrite(rw); - sidField.setText(m_cc.getDbName()); - // - dbUidLabel.setReadWrite(rw); - dbUidField.setReadWrite(rw); - dbUidField.setText(m_cc.getDbUid()); - dbPwdField.setEditable(rw); - dbPwdField.setText(m_cc.getDbPwd()); - // - cbBequeath.setReadWrite(rw); - cbBequeath.setEnabled(m_cc.isOracle()); - cbBequeath.setSelected(m_cc.isBequeath()); - // - boolean fwEnabled = rw && m_cc.isViaFirewall() && m_cc.isOracle(); - cbFirewall.setReadWrite(rw && m_cc.isOracle()); - cbFirewall.setSelected(m_cc.isViaFirewall()); - fwHostLabel.setReadWrite(fwEnabled); - fwHostField.setReadWrite(fwEnabled); - fwHostField.setText(m_cc.getFwHost()); - fwPortLabel.setReadWrite(fwEnabled); - fwPortField.setReadWrite(fwEnabled); - fwPortField.setText(String.valueOf(m_cc.getFwPort())); - // - bTestDB.setToolTipText(m_cc.getConnectionURL()); - bTestDB.setIcon(getStatusIcon(m_cc.isDatabaseOK())); - m_updating = false; - } // updateInfo - - /** - * Get Status Icon - ok or not - * @param ok ok - * @return Icon - */ - private Icon getStatusIcon (boolean ok) - { - if (ok) - return bOK.getIcon(); - else - return bCancel.getIcon(); - } // getStatusIcon - - /** - * Test Database connection - */ - private void cmd_testDB() - { - setBusy (true); - Exception e = m_cc.testDatabase(true); - if (e != null) - { - JOptionPane.showMessageDialog(this, - e, // message - res.getString("ConnectionError") + ": " + m_cc.getConnectionURL(), - JOptionPane.ERROR_MESSAGE); - } - setBusy (false); - } // cmd_testDB - - /** - * Test Application connection - */ - private void cmd_testApps() - { - setBusy (true); - Exception e = m_cc.testAppsServer(); - if (e != null) - { - JOptionPane.showMessageDialog(this, - e.getLocalizedMessage(), - res.getString("ServerNotActive") + " - " + m_cc.getAppsHost(), - JOptionPane.ERROR_MESSAGE); - } - setBusy (false); - } // cmd_testApps - -} // CConnectionDialog + appsHostLabel.setVisible(false); + appsHostField.setVisible(false); + appsPortLabel.setVisible(false); + appsPortField.setVisible(false); + bTestApps.setVisible(false); + connectionProfileLabel.setVisible(false); + connectionProfileField.setVisible(false); + } + else // Client + cbBequeath.setVisible(false); + } // jbInit + + /** + * Set Busy - lock UI + * @param busy busy + */ + private void setBusy (boolean busy) + { + if (busy) + this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + else + this.setCursor(Cursor.getDefaultCursor()); + m_updating = busy; + } // setBusy + + /** + * Set Connection + * @param cc - if null use current connection + */ + public void setConnection (CConnection cc) + { + m_cc = cc; + if (m_cc == null) + { + m_cc = CConnection.get(); + m_cc.setName(); + } + // Should copy values + m_ccResult = m_cc; + // + String type = m_cc.getType(); + if (type == null || type.length() == 0) + dbTypeField.setSelectedItem(null); + else + m_cc.setType(m_cc.getType()); // sets defaults + updateInfo(); + } // setConnection + + /** + * Get Connection + * @return CConnection + */ + public CConnection getConnection() + { + return m_ccResult; + } // getConnection; + + /** + * ActionListener + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + if (m_updating) + return; + Object src = e.getSource(); + + if (src == bOK) + { + m_cc.setName(); + m_ccResult = m_cc; + dispose(); + return; + } + else if (src == bCancel) + { + m_cc.setName(); + dispose(); + return; + } + else if (src == connectionProfileField) + { + ValueNamePair pp = (ValueNamePair)connectionProfileField.getSelectedItem(); + m_cc.setConnectionProfile(pp.getValue()); + if (m_cc.isRMIoverHTTP()) + appsPortField.setText(APPS_PORT_HTTP); + else + appsPortField.setText(APPS_PORT_JNP); + return; + } + else if (src == dbTypeField) + { + if (dbTypeField.getSelectedItem() == null) + return; + } + + + if (Ini.isClient()) + { + m_cc.setAppsHost(appsHostField.getText()); + m_cc.setAppsPort(appsPortField.getText()); + } + else + m_cc.setAppsHost("localhost"); + // + ValueNamePair pp = (ValueNamePair)connectionProfileField.getSelectedItem(); + m_cc.setConnectionProfile(pp.getValue()); + // + m_cc.setType((String)dbTypeField.getSelectedItem()); + m_cc.setDbHost(hostField.getText()); + m_cc.setDbPort(dbPortField.getText()); + m_cc.setDbName(sidField.getText()); + m_cc.setDbUid(dbUidField.getText()); + m_cc.setDbPwd(String.valueOf(dbPwdField.getPassword())); + m_cc.setBequeath(cbBequeath.isSelected()); + m_cc.setViaFirewall(cbFirewall.isSelected()); + m_cc.setFwHost(fwHostField.getText()); + m_cc.setFwPort(fwPortField.getText()); + // + if (src == bTestApps) + cmd_testApps(); + + // Database Selection Changed + else if (src == dbTypeField) + { + m_cc.setType((String)dbTypeField.getSelectedItem()); + dbPortField.setText(String.valueOf(m_cc.getDbPort())); + cbBequeath.setSelected(m_cc.isBequeath()); + fwPortField.setText(String.valueOf(m_cc.getFwPort())); + } + // + else if (src == bTestDB) + cmd_testDB(); + + // Name + if (src == nameField) + m_cc.setName(nameField.getText()); + + updateInfo(); + } // actionPerformed + + /** + * Update Fields from Connection + */ + private void updateInfo() + { + m_updating = true; + nameField.setText(m_cc.getName()); + appsHostField.setText(m_cc.getAppsHost()); + appsPortField.setText(String.valueOf(m_cc.getAppsPort())); + // + String cp = m_cc.getConnectionProfile(); + ValueNamePair cpPP = null; + for (int i = 0; i < CConnection.CONNECTIONProfiles.length; i++) + { + if (cp.equals(CConnection.CONNECTIONProfiles[i].getValue())) + { + cpPP = CConnection.CONNECTIONProfiles[i]; + break; + } + } + if (cpPP == null) // LAN + cpPP = CConnection.CONNECTIONProfiles[0]; + connectionProfileField.setSelectedItem(cpPP); + bTestApps.setIcon(getStatusIcon(m_cc.isAppsServerOK(false))); + // bTestApps.setToolTipText(m_cc.getRmiUri()); + + cbOverwrite.setVisible(m_cc.isAppsServerOK(false)); + boolean rw = cbOverwrite.isSelected() || !m_cc.isAppsServerOK(false); + // + dbTypeLabel.setReadWrite(rw); + dbTypeField.setReadWrite(rw); + dbTypeField.setSelectedItem(m_cc.getType()); + // + hostLabel.setReadWrite(rw); + hostField.setReadWrite(rw); + hostField.setText(m_cc.getDbHost()); + portLabel.setReadWrite(rw); + dbPortField.setReadWrite(rw); + dbPortField.setText(String.valueOf(m_cc.getDbPort())); + sidLabel.setReadWrite(rw); + sidField.setReadWrite(rw); + sidField.setText(m_cc.getDbName()); + // + dbUidLabel.setReadWrite(rw); + dbUidField.setReadWrite(rw); + dbUidField.setText(m_cc.getDbUid()); + dbPwdField.setEditable(rw); + dbPwdField.setText(m_cc.getDbPwd()); + // + cbBequeath.setReadWrite(rw); + cbBequeath.setEnabled(m_cc.isOracle()); + cbBequeath.setSelected(m_cc.isBequeath()); + // + boolean fwEnabled = rw && m_cc.isViaFirewall() && m_cc.isOracle(); + cbFirewall.setReadWrite(rw && m_cc.isOracle()); + cbFirewall.setSelected(m_cc.isViaFirewall()); + fwHostLabel.setReadWrite(fwEnabled); + fwHostField.setReadWrite(fwEnabled); + fwHostField.setText(m_cc.getFwHost()); + fwPortLabel.setReadWrite(fwEnabled); + fwPortField.setReadWrite(fwEnabled); + fwPortField.setText(String.valueOf(m_cc.getFwPort())); + // + bTestDB.setToolTipText(m_cc.getConnectionURL()); + bTestDB.setIcon(getStatusIcon(m_cc.isDatabaseOK())); + m_updating = false; + } // updateInfo + + /** + * Get Status Icon - ok or not + * @param ok ok + * @return Icon + */ + private Icon getStatusIcon (boolean ok) + { + if (ok) + return bOK.getIcon(); + else + return bCancel.getIcon(); + } // getStatusIcon + + /** + * Test Database connection + */ + private void cmd_testDB() + { + setBusy (true); + Exception e = m_cc.testDatabase(true); + if (e != null) + { + JOptionPane.showMessageDialog(this, + e, // message + res.getString("ConnectionError") + ": " + m_cc.getConnectionURL(), + JOptionPane.ERROR_MESSAGE); + } + setBusy (false); + } // cmd_testDB + + /** + * Test Application connection + */ + private void cmd_testApps() + { + setBusy (true); + Exception e = m_cc.testAppsServer(); + if (e != null) + { + JOptionPane.showMessageDialog(this, + e.getLocalizedMessage(), + res.getString("ServerNotActive") + " - " + m_cc.getAppsHost(), + JOptionPane.ERROR_MESSAGE); + } + setBusy (false); + } // cmd_testApps + +} // CConnectionDialog diff --git a/dbPort/src/org/compiere/db/DB_Fyracle.java b/dbPort/src/org/compiere/db/DB_Fyracle.java index 472b2cf5d2..d274553693 100644 --- a/dbPort/src/org/compiere/db/DB_Fyracle.java +++ b/dbPort/src/org/compiere/db/DB_Fyracle.java @@ -624,4 +624,10 @@ class DataSourceImpl implements DataSource { return impl.toString(); } + public boolean isWrapperFor(java.lang.Class iface) throws java.sql.SQLException + { + return false; + } + + public T unwrap(java.lang.Class iface) throws java.sql.SQLException{return null;} } \ No newline at end of file diff --git a/dbPort/src/org/compiere/db/DB_PostgreSQL.java b/dbPort/src/org/compiere/db/DB_PostgreSQL.java index 4c70c0ae36..b2943f899b 100755 --- a/dbPort/src/org/compiere/db/DB_PostgreSQL.java +++ b/dbPort/src/org/compiere/db/DB_PostgreSQL.java @@ -1,16 +1,17 @@ /****************************************************************************** - * The contents of this file are subject to the Compiere License Version 1.1 - * ("License"); You may not use this file except in compliance with the License - * You may obtain a copy of the License at http://www.compiere.org/license.html - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - * the specific language governing rights and limitations under the License. - * The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial - * Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke - * are Copyright (C) 1999-2005 Jorg Janke. - * All parts are Copyright (C) 1999-2005 ComPiere, Inc. All Rights Reserved. - * Portions created by Victor Perez are Copyright (C) 1999-2005 e-Evolution,S.C - * Contributor(s): Victor Perez + * Product: Adempiere ERP & CRM Smart Business Solution + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. + * This program is free software; you can redistribute it and/or modify it + * under the terms version 2 of the GNU General Public License as published + * by the Free Software Foundation. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org *****************************************************************************/ package org.compiere.db; diff --git a/dbPort/src/org/compiere/db/DerbyServer.java b/dbPort/src/org/compiere/db/DerbyServer.java new file mode 100755 index 0000000000..5cafc12d83 --- /dev/null +++ b/dbPort/src/org/compiere/db/DerbyServer.java @@ -0,0 +1,426 @@ +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. + * This program is free software; you can redistribute it and/or modify it + * under the terms version 2 of the GNU General Public License as published + * by the Free Software Foundation. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org + *****************************************************************************/ +package org.compiere.db; + +import java.io.*; +import java.net.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; + +import org.apache.derby.drda.*; +import org.apache.derby.impl.drda.*; +import org.apache.derby.jdbc.*; +import org.compiere.util.*; + +/** + * Derby DB Server + * + * @author Jorg Janke + * @version $Id: DerbyServer.java,v 1.5 2006/07/30 00:55:13 jjanke Exp $ + */ +public class DerbyServer extends Thread +{ + /** + * Get/Create Derby Server + * @return server + */ + public static synchronized DerbyServer get() + { + if (s_server == null) + { + InetAddress address = null; + int port = PORT; + try + { + address = InetAddress.getByAddress(new byte[] {0,0,0,0}); // all ports + s_server = new DerbyServer(address, port); + s_server.start(); + } + catch (Exception e) + { + String msg = null; + if (address == null) + msg = ""; + else + msg = address.toString(); + msg += ":" + port; + log.log(Level.SEVERE, msg, e); + } + } + return s_server; + } // get + + /** + * Start Server + * @return true if started + */ + public static boolean startServer() + { + if (get() == null) + return false; + return s_server.isServerStarted(); + } // startServer + + /** + * Stop Server + * @return true if stopped / not running + */ + public static boolean stopServer() + { + if (s_server == null) + return true; + try + { + s_server.shutdown(); + s_server = null; + return true; + } + catch (Exception e) + { + log.log(Level.SEVERE, e.getMessage(), e); + } + return false; + } // stopServer + + /** Singleton */ + private static DerbyServer s_server = null; + /** Default Port 1527 */ + public static final int PORT = NetworkServerControl.DEFAULT_PORTNUMBER; + + + /** Logger */ + private static CLogger log = CLogger.getCLogger (DerbyServer.class); + + + /************************************************************************** + * Derby Server + * @param address server address + * @param port port + * @throws Exception + */ + private DerbyServer (InetAddress address, int port) throws Exception + { + super("CompiereDerby"); + if (s_impl != null) + throw new IllegalStateException("Derby Server already started"); + // + String compiereHome = Ini.getAdempiereHome(); + s_derbyHome = compiereHome + File.separator + "derby"; + File dir = new File(s_derbyHome); + if (!dir.exists()) + dir.mkdir(); + // + System.setProperty("derby.system.home", s_derbyHome); + System.setProperty("derby.drda.traceDirectory", s_derbyHome); + // + String logIt = "false"; + if (CLogMgt.isLevelFiner()) + logIt = "true"; + System.setProperty("derby.drda.logConnections", logIt); + System.setProperty("derby.drda.traceAll", logIt); + // + System.setProperty("derby.connection.requireAuthentication", "true"); + System.setProperty("derby.authentication.provider", "BUILTIN"); + addUser("compiere", "compiere"); + // + s_address = address; + s_port = port; + s_impl = new NetworkServerControlImpl (s_address, s_port); + } // DerbyServer + + /** Singleton */ + private static NetworkServerControlImpl s_impl = null; + /** Derby Home */ + private static String s_derbyHome = ""; + /** Address */ + private static InetAddress s_address = null; + /** Port */ + private static int s_port = 0; + + /** + * Run + */ + public void run() + { + log.info("starting ..."); + PrintWriter consoleWriter = new PrintWriter(System.out, true); // flush + try + { + s_impl.blockingStart(consoleWriter); + } + catch (Exception e) + { + log.log(Level.SEVERE, e.getMessage(), e); + s_impl = null; + } + log.info("done"); + } // run + + /** + * Interrupt - shutdown + */ + public void interrupt () + { + super.interrupt (); + shutdown(); + } // interrupt + + /** + * Is Server Started + * @return server started + */ + public boolean isServerStarted() + { + if (s_impl == null) + return false; + try + { + s_impl.ping(); + } + catch (Exception e) + { + return false; + } + return true; + } // isServerStarted + + /** + * Shutdown + * @return true if shut down + */ + public boolean shutdown() + { + if (s_impl != null) + { + try + { + log.info("shutting down ..."); + s_impl.shutdown(); + log.info("shutdown"); + return true; + } + catch (Exception e) + { + return false; + } + } + return true; + } // shutdown + + + /** + * String Representation + * @return info + */ + public String toString () + { + StringBuffer sb = new StringBuffer ("DerbyServer["); + sb.append (s_derbyHome) + .append(";").append(s_address) + .append(":").append(s_port) + .append(";Alive=").append(isAlive()) + .append(";Started=").append(isServerStarted()); + sb.append ("]"); + return sb.toString (); + } // toString + + /** + * Get Derby Home + * @return home + */ + public String getDerbyHome() + { + return s_derbyHome; + } // getDerbyHome + + /** + * Get Runtime Info + * @return info + */ + public String getRuntimeInfo() + { + try + { + if (s_impl != null) + return s_impl.runtimeInfo(); + } + catch (Exception e) + { + return e.getMessage(); + } + return ""; + } // getRuntimeInfo + + + /** + * Get System Info + * @return info + */ + public String getSysInfo() + { + try + { + if (s_impl != null) + return s_impl.sysinfo(); + } + catch (Exception e) + { + return e.getMessage(); + } + return ""; + } // getSysInfo + + /** + * Get current Network server properties. + * @return Properties object containing Network server properties + * @exception Exception throws an exception if an error occurs + */ + public Properties getCurrentProperties() throws Exception + { + return s_impl.getCurrentProperties(); + } // getCurrentProperties + + /** + * Add User + * @param dbUid user id + * @param dbPwd user password + */ + public void addUser (String dbUid, String dbPwd) + { + System.setProperty("derby.user." + dbUid, dbPwd); + Properties dp = new Properties(); + + } // addUser + + /** + * Create Database + * @param dbName database name + * @param dbUid user id + * @param dbPwd user password + * @return true if exists or created + */ + public boolean createDatabase (String dbName, + String dbUid, String dbPwd) + { + addUser (dbUid, dbPwd); + // Embedded Driver + try + { + EmbeddedDriver driver = new EmbeddedDriver(); + DriverManager.registerDriver (driver); + } + catch (Exception e) + { + log.log(Level.SEVERE, "DriverIssue", e); + return false; + } + // Connection + String dbUrl = "jdbc:derby:" + dbName; + Connection conn = null; + try + { + String urlAttributes = ";create=true" + // + "dataEncryption=true;bootPassword=cLo4u922sc23aPe" + // + ";territory=en_US" + + ";user=" + dbUid + + ";password=" + dbPwd; + conn = DriverManager.getConnection(dbUrl + urlAttributes); + log.info("Created DB: " + dbName); + // new JDBCInfo(conn); + } + catch (Exception e) + { + log.severe(e.getMessage()); + } + try + { + if (conn != null) + conn.close(); + conn = null; + } + catch (Exception e) + { + } + + // Connection test + try + { + conn = DriverManager.getConnection(dbUrl, dbUid, dbPwd); + log.info("Connected to DB: " + dbName); + // new JDBCInfo(conn); + } + catch (Exception e) + { + log.severe(e.getMessage()); + conn = null; + return false; + } + // Connection test + Statement stmt = null; + try + { + stmt = conn.createStatement(); + stmt.executeUpdate("CREATE TABLE XX (XX VARCHAR(5))"); + stmt.executeUpdate("INSERT INTO XX (XX) VALUES ('A')"); + } + catch (Exception e) + { + log.info(e.getMessage()); + } + try + { + if (stmt != null) + stmt.close(); + if (conn != null) + conn.close(); + conn = null; + } + catch (Exception e) + { + } + + return true; + } // createDatabase + + /************************************************************************** + * Start Derby Server + * @param args + */ + public static void main (String[] args) + { + CLogMgt.setLevel(Level.FINE); + DerbyServer server = DerbyServer.get(); + startServer(); + server.createDatabase("compiere", "compiere", "compiere"); + // log.info(server.getRuntimeInfo()); + // log.info(server.getSysInfo()); + + try + { + // log.info(server.getCurrentProperties().toString()); + // + log.info("Sleeping " + get()); + Thread.sleep(5000); + } + catch (Exception e) + { + + } + // stopServer(); + } // main + +} // DerbyServer diff --git a/dbPort/src/org/compiere/db/LDAP.java b/dbPort/src/org/compiere/db/LDAP.java index 2d7d159709..eaff780619 100644 --- a/dbPort/src/org/compiere/db/LDAP.java +++ b/dbPort/src/org/compiere/db/LDAP.java @@ -1,200 +1,200 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.db; - -import java.util.*; -import java.util.logging.*; - -import javax.naming.*; -import javax.naming.ldap.*; -import javax.naming.directory.*; - -import org.compiere.util.*; - - -/** - * LDAP Management Interface - * - * @author Jorg Janke - * @version $Id: LDAP.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $ - */ -public class LDAP -{ - /** - * Validate User - * @param ldapURL provider url - e.g. ldap://dc.adempiere.org - * @param domain domain name = e.g. adempiere.org - * @param userName user name - e.g. jjanke - * @param password password - * @return true if validated with ldap - */ - public static boolean validate (String ldapURL, String domain, String userName, String password) - { - Hashtable env = new Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); - // ldap://dc.adempiere.org - env.put(Context.PROVIDER_URL, ldapURL); - env.put(Context.SECURITY_AUTHENTICATION, "simple"); - // jjanke@adempiere.org - StringBuffer principal = new StringBuffer (userName) - .append("@").append(domain); - env.put(Context.SECURITY_PRINCIPAL, principal.toString()); - env.put(Context.SECURITY_CREDENTIALS, password); - // - try - { - // Create the initial context - InitialLdapContext ctx = new InitialLdapContext(env, null); - // DirContext ctx = new InitialDirContext(env); - - // Test - Get the attributes - Attributes answer = ctx.getAttributes(""); - - // Print the answer - // dump (answer); - } - catch (AuthenticationException e) - { - log.info("Error: " + principal + " - " + e.getLocalizedMessage()); - return false; - } - catch (Exception e) - { - log.log (Level.SEVERE, ldapURL + " - " + principal, e); - return false; - } - log.info("OK: " + principal); - return true; - } // validate - - /** Logger */ - private static CLogger log = CLogger.getCLogger (LDAP.class); - - - /** - * Test NT - * @throws LoginException - * - private static void testNT () throws LoginException - { - try - { - System.out.println ("NT system ----------------------------"); - NTSystem ntsystem = new NTSystem (); - System.out.println (ntsystem); - System.out.println (ntsystem.getDomain ()); - System.out.println (ntsystem.getDomainSID ()); - System.out.println (ntsystem.getName ()); - System.out.println (ntsystem.getUserSID ()); - System.out.println ("NT login ----------------------------"); - NTLoginModule ntlogin = new NTLoginModule (); - System.out.println (ntlogin); - Map map = new HashMap(); - map.put ("debug", "true"); - ntlogin.initialize (null, null, null, map); - System.out.println (ntlogin.login ()); - } - catch (LoginException le) - { - System.err.println ("Authentication attempt failed" + le); - } - } // testNT - - - /** - * testKerberos - * @throws LoginException - * - private static void testKerberos () - throws LoginException - { - System.out.println ("Krb login ----------------------------"); - Map map = new HashMap(); - // map.put("debug", "true"); - // map.put("debugNative", "true"); - Krb5LoginModule klogin = new Krb5LoginModule (); - System.out.println (klogin); - map.put ("principal", "username@adempiere.org"); - map.put ("credential", "pass"); - klogin.initialize (null, null, null, map); - System.out.println (klogin.login ()); - /*********************************************************************** - * ** No krb5.ini file found in entire system Debug is true storeKey - * false useTicketCache false useKeyTab false doNotPrompt false - * ticketCache is null KeyTab is null refreshKrb5Config is false - * principal is jjanke tryFirstPass is false useFirstPass is false - * storePass is false clearPass is false [Krb5LoginModule] - * authentication failed Could not load configuration file - * c:\winnt\krb5.ini (The system cannot find the file specified) - * javax.security.auth.login.LoginException: Could not load - * configuration file c:\winnt\krb5.ini (The system cannot find the file - * specified) - * - } // testKerbos - /**/ - - /** - * Print Attributes to System.out - * @param attrs - */ - private static void dump (Attributes attrs) - { - if (attrs == null) - { - System.out.println ("No attributes"); - } - else - { - /* Print each attribute */ - try - { - for (NamingEnumeration ae = attrs.getAll (); ae.hasMore ();) - { - Attribute attr = (Attribute) ae.next (); - System.out.println ("attribute: " + attr.getID ()); - /* print each value */ - for (NamingEnumeration e = attr.getAll(); - e.hasMore (); - System.out.println (" value: " + e.next())) - ; - } - } - catch (NamingException e) - { - e.printStackTrace (); - } - } - } // dump - - /** - * Test - * @param args ignored - */ - public static void main (String[] args) - { - try - { - validate("ldap://dc.adempiere.org", "adempiere.org", "red1", "ikeepforgetting"); - } - catch (Exception e) - { - e.printStackTrace(); - } - } // main - -} // LDAP - +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. + * This program is free software; you can redistribute it and/or modify it + * under the terms version 2 of the GNU General Public License as published + * by the Free Software Foundation. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org + *****************************************************************************/ +package org.compiere.db; + +import java.util.*; +import java.util.logging.*; + +import javax.naming.*; +import javax.naming.ldap.*; +import javax.naming.directory.*; + +import org.compiere.util.*; + + +/** + * LDAP Management Interface + * + * @author Jorg Janke + * @version $Id: LDAP.java,v 1.2 2006/07/30 00:55:13 jjanke Exp $ + */ +public class LDAP +{ + /** + * Validate User + * @param ldapURL provider url - e.g. ldap://dc.compiere.org + * @param domain domain name = e.g. compiere.org + * @param userName user name - e.g. jjanke + * @param password password + * @return true if validated with ldap + */ + public static boolean validate (String ldapURL, String domain, String userName, String password) + { + Hashtable env = new Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + // ldap://dc.compiere.org + env.put(Context.PROVIDER_URL, ldapURL); + env.put(Context.SECURITY_AUTHENTICATION, "simple"); + // jjanke@compiere.org + StringBuffer principal = new StringBuffer (userName) + .append("@").append(domain); + env.put(Context.SECURITY_PRINCIPAL, principal.toString()); + env.put(Context.SECURITY_CREDENTIALS, password); + // + try + { + // Create the initial context + InitialLdapContext ctx = new InitialLdapContext(env, null); + // DirContext ctx = new InitialDirContext(env); + + // Test - Get the attributes + Attributes answer = ctx.getAttributes(""); + + // Print the answer + if (false) + dump (answer); + } + catch (AuthenticationException e) + { + log.info("Error: " + principal + " - " + e.getLocalizedMessage()); + return false; + } + catch (Exception e) + { + log.log (Level.SEVERE, ldapURL + " - " + principal, e); + return false; + } + log.info("OK: " + principal); + return true; + } // validate + + /** Logger */ + private static CLogger log = CLogger.getCLogger (LDAP.class); + + + /** + * Test NT + * @throws LoginException + * + private static void testNT () throws LoginException + { + try + { + System.out.println ("NT system ----------------------------"); + NTSystem ntsystem = new NTSystem (); + System.out.println (ntsystem); + System.out.println (ntsystem.getDomain ()); + System.out.println (ntsystem.getDomainSID ()); + System.out.println (ntsystem.getName ()); + System.out.println (ntsystem.getUserSID ()); + System.out.println ("NT login ----------------------------"); + NTLoginModule ntlogin = new NTLoginModule (); + System.out.println (ntlogin); + Map map = new HashMap(); + map.put ("debug", "true"); + ntlogin.initialize (null, null, null, map); + System.out.println (ntlogin.login ()); + } + catch (LoginException le) + { + System.err.println ("Authentication attempt failed" + le); + } + } // testNT + + + /** + * testKerberos + * @throws LoginException + * + private static void testKerberos () + throws LoginException + { + System.out.println ("Krb login ----------------------------"); + Map map = new HashMap(); + // map.put("debug", "true"); + // map.put("debugNative", "true"); + Krb5LoginModule klogin = new Krb5LoginModule (); + System.out.println (klogin); + map.put ("principal", "username@compiere.org"); + map.put ("credential", "pass"); + klogin.initialize (null, null, null, map); + System.out.println (klogin.login ()); + /*********************************************************************** + * ** No krb5.ini file found in entire system Debug is true storeKey + * false useTicketCache false useKeyTab false doNotPrompt false + * ticketCache is null KeyTab is null refreshKrb5Config is false + * principal is jjanke tryFirstPass is false useFirstPass is false + * storePass is false clearPass is false [Krb5LoginModule] + * authentication failed Could not load configuration file + * c:\winnt\krb5.ini (The system cannot find the file specified) + * javax.security.auth.login.LoginException: Could not load + * configuration file c:\winnt\krb5.ini (The system cannot find the file + * specified) + * + } // testKerbos + /**/ + + /** + * Print Attributes to System.out + * @param attrs + */ + private static void dump (Attributes attrs) + { + if (attrs == null) + { + System.out.println ("No attributes"); + } + else + { + /* Print each attribute */ + try + { + for (NamingEnumeration ae = attrs.getAll (); ae.hasMore ();) + { + Attribute attr = (Attribute) ae.next (); + System.out.println ("attribute: " + attr.getID ()); + /* print each value */ + for (NamingEnumeration e = attr.getAll(); + e.hasMore (); + System.out.println (" value: " + e.next())) + ; + } + } + catch (NamingException e) + { + e.printStackTrace (); + } + } + } // dump + + /** + * Test + * @param args ignored + */ + public static void main (String[] args) + { + try + { + validate("ldap://dc.compiere.org", "compiere.org", "jjanke", "ikeepforgetting"); + } + catch (Exception e) + { + e.printStackTrace(); + } + } // main + +} // LDAP + diff --git a/dbPort/src/org/compiere/dbPort/JdbcTestPG.java b/dbPort/src/org/compiere/dbPort/JdbcTestPG.java index 7cf72998e2..c1cb167481 100755 --- a/dbPort/src/org/compiere/dbPort/JdbcTestPG.java +++ b/dbPort/src/org/compiere/dbPort/JdbcTestPG.java @@ -1,15 +1,17 @@ /****************************************************************************** - * The contents of this file are subject to the Compiere License Version 1.1 - * ("License"); You may not use this file except in compliance with the License - * You may obtain a copy of the License at http://www.compiere.org/license.html - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - * the specific language governing rights and limitations under the License. - * The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial - * Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke - * are Copyright (C) 1999-2005 Jorg Janke. - * All parts are Copyright (C) 1999-2005 ComPiere, Inc. All Rights Reserved. - * Contributor(s): ______________________________________. + * Product: Adempiere ERP & CRM Smart Business Solution + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. + * This program is free software; you can redistribute it and/or modify it + * under the terms version 2 of the GNU General Public License as published + * by the Free Software Foundation. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org *****************************************************************************/ package org.compiere.dbPort; diff --git a/dbPort/src/org/compiere/dbPort/PostgresConvertTest.java b/dbPort/src/org/compiere/dbPort/PostgresConvertTest.java index 1fecadc2fd..070535ab06 100755 --- a/dbPort/src/org/compiere/dbPort/PostgresConvertTest.java +++ b/dbPort/src/org/compiere/dbPort/PostgresConvertTest.java @@ -1,15 +1,17 @@ /****************************************************************************** - * The contents of this file are subject to the Compiere License Version 1.1 - * ("License"); You may not use this file except in compliance with the License - * You may obtain a copy of the License at http://www.compiere.org/license.html - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - * the specific language governing rights and limitations under the License. - * The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial - * Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke - * are Copyright (C) 1999-2005 Jorg Janke. - * All parts are Copyright (C) 1999-2005 ComPiere, Inc. All Rights Reserved. - * Contributor(s): ______________________________________. + * Product: Adempiere ERP & CRM Smart Business Solution + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. + * This program is free software; you can redistribute it and/or modify it + * under the terms version 2 of the GNU General Public License as published + * by the Free Software Foundation. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org *****************************************************************************/ package org.compiere.dbPort; diff --git a/dbPort/src/org/compiere/model/AccessSqlParserTest.java b/dbPort/src/org/compiere/model/AccessSqlParserTest.java index 1dd2e5eb36..4f2d2cc5a5 100644 --- a/dbPort/src/org/compiere/model/AccessSqlParserTest.java +++ b/dbPort/src/org/compiere/model/AccessSqlParserTest.java @@ -3,58 +3,58 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.model; - -import junit.framework.*; -import org.compiere.*; - -/** - * AccessSqlParserTest tests the class - * AccessSqlParser - * - * @author Jorg Janke - * @version $Id: AccessSqlParserTest.java,v 1.2 2006/07/30 00:58:04 jjanke Exp $ - */ -public class AccessSqlParserTest extends TestCase -{ - /** - * Construct new test instance - * - * @param name the test name - */ - public AccessSqlParserTest(String name) - { - super(name); - } - - /** - * Launch the test. - * - * @param args String[] - */ - public static void main(String[] args) - { - junit.swingui.TestRunner.run(AccessSqlParserTest.class); - } - - /** - * Perform pre-test initialization - * - * @throws Exception - * - * @see TestCase#setUp() - */ + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.model; + +import junit.framework.*; +import org.compiere.*; + +/** + * AccessSqlParserTest tests the class + * AccessSqlParser + * + * @author Jorg Janke + * @version $Id: AccessSqlParserTest.java,v 1.2 2006/07/30 00:58:04 jjanke Exp $ + */ +public class AccessSqlParserTest extends TestCase +{ + /** + * Construct new test instance + * + * @param name the test name + */ + public AccessSqlParserTest(String name) + { + super(name); + } + + /** + * Launch the test. + * + * @param args String[] + */ + public static void main(String[] args) + { + junit.swingui.TestRunner.run(AccessSqlParserTest.class); + } + + /** + * Perform pre-test initialization + * + * @throws Exception + * + * @see TestCase#setUp() + */ protected void setUp() throws Exception { super.setUp(); @@ -62,170 +62,170 @@ public class AccessSqlParserTest extends TestCase } /** - * Run the oneTable test - */ - public void testOneTable() - { - String sql = "SELECT AD_Table_ID, TableName FROM AD_Table WHERE IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table|0]", fixture.toString()); - } - - /** - * Run the oneTableSyn test - */ - public void testOneTableSyn() - { - String sql = "SELECT t.AD_Table_ID, t.TableName FROM AD_Table t WHERE t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table=t|0]", fixture.toString()); - } - - /** - * Run the oneTableSyn test - */ - public void testOneTableSynAS() - { - String sql = "SELECT t.AD_Table_ID, t.TableName FROM AD_Table AS t WHERE t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table=t|0]", fixture.toString()); - } - - /** - * Run the twoTable test - */ - public void testTwoTable() - { - String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName FROM AD_Table t, AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID AND t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); - } - - /** - * Run the twoTableSyn test - */ - public void testTwoTableSyn() - { - String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName FROM AD_Table as t, AD_Column AS c WHERE t.AD_Table_ID=c.AD_Table_ID AND t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); - } - - /** - * Run the joinInner test - */ - public void testJoinInner() - { - String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName " - + "FROM AD_Table t INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) WHERE t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); - } - - /** - * Run the joinOuter test - */ - public void testJoinOuter() - { - String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName " - + "FROM AD_Table t LEFT OUTER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) WHERE t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); - } - - /** - * Run the exists test - */ - public void testExists() - { - String sql = "SELECT AD_Table.AD_Table_ID, AD_Table.TableName " - + "FROM AD_Table " - + "WHERE EXISTS (SELECT * FROM AD_Column c WHERE AD_Table.AD_Table_ID=c.AD_Table_ID)"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Column=c|AD_Table|1]", fixture.toString()); - } - - /** - * Run the exists test with syn - */ - public void testExistsSyn() - { - String sql = "SELECT t.AD_Table_ID, t.TableName " - + "FROM AD_Table t " - + "WHERE EXISTS (SELECT * FROM AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID)"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Column=c|AD_Table=t|1]", fixture.toString()); - } - - /** - * Run the embeddedSelect test - */ - public void testEmbeddedSelect() - { - String sql = "SELECT t.AD_Table_ID, t.TableName," - + "(SELECT COUNT(c.ColumnName) FROM AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID) " - + "FROM AD_Table t WHERE t.IsActive='Y'"; - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Column=c|AD_Table=t|1]", fixture.toString()); - } - - /** - * Run the embeddedFrom test - */ - public void testEmbeddedFrom() - { - String sql = "SELECT t.AD_Table_ID, t.TableName, cc.CCount " - + "FROM AD_Table t," - + "(SELECT COUNT(ColumnName) AS CCount FROM AD_Column) cc " - + "WHERE t.IsActive='Y'"; - - AccessSqlParser fixture = new AccessSqlParser(sql); - assertEquals("AccessSqlParser[AD_Column|AD_Table=t,(##)=cc|1]", fixture.toString()); - } - - /** - * Run the Product & Instance Attribute Query + * Run the oneTable test + */ + public void testOneTable() + { + String sql = "SELECT AD_Table_ID, TableName FROM AD_Table WHERE IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table|0]", fixture.toString()); + } + + /** + * Run the oneTableSyn test + */ + public void testOneTableSyn() + { + String sql = "SELECT t.AD_Table_ID, t.TableName FROM AD_Table t WHERE t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table=t|0]", fixture.toString()); + } + + /** + * Run the oneTableSyn test + */ + public void testOneTableSynAS() + { + String sql = "SELECT t.AD_Table_ID, t.TableName FROM AD_Table AS t WHERE t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table=t|0]", fixture.toString()); + } + + /** + * Run the twoTable test + */ + public void testTwoTable() + { + String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName FROM AD_Table t, AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID AND t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); + } + + /** + * Run the twoTableSyn test + */ + public void testTwoTableSyn() + { + String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName FROM AD_Table as t, AD_Column AS c WHERE t.AD_Table_ID=c.AD_Table_ID AND t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); + } + + /** + * Run the joinInner test + */ + public void testJoinInner() + { + String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName " + + "FROM AD_Table t INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) WHERE t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); + } + + /** + * Run the joinOuter test + */ + public void testJoinOuter() + { + String sql = "SELECT t.AD_Table_ID, t.TableName, c.AD_Column_ID, c.ColumnName " + + "FROM AD_Table t LEFT OUTER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) WHERE t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Table=t,AD_Column=c|0]", fixture.toString()); + } + + /** + * Run the exists test + */ + public void testExists() + { + String sql = "SELECT AD_Table.AD_Table_ID, AD_Table.TableName " + + "FROM AD_Table " + + "WHERE EXISTS (SELECT * FROM AD_Column c WHERE AD_Table.AD_Table_ID=c.AD_Table_ID)"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Column=c|AD_Table|1]", fixture.toString()); + } + + /** + * Run the exists test with syn + */ + public void testExistsSyn() + { + String sql = "SELECT t.AD_Table_ID, t.TableName " + + "FROM AD_Table t " + + "WHERE EXISTS (SELECT * FROM AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID)"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Column=c|AD_Table=t|1]", fixture.toString()); + } + + /** + * Run the embeddedSelect test + */ + public void testEmbeddedSelect() + { + String sql = "SELECT t.AD_Table_ID, t.TableName," + + "(SELECT COUNT(c.ColumnName) FROM AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID) " + + "FROM AD_Table t WHERE t.IsActive='Y'"; + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Column=c|AD_Table=t|1]", fixture.toString()); + } + + /** + * Run the embeddedFrom test + */ + public void testEmbeddedFrom() + { + String sql = "SELECT t.AD_Table_ID, t.TableName, cc.CCount " + + "FROM AD_Table t," + + "(SELECT COUNT(ColumnName) AS CCount FROM AD_Column) cc " + + "WHERE t.IsActive='Y'"; + + AccessSqlParser fixture = new AccessSqlParser(sql); + assertEquals("AccessSqlParser[AD_Column|AD_Table=t,(##)=cc|1]", fixture.toString()); + } + + /** + * Run the Product & Instance Attribute Query */ public void testProductInstanceAttributeQuery() { - String sql = "SELECT p.M_Product_ID, p.Discontinued, p.Value, p.Name, BOM_Qty_Available(p.M_Product_ID,?) AS QtyAvailable, bomQtyList(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceList, bomQtyStd(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceStd, BOM_Qty_OnHand(p.M_Product_ID,?) AS QtyOnHand, BOM_Qty_Reserved(p.M_Product_ID,?) AS QtyReserved, BOM_Qty_Ordered(p.M_Product_ID,?) AS QtyOrdered, bomQtyStd(p.M_Product_ID, pr.M_PriceList_Version_ID)-bomQtyLimit(p.M_Product_ID, pr.M_PriceList_Version_ID) AS Margin, bomQtyLimit(p.M_Product_ID, pr.M_PriceList_Version_ID) AS PriceLimit, pa.IsInstanceAttribute FROM M_Product p INNER JOIN M_ProductPrice pr ON (p.M_Product_ID=pr.M_Product_ID) LEFT OUTER JOIN M_AttributeSet pa ON (p.M_AttributeSet_ID=pa.M_AttributeSet_ID) WHERE p.IsSummary='N' AND p.IsActive='Y' AND pr.IsActive='Y' AND pr.M_PriceList_Version_ID=? AND EXISTS (SELECT * FROM M_Storage s INNER JOIN M_AttributeSetInstance asi ON (s.M_AttributeSetInstance_ID=asi.M_AttributeSetInstance_ID) WHERE s.M_Product_ID=p.M_Product_ID AND asi.SerNo LIKE '33' AND asi.Lot LIKE '33' AND asi.M_Lot_ID=101 AND TRUNC(asi.GuaranteeDate,'DD')'x' AND IsActive='Y'"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - ResultSet rs = pstmt.executeQuery (); - while (rs.next ()) - { - int Client_ID = rs.getInt(1); - int table_ID = rs.getInt(2); - String key = Client_ID + "_" + table_ID; - String ShareType = rs.getString(3); - if (ShareType.equals(SHARETYPE_ClientAllShared)) - s_shares.put(key, Boolean.TRUE); - else if (ShareType.equals(SHARETYPE_OrgNotShared)) - s_shares.put(key, Boolean.FALSE); - } - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - s_log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - if (s_shares.isEmpty()) // put in something - s_shares.put("0_0", Boolean.TRUE); - } // load - String key = AD_Client_ID + "_" + AD_Table_ID; - return s_shares.get(key); - } // load - - /** Shared Info */ - private static CCache s_shares - = new CCache("AD_ClientShare", 10, 120); // 2h - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MClientShare.class); - - /************************************************************************** - * Default Constructor - * @param ctx context - * @param AD_ClientShare_ID id - * @param trxName trx - */ - public MClientShare (Properties ctx, int AD_ClientShare_ID, String trxName) - { - super (ctx, AD_ClientShare_ID, trxName); - } // MClientShare - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName trx - */ - public MClientShare (Properties ctx, ResultSet rs, String trxName) - { - super (ctx, rs, trxName); - } // MClientShare - - /** The Table */ - private MTable m_table = null; - - /** - * Is Client Level Only - * @return true if client level only (shared) - */ - public boolean isClientLevelOnly() - { - return getShareType().equals(SHARETYPE_ClientAllShared); - } // isClientLevelOnly - - /** - * Is Org Level Only - * @return true if org level only (not shared) - */ - public boolean isOrgLevelOnly() - { - return getShareType().equals(SHARETYPE_OrgNotShared); - } // isOrgLevelOnly - - /** - * Get Table model - * @return table - */ - public MTable getTable() - { - if (m_table == null) - m_table = MTable.get(getCtx(), getAD_Table_ID()); - return m_table; - } // getTable - - /** - * Get Table Name - * @return table name - */ - public String getTableName() - { - return getTable().getTableName(); - } // getTableName - - /** - * After Save - * @param newRecord new - * @param success success - * @return true - */ - protected boolean afterSave (boolean newRecord, boolean success) - { - if (isActive()) - { - setDataToLevel(); - listChildRecords(); - } - return true; - } // afterSave - - /** - * Set Data To Level - * @return info - */ - public String setDataToLevel() - { - String info = "-"; - if (isClientLevelOnly()) - { - StringBuffer sql = new StringBuffer("UPDATE ") - .append(getTableName()) - .append(" SET AD_Org_ID=0 WHERE AD_Org_ID<>0 AND AD_Client_ID=?"); - int no = DB.executeUpdate(sql.toString(), getAD_Client_ID(), get_TrxName()); - info = getTableName() + " set to Shared #" + no; - log.info(info); - } - else if (isOrgLevelOnly()) - { - StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM ") - .append(getTableName()) - .append(" WHERE AD_Org_ID=0 WHERE AD_Client_ID=?"); - int no = DB.getSQLValue(get_TrxName(), sql.toString(), getAD_Client_ID()); - info = getTableName() + " Shared records #" + no; - log.info(info); - } - return info; - } // setDataToLevel - - /** - * List Child Tables - * @return child tables - */ - public String listChildRecords() - { + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.model; + +import java.sql.*; +import java.util.*; +import java.util.logging.*; + +import org.compiere.util.*; + +/** + * Client Share Info + * + * @author Jorg Janke + * @version $Id: MClientShare.java,v 1.3 2006/07/30 00:58:37 jjanke Exp $ + */ +public class MClientShare extends X_AD_ClientShare +{ + /** + * Is Table Client Level Only + * @param AD_Client_ID client + * @param AD_Table_ID table + * @return true if client level only (default false) + */ + public static boolean isClientLevelOnly (int AD_Client_ID, int AD_Table_ID) + { + Boolean share = isShared(AD_Client_ID, AD_Table_ID); + if (share != null) + return share.booleanValue(); + return false; + } // isClientLevel + + /** + * Is Table Org Level Only + * @param AD_Client_ID client + * @param AD_Table_ID table + * @return true if Org level only (default false) + */ + public static boolean isOrgLevelOnly (int AD_Client_ID, int AD_Table_ID) + { + Boolean share = isShared(AD_Client_ID, AD_Table_ID); + if (share != null) + return !share.booleanValue(); + return false; + } // isOrgLevel + + /** + * Is Table Shared for Client + * @param AD_Client_ID client + * @param AD_Table_ID table + * @return info or null + */ + private static Boolean isShared (int AD_Client_ID, int AD_Table_ID) + { + // Load + if (s_shares.isEmpty()) + { + String sql = "SELECT AD_Client_ID, AD_Table_ID, ShareType " + + "FROM AD_ClientShare WHERE ShareType<>'x' AND IsActive='Y'"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + ResultSet rs = pstmt.executeQuery (); + while (rs.next ()) + { + int Client_ID = rs.getInt(1); + int table_ID = rs.getInt(2); + String key = Client_ID + "_" + table_ID; + String ShareType = rs.getString(3); + if (ShareType.equals(SHARETYPE_ClientAllShared)) + s_shares.put(key, Boolean.TRUE); + else if (ShareType.equals(SHARETYPE_OrgNotShared)) + s_shares.put(key, Boolean.FALSE); + } + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + s_log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + if (s_shares.isEmpty()) // put in something + s_shares.put("0_0", Boolean.TRUE); + } // load + String key = AD_Client_ID + "_" + AD_Table_ID; + return s_shares.get(key); + } // load + + /** Shared Info */ + private static CCache s_shares + = new CCache("AD_ClientShare", 10, 120); // 2h + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MClientShare.class); + + /************************************************************************** + * Default Constructor + * @param ctx context + * @param AD_ClientShare_ID id + * @param trxName trx + */ + public MClientShare (Properties ctx, int AD_ClientShare_ID, String trxName) + { + super (ctx, AD_ClientShare_ID, trxName); + } // MClientShare + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName trx + */ + public MClientShare (Properties ctx, ResultSet rs, String trxName) + { + super (ctx, rs, trxName); + } // MClientShare + + /** The Table */ + private MTable m_table = null; + + /** + * Is Client Level Only + * @return true if client level only (shared) + */ + public boolean isClientLevelOnly() + { + return getShareType().equals(SHARETYPE_ClientAllShared); + } // isClientLevelOnly + + /** + * Is Org Level Only + * @return true if org level only (not shared) + */ + public boolean isOrgLevelOnly() + { + return getShareType().equals(SHARETYPE_OrgNotShared); + } // isOrgLevelOnly + + /** + * Get Table model + * @return table + */ + public MTable getTable() + { + if (m_table == null) + m_table = MTable.get(getCtx(), getAD_Table_ID()); + return m_table; + } // getTable + + /** + * Get Table Name + * @return table name + */ + public String getTableName() + { + return getTable().getTableName(); + } // getTableName + + /** + * After Save + * @param newRecord new + * @param success success + * @return true + */ + protected boolean afterSave (boolean newRecord, boolean success) + { + if (isActive()) + { + setDataToLevel(); + listChildRecords(); + } + return true; + } // afterSave + + /** + * Set Data To Level + * @return info + */ + public String setDataToLevel() + { + String info = "-"; + if (isClientLevelOnly()) + { + StringBuffer sql = new StringBuffer("UPDATE ") + .append(getTableName()) + .append(" SET AD_Org_ID=0 WHERE AD_Org_ID<>0 AND AD_Client_ID=?"); + int no = DB.executeUpdate(sql.toString(), getAD_Client_ID(), get_TrxName()); + info = getTableName() + " set to Shared #" + no; + log.info(info); + } + else if (isOrgLevelOnly()) + { + StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM ") + .append(getTableName()) + .append(" WHERE AD_Org_ID=0 WHERE AD_Client_ID=?"); + int no = DB.getSQLValue(get_TrxName(), sql.toString(), getAD_Client_ID()); + info = getTableName() + " Shared records #" + no; + log.info(info); + } + return info; + } // setDataToLevel + + /** + * List Child Tables + * @return child tables + */ + public String listChildRecords() + { StringBuffer info = new StringBuffer(); String sql = "SELECT AD_Table_ID, TableName " + "FROM AD_Table t " - + "WHERE AccessLevel='3' AND IsView='N'" //jz put quote for typing + + "WHERE AccessLevel=3 AND IsView='N'" + " AND EXISTS (SELECT * FROM AD_Column c " + "WHERE t.AD_Table_ID=c.AD_Table_ID" + " AND c.IsParent='Y'" @@ -242,50 +242,50 @@ public class MClientShare extends X_AD_ClientShare + "WHERE cc.IsKey='Y' AND cc.AD_Table_ID=?))"; PreparedStatement pstmt = null; try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, getAD_Table_ID()); - ResultSet rs = pstmt.executeQuery (); - while (rs.next ()) - { - int AD_Table_ID = rs.getInt(1); - String TableName = rs.getString(2); - if (info.length() != 0) - info.append(", "); - info.append(TableName); - } - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - log.info(info.toString()); - return info.toString(); - } // listChildRecords - - /** - * Before Save - * @param newRecord new - * @return true - */ - protected boolean beforeSave (boolean newRecord) - { - if (getAD_Org_ID() != 0) - setAD_Org_ID(0); - return true; - } // beforeSave - -} // MClientShare + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, getAD_Table_ID()); + ResultSet rs = pstmt.executeQuery (); + while (rs.next ()) + { + int AD_Table_ID = rs.getInt(1); + String TableName = rs.getString(2); + if (info.length() != 0) + info.append(", "); + info.append(TableName); + } + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + log.info(info.toString()); + return info.toString(); + } // listChildRecords + + /** + * Before Save + * @param newRecord new + * @return true + */ + protected boolean beforeSave (boolean newRecord) + { + if (getAD_Org_ID() != 0) + setAD_Org_ID(0); + return true; + } // beforeSave + +} // MClientShare diff --git a/dbPort/src/org/compiere/model/MCostElement.java b/dbPort/src/org/compiere/model/MCostElement.java index e6f868f706..abe0c98a14 100644 --- a/dbPort/src/org/compiere/model/MCostElement.java +++ b/dbPort/src/org/compiere/model/MCostElement.java @@ -3,52 +3,52 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.model; - -import java.sql.*; -import java.util.*; -import java.util.logging.*; - -import org.compiere.util.*; - -/** - * Cost Element Model - * @author Jorg Janke - * @version $Id: MCostElement.java,v 1.2 2006/07/30 00:58:04 jjanke Exp $ - */ -public class MCostElement extends X_M_CostElement -{ - /** - * Get Material Cost Element or create it - * @param po parent - * @param CostingMethod method - * @return cost element - */ - public static MCostElement getMaterialCostElement (PO po, String CostingMethod) - { - if (CostingMethod == null || CostingMethod.length() == 0) - { - s_log.severe("No CostingMethod"); - return null; - } - // - MCostElement retValue = null; - String sql = "SELECT * FROM M_CostElement WHERE AD_Client_ID=? AND CostingMethod=? ORDER BY AD_Org_ID"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, po.get_TrxName()); + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.model; + +import java.sql.*; +import java.util.*; +import java.util.logging.*; + +import org.compiere.util.*; + +/** + * Cost Element Model + * @author Jorg Janke + * @version $Id: MCostElement.java,v 1.2 2006/07/30 00:58:04 jjanke Exp $ + */ +public class MCostElement extends X_M_CostElement +{ + /** + * Get Material Cost Element or create it + * @param po parent + * @param CostingMethod method + * @return cost element + */ + public static MCostElement getMaterialCostElement (PO po, String CostingMethod) + { + if (CostingMethod == null || CostingMethod.length() == 0) + { + s_log.severe("No CostingMethod"); + return null; + } + // + MCostElement retValue = null; + String sql = "SELECT * FROM M_CostElement WHERE AD_Client_ID=? AND CostingMethod=? ORDER BY AD_Org_ID"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, po.get_TrxName()); pstmt.setInt (1, po.getAD_Client_ID()); pstmt.setString(2, CostingMethod); ResultSet rs = pstmt.executeQuery (); @@ -59,400 +59,400 @@ public class MCostElement extends X_M_CostElement s_log.warning("More then one Material Cost Element for CostingMethod=" + CostingMethod); rs.close (); pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - s_log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - if (retValue != null) - return retValue; - - // Create New - retValue = new MCostElement (po.getCtx(), 0, po.get_TrxName()); - retValue.setClientOrg(po.getAD_Client_ID(), 0); - String name = MRefList.getListName(po.getCtx(), COSTINGMETHOD_AD_Reference_ID, CostingMethod); - if (name == null || name.length() == 0) - name = CostingMethod; - retValue.setName(name); - retValue.setCostElementType(COSTELEMENTTYPE_Material); - retValue.setCostingMethod(CostingMethod); - retValue.save(); - // - return retValue; - } // getMaterialCostElement - - /** - * Get first Material Cost Element - * @param ctx context - * @param CostingMethod costing method - * @return Cost Element or null - */ - public static MCostElement getMaterialCostElement(Properties ctx, String CostingMethod) - { - MCostElement retValue = null; - String sql = "SELECT * FROM M_CostElement WHERE AD_Client_ID=? AND CostingMethod=? ORDER BY AD_Org_ID"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, Env.getAD_Client_ID(ctx)); - pstmt.setString(2, CostingMethod); - ResultSet rs = pstmt.executeQuery (); - if (rs.next ()) - retValue = new MCostElement (ctx, rs, null); - if (rs.next()) - s_log.info("More then one Material Cost Element for CostingMethod=" + CostingMethod); - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - s_log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - return retValue; - } // getMaterialCostElement - - - /** - * Get active Material Cost Element for client - * @param po parent - * @return cost element array - */ - public static MCostElement[] getCostingMethods (PO po) - { - ArrayList list = new ArrayList(); - String sql = "SELECT * FROM M_CostElement " - + "WHERE AD_Client_ID=?" - + " AND IsActive='Y' AND CostElementType='M' AND CostingMethod IS NOT NULL"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, po.get_TrxName()); - pstmt.setInt (1, po.getAD_Client_ID()); - ResultSet rs = pstmt.executeQuery (); - while (rs.next ()) - list.add(new MCostElement (po.getCtx(), rs, po.get_TrxName())); - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - s_log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - // - MCostElement[] retValue = new MCostElement[list.size ()]; - list.toArray (retValue); - return retValue; - } // getMaterialCostElement - - - /** - * Get Cost Element from Cache - * @param ctx context - * @param M_CostElement_ID id - * @return Cost Element - */ - public static MCostElement get (Properties ctx, int M_CostElement_ID) - { - Integer key = new Integer (M_CostElement_ID); - MCostElement retValue = (MCostElement) s_cache.get (key); - if (retValue != null) - return retValue; - retValue = new MCostElement (ctx, M_CostElement_ID, null); - if (retValue.get_ID () != 0) - s_cache.put (key, retValue); - return retValue; - } // get - - /** Cache */ - private static CCache s_cache = new CCache("M_CostElement", 20); - - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MCostElement.class); - - - /************************************************************************** - * Standard Constructor - * @param ctx context - * @param M_CostElement_ID id - * @param trxName trx - */ - public MCostElement (Properties ctx, int M_CostElement_ID, String trxName) - { - super (ctx, M_CostElement_ID, trxName); - if (M_CostElement_ID == 0) - { - // setName (null); - setCostElementType (COSTELEMENTTYPE_Material); - setIsCalculated (false); - } - } // MCostElement - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName trx - */ - public MCostElement (Properties ctx, ResultSet rs, String trxName) - { - super (ctx, rs, trxName); - } // MCostElement - - /** - * Before Save - * @param newRecord new - * @return true - */ - protected boolean beforeSave (boolean newRecord) - { - // Check Unique Costing Method + pstmt = null; + } + catch (Exception e) + { + s_log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + if (retValue != null) + return retValue; + + // Create New + retValue = new MCostElement (po.getCtx(), 0, po.get_TrxName()); + retValue.setClientOrg(po.getAD_Client_ID(), 0); + String name = MRefList.getListName(po.getCtx(), COSTINGMETHOD_AD_Reference_ID, CostingMethod); + if (name == null || name.length() == 0) + name = CostingMethod; + retValue.setName(name); + retValue.setCostElementType(COSTELEMENTTYPE_Material); + retValue.setCostingMethod(CostingMethod); + retValue.save(); + // + return retValue; + } // getMaterialCostElement + + /** + * Get first Material Cost Element + * @param ctx context + * @param CostingMethod costing method + * @return Cost Element or null + */ + public static MCostElement getMaterialCostElement(Properties ctx, String CostingMethod) + { + MCostElement retValue = null; + String sql = "SELECT * FROM M_CostElement WHERE AD_Client_ID=? AND CostingMethod=? ORDER BY AD_Org_ID"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, Env.getAD_Client_ID(ctx)); + pstmt.setString(2, CostingMethod); + ResultSet rs = pstmt.executeQuery (); + if (rs.next ()) + retValue = new MCostElement (ctx, rs, null); + if (rs.next()) + s_log.info("More then one Material Cost Element for CostingMethod=" + CostingMethod); + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + s_log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + return retValue; + } // getMaterialCostElement + + + /** + * Get active Material Cost Element for client + * @param po parent + * @return cost element array + */ + public static MCostElement[] getCostingMethods (PO po) + { + ArrayList list = new ArrayList(); + String sql = "SELECT * FROM M_CostElement " + + "WHERE AD_Client_ID=?" + + " AND IsActive='Y' AND CostElementType='M' AND CostingMethod IS NOT NULL"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, po.get_TrxName()); + pstmt.setInt (1, po.getAD_Client_ID()); + ResultSet rs = pstmt.executeQuery (); + while (rs.next ()) + list.add(new MCostElement (po.getCtx(), rs, po.get_TrxName())); + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + s_log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + // + MCostElement[] retValue = new MCostElement[list.size ()]; + list.toArray (retValue); + return retValue; + } // getMaterialCostElement + + + /** + * Get Cost Element from Cache + * @param ctx context + * @param M_CostElement_ID id + * @return Cost Element + */ + public static MCostElement get (Properties ctx, int M_CostElement_ID) + { + Integer key = new Integer (M_CostElement_ID); + MCostElement retValue = (MCostElement) s_cache.get (key); + if (retValue != null) + return retValue; + retValue = new MCostElement (ctx, M_CostElement_ID, null); + if (retValue.get_ID () != 0) + s_cache.put (key, retValue); + return retValue; + } // get + + /** Cache */ + private static CCache s_cache = new CCache("M_CostElement", 20); + + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MCostElement.class); + + + /************************************************************************** + * Standard Constructor + * @param ctx context + * @param M_CostElement_ID id + * @param trxName trx + */ + public MCostElement (Properties ctx, int M_CostElement_ID, String trxName) + { + super (ctx, M_CostElement_ID, trxName); + if (M_CostElement_ID == 0) + { + // setName (null); + setCostElementType (COSTELEMENTTYPE_Material); + setIsCalculated (false); + } + } // MCostElement + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName trx + */ + public MCostElement (Properties ctx, ResultSet rs, String trxName) + { + super (ctx, rs, trxName); + } // MCostElement + + /** + * Before Save + * @param newRecord new + * @return true + */ + protected boolean beforeSave (boolean newRecord) + { + // Check Unique Costing Method if (COSTELEMENTTYPE_Material.equals(getCostElementType()) && (newRecord || is_ValueChanged("CostingMethod"))) { - String sql = "SELECT MAX(COALESCE(M_CostElement_ID,0)) FROM M_CostElement " + String sql = "SELECT COALESCE(MAX(M_CostElement_ID),0) FROM M_CostElement " + "WHERE AD_Client_ID=? AND CostingMethod=?"; int id = DB.getSQLValue(get_TrxName(), sql, getAD_Client_ID(), getCostingMethod()); if (id > 0 && id != get_ID()) - { - log.saveError("AlreadyExists", Msg.getElement(getCtx(), "CostingMethod")); - return false; - } - } - - // Maintain Calclated - if (COSTELEMENTTYPE_Material.equals(getCostElementType())) - { - String cm = getCostingMethod(); - if (cm == null || cm.length() == 0 - || COSTINGMETHOD_StandardCosting.equals(cm)) - setIsCalculated(false); - else - setIsCalculated(true); - } - else - { - if (isCalculated()) - setIsCalculated(false); - if (getCostingMethod() != null) - setCostingMethod(null); - } - - if (getAD_Org_ID() != 0) - setAD_Org_ID(0); - return true; - } // beforeSave - - /** - * Before Delete - * @return true if can be deleted - */ - protected boolean beforeDelete () - { - String cm = getCostingMethod(); - if (cm == null - || !COSTELEMENTTYPE_Material.equals(getCostElementType())) - return true; - - // Costing Methods on AS level - MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(getCtx(), getAD_Client_ID()); - for (int i = 0; i < ass.length; i++) - { - if (ass[i].getCostingMethod().equals(getCostingMethod())) - { - log.saveError("CannotDeleteUsed", Msg.getElement(getCtx(), "C_AcctSchema_ID") - + " - " + ass[i].getName()); - return false; - } - } - - // Costing Methods on PC level - String sql = "SELECT M_Product_Category_ID FROM M_Product_Category_Acct WHERE AD_Client_ID=? AND CostingMethod=?"; - int M_Product_Category_ID = 0; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, getAD_Client_ID()); - pstmt.setString (2, getCostingMethod()); - ResultSet rs = pstmt.executeQuery (); - if (rs.next ()) - { - M_Product_Category_ID = rs.getInt(1); - } - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - if (M_Product_Category_ID != 0) - { - log.saveError("CannotDeleteUsed", Msg.getElement(getCtx(), "M_Product_Category_ID") - + " (ID=" + M_Product_Category_ID + ")"); - return false; - } - return true; - } // beforeDelete - - /** - * Is this a Costing Method - * @return true if not Material cost or no costing method. - */ - public boolean isCostingMethod() - { - return COSTELEMENTTYPE_Material.equals(getCostElementType()) - && getCostingMethod() != null; - } // isCostingMethod - - /** - * Is Avg Invoice Costing Method - * @return true if AverageInvoice - */ - public boolean isAverageInvoice() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_AverageInvoice) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isAverageInvoice - - /** - * Is Avg PO Costing Method - * @return true if AveragePO - */ - public boolean isAveragePO() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_AveragePO) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isAveragePO - /** - * Is FiFo Costing Method - * @return true if Fifo - */ - public boolean isFifo() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_Fifo) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isFifo - /** - * Is Last Invoice Costing Method - * @return true if LastInvoice - */ - public boolean isLastInvoice() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_LastInvoice) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isLastInvoice - /** - * Is Last PO Costing Method - * @return true if LastPOPrice - */ - public boolean isLastPOPrice() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_LastPOPrice) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isLastPOPrice - /** - * Is LiFo Costing Method - * @return true if Lifo - */ - public boolean isLifo() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_Lifo) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isLiFo - /** - * Is Std Costing Method - * @return true if StandardCosting - */ - public boolean isStandardCosting() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_StandardCosting) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isStandardCosting - /** - * Is User Costing Method - * @return true if User Defined - */ - public boolean isUserDefined() - { - String cm = getCostingMethod(); - return cm != null - && cm.equals(COSTINGMETHOD_UserDefined) - && COSTELEMENTTYPE_Material.equals(getCostElementType()); - } // isAveragePO - - /** - * String Representation - * @return info - */ - public String toString () - { - StringBuffer sb = new StringBuffer ("MCostElement["); - sb.append (get_ID ()) - .append ("-").append (getName()) - .append(",Type=").append(getCostElementType()) - .append(",Method=").append(getCostingMethod()) - .append ("]"); - return sb.toString (); - } // toString - -} // MCostElement + { + log.saveError("AlreadyExists", Msg.getElement(getCtx(), "CostingMethod")); + return false; + } + } + + // Maintain Calclated + if (COSTELEMENTTYPE_Material.equals(getCostElementType())) + { + String cm = getCostingMethod(); + if (cm == null || cm.length() == 0 + || COSTINGMETHOD_StandardCosting.equals(cm)) + setIsCalculated(false); + else + setIsCalculated(true); + } + else + { + if (isCalculated()) + setIsCalculated(false); + if (getCostingMethod() != null) + setCostingMethod(null); + } + + if (getAD_Org_ID() != 0) + setAD_Org_ID(0); + return true; + } // beforeSave + + /** + * Before Delete + * @return true if can be deleted + */ + protected boolean beforeDelete () + { + String cm = getCostingMethod(); + if (cm == null + || !COSTELEMENTTYPE_Material.equals(getCostElementType())) + return true; + + // Costing Methods on AS level + MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(getCtx(), getAD_Client_ID()); + for (int i = 0; i < ass.length; i++) + { + if (ass[i].getCostingMethod().equals(getCostingMethod())) + { + log.saveError("CannotDeleteUsed", Msg.getElement(getCtx(), "C_AcctSchema_ID") + + " - " + ass[i].getName()); + return false; + } + } + + // Costing Methods on PC level + String sql = "SELECT M_Product_Category_ID FROM M_Product_Category_Acct WHERE AD_Client_ID=? AND CostingMethod=?"; + int M_Product_Category_ID = 0; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, getAD_Client_ID()); + pstmt.setString (2, getCostingMethod()); + ResultSet rs = pstmt.executeQuery (); + if (rs.next ()) + { + M_Product_Category_ID = rs.getInt(1); + } + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + if (M_Product_Category_ID != 0) + { + log.saveError("CannotDeleteUsed", Msg.getElement(getCtx(), "M_Product_Category_ID") + + " (ID=" + M_Product_Category_ID + ")"); + return false; + } + return true; + } // beforeDelete + + /** + * Is this a Costing Method + * @return true if not Material cost or no costing method. + */ + public boolean isCostingMethod() + { + return COSTELEMENTTYPE_Material.equals(getCostElementType()) + && getCostingMethod() != null; + } // isCostingMethod + + /** + * Is Avg Invoice Costing Method + * @return true if AverageInvoice + */ + public boolean isAverageInvoice() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_AverageInvoice) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isAverageInvoice + + /** + * Is Avg PO Costing Method + * @return true if AveragePO + */ + public boolean isAveragePO() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_AveragePO) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isAveragePO + /** + * Is FiFo Costing Method + * @return true if Fifo + */ + public boolean isFifo() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_Fifo) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isFifo + /** + * Is Last Invoice Costing Method + * @return true if LastInvoice + */ + public boolean isLastInvoice() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_LastInvoice) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isLastInvoice + /** + * Is Last PO Costing Method + * @return true if LastPOPrice + */ + public boolean isLastPOPrice() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_LastPOPrice) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isLastPOPrice + /** + * Is LiFo Costing Method + * @return true if Lifo + */ + public boolean isLifo() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_Lifo) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isLiFo + /** + * Is Std Costing Method + * @return true if StandardCosting + */ + public boolean isStandardCosting() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_StandardCosting) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isStandardCosting + /** + * Is User Costing Method + * @return true if User Defined + */ + public boolean isUserDefined() + { + String cm = getCostingMethod(); + return cm != null + && cm.equals(COSTINGMETHOD_UserDefined) + && COSTELEMENTTYPE_Material.equals(getCostElementType()); + } // isAveragePO + + /** + * String Representation + * @return info + */ + public String toString () + { + StringBuffer sb = new StringBuffer ("MCostElement["); + sb.append (get_ID ()) + .append ("-").append (getName()) + .append(",Type=").append(getCostElementType()) + .append(",Method=").append(getCostingMethod()) + .append ("]"); + return sb.toString (); + } // toString + +} // MCostElement diff --git a/dbPort/src/org/compiere/model/MLookupFactory.java b/dbPort/src/org/compiere/model/MLookupFactory.java index db942fa37f..9b9da8cbda 100644 --- a/dbPort/src/org/compiere/model/MLookupFactory.java +++ b/dbPort/src/org/compiere/model/MLookupFactory.java @@ -3,194 +3,194 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.model; - -import java.sql.*; -import java.util.*; -import java.util.logging.*; -import org.compiere.util.*; - -/** - * Create MLookups - * - * @author Jorg Janke - * @version $Id: MLookupFactory.java,v 1.3 2006/07/30 00:58:04 jjanke Exp $ - */ -public class MLookupFactory -{ - /** Logging */ - private static CLogger s_log = CLogger.getCLogger(MLookupFactory.class); - /** Table Reference Cache */ - private static CCache s_cacheRefTable = new CCache("AD_Ref_Table", 30, 60); // 1h - - - /** - * Create MLookup - * - * @param ctx context for access - * @param WindowNo window no - * @param AD_Reference_ID display type - * @param Column_ID AD_Column_ID or AD_Process_Para_ID - * @param language report language - * @param ColumnName key column name - * @param AD_Reference_Value_ID AD_Reference (List, Table) - * @param IsParent parent (prevents query to directly access value) - * @param ValidationCode optional SQL validation - * @throws Exception if Lookup could not be created - * @return MLookup - */ - public static MLookup get (Properties ctx, int WindowNo, int Column_ID, int AD_Reference_ID, - Language language, String ColumnName, int AD_Reference_Value_ID, - boolean IsParent, String ValidationCode) - throws Exception - { - MLookupInfo info = getLookupInfo (ctx, WindowNo, Column_ID, AD_Reference_ID, - language, ColumnName, AD_Reference_Value_ID, IsParent, ValidationCode); - if (info == null) - throw new Exception ("MLookup.create - no LookupInfo"); - return new MLookup(info, 0); - } // create - - /** - * Create MLookup - * - * @param ctx context for access - * @param WindowNo window no - * @param TabNo TabNo - * @param Column_ID AD_Column_ID or AD_Process_Para_ID - * @param AD_Reference_ID display type - * @return MLookup - */ - public static MLookup get (Properties ctx, int WindowNo, int TabNo, int Column_ID, int AD_Reference_ID) - { - String ColumnName = ""; - int AD_Reference_Value_ID = 0; - boolean IsParent = false; - String ValidationCode = ""; - // - String sql = "SELECT c.ColumnName, c.AD_Reference_Value_ID, c.IsParent, vr.Code " - + "FROM AD_Column c" - + " LEFT OUTER JOIN AD_Val_Rule vr ON (c.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) " - + "WHERE c.AD_Column_ID=?"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, Column_ID); - // - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - ColumnName = rs.getString(1); - AD_Reference_Value_ID = rs.getInt(2); - IsParent = "Y".equals(rs.getString(3)); - ValidationCode = rs.getString(4); - } - else - s_log.log(Level.SEVERE, "Column Not Found - AD_Column_ID=" + Column_ID); - rs.close(); - // - pstmt.close(); - pstmt = null; - } - catch (SQLException ex) - { - s_log.log(Level.SEVERE, "create", ex); - } - try - { - if (pstmt != null) - pstmt.close(); - } - catch (SQLException ex1) - { - } - pstmt = null; - // - MLookupInfo info = getLookupInfo (ctx, WindowNo, Column_ID, AD_Reference_ID, - Env.getLanguage(ctx), ColumnName, AD_Reference_Value_ID, IsParent, ValidationCode); - return new MLookup(info, TabNo); - } // get - - - /************************************************************************** - * Get Information for Lookups based on Column_ID for Table Columns or Process Parameters. - * - * The SQL returns three columns: - *
-	 *		Key, Value, Name, IsActive	(where either key or value is null)
-	 *  
- * @param ctx context for access - * @param language report language - * @param WindowNo window no - * @param Column_ID AD_Column_ID or AD_Process_Para_ID - * @param ColumnName key column name - * @param AD_Reference_ID display type - * @param AD_Reference_Value_ID AD_Reference (List, Table) - * @param IsParent parent (prevents query to directly access value) - * @param ValidationCode optional SQL validation - * @return lookup info structure - */ - static public MLookupInfo getLookupInfo (Properties ctx, int WindowNo, - int Column_ID, int AD_Reference_ID, - Language language, String ColumnName, int AD_Reference_Value_ID, - boolean IsParent, String ValidationCode) - { - MLookupInfo info = null; - boolean needToAddSecurity = true; - // List - if (AD_Reference_ID == DisplayType.List) // 17 - { - info = getLookup_List(language, AD_Reference_Value_ID); - needToAddSecurity = false; - } - // Table or Search with Reference_Value - else if ((AD_Reference_ID == DisplayType.Table || AD_Reference_ID == DisplayType.Search) - && AD_Reference_Value_ID != 0) - { - info = getLookup_Table (ctx, language, WindowNo, AD_Reference_Value_ID); - } - // TableDir, Search, ID, ... - else - { - info = getLookup_TableDir (ctx, language, WindowNo, ColumnName); - } - // do we have basic info? - if (info == null) - { - s_log.severe ("No SQL - " + ColumnName); - return null; - } - // remaining values - info.ctx = ctx; - info.WindowNo = WindowNo; - info.Column_ID = Column_ID; - info.DisplayType = AD_Reference_ID; - info.AD_Reference_Value_ID = AD_Reference_Value_ID; - info.IsParent = IsParent; - info.ValidationCode = ValidationCode; - if (info.ValidationCode == null) - info.ValidationCode = ""; - - // Variables in SQL WHERE - if (info.Query.indexOf("@") != -1) - { - // String newSQL = Env.parseContext(ctx, WindowNo, info.Query, false); - String newSQL = Env.parseContext(ctx, 0, info.Query, false); // only global - if (newSQL.length() == 0) - { - s_log.severe ("SQL parse error: " + info.Query); + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.model; + +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Create MLookups + * + * @author Jorg Janke + * @version $Id: MLookupFactory.java,v 1.3 2006/07/30 00:58:04 jjanke Exp $ + */ +public class MLookupFactory +{ + /** Logging */ + private static CLogger s_log = CLogger.getCLogger(MLookupFactory.class); + /** Table Reference Cache */ + private static CCache s_cacheRefTable = new CCache("AD_Ref_Table", 30, 60); // 1h + + + /** + * Create MLookup + * + * @param ctx context for access + * @param WindowNo window no + * @param AD_Reference_ID display type + * @param Column_ID AD_Column_ID or AD_Process_Para_ID + * @param language report language + * @param ColumnName key column name + * @param AD_Reference_Value_ID AD_Reference (List, Table) + * @param IsParent parent (prevents query to directly access value) + * @param ValidationCode optional SQL validation + * @throws Exception if Lookup could not be created + * @return MLookup + */ + public static MLookup get (Properties ctx, int WindowNo, int Column_ID, int AD_Reference_ID, + Language language, String ColumnName, int AD_Reference_Value_ID, + boolean IsParent, String ValidationCode) + throws Exception + { + MLookupInfo info = getLookupInfo (ctx, WindowNo, Column_ID, AD_Reference_ID, + language, ColumnName, AD_Reference_Value_ID, IsParent, ValidationCode); + if (info == null) + throw new Exception ("MLookup.create - no LookupInfo"); + return new MLookup(info, 0); + } // create + + /** + * Create MLookup + * + * @param ctx context for access + * @param WindowNo window no + * @param TabNo TabNo + * @param Column_ID AD_Column_ID or AD_Process_Para_ID + * @param AD_Reference_ID display type + * @return MLookup + */ + public static MLookup get (Properties ctx, int WindowNo, int TabNo, int Column_ID, int AD_Reference_ID) + { + String ColumnName = ""; + int AD_Reference_Value_ID = 0; + boolean IsParent = false; + String ValidationCode = ""; + // + String sql = "SELECT c.ColumnName, c.AD_Reference_Value_ID, c.IsParent, vr.Code " + + "FROM AD_Column c" + + " LEFT OUTER JOIN AD_Val_Rule vr ON (c.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) " + + "WHERE c.AD_Column_ID=?"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, Column_ID); + // + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + ColumnName = rs.getString(1); + AD_Reference_Value_ID = rs.getInt(2); + IsParent = "Y".equals(rs.getString(3)); + ValidationCode = rs.getString(4); + } + else + s_log.log(Level.SEVERE, "Column Not Found - AD_Column_ID=" + Column_ID); + rs.close(); + // + pstmt.close(); + pstmt = null; + } + catch (SQLException ex) + { + s_log.log(Level.SEVERE, "create", ex); + } + try + { + if (pstmt != null) + pstmt.close(); + } + catch (SQLException ex1) + { + } + pstmt = null; + // + MLookupInfo info = getLookupInfo (ctx, WindowNo, Column_ID, AD_Reference_ID, + Env.getLanguage(ctx), ColumnName, AD_Reference_Value_ID, IsParent, ValidationCode); + return new MLookup(info, TabNo); + } // get + + + /************************************************************************** + * Get Information for Lookups based on Column_ID for Table Columns or Process Parameters. + * + * The SQL returns three columns: + *
+	 *		Key, Value, Name, IsActive	(where either key or value is null)
+	 *  
+ * @param ctx context for access + * @param language report language + * @param WindowNo window no + * @param Column_ID AD_Column_ID or AD_Process_Para_ID + * @param ColumnName key column name + * @param AD_Reference_ID display type + * @param AD_Reference_Value_ID AD_Reference (List, Table) + * @param IsParent parent (prevents query to directly access value) + * @param ValidationCode optional SQL validation + * @return lookup info structure + */ + static public MLookupInfo getLookupInfo (Properties ctx, int WindowNo, + int Column_ID, int AD_Reference_ID, + Language language, String ColumnName, int AD_Reference_Value_ID, + boolean IsParent, String ValidationCode) + { + MLookupInfo info = null; + boolean needToAddSecurity = true; + // List + if (AD_Reference_ID == DisplayType.List) // 17 + { + info = getLookup_List(language, AD_Reference_Value_ID); + needToAddSecurity = false; + } + // Table or Search with Reference_Value + else if ((AD_Reference_ID == DisplayType.Table || AD_Reference_ID == DisplayType.Search) + && AD_Reference_Value_ID != 0) + { + info = getLookup_Table (ctx, language, WindowNo, AD_Reference_Value_ID); + } + // TableDir, Search, ID, ... + else + { + info = getLookup_TableDir (ctx, language, WindowNo, ColumnName); + } + // do we have basic info? + if (info == null) + { + s_log.severe ("No SQL - " + ColumnName); + return null; + } + // remaining values + info.ctx = ctx; + info.WindowNo = WindowNo; + info.Column_ID = Column_ID; + info.DisplayType = AD_Reference_ID; + info.AD_Reference_Value_ID = AD_Reference_Value_ID; + info.IsParent = IsParent; + info.ValidationCode = ValidationCode; + if (info.ValidationCode == null) + info.ValidationCode = ""; + + // Variables in SQL WHERE + if (info.Query.indexOf("@") != -1) + { + // String newSQL = Env.parseContext(ctx, WindowNo, info.Query, false); + String newSQL = Env.parseContext(ctx, 0, info.Query, false); // only global + if (newSQL.length() == 0) + { + s_log.severe ("SQL parse error: " + info.Query); return null; } info.Query = newSQL; @@ -198,36 +198,36 @@ public class MLookupFactory } // Direct Query - NO Validation/Security - int posOrder = info.Query.lastIndexOf(" ORDER BY "); - boolean hasWhere = info.Query.lastIndexOf(" WHERE ") != -1; - if (hasWhere) // might be for a select sub-query - { - // SELECT (SELECT .. FROM .. WHERE ..) FROM .. - // SELECT .. FROM .. WHERE EXISTS (SELECT .. FROM .. WHERE ..) - AccessSqlParser asp = new AccessSqlParser(info.Query); - String mainQuery = asp.getMainSql(); - hasWhere = mainQuery.indexOf(" WHERE ") != -1; - } - if (posOrder == -1) - info.QueryDirect = info.Query - + (hasWhere ? " AND " : " WHERE ") + info.KeyColumn + "=?"; - else - info.QueryDirect = info.Query.substring(0, posOrder) - + (hasWhere ? " AND " : " WHERE ") + info.KeyColumn + "=?"; - - // Validation - String local_validationCode = ""; - if (info.ValidationCode.length() == 0) - info.IsValidated = true; - else - { - local_validationCode = Env.parseContext (ctx, WindowNo, info.ValidationCode, true); - if (local_validationCode.length() == 0) // returns "" if not all variables were parsed - info.IsValidated = false; - else - info.IsValidated = true; - } - + int posOrder = info.Query.lastIndexOf(" ORDER BY "); + boolean hasWhere = info.Query.lastIndexOf(" WHERE ") != -1; + if (hasWhere) // might be for a select sub-query + { + // SELECT (SELECT .. FROM .. WHERE ..) FROM .. + // SELECT .. FROM .. WHERE EXISTS (SELECT .. FROM .. WHERE ..) + AccessSqlParser asp = new AccessSqlParser(info.Query); + String mainQuery = asp.getMainSql(); + hasWhere = mainQuery.indexOf(" WHERE ") != -1; + } + if (posOrder == -1) + info.QueryDirect = info.Query + + (hasWhere ? " AND " : " WHERE ") + info.KeyColumn + "=?"; + else + info.QueryDirect = info.Query.substring(0, posOrder) + + (hasWhere ? " AND " : " WHERE ") + info.KeyColumn + "=?"; + + // Validation + String local_validationCode = ""; + if (info.ValidationCode.length() == 0) + info.IsValidated = true; + else + { + local_validationCode = Env.parseContext (ctx, WindowNo, info.ValidationCode, true); + if (local_validationCode.length() == 0) // returns "" if not all variables were parsed + info.IsValidated = false; + else + info.IsValidated = true; + } + // Add Local Validation if (local_validationCode.length() != 0) { @@ -242,544 +242,538 @@ public class MLookupFactory } // Add Security - if (needToAddSecurity) - info.Query = MRole.getDefault(ctx, false).addAccessSQL(info.Query, - info.TableName, MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); - // - // s_log.finest("Query: " + info.Query); - // s_log.finest("Direct: " + info.QueryDirect); - return info; - } // createLookupInfo - - - /************************************************************************** - * Get Lookup SQL for Lists - * @param language report language - * @param AD_Reference_Value_ID reference value - * @return SELECT NULL, Value, Name, IsActive FROM AD_Ref_List - */ - static public MLookupInfo getLookup_List(Language language, int AD_Reference_Value_ID) - { - StringBuffer realSQL = new StringBuffer ("SELECT NULL, AD_Ref_List.Value,"); - if (Env.isBaseLanguage(language, "AD_Ref_List")) - realSQL.append("AD_Ref_List.Name,AD_Ref_List.IsActive FROM AD_Ref_List"); - else - realSQL.append("trl.Name, AD_Ref_List.IsActive " - + "FROM AD_Ref_List INNER JOIN AD_Ref_List_Trl trl " - + " ON (AD_Ref_List.AD_Ref_List_ID=trl.AD_Ref_List_ID AND trl.AD_Language='") - .append(language.getAD_Language()).append("')"); - realSQL.append(" WHERE AD_Ref_List.AD_Reference_ID=").append(AD_Reference_Value_ID); - realSQL.append(" ORDER BY 2"); - // - return new MLookupInfo(realSQL.toString(), "AD_Ref_List", "AD_Ref_List.Value", - 101,101, MQuery.getEqualQuery("AD_Reference_ID", AD_Reference_Value_ID)); // Zoom Window+Query - } // getLookup_List - - /** - * Get Lookup SQL for List - * @param language report Language - * @param AD_Reference_Value_ID reference value - * @param linkColumnName link column name - * @return SELECT Name FROM AD_Ref_List WHERE AD_Reference_ID=x AND Value=linkColumn - */ - static public String getLookup_ListEmbed(Language language, - int AD_Reference_Value_ID, String linkColumnName) - { - StringBuffer realSQL = new StringBuffer ("SELECT "); - if (Env.isBaseLanguage(language, "AD_Ref_List")) - realSQL.append("AD_Ref_List.Name FROM AD_Ref_List"); - else - realSQL.append("trl.Name " - + "FROM AD_Ref_List INNER JOIN AD_Ref_List_Trl trl " - + " ON (AD_Ref_List.AD_Ref_List_ID=trl.AD_Ref_List_ID AND trl.AD_Language='") - .append(language.getAD_Language()).append("')"); - realSQL.append(" WHERE AD_Ref_List.AD_Reference_ID=").append(AD_Reference_Value_ID) - .append(" AND AD_Ref_List.Value=").append(linkColumnName); - - // - return realSQL.toString(); - } // getLookup_ListEmbed - - /*************************************************************************** - * Get Lookup SQL for Table Lookup - * @param ctx context for access and dynamic access - * @param language report language - * @param WindowNo window no - * @param AD_Reference_Value_ID reference value - * @return SELECT Key, NULL, Name, IsActive FROM Table - if KeyColumn end with _ID - * otherwise SELECT NULL, Key, Name, IsActive FROM Table - */ - static private MLookupInfo getLookup_Table (Properties ctx, Language language, - int WindowNo, int AD_Reference_Value_ID) - { - // Try cache - assume no language change - String key = String.valueOf(AD_Reference_Value_ID); - MLookupInfo retValue = (MLookupInfo)s_cacheRefTable.get(key); - if (retValue != null) - { - s_log.finest("Cache: " + retValue); - return retValue.cloneIt(); - } - // - String sql0 = "SELECT t.TableName,ck.ColumnName AS KeyColumn," // 1..2 - + "cd.ColumnName AS DisplayColumn,rt.IsValueDisplayed,cd.IsTranslated," // 3..5 - + "rt.WhereClause,rt.OrderByClause,t.AD_Window_ID,t.PO_Window_ID, " // 6..9 - + "t.AD_Table_ID " // 10 - + "FROM AD_Ref_Table rt" - + " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID)" - + " INNER JOIN AD_Column ck ON (rt.AD_Key=ck.AD_Column_ID)" - + " INNER JOIN AD_Column cd ON (rt.AD_Display=cd.AD_Column_ID) " - + "WHERE rt.AD_Reference_ID=?" - + " AND rt.IsActive='Y' AND t.IsActive='Y'"; - // - String KeyColumn = null, DisplayColumn = null, TableName = null, WhereClause = null, OrderByClause = null; - boolean IsTranslated = false, isValueDisplayed = false; - boolean isSOTrx = !"N".equals(Env.getContext(ctx, WindowNo, "IsSOTrx")); - int ZoomWindow = 0; - int ZoomWindowPO = 0; - int AD_Table_ID = 0; - boolean loaded = false; - - try - { - PreparedStatement pstmt = DB.prepareStatement(sql0, null); - pstmt.setInt(1, AD_Reference_Value_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - TableName = rs.getString(1); - KeyColumn = rs.getString(2); - DisplayColumn = rs.getString(3); - isValueDisplayed = "Y".equals(rs.getString(4)); - IsTranslated = "Y".equals(rs.getString(5)); - WhereClause = rs.getString(6); - OrderByClause = rs.getString(7); - ZoomWindow = rs.getInt(8); - ZoomWindowPO = rs.getInt(9); - AD_Table_ID = rs.getInt(10); - loaded = true; - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, sql0, e); - return null; - } - if (!loaded) - { - s_log.log(Level.SEVERE, "No Table Reference Table ID=" + AD_Reference_Value_ID); - return null; - } - - StringBuffer realSQL = new StringBuffer("SELECT "); - if (!KeyColumn.endsWith("_ID")) - realSQL.append("NULL,"); - - // Translated - if (IsTranslated && !Env.isBaseLanguage(language, TableName)) - { - realSQL.append(TableName).append(".").append(KeyColumn).append(","); - if (KeyColumn.endsWith("_ID")) - realSQL.append("NULL,"); - if (isValueDisplayed) - realSQL.append(TableName).append(".Value || '-' || "); - realSQL.append(TableName).append("_Trl.").append(DisplayColumn) - .append(",").append(TableName).append(".IsActive"); - realSQL.append(" FROM ").append(TableName) - .append(" INNER JOIN ").append(TableName).append("_TRL ON (") - .append(TableName).append(".").append(KeyColumn) - .append("=").append(TableName).append("_Trl.").append(KeyColumn) - .append(" AND ").append(TableName).append("_Trl.AD_Language='") - .append(language.getAD_Language()).append("')"); - } - // Not Translated - else - { - realSQL.append(TableName).append(".").append(KeyColumn).append(","); - if (KeyColumn.endsWith("_ID")) - realSQL.append("NULL,"); - if (isValueDisplayed) - realSQL.append(TableName).append(".Value || '-' || "); - realSQL.append(TableName).append(".").append(DisplayColumn); - realSQL.append(",").append(TableName).append(".IsActive"); - realSQL.append(" FROM ").append(TableName); - } - - // add WHERE clause - MQuery zoomQuery = null; - if (WhereClause != null) - { - String where = WhereClause; - if (where.indexOf("@") != -1) - where = Env.parseContext(ctx, WindowNo, where, false); - if (where.length() == 0 && WhereClause.length() != 0) - s_log.severe ("Could not resolve: " + WhereClause); - - // We have no context - if (where.length() != 0) - { - realSQL.append(" WHERE ").append(where); - if (where.indexOf(".") == -1) - s_log.log(Level.SEVERE, "getLookup_Table - " + TableName - + ": WHERE should be fully qualified: " + WhereClause); - zoomQuery = new MQuery (TableName); - zoomQuery.addRestriction(where); - } - } - - // Order By qualified term or by Name - if (OrderByClause != null) - { - realSQL.append(" ORDER BY ").append(OrderByClause); - if (OrderByClause.indexOf(".") == -1) - s_log.log(Level.SEVERE, "getLookup_Table - " + TableName - + ": ORDER BY must fully qualified: " + OrderByClause); - } - else - realSQL.append(" ORDER BY 3"); - - s_log.finest("AD_Reference_Value_ID=" + AD_Reference_Value_ID + " - " + realSQL); - retValue = new MLookupInfo (realSQL.toString(), TableName, - TableName + "." + KeyColumn, ZoomWindow, ZoomWindowPO, zoomQuery); - s_cacheRefTable.put(key, retValue.cloneIt()); - return retValue; - } // getLookup_Table - - /** - * Get Embedded Lookup SQL for Table Lookup - * @param language report language - * @param BaseColumn base column name - * @param BaseTable base table name - * @param AD_Reference_Value_ID reference value - * @return SELECT Name FROM Table - */ - static public String getLookup_TableEmbed (Language language, - String BaseColumn, String BaseTable, int AD_Reference_Value_ID) - { - String sql = "SELECT t.TableName,ck.ColumnName AS KeyColumn," - + "cd.ColumnName AS DisplayColumn,rt.isValueDisplayed,cd.IsTranslated " - + "FROM AD_Ref_Table rt" - + " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID)" - + " INNER JOIN AD_Column ck ON (rt.AD_Key=ck.AD_Column_ID)" - + " INNER JOIN AD_Column cd ON (rt.AD_Display=cd.AD_Column_ID) " - + "WHERE rt.AD_Reference_ID=?" - + " AND rt.IsActive='Y' AND t.IsActive='Y'"; - // - String KeyColumn, DisplayColumn, TableName; - boolean IsTranslated, isValueDisplayed; - - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Reference_Value_ID); - ResultSet rs = pstmt.executeQuery(); - if (!rs.next()) - { - s_log.log(Level.SEVERE, "Cannot find Reference Table, ID=" + AD_Reference_Value_ID - + ", Base=" + BaseTable + "." + BaseColumn); - rs.close(); - pstmt.close(); - return null; - } - - TableName = rs.getString(1); - KeyColumn = rs.getString(2); - DisplayColumn = rs.getString(3); - isValueDisplayed = rs.getString(4).equals("Y"); - IsTranslated = rs.getString(5).equals("Y"); - - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, sql, e); - return null; - } - - StringBuffer embedSQL = new StringBuffer("SELECT "); - - // Translated - if (IsTranslated && !Env.isBaseLanguage(language, TableName)) - { - if (isValueDisplayed) - embedSQL.append(TableName).append(".Value||'-'||"); - embedSQL.append(TableName).append("_Trl.").append(DisplayColumn); - // - embedSQL.append(" FROM ").append(TableName) - .append(" INNER JOIN ").append(TableName).append("_TRL ON (") - .append(TableName).append(".").append(KeyColumn) - .append("=").append(TableName).append("_Trl.").append(KeyColumn) - .append(" AND ").append(TableName).append("_Trl.AD_Language='") - .append(language.getAD_Language()).append("')"); - } - // Not Translated - else - { - if (isValueDisplayed) - embedSQL.append(TableName).append(".Value||'-'||"); - embedSQL.append(TableName).append(".").append(DisplayColumn); - // - embedSQL.append(" FROM ").append(TableName); - } - - embedSQL.append(" WHERE ").append(BaseTable).append(".").append(BaseColumn); - embedSQL.append("=").append(TableName).append(".").append(KeyColumn); - - return embedSQL.toString(); - } // getLookup_TableEmbed - - - /************************************************************************** - * Get Lookup SQL for direct Table Lookup - * @param ctx context for access - * @param language report language - * @param ColumnName column name - * @param WindowNo Window (for SOTrx) - * @return SELECT Key, NULL, Name, IsActive from Table (fully qualified) - */ - static private MLookupInfo getLookup_TableDir (Properties ctx, Language language, - int WindowNo, String ColumnName) - { - if (!ColumnName.endsWith("_ID")) - { - s_log.log(Level.SEVERE, "Key does not end with '_ID': " + ColumnName); - return null; - } - - // Hardcoded BPartner Org - if (ColumnName.equals("AD_OrgBP_ID")) - ColumnName = "AD_Org_ID"; - - String TableName = ColumnName.substring(0,ColumnName.length()-3); - boolean isSOTrx = !"N".equals(Env.getContext(ctx, WindowNo, "IsSOTrx")); - int ZoomWindow = 0; - int ZoomWindowPO = 0; - - // get display column names - String sql0 = "SELECT c.ColumnName,c.IsTranslated,c.AD_Reference_ID," - + "c.AD_Reference_Value_ID,t.AD_Window_ID,t.PO_Window_ID " - + "FROM AD_Table t" - + " INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) " - + "WHERE TableName=?" - + " AND c.IsIdentifier='Y' " - + "ORDER BY c.SeqNo"; - // - String KeyColumn = ColumnName; - // - ArrayList list = new ArrayList(); - boolean isTranslated = false; - // - try - { - PreparedStatement pstmt = DB.prepareStatement(sql0, null); - pstmt.setString(1, TableName); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - LookupDisplayColumn ldc = new LookupDisplayColumn (rs.getString(1), - "Y".equals(rs.getString(2)), rs.getInt(3), rs.getInt(4)); - list.add (ldc); - // s_log.fine("getLookup_TableDir: " + ColumnName + " - " + ldc); - // - if (!isTranslated && ldc.IsTranslated) - isTranslated = true; - ZoomWindow = rs.getInt(5); - ZoomWindowPO = rs.getInt(6); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, sql0, e); - return null; - } - // Do we have columns ? - if (list.size() == 0) - { - s_log.log(Level.SEVERE, "No Identifier records found: " + ColumnName); - return null; - } - - StringBuffer realSQL = new StringBuffer("SELECT "); - realSQL.append(TableName).append(".").append(KeyColumn).append(",NULL,"); - - StringBuffer displayColumn = new StringBuffer(); - int size = list.size(); - // Get Display Column - for (int i = 0; i < size; i++) - { - if (i > 0) - displayColumn.append(" ||'_'|| " ); - LookupDisplayColumn ldc = (LookupDisplayColumn)list.get(i); - - // translated - if (ldc.IsTranslated && !Env.isBaseLanguage(language, TableName)) - displayColumn.append(TableName).append("_Trl.").append(ldc.ColumnName); - // date - else if (DisplayType.isDate(ldc.DisplayType)) - { - displayColumn.append(DB.TO_CHAR(TableName + "." + ldc.ColumnName, ldc.DisplayType, language.getAD_Language())); - } - // TableDir - else if ((ldc.DisplayType == DisplayType.TableDir || ldc.DisplayType == DisplayType.Search) - && ldc.ColumnName.endsWith("_ID")) - { - String embeddedSQL = getLookup_TableDirEmbed(language, ldc.ColumnName, TableName); - if (embeddedSQL != null) - displayColumn.append("(").append(embeddedSQL).append(")"); - } - // Table - else if (ldc.DisplayType == DisplayType.Table && ldc.AD_Reference_ID != 0) - { - String embeddedSQL = getLookup_TableEmbed (language, ldc.ColumnName, TableName, ldc.AD_Reference_ID); - if (embeddedSQL != null) - displayColumn.append("(").append(embeddedSQL).append(")"); - } - // number - else if (DisplayType.isNumeric(ldc.DisplayType)) - { - displayColumn.append(DB.TO_CHAR(TableName + "." + ldc.ColumnName, ldc.DisplayType, language.getAD_Language())); - } - // String - else - displayColumn.append(TableName).append(".").append(ldc.ColumnName); - } - realSQL.append(displayColumn.toString()); - realSQL.append(",").append(TableName).append(".IsActive"); - - // Translation - if (isTranslated && !Env.isBaseLanguage(language, TableName)) - { - realSQL.append(" FROM ").append(TableName) - .append(" INNER JOIN ").append(TableName).append("_TRL ON (") - .append(TableName).append(".").append(KeyColumn) - .append("=").append(TableName).append("_Trl.").append(KeyColumn) - .append(" AND ").append(TableName).append("_Trl.AD_Language='") - .append(language.getAD_Language()).append("')"); - } - else // no translation - { + if (needToAddSecurity) + info.Query = MRole.getDefault(ctx, false).addAccessSQL(info.Query, + info.TableName, MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); + // + // s_log.finest("Query: " + info.Query); + // s_log.finest("Direct: " + info.QueryDirect); + return info; + } // createLookupInfo + + + /************************************************************************** + * Get Lookup SQL for Lists + * @param language report language + * @param AD_Reference_Value_ID reference value + * @return SELECT NULL, Value, Name, IsActive FROM AD_Ref_List + */ + static public MLookupInfo getLookup_List(Language language, int AD_Reference_Value_ID) + { + StringBuffer realSQL = new StringBuffer ("SELECT NULL, AD_Ref_List.Value,"); + if (Env.isBaseLanguage(language, "AD_Ref_List")) + realSQL.append("AD_Ref_List.Name,AD_Ref_List.IsActive FROM AD_Ref_List"); + else + realSQL.append("trl.Name, AD_Ref_List.IsActive " + + "FROM AD_Ref_List INNER JOIN AD_Ref_List_Trl trl " + + " ON (AD_Ref_List.AD_Ref_List_ID=trl.AD_Ref_List_ID AND trl.AD_Language='") + .append(language.getAD_Language()).append("')"); + realSQL.append(" WHERE AD_Ref_List.AD_Reference_ID=").append(AD_Reference_Value_ID); + realSQL.append(" ORDER BY 2"); + // + return new MLookupInfo(realSQL.toString(), "AD_Ref_List", "AD_Ref_List.Value", + 101,101, MQuery.getEqualQuery("AD_Reference_ID", AD_Reference_Value_ID)); // Zoom Window+Query + } // getLookup_List + + /** + * Get Lookup SQL for List + * @param language report Language + * @param AD_Reference_Value_ID reference value + * @param linkColumnName link column name + * @return SELECT Name FROM AD_Ref_List WHERE AD_Reference_ID=x AND Value=linkColumn + */ + static public String getLookup_ListEmbed(Language language, + int AD_Reference_Value_ID, String linkColumnName) + { + StringBuffer realSQL = new StringBuffer ("SELECT "); + if (Env.isBaseLanguage(language, "AD_Ref_List")) + realSQL.append("AD_Ref_List.Name FROM AD_Ref_List"); + else + realSQL.append("trl.Name " + + "FROM AD_Ref_List INNER JOIN AD_Ref_List_Trl trl " + + " ON (AD_Ref_List.AD_Ref_List_ID=trl.AD_Ref_List_ID AND trl.AD_Language='") + .append(language.getAD_Language()).append("')"); + realSQL.append(" WHERE AD_Ref_List.AD_Reference_ID=").append(AD_Reference_Value_ID) + .append(" AND AD_Ref_List.Value=").append(linkColumnName); + + // + return realSQL.toString(); + } // getLookup_ListEmbed + + /*************************************************************************** + * Get Lookup SQL for Table Lookup + * @param ctx context for access and dynamic access + * @param language report language + * @param WindowNo window no + * @param AD_Reference_Value_ID reference value + * @return SELECT Key, NULL, Name, IsActive FROM Table - if KeyColumn end with _ID + * otherwise SELECT NULL, Key, Name, IsActive FROM Table + */ + static private MLookupInfo getLookup_Table (Properties ctx, Language language, + int WindowNo, int AD_Reference_Value_ID) + { + // Try cache - assume no language change + String key = String.valueOf(AD_Reference_Value_ID); + MLookupInfo retValue = (MLookupInfo)s_cacheRefTable.get(key); + if (retValue != null) + { + s_log.finest("Cache: " + retValue); + return retValue.cloneIt(); + } + // + String sql0 = "SELECT t.TableName,ck.ColumnName AS KeyColumn," // 1..2 + + "cd.ColumnName AS DisplayColumn,rt.IsValueDisplayed,cd.IsTranslated," // 3..5 + + "rt.WhereClause,rt.OrderByClause,t.AD_Window_ID,t.PO_Window_ID, " // 6..9 + + "t.AD_Table_ID " // 10 + + "FROM AD_Ref_Table rt" + + " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID)" + + " INNER JOIN AD_Column ck ON (rt.AD_Key=ck.AD_Column_ID)" + + " INNER JOIN AD_Column cd ON (rt.AD_Display=cd.AD_Column_ID) " + + "WHERE rt.AD_Reference_ID=?" + + " AND rt.IsActive='Y' AND t.IsActive='Y'"; + // + String KeyColumn = null, DisplayColumn = null, TableName = null, WhereClause = null, OrderByClause = null; + boolean IsTranslated = false, isValueDisplayed = false; + boolean isSOTrx = !"N".equals(Env.getContext(ctx, WindowNo, "IsSOTrx")); + int ZoomWindow = 0; + int ZoomWindowPO = 0; + int AD_Table_ID = 0; + boolean loaded = false; + + try + { + PreparedStatement pstmt = DB.prepareStatement(sql0, null); + pstmt.setInt(1, AD_Reference_Value_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + TableName = rs.getString(1); + KeyColumn = rs.getString(2); + DisplayColumn = rs.getString(3); + isValueDisplayed = "Y".equals(rs.getString(4)); + IsTranslated = "Y".equals(rs.getString(5)); + WhereClause = rs.getString(6); + OrderByClause = rs.getString(7); + ZoomWindow = rs.getInt(8); + ZoomWindowPO = rs.getInt(9); + AD_Table_ID = rs.getInt(10); + loaded = true; + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, sql0, e); + return null; + } + if (!loaded) + { + s_log.log(Level.SEVERE, "No Table Reference Table ID=" + AD_Reference_Value_ID); + return null; + } + + StringBuffer realSQL = new StringBuffer("SELECT "); + if (!KeyColumn.endsWith("_ID")) + realSQL.append("NULL,"); + + // Translated + if (IsTranslated && !Env.isBaseLanguage(language, TableName)) + { + realSQL.append(TableName).append(".").append(KeyColumn).append(","); + if (KeyColumn.endsWith("_ID")) + realSQL.append("NULL,"); + if (isValueDisplayed) + realSQL.append(TableName).append(".Value || '-' || "); + realSQL.append(TableName).append("_Trl.").append(DisplayColumn) + .append(",").append(TableName).append(".IsActive"); + realSQL.append(" FROM ").append(TableName) + .append(" INNER JOIN ").append(TableName).append("_TRL ON (") + .append(TableName).append(".").append(KeyColumn) + .append("=").append(TableName).append("_Trl.").append(KeyColumn) + .append(" AND ").append(TableName).append("_Trl.AD_Language='") + .append(language.getAD_Language()).append("')"); + } + // Not Translated + else + { + realSQL.append(TableName).append(".").append(KeyColumn).append(","); + if (KeyColumn.endsWith("_ID")) + realSQL.append("NULL,"); + if (isValueDisplayed) + realSQL.append(TableName).append(".Value || '-' || "); + realSQL.append(TableName).append(".").append(DisplayColumn); + realSQL.append(",").append(TableName).append(".IsActive"); realSQL.append(" FROM ").append(TableName); } - // Order by Display - if (DB.isDerby()) //jz derby restriction + // add WHERE clause + MQuery zoomQuery = null; + if (WhereClause != null) { - if (size > 3) - realSQL.append(" ORDER BY " + ((LookupDisplayColumn)list.get(2)).ColumnName); + String where = WhereClause; + if (where.indexOf("@") != -1) + where = Env.parseContext(ctx, WindowNo, where, false); + if (where.length() == 0 && WhereClause.length() != 0) + s_log.severe ("Could not resolve: " + WhereClause); + + // We have no context + if (where.length() != 0) + { + realSQL.append(" WHERE ").append(where); + if (where.indexOf(".") == -1) + s_log.log(Level.SEVERE, "getLookup_Table - " + TableName + + ": WHERE should be fully qualified: " + WhereClause); + zoomQuery = new MQuery (TableName); + zoomQuery.addRestriction(where); + } } - else + + // Order By qualified term or by Name + if (OrderByClause != null) + { + realSQL.append(" ORDER BY ").append(OrderByClause); + if (OrderByClause.indexOf(".") == -1) + s_log.log(Level.SEVERE, "getLookup_Table - " + TableName + + ": ORDER BY must fully qualified: " + OrderByClause); + } + else realSQL.append(" ORDER BY 3"); + + s_log.finest("AD_Reference_Value_ID=" + AD_Reference_Value_ID + " - " + realSQL); + retValue = new MLookupInfo (realSQL.toString(), TableName, + TableName + "." + KeyColumn, ZoomWindow, ZoomWindowPO, zoomQuery); + s_cacheRefTable.put(key, retValue.cloneIt()); + return retValue; + } // getLookup_Table + + /** + * Get Embedded Lookup SQL for Table Lookup + * @param language report language + * @param BaseColumn base column name + * @param BaseTable base table name + * @param AD_Reference_Value_ID reference value + * @return SELECT Name FROM Table + */ + static public String getLookup_TableEmbed (Language language, + String BaseColumn, String BaseTable, int AD_Reference_Value_ID) + { + String sql = "SELECT t.TableName,ck.ColumnName AS KeyColumn," + + "cd.ColumnName AS DisplayColumn,rt.isValueDisplayed,cd.IsTranslated " + + "FROM AD_Ref_Table rt" + + " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID)" + + " INNER JOIN AD_Column ck ON (rt.AD_Key=ck.AD_Column_ID)" + + " INNER JOIN AD_Column cd ON (rt.AD_Display=cd.AD_Column_ID) " + + "WHERE rt.AD_Reference_ID=?" + + " AND rt.IsActive='Y' AND t.IsActive='Y'"; + // + String KeyColumn, DisplayColumn, TableName; + boolean IsTranslated, isValueDisplayed; + + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Reference_Value_ID); + ResultSet rs = pstmt.executeQuery(); + if (!rs.next()) + { + s_log.log(Level.SEVERE, "Cannot find Reference Table, ID=" + AD_Reference_Value_ID + + ", Base=" + BaseTable + "." + BaseColumn); + rs.close(); + pstmt.close(); + return null; + } + + TableName = rs.getString(1); + KeyColumn = rs.getString(2); + DisplayColumn = rs.getString(3); + isValueDisplayed = rs.getString(4).equals("Y"); + IsTranslated = rs.getString(5).equals("Y"); + + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, sql, e); + return null; + } + + StringBuffer embedSQL = new StringBuffer("SELECT "); + + // Translated + if (IsTranslated && !Env.isBaseLanguage(language, TableName)) + { + if (isValueDisplayed) + embedSQL.append(TableName).append(".Value||'-'||"); + embedSQL.append(TableName).append("_Trl.").append(DisplayColumn); + // + embedSQL.append(" FROM ").append(TableName) + .append(" INNER JOIN ").append(TableName).append("_TRL ON (") + .append(TableName).append(".").append(KeyColumn) + .append("=").append(TableName).append("_Trl.").append(KeyColumn) + .append(" AND ").append(TableName).append("_Trl.AD_Language='") + .append(language.getAD_Language()).append("')"); + } + // Not Translated + else + { + if (isValueDisplayed) + embedSQL.append(TableName).append(".Value||'-'||"); + embedSQL.append(TableName).append(".").append(DisplayColumn); + // + embedSQL.append(" FROM ").append(TableName); + } + + embedSQL.append(" WHERE ").append(BaseTable).append(".").append(BaseColumn); + embedSQL.append("=").append(TableName).append(".").append(KeyColumn); + + return embedSQL.toString(); + } // getLookup_TableEmbed + + + /************************************************************************** + * Get Lookup SQL for direct Table Lookup + * @param ctx context for access + * @param language report language + * @param ColumnName column name + * @param WindowNo Window (for SOTrx) + * @return SELECT Key, NULL, Name, IsActive from Table (fully qualified) + */ + static private MLookupInfo getLookup_TableDir (Properties ctx, Language language, + int WindowNo, String ColumnName) + { + if (!ColumnName.endsWith("_ID")) + { + s_log.log(Level.SEVERE, "Key does not end with '_ID': " + ColumnName); + return null; + } + + // Hardcoded BPartner Org + if (ColumnName.equals("AD_OrgBP_ID")) + ColumnName = "AD_Org_ID"; + + String TableName = ColumnName.substring(0,ColumnName.length()-3); + boolean isSOTrx = !"N".equals(Env.getContext(ctx, WindowNo, "IsSOTrx")); + int ZoomWindow = 0; + int ZoomWindowPO = 0; + + // get display column names + String sql0 = "SELECT c.ColumnName,c.IsTranslated,c.AD_Reference_ID," + + "c.AD_Reference_Value_ID,t.AD_Window_ID,t.PO_Window_ID " + + "FROM AD_Table t" + + " INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) " + + "WHERE TableName=?" + + " AND c.IsIdentifier='Y' " + + "ORDER BY c.SeqNo"; + // + String KeyColumn = ColumnName; + // + ArrayList list = new ArrayList(); + boolean isTranslated = false; + // + try + { + PreparedStatement pstmt = DB.prepareStatement(sql0, null); + pstmt.setString(1, TableName); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + LookupDisplayColumn ldc = new LookupDisplayColumn (rs.getString(1), + "Y".equals(rs.getString(2)), rs.getInt(3), rs.getInt(4)); + list.add (ldc); + // s_log.fine("getLookup_TableDir: " + ColumnName + " - " + ldc); + // + if (!isTranslated && ldc.IsTranslated) + isTranslated = true; + ZoomWindow = rs.getInt(5); + ZoomWindowPO = rs.getInt(6); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, sql0, e); + return null; + } + // Do we have columns ? + if (list.size() == 0) + { + s_log.log(Level.SEVERE, "No Identifier records found: " + ColumnName); + return null; + } + + StringBuffer realSQL = new StringBuffer("SELECT "); + realSQL.append(TableName).append(".").append(KeyColumn).append(",NULL,"); + + StringBuffer displayColumn = new StringBuffer(); + int size = list.size(); + // Get Display Column + for (int i = 0; i < size; i++) + { + if (i > 0) + displayColumn.append(" ||'_'|| " ); + LookupDisplayColumn ldc = (LookupDisplayColumn)list.get(i); + + // translated + if (ldc.IsTranslated && !Env.isBaseLanguage(language, TableName)) + displayColumn.append(TableName).append("_Trl.").append(ldc.ColumnName); + // date + else if (DisplayType.isDate(ldc.DisplayType)) + { + displayColumn.append(DB.TO_CHAR(TableName + "." + ldc.ColumnName, ldc.DisplayType, language.getAD_Language())); + } + // TableDir + else if ((ldc.DisplayType == DisplayType.TableDir || ldc.DisplayType == DisplayType.Search) + && ldc.ColumnName.endsWith("_ID")) + { + String embeddedSQL = getLookup_TableDirEmbed(language, ldc.ColumnName, TableName); + if (embeddedSQL != null) + displayColumn.append("(").append(embeddedSQL).append(")"); + } + // Table + else if (ldc.DisplayType == DisplayType.Table && ldc.AD_Reference_ID != 0) + { + String embeddedSQL = getLookup_TableEmbed (language, ldc.ColumnName, TableName, ldc.AD_Reference_ID); + if (embeddedSQL != null) + displayColumn.append("(").append(embeddedSQL).append(")"); + } + // number + else if (DisplayType.isNumeric(ldc.DisplayType)) + { + displayColumn.append(DB.TO_CHAR(TableName + "." + ldc.ColumnName, ldc.DisplayType, language.getAD_Language())); + } + // String + else + displayColumn.append(TableName).append(".").append(ldc.ColumnName); + } + realSQL.append(displayColumn.toString()); + realSQL.append(",").append(TableName).append(".IsActive"); + + // Translation + if (isTranslated && !Env.isBaseLanguage(language, TableName)) + { + realSQL.append(" FROM ").append(TableName) + .append(" INNER JOIN ").append(TableName).append("_TRL ON (") + .append(TableName).append(".").append(KeyColumn) + .append("=").append(TableName).append("_Trl.").append(KeyColumn) + .append(" AND ").append(TableName).append("_Trl.AD_Language='") + .append(language.getAD_Language()).append("')"); + } + else // no translation + { + realSQL.append(" FROM ").append(TableName); + } + + // Order by Display + realSQL.append(" ORDER BY 3"); MQuery zoomQuery = null; // corrected in VLookup if (CLogMgt.isLevelFinest()) - s_log.fine("ColumnName=" + ColumnName + " - " + realSQL); - MLookupInfo lInfo = new MLookupInfo(realSQL.toString(), TableName, - TableName + "." + KeyColumn, ZoomWindow, ZoomWindowPO, zoomQuery); - return lInfo; - } // getLookup_TableDir - - - /** - * Get embedded SQL for TableDir Lookup (no translation) - * - * @param language report language - * @param ColumnName column name - * @param BaseTable base table - * @return SELECT Column FROM TableName WHERE BaseTable.ColumnName=TableName.ColumnName - */ - static public String getLookup_TableDirEmbed (Language language, String ColumnName, String BaseTable) - { - return getLookup_TableDirEmbed (language, ColumnName, BaseTable, ColumnName); - } // getLookup_TableDirEmbed - - /** - * Get embedded SQL for TableDir Lookup (no translation) - * - * @param language report language - * @param ColumnName column name - * @param BaseTable base table - * @param BaseColumn base column - * @return SELECT Column FROM TableName WHERE BaseTable.BaseColumn=TableName.ColumnName - */ - static public String getLookup_TableDirEmbed (Language language, - String ColumnName, String BaseTable, String BaseColumn) - { - String TableName = ColumnName.substring(0,ColumnName.length()-3); - - // get display column name (first identifier column) - String sql = "SELECT c.ColumnName,c.IsTranslated,c.AD_Reference_ID,c.AD_Reference_Value_ID " - + "FROM AD_Table t INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) " - + "WHERE TableName=?" - + " AND c.IsIdentifier='Y' " - + "ORDER BY c.SeqNo"; - // - ArrayList list = new ArrayList(); - // - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setString(1, TableName); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - LookupDisplayColumn ldc = new LookupDisplayColumn (rs.getString(1), - "Y".equals(rs.getString(2)), rs.getInt(3), rs.getInt(4)); - list.add (ldc); - // s_log.fine("getLookup_TableDirEmbed: " + ColumnName + " - " + ldc); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, sql, e); - return ""; - } - // Do we have columns ? - if (list.size() == 0) - { - s_log.log(Level.SEVERE, "No Identifier records found: " + ColumnName); - return ""; - } - - // - StringBuffer embedSQL = new StringBuffer("SELECT "); - - int size = list.size(); - for (int i = 0; i < size; i++) - { - if (i > 0) - embedSQL.append("||' - '||" ); - LookupDisplayColumn ldc = (LookupDisplayColumn)list.get(i); - - // date, number - if (DisplayType.isDate(ldc.DisplayType) || DisplayType.isNumeric(ldc.DisplayType)) - { - embedSQL.append(DB.TO_CHAR(TableName + "." + ldc.ColumnName, ldc.DisplayType, language.getAD_Language())); - } - // TableDir - else if ((ldc.DisplayType == DisplayType.TableDir || ldc.DisplayType == DisplayType.Search) - && ldc.ColumnName.endsWith("_ID")) - { - String embeddedSQL = getLookup_TableDirEmbed(language, ldc.ColumnName, TableName); - embedSQL.append("(").append(embeddedSQL).append(")"); - } - // String - else - embedSQL.append(TableName).append(".").append(ldc.ColumnName); - } - - embedSQL.append(" FROM ").append(TableName); - embedSQL.append(" WHERE ").append(BaseTable).append(".").append(BaseColumn); - embedSQL.append("=").append(TableName).append(".").append(ColumnName); - // - return embedSQL.toString(); - } // getLookup_TableDirEmbed - -} // MLookupFactory - + s_log.fine("ColumnName=" + ColumnName + " - " + realSQL); + MLookupInfo lInfo = new MLookupInfo(realSQL.toString(), TableName, + TableName + "." + KeyColumn, ZoomWindow, ZoomWindowPO, zoomQuery); + return lInfo; + } // getLookup_TableDir + + + /** + * Get embedded SQL for TableDir Lookup (no translation) + * + * @param language report language + * @param ColumnName column name + * @param BaseTable base table + * @return SELECT Column FROM TableName WHERE BaseTable.ColumnName=TableName.ColumnName + */ + static public String getLookup_TableDirEmbed (Language language, String ColumnName, String BaseTable) + { + return getLookup_TableDirEmbed (language, ColumnName, BaseTable, ColumnName); + } // getLookup_TableDirEmbed + + /** + * Get embedded SQL for TableDir Lookup (no translation) + * + * @param language report language + * @param ColumnName column name + * @param BaseTable base table + * @param BaseColumn base column + * @return SELECT Column FROM TableName WHERE BaseTable.BaseColumn=TableName.ColumnName + */ + static public String getLookup_TableDirEmbed (Language language, + String ColumnName, String BaseTable, String BaseColumn) + { + String TableName = ColumnName.substring(0,ColumnName.length()-3); + + // get display column name (first identifier column) + String sql = "SELECT c.ColumnName,c.IsTranslated,c.AD_Reference_ID,c.AD_Reference_Value_ID " + + "FROM AD_Table t INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) " + + "WHERE TableName=?" + + " AND c.IsIdentifier='Y' " + + "ORDER BY c.SeqNo"; + // + ArrayList list = new ArrayList(); + // + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setString(1, TableName); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + LookupDisplayColumn ldc = new LookupDisplayColumn (rs.getString(1), + "Y".equals(rs.getString(2)), rs.getInt(3), rs.getInt(4)); + list.add (ldc); + // s_log.fine("getLookup_TableDirEmbed: " + ColumnName + " - " + ldc); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, sql, e); + return ""; + } + // Do we have columns ? + if (list.size() == 0) + { + s_log.log(Level.SEVERE, "No Identifier records found: " + ColumnName); + return ""; + } + + // + StringBuffer embedSQL = new StringBuffer("SELECT "); + + int size = list.size(); + for (int i = 0; i < size; i++) + { + if (i > 0) + embedSQL.append("||' - '||" ); + LookupDisplayColumn ldc = (LookupDisplayColumn)list.get(i); + + // date, number + if (DisplayType.isDate(ldc.DisplayType) || DisplayType.isNumeric(ldc.DisplayType)) + { + embedSQL.append(DB.TO_CHAR(TableName + "." + ldc.ColumnName, ldc.DisplayType, language.getAD_Language())); + } + // TableDir + else if ((ldc.DisplayType == DisplayType.TableDir || ldc.DisplayType == DisplayType.Search) + && ldc.ColumnName.endsWith("_ID")) + { + String embeddedSQL = getLookup_TableDirEmbed(language, ldc.ColumnName, TableName); + embedSQL.append("(").append(embeddedSQL).append(")"); + } + // String + else + embedSQL.append(TableName).append(".").append(ldc.ColumnName); + } + + embedSQL.append(" FROM ").append(TableName); + embedSQL.append(" WHERE ").append(BaseTable).append(".").append(BaseColumn); + embedSQL.append("=").append(TableName).append(".").append(ColumnName); + // + return embedSQL.toString(); + } // getLookup_TableDirEmbed + +} // MLookupFactory + diff --git a/dbPort/src/org/compiere/model/MOrg.java b/dbPort/src/org/compiere/model/MOrg.java index 9b43486bb5..a4fd6ca246 100644 --- a/dbPort/src/org/compiere/model/MOrg.java +++ b/dbPort/src/org/compiere/model/MOrg.java @@ -3,224 +3,217 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.model; - -import java.sql.*; -import java.util.*; -import java.util.logging.*; -import org.compiere.util.*; - -/** - * Organization Model - * - * @author Jorg Janke - * @version $Id: MOrg.java,v 1.3 2006/07/30 00:58:04 jjanke Exp $ - */ -public class MOrg extends X_AD_Org -{ - /** - * Get Organizations Of Client - * @param po persistent object - * @return array of orgs - */ - public static MOrg[] getOfClient (PO po) - { - ArrayList list = new ArrayList(); - String sql = "SELECT * FROM AD_Org WHERE AD_Client_ID=? ORDER BY Value"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, po.getAD_Client_ID()); - ResultSet rs = pstmt.executeQuery (); - while (rs.next ()) - list.add (new MOrg (po.getCtx(), rs, null)); - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - s_log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - - MOrg[] retValue = new MOrg[list.size ()]; - list.toArray (retValue); - return retValue; - } // getOfClient - - /** - * Get Org from Cache - * @param ctx context - * @param AD_Org_ID id - * @return MOrg - */ - public static MOrg get (Properties ctx, int AD_Org_ID) - { - Integer key = new Integer (AD_Org_ID); - MOrg retValue = (MOrg) s_cache.get (key); - if (retValue != null) - return retValue; - retValue = new MOrg (ctx, AD_Org_ID, null); - if (retValue.get_ID () != 0) - s_cache.put (key, retValue); - return retValue; - } // get - - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (MOrg.class); - /** Cache */ - private static CCache s_cache = new CCache("AD_Org", 20); - - - /************************************************************************** - * Standard Constructor - * @param ctx context - * @param AD_Org_ID id - * @param trxName transaction - */ - public MOrg (Properties ctx, int AD_Org_ID, String trxName) - { - super(ctx, AD_Org_ID, trxName); - if (AD_Org_ID == 0) - { - // setValue (null); - // setName (null); - setIsSummary (false); - } - } // MOrg - - /** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName transaction - */ - public MOrg (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MOrg - - /** - * Parent Constructor - * @param client client - * @param name name - */ - public MOrg (MClient client, String name) - { - this (client.getCtx(), 0, client.get_TrxName()); - setAD_Client_ID (client.getAD_Client_ID()); - setValue (name); - setName (name); - } // MOrg - - /** Org Info */ - private MOrgInfo m_info = null; - /** Linked Business Partner */ - private Integer m_linkedBPartner = null; - - /** - * Get Org Info - * @return Org Info - */ - public MOrgInfo getInfo() - { - if (m_info == null) - m_info = MOrgInfo.get (getCtx(), getAD_Org_ID()); - return m_info; - } // getMOrgInfo - - - - /** - * After Save - * @param newRecord new Record - * @param success save success - * @return success - */ - protected boolean afterSave (boolean newRecord, boolean success) - { - if (!success) - return success; - if (newRecord) - { - // Info - m_info = new MOrgInfo (this); - m_info.save(); - // Access - MRoleOrgAccess.createForOrg (this); - MRole.getDefault(getCtx(), true); // reload - // TreeNode - insert_Tree(MTree_Base.TREETYPE_Organization); - } - // Value/Name change - if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) - { - MAccount.updateValueDescription(getCtx(), "AD_Org_ID=" + getAD_Org_ID(), get_TrxName()); - if ("Y".equals(Env.getContext(getCtx(), "$Element_OT"))) - MAccount.updateValueDescription(getCtx(), "AD_OrgTrx_ID=" + getAD_Org_ID(), get_TrxName()); - } - - return true; - } // afterSave - - /** - * After Delete - * @param success - * @return deleted - */ - protected boolean afterDelete (boolean success) - { - if (success) - delete_Tree(MTree_Base.TREETYPE_Organization); - return success; - } // afterDelete - - - /** - * Get Linked BPartner - * @return C_BPartner_ID + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.model; + +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Organization Model + * + * @author Jorg Janke + * @version $Id: MOrg.java,v 1.3 2006/07/30 00:58:04 jjanke Exp $ + */ +public class MOrg extends X_AD_Org +{ + /** + * Get Organizations Of Client + * @param po persistent object + * @return array of orgs + */ + public static MOrg[] getOfClient (PO po) + { + ArrayList list = new ArrayList(); + String sql = "SELECT * FROM AD_Org WHERE AD_Client_ID=? ORDER BY Value"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, po.getAD_Client_ID()); + ResultSet rs = pstmt.executeQuery (); + while (rs.next ()) + list.add (new MOrg (po.getCtx(), rs, null)); + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + s_log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + + MOrg[] retValue = new MOrg[list.size ()]; + list.toArray (retValue); + return retValue; + } // getOfClient + + /** + * Get Org from Cache + * @param ctx context + * @param AD_Org_ID id + * @return MOrg + */ + public static MOrg get (Properties ctx, int AD_Org_ID) + { + Integer key = new Integer (AD_Org_ID); + MOrg retValue = (MOrg) s_cache.get (key); + if (retValue != null) + return retValue; + retValue = new MOrg (ctx, AD_Org_ID, null); + if (retValue.get_ID () != 0) + s_cache.put (key, retValue); + return retValue; + } // get + + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (MOrg.class); + /** Cache */ + private static CCache s_cache = new CCache("AD_Org", 20); + + + /************************************************************************** + * Standard Constructor + * @param ctx context + * @param AD_Org_ID id + * @param trxName transaction + */ + public MOrg (Properties ctx, int AD_Org_ID, String trxName) + { + super(ctx, AD_Org_ID, trxName); + if (AD_Org_ID == 0) + { + // setValue (null); + // setName (null); + setIsSummary (false); + } + } // MOrg + + /** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName transaction + */ + public MOrg (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MOrg + + /** + * Parent Constructor + * @param client client + * @param name name + */ + public MOrg (MClient client, String name) + { + this (client.getCtx(), 0, client.get_TrxName()); + setAD_Client_ID (client.getAD_Client_ID()); + setValue (name); + setName (name); + } // MOrg + + /** Org Info */ + private MOrgInfo m_info = null; + /** Linked Business Partner */ + private Integer m_linkedBPartner = null; + + /** + * Get Org Info + * @return Org Info + */ + public MOrgInfo getInfo() + { + if (m_info == null) + m_info = MOrgInfo.get (getCtx(), getAD_Org_ID()); + return m_info; + } // getMOrgInfo + + + + /** + * After Save + * @param newRecord new Record + * @param success save success + * @return success + */ + protected boolean afterSave (boolean newRecord, boolean success) + { + if (!success) + return success; + if (newRecord) + { + // Info + m_info = new MOrgInfo (this); + m_info.save(); + // Access + MRoleOrgAccess.createForOrg (this); + MRole.getDefault(getCtx(), true); // reload + // TreeNode + insert_Tree(MTree_Base.TREETYPE_Organization); + } + // Value/Name change + if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) + { + MAccount.updateValueDescription(getCtx(), "AD_Org_ID=" + getAD_Org_ID(), get_TrxName()); + if ("Y".equals(Env.getContext(getCtx(), "$Element_OT"))) + MAccount.updateValueDescription(getCtx(), "AD_OrgTrx_ID=" + getAD_Org_ID(), get_TrxName()); + } + + return true; + } // afterSave + + /** + * After Delete + * @param success + * @return deleted + */ + protected boolean afterDelete (boolean success) + { + if (success) + delete_Tree(MTree_Base.TREETYPE_Organization); + return success; + } // afterDelete + + + /** + * Get Linked BPartner + * @return C_BPartner_ID */ public int getLinkedC_BPartner_ID() - { - return getLinkedC_BPartner_ID(null); - } - - - public int getLinkedC_BPartner_ID(String trxName) { if (m_linkedBPartner == null) { - //jz int C_BPartner_ID = DB.getSQLValue(null, - int C_BPartner_ID = DB.getSQLValue(trxName, + int C_BPartner_ID = DB.getSQLValue(null, "SELECT C_BPartner_ID FROM C_BPartner WHERE AD_OrgBP_ID=?", getAD_Org_ID()); if (C_BPartner_ID < 0) // not found = -1 - C_BPartner_ID = 0; - m_linkedBPartner = new Integer (C_BPartner_ID); - } - return m_linkedBPartner.intValue(); - } // getLinkedC_BPartner_ID - -} // MOrg + C_BPartner_ID = 0; + m_linkedBPartner = new Integer (C_BPartner_ID); + } + return m_linkedBPartner.intValue(); + } // getLinkedC_BPartner_ID + +} // MOrg diff --git a/dbPort/src/org/compiere/model/MOrgInfo.java b/dbPort/src/org/compiere/model/MOrgInfo.java index 1ce1385bc3..ec2df28b35 100644 --- a/dbPort/src/org/compiere/model/MOrgInfo.java +++ b/dbPort/src/org/compiere/model/MOrgInfo.java @@ -1,56 +1,55 @@ /****************************************************************************** - * Product: Compiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.model; - -import java.sql.*; -import java.util.*; - -import java.util.logging.*; -import org.compiere.util.*; - -/** - * Organization Info Model - * - * @author Jorg Janke - * @version $Id: MOrgInfo.java,v 1.3 2006/07/30 00:58:37 jjanke Exp $ - */ -public class MOrgInfo extends X_AD_OrgInfo -{ - /** - * Load Constructor - * @param ctx context - * @param AD_Org_ID id - * @return Org Info - */ - public static MOrgInfo get (Properties ctx, int AD_Org_ID) - { - MOrgInfo retValue = null; - String sql = "SELECT * FROM AD_OrgInfo WHERE AD_Org_ID=?"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Org_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = new MOrgInfo (ctx, rs, null); - rs.close(); - pstmt.close(); - pstmt = null; + * Product: Adempiere ERP & CRM Smart Business Solution + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. + * This program is free software; you can redistribute it and/or modify it + * under the terms version 2 of the GNU General Public License as published + * by the Free Software Foundation. This program is distributed in the hope + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * You may reach us at: ComPiere, Inc. - http://www.compiere.org/license.html + * 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA or info@compiere.org + *****************************************************************************/ +package org.compiere.model; + +import java.sql.*; +import java.util.*; + +import java.util.logging.*; +import org.compiere.util.*; + +/** + * Organization Info Model + * + * @author Jorg Janke + * @version $Id: MOrgInfo.java,v 1.3 2006/07/30 00:58:37 jjanke Exp $ + */ +public class MOrgInfo extends X_AD_OrgInfo +{ + /** + * Load Constructor + * @param ctx context + * @param AD_Org_ID id + * @return Org Info + */ + public static MOrgInfo get (Properties ctx, int AD_Org_ID) + { + MOrgInfo retValue = null; + String sql = "SELECT * FROM AD_OrgInfo WHERE AD_Org_ID=?"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Org_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = new MOrgInfo (ctx, rs, null); + rs.close(); + pstmt.close(); + pstmt = null; } catch (Exception e) { @@ -58,42 +57,42 @@ public class MOrgInfo extends X_AD_OrgInfo } try { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - return retValue; - } // get - - /** Static Logger */ - private static CLogger s_log = CLogger.getCLogger (MOrgInfo.class); - - - /************************************************************************** - * Load Constructor - * @param ctx context - * @param rs result set - * @param trxName transaction - */ - public MOrgInfo (Properties ctx, ResultSet rs, String trxName) - { - super(ctx, rs, trxName); - } // MOrgInfo - - /** - * Organization constructor - * @param org org - */ - public MOrgInfo (MOrg org) - { - super(org.getCtx(), 0, org.get_TrxName()); - setClientOrg(org); - setDUNS ("?"); - setTaxID ("?"); - } // MOrgInfo - -} // MOrgInfo + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + return retValue; + } // get + + /** Static Logger */ + private static CLogger s_log = CLogger.getCLogger (MOrgInfo.class); + + + /************************************************************************** + * Load Constructor + * @param ctx context + * @param rs result set + * @param trxName transaction + */ + public MOrgInfo (Properties ctx, ResultSet rs, String trxName) + { + super(ctx, rs, trxName); + } // MOrgInfo + + /** + * Organization constructor + * @param org org + */ + public MOrgInfo (MOrg org) + { + super(org.getCtx(), 0, org.get_TrxName()); + setClientOrg(org); + setDUNS ("?"); + setTaxID ("?"); + } // MOrgInfo + +} // MOrgInfo diff --git a/dbPort/src/org/compiere/util/AmtInWords_IN.java b/dbPort/src/org/compiere/util/AmtInWords_IN.java index c06c0763bc..4ef250e639 100644 --- a/dbPort/src/org/compiere/util/AmtInWords_IN.java +++ b/dbPort/src/org/compiere/util/AmtInWords_IN.java @@ -3,17 +3,18 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ + package org.compiere.util; /** @@ -24,225 +25,240 @@ package org.compiere.util; */ public class AmtInWords_IN implements AmtInWords { - /** - * AmtInWords_IN - */ - public AmtInWords_IN () - { - super (); - } // AmtInWords_IN - - private static final String[] basenumbers = new String[]{ - "Nol", - "Satu", - "Dua", - "Tiga", - "Empat", - "Lima", - "Enam", - "Tujuh", - "Delapan", - "Sembilan", + /** + * AmtInWords_IN + */ + public AmtInWords_IN () + { + super (); + } // AmtInWords_IN + + private static final String[] basenumbers = new String[]{ + "Nol", + "Satu", + "Dua", + "Tiga", + "Empat", + "Lima", + "Enam", + "Tujuh", + "Delapan", + "Sembilan", "Sepuluh", "Sebelas", }; + private static final long POWER_THREE = 1000L; private static final long POWER_SIX = 1000000L; private static final long POWER_NINE = 1000000000L; private static final long POWER_TWELVE = 1000000000000L; private static final long POWER_FIFTEEN = 1000000000000000L; + + /** Static Logger */ + private static CLogger s_log = CLogger.getCLogger (AmtInWords_IN.class); //-------------------------- STATIC METHODS -------------------------- - /** - * Convenient method for {@link #sayNumber(StringBuffer, long)}. - * + /** + * Convenient method for {@link #sayNumber(StringBuffer, long)}. + * * @param number number to say * @return said number */ - public static String sayNumber(long number) { + public static String sayNumber(double number) { StringBuffer result = new StringBuffer(); sayNumber(result, number); + result.append(" Rupiah"); return result.toString(); } - /** - * Say a number. This method will append the result to the given string buffer. - * - * @param appendTo the string buffer - * @param number number to say + /** + * Say a number. This method will append the result to the given string buffer. + * + * @param appendTo the string buffer + * @param number number to say * @return said number * @throws IllegalArgumentException if the number equals to {@link Long#MIN_VALUE} */ - public static String sayNumber(StringBuffer appendTo, long number) + public static String sayNumber(StringBuffer appendTo, double number) throws IllegalArgumentException { - if (number == Long.MIN_VALUE) { + if (number == Double.MIN_VALUE) { throw new IllegalArgumentException("Out of range"); } if (number < 0) { appendTo.append("Minus "); } - long abs = Math.abs(number); + double abs = Math.abs(number); + // s_log.warning("Debug=" + abs); if (abs < POWER_THREE) { saySimpleNumber(appendTo, (int) abs); + } else if (abs < 2000) { + int thousand = (int) (abs % POWER_THREE); + appendTo.append("Seribu "); + saySimpleNumber(appendTo, thousand); } else if (abs < POWER_SIX) { int thousand = (int) (abs % POWER_SIX / POWER_THREE); saySimpleNumber(appendTo, thousand); appendTo.append(" Ribu"); - long remainder = abs - thousand * POWER_THREE; + double remainder = abs - thousand * POWER_THREE; if (remainder > 0) { appendTo.append(' '); sayNumber(appendTo, remainder); - } - } else if (abs < POWER_NINE) { + } + } else if (abs < POWER_NINE) { int million = (int) (abs % POWER_NINE / POWER_SIX); saySimpleNumber(appendTo, million); appendTo.append(" Juta"); - long remainder = abs - million * POWER_SIX; + double remainder = abs - million * POWER_SIX; if (remainder > 0) { appendTo.append(' '); sayNumber(appendTo, remainder); - } - } else if (abs < POWER_TWELVE) { + } + } else if (abs < POWER_TWELVE) { int billion = (int) (abs % POWER_TWELVE / POWER_NINE); saySimpleNumber(appendTo, billion); appendTo.append(" Milyar"); - long remainder = abs - billion * POWER_NINE; + double remainder = abs - billion * POWER_NINE; if (remainder > 0) { appendTo.append(' '); sayNumber(appendTo, remainder); - } - } else if (abs < POWER_FIFTEEN) { + } + } else if (abs < POWER_FIFTEEN) { int trillion = (int) (abs % POWER_FIFTEEN / POWER_TWELVE); saySimpleNumber(appendTo, trillion); appendTo.append(" Trilyun"); - long remainder = abs - trillion * POWER_TWELVE; + double remainder = abs - trillion * POWER_TWELVE; if (remainder > 0) { appendTo.append(' '); sayNumber(appendTo, remainder); } } else { - int log = (int) Math.floor(Math.log(abs) / Math.log(10)); - - // we want to break the number to several billions. - int logWhole = log - log % 12; - - long powerWhole = (long) Math.pow(10, logWhole); - - long part = abs / powerWhole; - sayNumber(appendTo, part); - appendTo.append(" Trilyun"); - - long remainder = abs - part * powerWhole; - if (remainder > 0) { - appendTo.append(' '); - sayNumber(appendTo, remainder); - } + appendTo.append("Lebih Dari Seribu Triliun"); } return appendTo.toString(); } - - - - static void saySimpleNumber(StringBuffer appendTo, int number) { - - - assert number < 1000 && number >= 0: "Must be between 0 and 1000"; - - if (number < 12) { - assert number < 12 && number >= 0: "Must be between 0 and 11"; - appendTo.append(basenumbers[number]); - } else if (number < 20) { - assert number >= 12 && number <= 19: "Must be between 12 and 19"; - int belasan = number % 10; - appendTo.append(basenumbers[belasan]); - appendTo.append(" Belas"); - } else if (number < 100) { - assert number >= 20 && number <= 99: "Must be between 20 and 99"; - int puluhan = number / 10; - appendTo.append(basenumbers[puluhan]); - appendTo.append(" Puluh"); - int remainder = number - puluhan * 10; - if (remainder > 0) { + + + + static void saySimpleNumber(StringBuffer appendTo, int number) { + + + assert number < 1000 && number >= 0: "Must be between 0 and 1000"; + + if (number < 12) { + assert number < 12 && number >= 0: "Must be between 0 and 11"; + appendTo.append(basenumbers[number]); + } else if (number < 20) { + assert number >= 12 && number <= 19: "Must be between 12 and 19"; + int belasan = number % 10; + appendTo.append(basenumbers[belasan]); + appendTo.append(" Belas"); + } else if (number < 100) { + assert number >= 20 && number <= 99: "Must be between 20 and 99"; + int puluhan = number / 10; + appendTo.append(basenumbers[puluhan]); + appendTo.append(" Puluh"); + int remainder = number - puluhan * 10; + if (remainder > 0) { + appendTo.append(' '); + saySimpleNumber(appendTo, remainder); + } + } else if (number < 200) { + assert number >= 100 && number <= 199: "Must be between 100 and 199"; + appendTo.append("Seratus"); + + int remainder = number - 100; + if (remainder > 0) { + appendTo.append(' '); + saySimpleNumber(appendTo, remainder); + } + } else if (number != 0) { + assert number >= 200 && number <= 999: "Must be between 200 and 999"; + + int ratusan = number % 1000 / 100; + assert ratusan > 0 && ratusan < 10 :"1-9"; + appendTo.append(basenumbers[ratusan]); + appendTo.append(" Ratus"); + int remainder = number - ratusan * 100; + if (remainder > 0) { appendTo.append(' '); saySimpleNumber(appendTo, remainder); } - } else if (number < 200) { - assert number >= 100 && number <= 199: "Must be between 100 and 199"; - appendTo.append("Seratus"); - - int remainder = number - 100; - if (remainder > 0) { - appendTo.append(' '); - saySimpleNumber(appendTo, remainder); - } - } else if (number != 0) { - assert number >= 200 && number <= 999: "Must be between 200 and 999"; - - int ratusan = number % 1000 / 100; - assert ratusan > 0 && ratusan < 10 :"1-9"; - appendTo.append(basenumbers[ratusan]); - appendTo.append(" Ratus"); - int remainder = number - ratusan * 100; - if (remainder > 0) { - appendTo.append(' '); - saySimpleNumber(appendTo, remainder); - } - } + } } - /************************************************************************** + /************************************************************************** * Get Amount in Words * @param amount numeric amount (352.80) * @return amount in words (three*five*two 80/100) - * @throws Exception */ public String getAmtInWords (String amount) throws Exception { if (amount == null) return amount; // - amount = amount.replaceAll (",", ""); - float numFloat = Float.parseFloat(amount); - long number = 0L; - number = (long)numFloat; - return AmtInWords_IN.sayNumber(number); + StringBuffer result = new StringBuffer(); + + int pos = amount.lastIndexOf ('.'); + String oldamt = amount; + amount = amount.replaceAll (",", ""); + String cents = pos > 0 ? oldamt.substring (pos + 1):null; + double numDouble = Double.parseDouble(amount); + sayNumber(result, numDouble); + if (cents != null) + { + result.append(" Koma "); + numDouble = Double.parseDouble(cents); + sayNumber(result, numDouble); + } + result.append(" Rupiah"); + return result.toString(); } // getAmtInWords /** - * Test Print - * @param amt amount - */ - private void print (String amt) - { - try - { - System.out.println(amt + " = " + getAmtInWords(amt)); - } - catch (Exception e) - { - e.printStackTrace(); - } - } // print - - /** - * Test - * @param args ignored - */ + * Test Print + * @param amt amount + */ + private void print (String amt) + { + try + { + System.out.println(amt + " = " + getAmtInWords(amt)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } // print + + /** + * Test + * @param args ignored + */ public static void main (String[] args) { AmtInWords_IN aiw = new AmtInWords_IN(); - // I doubt decimal support for rupiah is still needed ;) - aiw.print (".23"); - aiw.print ("948,776,477,778,778,778"); - aiw.print ("1.79"); - // aiw.print ("12.345"); - // aiw.print ("123.45"); - // aiw.print ("1234.56"); - // aiw.print ("12345.78"); - // aiw.print ("123457.89"); - aiw.print ("1,234,578.90"); + aiw.print ("0.00"); + aiw.print ("0.23"); + aiw.print ("1.23876787"); + aiw.print ("11.45"); + aiw.print ("121.45"); + aiw.print ("1231.56"); + aiw.print ("10341.78"); + aiw.print ("12341.78"); + aiw.print ("123451.89"); + aiw.print ("12234571.90"); + aiw.print ("123234571.90"); + aiw.print ("1987234571.90"); + aiw.print ("11123234571.90"); + aiw.print ("123123234571.90"); + aiw.print ("2123123234571.90"); + aiw.print ("23,123,123,234,571.90"); + aiw.print ("100,000,000,000,000.90"); + aiw.print ("111,111,111"); + aiw.print ("222,222,222,222,222"); + aiw.print ("222,222,222,222,222,222,222"); } // main } // AmtInWords_IN diff --git a/dbPort/src/org/compiere/util/CLogger.java b/dbPort/src/org/compiere/util/CLogger.java index d2314af190..35fe52dee7 100644 --- a/dbPort/src/org/compiere/util/CLogger.java +++ b/dbPort/src/org/compiere/util/CLogger.java @@ -170,6 +170,9 @@ public class CLogger extends Logger implements Serializable public boolean saveWarning (String AD_Message, String message) { s_lastWarning = new ValueNamePair (AD_Message, message); + // print it + if (true) // issueError + warning(AD_Message + " - " + message); return true; } // saveWarning diff --git a/dbPort/src/org/compiere/util/CPreparedStatement.java b/dbPort/src/org/compiere/util/CPreparedStatement.java index ceeaa65853..cd92e5abbe 100644 --- a/dbPort/src/org/compiere/util/CPreparedStatement.java +++ b/dbPort/src/org/compiere/util/CPreparedStatement.java @@ -1066,6 +1066,113 @@ public class CPreparedStatement extends CStatement implements PreparedStatement throw new RuntimeException (ex); } } // remote_executeUpdate + + public void setAsciiStream(int parameterIndex, java.io.InputStream x, long length) + throws SQLException + { + + } + + //vpj-cd add support java 6 + public void setBinaryStream(int parameterIndex, java.io.InputStream x, + long length) throws SQLException + { + + } + + public void setCharacterStream(int parameterIndex, + java.io.Reader reader, + long length) throws SQLException + { + + } + + public void setAsciiStream(int parameterIndex, java.io.InputStream x) + throws SQLException + { + + } + + + public void setBinaryStream(int parameterIndex, java.io.InputStream x) + throws SQLException + { + + } + + public void setCharacterStream(int parameterIndex, + java.io.Reader reader) throws SQLException + { + + } + + public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException + { + + } + + public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException + { + + } + + public void setClob(int parameterIndex, Reader reader) + throws SQLException + { + + } + + public void setClob(int parameterIndex, Reader reader, long length) + throws SQLException + { + + } + + public void setNClob(int parameterIndex, NClob value) throws SQLException + { + + } + + + public void setNClob(int parameterIndex, Reader reader, long length) + throws SQLException + { + + } + + public void setNClob(int parameterIndex, Reader reader) + throws SQLException + { + + } + + public void setBlob(int parameterIndex, InputStream inputStream, long length) + throws SQLException + { + + } + + + public void setBlob(int parameterIndex, InputStream inputStream) + throws SQLException + { + + } + + + + + public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException + { + + } + + public void setNString(int parameterIndex, String value) throws SQLException + { + + } + + public void setRowId(int parameterIndex, RowId x) throws SQLException{} } // CPreparedStatement diff --git a/dbPort/src/org/compiere/util/CStatement.java b/dbPort/src/org/compiere/util/CStatement.java index 11607e0462..c1654de2f4 100644 --- a/dbPort/src/org/compiere/util/CStatement.java +++ b/dbPort/src/org/compiere/util/CStatement.java @@ -905,5 +905,15 @@ public class CStatement implements Statement } return rowSet; } // remote_getRowSet + + public boolean isPoolable() throws SQLException{ return false;} + + public void setPoolable(boolean a) throws SQLException{}; + + public boolean isClosed() throws SQLException{ return false;} + + public boolean isWrapperFor(java.lang.Class c) throws SQLException{ return false;} + + public T unwrap(java.lang.Class iface) throws java.sql.SQLException{return null;} } // CStatement diff --git a/dbPort/src/org/compiere/util/DB.java b/dbPort/src/org/compiere/util/DB.java index 2b1b3f7250..4952128737 100644 --- a/dbPort/src/org/compiere/util/DB.java +++ b/dbPort/src/org/compiere/util/DB.java @@ -1,1883 +1,1895 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.util; - -import java.io.*; -import java.math.*; -import java.rmi.*; -import java.sql.*; -import java.text.*; -import java.util.*; -import java.util.logging.*; -import javax.sql.*; -import javax.swing.*; -import oracle.jdbc.*; -// -import org.compiere.*; -import org.compiere.db.*; -import org.compiere.interfaces.*; -import org.compiere.model.*; -import org.compiere.process.*; - - -/** - * General Database Interface - * - * @author Jorg Janke - * @version $Id: DB.java,v 1.8 2006/10/09 00:22:29 jjanke Exp $ - */ -public final class DB -{ - /** Connection Descriptor */ - private static CConnection s_cc = null; - /** Connection Cache r/o */ - private static Connection[] s_connections = null; - /** Connection Cache Size */ - private static int s_conCacheSize = Ini.isClient() ? 1 : 3; - /** Connection counter */ - private static int s_conCount = 0; - /** Connection r/w */ - private static Connection s_connectionRW = null; - /** Connection r/w for ID */ - private static Connection s_connectionID = null; - /** Logger */ - private static CLogger log = CLogger.getCLogger (DB.class); - - /** SQL Statement Separator "; " */ - public static final String SQLSTATEMENT_SEPARATOR = "; "; - - - /************************************************************************** - * Check need for post Upgrade - * @param ctx context - * @return true if post upgrade ran - false if there was no need - */ - public static boolean afterMigration (Properties ctx) - { - // UPDATE AD_System SET IsJustMigrated='Y' - MSystem system = MSystem.get(ctx); - if (!system.isJustMigrated()) - return false; - - // Role update - log.info("Role"); - String sql = "SELECT * FROM AD_Role"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - ResultSet rs = pstmt.executeQuery (); - while (rs.next ()) - { - MRole role = new MRole (ctx, rs, null); - role.updateAccessRecords(); - } - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, "(1)", e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - - // Release Specif stuff & Print Format - try - { - Class clazz = Class.forName("org.compiere.MigrateData"); - clazz.newInstance(); - } - catch (Exception e) - { - log.log (Level.SEVERE, "Data", e); - } - - // Language check - log.info("Language"); - MLanguage.maintain(ctx); - - // Sequence check - log.info("Sequence"); - SequenceCheck.validate(ctx); - - // Costing Setup - log.info("Costing"); - MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(ctx, 0); - for (int i = 0; i < ass.length; i++) - { - ass[i].checkCosting(); - ass[i].save(); - } - - // Reset Flag - system.setIsJustMigrated(false); - return system.save(); - } // afterMigration - - /** - * Update Mail Settings for System Client and System User - */ - public static void updateMail() - { - // Get Property File - String envName = Ini.getAdempiereHome(); - if (envName == null) - return; - envName += File.separator + "AdempiereEnv.properties"; - File envFile = new File(envName); - if (!envFile.exists()) - return; - - Properties env = new Properties(); - try - { - FileInputStream in = new FileInputStream(envFile); - env.load(in); - in.close(); - } - catch (Exception e) - { - return; - } - String updated = env.getProperty("ADEMPIERE_MAIL_UPDATED"); - if (updated != null || updated.equals("Y")) - return; - - // See org.compiere.install.ConfigurationData - String server = env.getProperty("ADEMPIERE_MAIL_SERVER"); - if (server == null || server.length() == 0) - return; - String adminEMail = env.getProperty("ADEMPIERE_ADMIN_EMAIL"); - if (adminEMail == null || adminEMail.length() == 0) - return; - String mailUser = env.getProperty("ADEMPIERE_MAIL_USER"); - if (mailUser == null || mailUser.length() == 0) - return; - String mailPassword = env.getProperty("ADEMPIERE_MAIL_PASSWORD"); - // if (mailPassword == null || mailPassword.length() == 0) - // return; - // - StringBuffer sql = new StringBuffer("UPDATE AD_Client SET") - .append(" SMTPHost=").append(DB.TO_STRING(server)) - .append(", RequestEMail=").append(DB.TO_STRING(adminEMail)) - .append(", RequestUser=").append(DB.TO_STRING(mailUser)) - .append(", RequestUserPW=").append(DB.TO_STRING(mailPassword)) - .append(", IsSMTPAuthorization='Y' WHERE AD_Client_ID=0"); - int no = DB.executeUpdate(sql.toString(), null); - // - sql = new StringBuffer("UPDATE AD_User SET ") - .append(" EMail=").append(DB.TO_STRING(adminEMail)) - .append(", EMailUser=").append(DB.TO_STRING(mailUser)) - .append(", EMailUserPW=").append(DB.TO_STRING(mailUser)) - .append(" WHERE AD_User_ID IN (0,100)"); - no = DB.executeUpdate(sql.toString(), null); - // - try - { - env.setProperty("ADEMPIERE_MAIL_UPDATED", "Y"); - FileOutputStream out = new FileOutputStream(envFile); - env.store(out, ""); - out.flush(); - out.close(); - } - catch (Exception e) - { - } - - } // updateMail - - /************************************************************************** - * Set connection - * @param cc connection - */ - public static void setDBTarget (CConnection cc) - { - if (cc == null) - throw new IllegalArgumentException("Connection is NULL"); - - if (s_cc != null && s_cc.equals(cc)) - return; - - DB.closeTarget(); - // - if (s_cc == null) - s_cc = cc; - synchronized (s_cc) // use as mutex - { - s_cc = cc; - s_connections = null; - s_connectionRW = null; - s_connectionID = null; - } - s_cc.setDataSource(); - log.config(s_cc + " - DS=" + s_cc.isDataSource()); - // Trace.printStack(); - } // setDBTarget - - /** - * Connect to database and initialise all connections. - * @return True if success, false otherwise - */ - public static boolean connect() { - boolean success =false; - try - { - success = getConnectionRW() != null; - if (success) success = getConnectionRO() != null; - if (success) success = getConnectionID() != null; - s_cc.readInfo(getConnectionRW()); - } catch (Exception e) - { - success = false; - } - return success; - } - - /** - * Is there a connection to the database ? - * @return true, if connected to database - */ - public static boolean isConnected() - { - boolean success = false; - CLogErrorBuffer eb = CLogErrorBuffer.get(false); - if (eb != null && eb.isIssueError()) - eb.setIssueError(false); - else - eb = null; // don't reset - try - { - success = getConnectionRW() != null; // try to get a connection - } - catch (Exception e) - { - success = false; - } - if (eb != null) - eb.setIssueError(true); - return success; - } // isConnected - - /** - * Return (pooled) r/w AutoCommit, Serializable connection. - * For Transaction control use Trx.getConnection() - * @return Connection (r/w) - */ - public static Connection getConnectionRW () - { - // check health of connection - try - { - if (s_connectionRW == null) - ; - else if (s_connectionRW.isClosed()) - { - log.finest("Closed"); - s_connectionRW = null; - } - else if (s_connectionRW instanceof OracleConnection && ((OracleConnection)s_connectionRW).pingDatabase(1) < 0) - { - log.warning("No ping"); - s_connectionRW = null; - } - else - { - if (s_connectionRW.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) - s_connectionRW.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - } - } - catch (Exception e) - { - s_connectionRW = null; - } - // Get new - if (s_connectionRW == null) - { - s_connectionRW = s_cc.getConnection (true, Connection.TRANSACTION_READ_COMMITTED); - log.finest("Con=" + s_connectionRW); - } - if (s_connectionRW == null) - throw new UnsupportedOperationException("No DBConnection"); - // - // System.err.println ("DB.getConnectionRW - " + s_connectionRW); - // Trace.printStack(); - return s_connectionRW; - } // getConnectionRW - - /** - * Return everytime a new r/w no AutoCommit, Serializable connection. - * To be used to ID - * @return Connection (r/w) - */ - public static Connection getConnectionID () - { - if (s_connectionID != null) - { - try - { - if (s_connectionID.isClosed()) - s_connectionID = null; - } - catch (Exception e) - { - s_connectionID = null; - } - } - if (s_connectionID == null) - { - s_connectionID = s_cc.getConnection (false, Connection.TRANSACTION_READ_COMMITTED); - } - if (s_connectionID == null) - throw new UnsupportedOperationException("No DBConnection"); - log.log(Level.ALL, s_connectionID.toString()); - return s_connectionID; - } // getConnectionID - - /** - * Return read committed, read/only from pool. - * @return Connection (r/o) - */ - public static Connection getConnectionRO () - { - try - { - synchronized (s_cc) // use as mutex as s_connection is null the first time - { - if (s_connections == null) - s_connections = createConnections (Connection.TRANSACTION_READ_COMMITTED); // see below - } - } - catch (Exception e) - { - log.log(Level.SEVERE, "RO", e); - } - - // check health of connection - int pos = s_conCount++; - int connectionNo = pos % s_conCacheSize; - Connection connection = s_connections[connectionNo]; - try - { - if (connection == null) - ; - else if (connection.isClosed()) - { - // RowSet.close also closes connection! - // System.out.println("DB.getConnectionRO - closed #" + connectionNo); - connection = null; - } - else if (connection instanceof OracleConnection && ((OracleConnection)connection).pingDatabase(1) < 0) - { - log.warning("No ping #" + connectionNo); - connection = null; - } - else - { - if (!connection.isReadOnly()) - connection.setReadOnly(true); - if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) - connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - } - } - catch (Exception e) - { - log.severe("#" + connectionNo + " - " + e.toString()); - connection = null; - } - // Get new - if (connection == null) - { - log.finest("Replacing connection #" + connectionNo); - connection = s_cc.getConnection (true, Connection.TRANSACTION_READ_COMMITTED); // see above - try - { - if (connection != null) - connection.setReadOnly(true); - } - catch (Exception e) - { - log.severe("Cannot set to R/O - " + e); - } - s_connections[connectionNo] = connection; - } - if (connection == null) - throw new UnsupportedOperationException("DB.getConnectionRO - @NoDBConnection@"); - log.log(Level.ALL, "#" + connectionNo + " - " + connection); - // System.err.println ("DB.getConnectionRO - " + connection); - return connection; - } // getConnectionRO - - /** - * Create new Connection. - * The connection must be closed explicitly by the application - * - * @param autoCommit auto commit - * @param trxLevel - Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ, or Connection.TRANSACTION_READ_COMMITTED. - * @return Connection connection - */ - public static Connection createConnection (boolean autoCommit, int trxLevel) - { - Connection conn = s_cc.getConnection (autoCommit, trxLevel); - if (CLogMgt.isLevelFinest()) - { - /** - try - { - log.finest(s_cc.getConnectionURL() - + ", UserID=" + s_cc.getDbUid() - + ", AutoCommit=" + conn.getAutoCommit() + " (" + autoCommit + ")" - + ", TrxIso=" + conn.getTransactionIsolation() + "( " + trxLevel + ")"); - } - catch (Exception e) - { - } - **/ - } - return conn; - } // createConnection - - /** - * Create new set of r/o Connections. - * R/O connection might not be supported by DB - * - * @param trxLevel - Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ, or Connection.TRANSACTION_READ_COMMITTED. - * @return Array of Connections (size based on s_conCacheSize) - */ - private static Connection[] createConnections (int trxLevel) - { - log.finest("(" + s_conCacheSize + ") " + s_cc.getConnectionURL() - + ", UserID=" + s_cc.getDbUid() - + ", TrxLevel=" + CConnection.getTransactionIsolationInfo(trxLevel)); - Connection cons[] = new Connection[s_conCacheSize]; - try - { - for (int i = 0; i < s_conCacheSize; i++) - { - cons[i] = s_cc.getConnection (true, trxLevel); // auto commit - if (cons[i] == null) - log.warning("Connection is NULL"); // don't use log - } - } - catch (Exception e) - { - log.severe(e.getMessage()); - } - return cons; - } // createConnections - - /** - * Get Database Driver. - * Access to database specific functionality. - * @return Adempiere Database Driver - */ - public static AdempiereDatabase getDatabase() - { - if (s_cc != null) - return s_cc.getDatabase(); - log.severe("No Database Connection"); - return null; - } // getDatabase - - /** - * Get Database Driver. - * Access to database specific functionality. - * @param URL JDBC connection url - * @return Adempiere Database Driver - */ - public static AdempiereDatabase getDatabase(String URL) - { - return Database.getDatabaseFromURL(URL); - } // getDatabase - - /** - * Do we have an Oracle DB ? - * @return true if connected to Oracle - */ - public static boolean isOracle() - { - if (s_cc != null) - return s_cc.isOracle(); - log.severe("No Database Connection"); - return false; - } // isOracle - - /** - * Do we have a Derby DB ? - * @return true if connected to Derby - */ - public static boolean isDerby() - { - if (s_cc != null) - return s_cc.isDerby(); - log.severe("No Database Connection"); - return false; - } // isDerby - - //begin vpj-cd e-evolution 02/07/2005 PostgreSQL - /** - * Do we have a Postgre DB ? - * @return true if connected to PostgreSQL - */ - public static boolean isPostgreSQL() - { - if (s_cc != null) - return s_cc.isPostgreSQL(); - log.severe("No Database"); - return false; - } // isPostgreSQL - //begin vpj-cd e-evolution 02/07/2005 PostgreSQL - - public static boolean isDB2() - { - if (s_cc != null) - return s_cc.isDB2(); - log.severe("No Database"); - return false; - } - public static boolean isFyracle() - { - if (s_cc != null) - return s_cc.isFyracle(); - log.severe("No Database"); - return false; - } // isFyracle - - /** - * Do we have a Postgre DB ? - * @return true if connected to PostgreSQL - */ -// public static boolean isEDB() -// { -// if (s_cc != null) -// return s_cc.isEDB(); -// log.severe("No Database"); -// return false; -// } // isPostgreSQL - //end vpj-cd e-evolution 02/07/2005 PostgreSQL - - /** - * Get Database Info - * @return info - */ - public static String getDatabaseInfo() - { - if (s_cc != null) - return s_cc.getDBInfo(); - return "No Database"; - } // getDatabaseInfo - - - /************************************************************************** - * Check database Version with Code version - * @param ctx context - * @return true if Database version (date) is the same - */ - public static boolean isDatabaseOK (Properties ctx) - { - // Check Version - String version = "?"; - String sql = "SELECT Version FROM AD_System"; - try - { - PreparedStatement pstmt = prepareStatement(sql, null); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - version = rs.getString(1); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, "Problem with AD_System Table - Run system.sql script - " + e.toString()); - return false; - } - log.info("DB_Version=" + version); - // Identical DB version - if (Adempiere.DB_VERSION.equals(version)) - return true; - - String AD_Message = "DatabaseVersionError"; - String title = org.compiere.Adempiere.getName() + " " + Msg.getMsg(ctx, AD_Message, true); - // Code assumes Database version {0}, but Database has Version {1}. - String msg = Msg.getMsg(ctx, AD_Message); // complete message - msg = MessageFormat.format(msg, new Object[] {Adempiere.DB_VERSION, version}); - Object[] options = { UIManager.get("OptionPane.noButtonText"), "Migrate" }; - int no = JOptionPane.showOptionDialog (null, msg, - title, JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, - UIManager.getIcon("OptionPane.errorIcon"), options, options[0]); - if (no == 1) - { - JOptionPane.showMessageDialog (null, - "Start RUN_Migrate (in utils)\nSee: http://www.adempiere.com/maintain", - title, JOptionPane.INFORMATION_MESSAGE); - Env.exitEnv(1); - } - return false; - } // isDatabaseOK - - - /************************************************************************** - * Close Target - */ - public static void closeTarget() - { - boolean closed = false; - // RO connection - if (s_connections != null) - { - for (int i = 0; i < s_conCacheSize; i++) - { - try - { - if (s_connections[i] != null) - { - closed = true; - s_connections[i].close(); - } - } - catch (SQLException e) - { - log.warning("#" + i + " - " + e.getMessage()); - } - s_connections[i] = null; - } - } - s_connections = null; - // RW connection - try - { - if (s_connectionRW != null) - { - closed = true; - s_connectionRW.close(); - } - } - catch (SQLException e) - { - log.log(Level.SEVERE, "R/W", e); - } - s_connectionRW = null; - - //ID Connection - try - { - if (s_connectionID != null) - { - s_connectionID.close(); - } - } catch (SQLException e) - { - log.log(Level.SEVERE, "Id", e); - } - s_connectionID = null; - - // CConnection - if (s_cc != null) - { - closed = true; - s_cc.setDataSource(null); - } - s_cc = null; - if (closed) - log.fine("closed"); - } // closeTarget - - - /************************************************************************** - * Prepare Forward Read Only Call - * @param RO_SQL sql (RO) - * @return Callable Statement - */ - public static CallableStatement prepareCall(String RO_SQL) - { - if (RO_SQL == null || RO_SQL.length() == 0) - throw new IllegalArgumentException("Required parameter missing - " + RO_SQL); - // - String sql = getDatabase().convertStatement(RO_SQL); - try - { - return getConnectionRO().prepareCall - (sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - // throw new DBException(e); - } - return null; - } // prepareCall - - - /************************************************************************** - * Prepare Read Only Statement - * @param RO_SQL sql (RO) - * @return Prepared Statement - * @deprecated - */ - public static CPreparedStatement prepareStatement (String RO_SQL) - { - return prepareStatement(RO_SQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); - } // prepareStatement - - /** - * Prepare Read Only Statement - * @param RO_SQL sql (RO) - * @param trxName transaction - * @return Prepared Statement - */ - public static CPreparedStatement prepareStatement (String RO_SQL, String trxName) - { - return prepareStatement(RO_SQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, trxName); - } // prepareStatement - - /** - * Prepare Statement. - * @param sql sql statement - * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE - * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE - * @return Prepared Statement r/o or r/w depending on concur - * @deprecated - */ - public static CPreparedStatement prepareStatement (String sql, - int resultSetType, int resultSetConcurrency) - { - return prepareStatement(sql, resultSetType, resultSetConcurrency, null); - } // prepareStatement - - /** - * Prepare Statement. - * @param sql sql statement - * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE - * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE - * @param trxName transaction name - * @return Prepared Statement r/o or r/w depending on concur - */ - public static CPreparedStatement prepareStatement(String sql, - int resultSetType, int resultSetConcurrency, String trxName) - { - if (sql == null || sql.length() == 0) - throw new IllegalArgumentException("No SQL"); - // - return new CPreparedStatement(resultSetType, resultSetConcurrency, sql, trxName); - } // prepareStatement - - /** - * Create Read Only Statement - * @return Statement - */ - public static Statement createStatement() - { - return createStatement (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); - } // createStatement - - /** - * Create Statement. - * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE - * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE - * @param trxName transaction name - * @return Statement - either r/w ir r/o depending on concur - */ - public static Statement createStatement(int resultSetType, int resultSetConcurrency, String trxName) - { - return new CStatement(resultSetType, resultSetConcurrency, trxName); - } // createStatement - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @return number of rows updated or -1 if error - * @deprecated - */ - public static int executeUpdate (String sql) - { - return executeUpdate(sql, null, false, null); - } // executeUpdate - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @param trxName optional transaction name - * @return number of rows updated or -1 if error - */ - public static int executeUpdate (String sql, String trxName) - { - return executeUpdate(sql, null, false, trxName); - } // executeUpdate - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @param ignoreError if true, no execution error is reported - * @return number of rows updated or -1 if error - * @deprecated - */ - public static int executeUpdate (String sql, boolean ignoreError) - { - return executeUpdate (sql, null, ignoreError, null); - } // executeUpdate - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @param ignoreError if true, no execution error is reported - * @param trxName transaction - * @return number of rows updated or -1 if error - */ - public static int executeUpdate (String sql, boolean ignoreError, String trxName) - { - return executeUpdate (sql, null, ignoreError, trxName); - } // executeUpdate - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @param param int param - * @param trxName transaction - * @return number of rows updated or -1 if error - */ - public static int executeUpdate (String sql, int param, String trxName) - { - return executeUpdate (sql, new Object[]{new Integer(param)}, false, trxName); - } // executeUpdate - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @param param int parameter - * @param ignoreError if true, no execution error is reported - * @param trxName transaction - * @return number of rows updated or -1 if error - */ - public static int executeUpdate (String sql, int param, boolean ignoreError, String trxName) - { - return executeUpdate (sql, new Object[]{new Integer(param)}, ignoreError, trxName); - } // executeUpdate - - /** - * Execute Update. - * saves "DBExecuteError" in Log - * @param sql sql - * @param params array of parameters - * @param ignoreError if true, no execution error is reported - * @param trxName optional transaction name - * @return number of rows updated or -1 if error - */ - public static int executeUpdate (String sql, Object[] params, boolean ignoreError, String trxName) - { - if (sql == null || sql.length() == 0) - throw new IllegalArgumentException("Required parameter missing - " + sql); - // - int no = -1; - CPreparedStatement cs = new CPreparedStatement(ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_UPDATABLE, sql, trxName); // converted in call - - try - { - // Set Parameter - if (params != null) - { - for (int i = 0; i < params.length; i++) - { - Object param = params[i]; - if (param instanceof String) - cs.setString(i+1, (String)param); - else if (param instanceof Integer) - cs.setInt(i+1, ((Integer)param).intValue()); - else if (param instanceof BigDecimal) - cs.setBigDecimal(i+1, (BigDecimal)param); - else if (param instanceof Timestamp) - cs.setTimestamp(i+1, (Timestamp)param); - } - } - // - no = cs.executeUpdate(); - // No Transaction - Commit - if (trxName == null) - { - cs.commit(); // Local commit - // Connection conn = cs.getConnection(); - // if (conn != null && !conn.getAutoCommit()) // is null for remote - // conn.commit(); - } - } - catch (SQLException e) - { - if (ignoreError) - log.log(Level.SEVERE, cs.getSql() + " [" + trxName + "] - " + e.getMessage()); - else - { - log.log(Level.SEVERE, cs.getSql() + " [" + trxName + "]", e); - log.saveError ("DBExecuteError", e); - } - // throw new DBException(e); - } - finally - { - // Always close cursor - try - { - cs.close(); - } - catch (SQLException e2) - { - log.log(Level.SEVERE, "Cannot close statement"); - } - } - return no; - } // executeUpdate - - /** - * Execute multiple Update statements. - * saves (last) "DBExecuteError" in Log - * @param sql multiple sql statements separated by "; " SQLSTATEMENT_SEPARATOR - * @param ignoreError if true, no execution error is reported - * @param trxName optional transaction name - * @return number of rows updated or -1 if error - */ - public static int executeUpdateMultiple (String sql, boolean ignoreError, String trxName) - { - if (sql == null || sql.length() == 0) - throw new IllegalArgumentException("Required parameter missing - " + sql); - int index = sql.indexOf(SQLSTATEMENT_SEPARATOR); - if (index == -1) - return executeUpdate(sql, null, ignoreError, trxName); - int no = 0; - // - String statements[] = sql.split(SQLSTATEMENT_SEPARATOR); - for (int i = 0; i < statements.length; i++) - { - log.fine(statements[i]); - no += executeUpdate(statements[i], null, ignoreError, trxName); - } - - return no; - } // executeUpdareMultiple - - /** - * Execute Update and throw exception. - * @param SQL sql - * @return number of rows updated or -1 if error - * @param trxName transaction - * @throws SQLException - */ - public static int executeUpdateEx (String SQL, String trxName) throws SQLException - { - if (SQL == null || SQL.length() == 0) - throw new IllegalArgumentException("Required parameter missing - " + SQL); - // - String sql = getDatabase().convertStatement(SQL); - int no = -1; - SQLException ex = null; - Connection conn = null; - Statement stmt = null; - try - { - Trx trx = trxName == null ? null : Trx.get(trxName, true); - if (trx != null) - conn = trx.getConnection(); - else - conn = DB.getConnectionRW (); - stmt = conn.createStatement(); - no = stmt.executeUpdate(sql); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql + " [" + trxName + "]", e); - ex = e; - } - finally - { - // Always close cursor - try - { - stmt.close(); - } - catch (SQLException e2) - { - log.log(Level.SEVERE, "Cannot close statement"); - } - } - if (ex != null) - throw new SQLException(ex.getMessage(), ex.getSQLState(), ex.getErrorCode()); - return no; - } // execute Update - - /** - * Commit - commit on RW connection. - * Is not required as RW connection is AutoCommit (exception: with transaction) - * @param throwException if true, re-throws exception - * @param trxName transaction name - * @return true if not needed or success - * @throws SQLException - */ - public static boolean commit (boolean throwException, String trxName) throws SQLException - { - try - { - Connection conn = null; - Trx trx = trxName == null ? null : Trx.get(trxName, true); - if (trx != null) - conn = trx.getConnection(); - else - conn = DB.getConnectionRW (); - // if (!conn.getAutoCommit()) - conn.commit(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, "[" + trxName + "]", e); - if (throwException) - throw e; - return false; - } - return true; - } // commit - - /** - * Rollback - rollback on RW connection. - * Is has no effect as RW connection is AutoCommit (exception: with transaction) - * @param throwException if true, re-throws exception - * @param trxName transaction name - * @return true if not needed or success - * @throws SQLException - */ - public static boolean rollback (boolean throwException, String trxName) throws SQLException - { - try - { - Connection conn = null; - Trx trx = trxName == null ? null : Trx.get(trxName, true); - if (trx != null) - conn = trx.getConnection(); - else - conn = DB.getConnectionRW (); - // if (!conn.getAutoCommit()) - conn.rollback(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, "[" + trxName + "]", e); - if (throwException) - throw e; - return false; - } - return true; - } // commit - - /** - * Get Row Set. - * When a Rowset is closed, it also closes the underlying connection. - * If the created RowSet is transfered by RMI, closing it makes no difference - * @param sql sql - * @param local local RowSet (own connection) - * @return row set or null - */ - public static RowSet getRowSet (String sql, boolean local) - { - RowSet retValue = null; - // Bugfix Gunther Hoppe, 02.09.2005 add vpj-cd e-evolution - // Begin - // CStatementVO info = new CStatementVO ( - // RowSet.TYPE_SCROLL_INSENSITIVE, RowSet.CONCUR_READ_ONLY, sql); - CStatementVO info = new CStatementVO (RowSet.TYPE_SCROLL_INSENSITIVE, RowSet.CONCUR_READ_ONLY, DB.getDatabase().convertStatement(sql)); - // End add vpj-cd e-evolution - CPreparedStatement stmt = new CPreparedStatement(info); - if (local) - { - retValue = stmt.local_getRowSet(); - } - else - { - retValue = stmt.remote_getRowSet(); - } - return retValue; - } // getRowSet - - /** - * Get Value from sql - * @param trxName trx - * @param sql sql - * @return first value or -1 - */ - public static int getSQLValue (String trxName, String sql) - { - int retValue = -1; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - else - log.fine("No Value " + sql); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValue - - /** - * Get Value from sql - * @param trxName trx - * @param sql sql - * @param int_param1 parameter 1 - * @return first value or -1 - */ - public static int getSQLValue (String trxName, String sql, int int_param1) - { - int retValue = -1; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - pstmt.setInt(1, int_param1); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - else - log.config("No Value " + sql + " - Param1=" + int_param1); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + " [" + trxName + "]", e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValue - - /** - * Get Value from sql - * @param trxName trx - * @param sql sql - * @param int_param1 parameter 1 - * @param int_param2 parameter 2 - * @return first value or -1 - */ - public static int getSQLValue (String trxName, String sql, int int_param1, int int_param2) - { - int retValue = -1; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - pstmt.setInt(1, int_param1); - pstmt.setInt(2, int_param2); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - else - log.info("No Value " + sql - + " - Param1=" + int_param1 + ",Param2=" + int_param2); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + ",Param2=" + int_param2 - + " [" + trxName + "]", e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValue - - /** - * Get Value from sql - * @param trxName trx - * @param sql sql - * @param str_param1 parameter 1 - * @return first value or -1 - */ - public static int getSQLValue (String trxName, String sql, String str_param1) - { - int retValue = -1; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - pstmt.setString(1, str_param1); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - else - log.info("No Value " + sql + " - Param1=" + str_param1); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql + " - Param1=" + str_param1, e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValue - - /** - * Get Value from sql - * @param trxName trx - * @param sql sql - * @param int_param1 parameter 1 - * @param s_param2 parameter 2 - * @return first value or -1 - */ - public static int getSQLValue (String trxName, String sql, int int_param1, String s_param2) - { - int retValue = -1; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - pstmt.setInt(1, int_param1); - pstmt.setString(2, s_param2); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - else - log.info("No Value: " + sql + " - Param1=" + int_param1 + ",Param2=" + s_param2); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + ",Param2=" + s_param2, e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValue - - /** - * Get String Value from sql - * @param trxName trx - * @param sql sql - * @param int_param1 parameter 1 - * @return first value or null - */ - public static String getSQLValueString (String trxName, String sql, int int_param1) - { - String retValue = null; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - pstmt.setInt(1, int_param1); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getString(1); - else - log.info("No Value " + sql + " - Param1=" + int_param1); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql + " - Param1=" + int_param1, e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValueString - - /** - * Get BigDecimal Value from sql - * @param trxName trx - * @param sql sql - * @param int_param1 parameter 1 - * @return first value or null - */ - public static BigDecimal getSQLValueBD (String trxName, String sql, int int_param1) - { - BigDecimal retValue = null; - PreparedStatement pstmt = null; - try - { - pstmt = prepareStatement(sql, trxName); - pstmt.setInt(1, int_param1); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getBigDecimal(1); - else - log.info("No Value " + sql + " - Param1=" + int_param1); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + " [" + trxName + "]", e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return retValue; - } // getSQLValueBD - - - /** - * Get Array of Key Name Pairs - * @param sql select with id / name as first / second column - * @param optional if true (-1,"") is added - * @return array of key name pairs - */ - public static KeyNamePair[] getKeyNamePairs(String sql, boolean optional) - { - PreparedStatement pstmt = null; - ArrayList list = new ArrayList(); - if (optional) - list.add (new KeyNamePair(-1, "")); - try - { - pstmt = DB.prepareStatement(sql, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - list.add(new KeyNamePair(rs.getInt(1), rs.getString(2))); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - KeyNamePair[] retValue = new KeyNamePair[list.size()]; - list.toArray(retValue); - // s_log.fine("getKeyNamePairs #" + retValue.length); - return retValue; - } // getKeyNamePairs - - /** - * Is Sales Order Trx. - * Assumes Sales Order. Queries IsSOTrx of table with where clause - * @param TableName table - * @param whereClause where clause - * @return true (default) or false if tested that not SO - */ - public static boolean isSOTrx (String TableName, String whereClause) - { - if (TableName == null || TableName.length() == 0) - { - log.severe("No TableName"); - return true; - } - if (whereClause == null || whereClause.length() == 0) - { - log.severe("No Where Clause"); - return true; - } - // - boolean isSOTrx = true; - String sql = "SELECT IsSOTrx FROM " + TableName - + " WHERE " + whereClause; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - ResultSet rs = pstmt.executeQuery (); - if (rs.next ()) - isSOTrx = "Y".equals(rs.getString(1)); - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - if (TableName.endsWith("Line")) - { - String hdr = TableName.substring(0, TableName.indexOf("Line")); - sql = "SELECT IsSOTrx FROM " + hdr - + " h WHERE EXISTS (SELECT * FROM " + TableName - + " l WHERE h." + hdr + "_ID=l." + hdr + "_ID AND " - + whereClause + ")"; - PreparedStatement pstmt2 = null; - try - { - pstmt2 = DB.prepareStatement (sql, null); - ResultSet rs2 = pstmt2.executeQuery (); - if (rs2.next ()) - isSOTrx = "Y".equals(rs2.getString(1)); - rs2.close (); - pstmt2.close (); - pstmt2 = null; - } - catch (Exception ee) - { - log.finest(sql + " - " + e.getMessage()); - } - try - { - if (pstmt2 != null) - pstmt2.close (); - pstmt2 = null; - } - catch (Exception ee) - { - pstmt2 = null; - } - } - else - { - log.finest(TableName + " - No SOTrx"); - // log.finest(sql + " - " + e.getMessage()); - } - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - return isSOTrx; - } // isSOTrx - - - /************************************************************************** - * Get next number for Key column = 0 is Error. - * * @param ctx client - @param TableName table name - * @param trxName optionl transaction name - * @return next no - */ - public static int getNextID (Properties ctx, String TableName, String trxName) - { - if (ctx == null) - throw new IllegalArgumentException("Context missing"); - if (TableName == null || TableName.length() == 0) - throw new IllegalArgumentException("TableName missing"); - return getNextID(Env.getAD_Client_ID(ctx), TableName, trxName); - } // getNextID - - /** - * Get next number for Key column = 0 is Error. - * @param AD_Client_ID client - * @param TableName table name - * @param trxName optional Transaction Name - * @return next no - */ - public static int getNextID (int AD_Client_ID, String TableName, String trxName) - { - if ((trxName == null || trxName.length() == 0) && isRemoteObjects()) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - int id = server.getNextID(AD_Client_ID, TableName, null); - log.finest("server => " + id); - if (id < 0) - throw new DBException("No NextID"); - return id; - } - log.log(Level.SEVERE, "AppsServer not found - " + TableName); - } - catch (RemoteException ex) - { - log.log(Level.SEVERE, "AppsServer error", ex); - } - // Try locally - } - int id = MSequence.getNextID (AD_Client_ID, TableName, trxName); // tries 3 times - // if (id <= 0) - // throw new DBException("No NextID (" + id + ")"); - return id; - } // getNextID - - /** - * Get Document No based on Document Type - * @param C_DocType_ID document type - * @param trxName optional Transaction Name - * @return document no or null - */ - public static String getDocumentNo(int C_DocType_ID, String trxName) - { - if ((trxName == null || trxName.length() == 0) && isRemoteObjects()) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - String dn = server.getDocumentNo (C_DocType_ID, trxName); - log.finest("Server => " + dn); - if (dn != null) - return dn; - } - log.log(Level.SEVERE, "AppsServer not found - " + C_DocType_ID); - } - catch (RemoteException ex) - { - log.log(Level.SEVERE, "AppsServer error", ex); - } - } - // fallback - String dn = MSequence.getDocumentNo (C_DocType_ID, trxName); - if (dn == null) // try again - dn = MSequence.getDocumentNo (C_DocType_ID, trxName); - // if (dn == null) - // throw new DBException ("No DocumentNo"); - return dn; - } // getDocumentNo - - - /** - * Get Document No from table - * @param AD_Client_ID client - * @param TableName table name - * @param trxName optional Transaction Name - * @return document no or null - */ - public static String getDocumentNo (int AD_Client_ID, String TableName, String trxName) - { - if ((trxName == null || trxName.length() == 0) && isRemoteObjects()) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - String dn = server.getDocumentNo (AD_Client_ID, TableName, trxName); - log.finest("Server => " + dn); - if (dn != null) - return dn; - } - log.log(Level.SEVERE, "AppsServer not found - " + TableName); - } - catch (RemoteException ex) - { - log.log(Level.SEVERE, "AppsServer error", ex); - } - } - // fallback - String dn = MSequence.getDocumentNo (AD_Client_ID, TableName, trxName); - if (dn == null) // try again - dn = MSequence.getDocumentNo (AD_Client_ID, TableName, trxName); - if (dn == null) - throw new DBException ("No DocumentNo"); - return dn; - } // getDocumentNo - - /** - * Get Document Number for current document. - *
- * - first search for DocType based Document No - * - then Search for DocumentNo based on TableName - * @param ctx context - * @param WindowNo window - * @param TableName table - * @param onlyDocType Do not search for document no based on TableName - * @param trxName optional Transaction Name - * @return DocumentNo or null, if no doc number defined - */ - public static String getDocumentNo (Properties ctx, int WindowNo, - String TableName, boolean onlyDocType, String trxName) - { - if (ctx == null || TableName == null || TableName.length() == 0) - throw new IllegalArgumentException("Required parameter missing"); - int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID"); - - // Get C_DocType_ID from context - NO Defaults - - int C_DocType_ID = Env.getContextAsInt(ctx, WindowNo + "|C_DocTypeTarget_ID"); - if (C_DocType_ID == 0) - C_DocType_ID = Env.getContextAsInt(ctx, WindowNo + "|C_DocType_ID"); - if (C_DocType_ID == 0) - { - log.fine("Window=" + WindowNo - + " - Target=" + Env.getContextAsInt(ctx, WindowNo + "|C_DocTypeTarget_ID") + "/" + Env.getContextAsInt(ctx, WindowNo, "C_DocTypeTarget_ID") - + " - Actual=" + Env.getContextAsInt(ctx, WindowNo + "|C_DocType_ID") + "/" + Env.getContextAsInt(ctx, WindowNo, "C_DocType_ID")); - return getDocumentNo (AD_Client_ID, TableName, trxName); - } - - String retValue = getDocumentNo (C_DocType_ID, trxName); - if (!onlyDocType && retValue == null) - return getDocumentNo (AD_Client_ID, TableName, trxName); - return retValue; - } // getDocumentNo - - /** - * Is this a remote client connection - * @return true if client and RMI or Objects on Server - */ - public static boolean isRemoteObjects() - { - return CConnection.get().isServerObjects() - && CConnection.get().isAppsServerOK(false); - } // isRemoteObjects - - /** - * Is this a remote client connection - * @return true if client and RMI or Process on Server - */ - public static boolean isRemoteProcess() - { - return CConnection.get().isServerProcess() - && CConnection.get().isAppsServerOK(false); - } // isRemoteProcess - - - /************************************************************************** - * Print SQL Warnings. - *
- * Usage: DB.printWarning("comment", rs.getWarnings()); - * @param comment comment - * @param warning warning - */ - public static void printWarning (String comment, SQLWarning warning) - { - if (comment == null || warning == null || comment.length() == 0) - throw new IllegalArgumentException("Required parameter missing"); - log.warning(comment); - if (warning == null) - return; - // - SQLWarning warn = warning; - while (warn != null) - { - StringBuffer buffer = new StringBuffer(); - buffer.append(warn.getMessage()) - .append("; State=").append(warn.getSQLState()) - .append("; ErrorCode=").append(warn.getErrorCode()); - log.warning(buffer.toString()); - warn = warn.getNextWarning(); - } - } // printWarning - - /** - * Create SQL TO Date String from Timestamp - * - * @param time Date to be converted - * @param dayOnly true if time set to 00:00:00 - * - * @return TO_DATE('2001-01-30 18:10:20',''YYYY-MM-DD HH24:MI:SS') - * or TO_DATE('2001-01-30',''YYYY-MM-DD') - */ - public static String TO_DATE (Timestamp time, boolean dayOnly) - { - return s_cc.getDatabase().TO_DATE(time, dayOnly); - } // TO_DATE - - /** - * Create SQL TO Date String from Timestamp - * @param day day time - * @return TO_DATE String (day only) - */ - public static String TO_DATE (Timestamp day) - { - return TO_DATE(day, true); - } // TO_DATE - - /** - * Create SQL for formatted Date, Number - * - * @param columnName the column name in the SQL - * @param displayType Display Type - * @param AD_Language 6 character language setting (from Env.LANG_*) - * - * @return TRIM(TO_CHAR(columnName,'9G999G990D00','NLS_NUMERIC_CHARACTERS='',.''')) - * or TRIM(TO_CHAR(columnName,'TM9')) depending on DisplayType and Language - * @see org.compiere.util.DisplayType - * @see org.compiere.util.Env - * - * */ - public static String TO_CHAR (String columnName, int displayType, String AD_Language) - { - if (columnName == null || AD_Language == null || columnName.length() == 0) - throw new IllegalArgumentException("Required parameter missing"); - return s_cc.getDatabase().TO_CHAR(columnName, displayType, AD_Language); - } // TO_CHAR - - /** - * Return number as string for INSERT statements with correct precision - * @param number number - * @param displayType display Type - * @return number as string - */ - public String TO_NUMBER (BigDecimal number, int displayType) - { - return s_cc.getDatabase().TO_NUMBER(number, displayType); - } // TO_NUMBER - - /** - * Package Strings for SQL command in quotes - * @param txt String with text - * @return escaped string for insert statement (NULL if null) - */ - public static String TO_STRING (String txt) - { - return TO_STRING (txt, 0); - } // TO_STRING - - /** - * Package Strings for SQL command in quotes. - *
-	 *		-	include in ' (single quotes)
-	 *		-	replace ' with ''
-	 *  
- * @param txt String with text - * @param maxLength Maximum Length of content or 0 to ignore - * @return escaped string for insert statement (NULL if null) - */ - public static String TO_STRING (String txt, int maxLength) - { - if (txt == null || txt.length() == 0) - return "NULL"; - - // Length - String text = txt; - if (maxLength != 0 && text.length() > maxLength) - text = txt.substring(0, maxLength); - - // copy characters (we need to look through anyway) - StringBuffer out = new StringBuffer(); - out.append(QUOTE); // ' - for (int i = 0; i < text.length(); i++) - { - char c = text.charAt(i); - if (c == QUOTE) - out.append("''"); - else - out.append(c); - } - out.append(QUOTE); // ' - // - return out.toString(); - } // TO_STRING - - /** Quote */ - private static final char QUOTE = '\''; - - /** - * Run Post Migration manually - * @param args ignored - */ - public static void main (String[] args) - { - Adempiere.startup(true); - MSystem system = MSystem.get(Env.getCtx()); - system.setIsJustMigrated(true); - afterMigration(Env.getCtx()); - } // main -} // DB - +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.util; + +import java.io.*; +import java.math.*; +import java.rmi.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; +import javax.sql.*; +import javax.swing.*; +import oracle.jdbc.*; +// +import org.compiere.*; +import org.compiere.db.*; +import org.compiere.interfaces.*; +import org.compiere.model.*; +import org.compiere.process.*; + + +/** + * General Database Interface + * + * @author Jorg Janke + * @version $Id: DB.java,v 1.8 2006/10/09 00:22:29 jjanke Exp $ + */ +public final class DB +{ + /** Connection Descriptor */ + private static CConnection s_cc = null; + /** Connection Cache r/o */ + private static Connection[] s_connections = null; + /** Connection Cache Size */ + private static int s_conCacheSize = Ini.isClient() ? 3 : 3; + /** Connection counter */ + private static int s_conCount = 0; + /** Connection r/w */ + private static Connection s_connectionRW = null; + /** Connection r/w for ID */ + private static Connection s_connectionID = null; + /** Logger */ + private static CLogger log = CLogger.getCLogger (DB.class); + + /** SQL Statement Separator "; " */ + public static final String SQLSTATEMENT_SEPARATOR = "; "; + + + /************************************************************************** + * Check need for post Upgrade + * @param ctx context + * @return true if post upgrade ran - false if there was no need + */ + public static boolean afterMigration (Properties ctx) + { + // UPDATE AD_System SET IsJustMigrated='Y' + MSystem system = MSystem.get(ctx); + if (!system.isJustMigrated()) + return false; + + // Role update + log.info("Role"); + String sql = "SELECT * FROM AD_Role"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + ResultSet rs = pstmt.executeQuery (); + while (rs.next ()) + { + MRole role = new MRole (ctx, rs, null); + role.updateAccessRecords(); + } + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, "(1)", e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + + // Release Specif stuff & Print Format + try + { + Class clazz = Class.forName("org.compiere.MigrateData"); + clazz.newInstance(); + } + catch (Exception e) + { + log.log (Level.SEVERE, "Data", e); + } + + // Language check + log.info("Language"); + MLanguage.maintain(ctx); + + // Sequence check + log.info("Sequence"); + SequenceCheck.validate(ctx); + + // Costing Setup + log.info("Costing"); + MAcctSchema[] ass = MAcctSchema.getClientAcctSchema(ctx, 0); + for (int i = 0; i < ass.length; i++) + { + ass[i].checkCosting(); + ass[i].save(); + } + + // Reset Flag + system.setIsJustMigrated(false); + return system.save(); + } // afterMigration + + /** + * Update Mail Settings for System Client and System User + */ + public static void updateMail() + { + // Get Property File + String envName = Ini.getAdempiereHome(); + if (envName == null) + return; + envName += File.separator + "AdempiereEnv.properties"; + File envFile = new File(envName); + if (!envFile.exists()) + return; + + Properties env = new Properties(); + try + { + FileInputStream in = new FileInputStream(envFile); + env.load(in); + in.close(); + } + catch (Exception e) + { + return; + } + String updated = env.getProperty("ADEMPIERE_MAIL_UPDATED"); + if (updated != null || updated.equals("Y")) + return; + + // See org.compiere.install.ConfigurationData + String server = env.getProperty("ADEMPIERE_MAIL_SERVER"); + if (server == null || server.length() == 0) + return; + String adminEMail = env.getProperty("ADEMPIERE_ADMIN_EMAIL"); + if (adminEMail == null || adminEMail.length() == 0) + return; + String mailUser = env.getProperty("ADEMPIERE_MAIL_USER"); + if (mailUser == null || mailUser.length() == 0) + return; + String mailPassword = env.getProperty("ADEMPIERE_MAIL_PASSWORD"); + // if (mailPassword == null || mailPassword.length() == 0) + // return; + // + StringBuffer sql = new StringBuffer("UPDATE AD_Client SET") + .append(" SMTPHost=").append(DB.TO_STRING(server)) + .append(", RequestEMail=").append(DB.TO_STRING(adminEMail)) + .append(", RequestUser=").append(DB.TO_STRING(mailUser)) + .append(", RequestUserPW=").append(DB.TO_STRING(mailPassword)) + .append(", IsSMTPAuthorization='Y' WHERE AD_Client_ID=0"); + int no = DB.executeUpdate(sql.toString(), null); + // + sql = new StringBuffer("UPDATE AD_User SET ") + .append(" EMail=").append(DB.TO_STRING(adminEMail)) + .append(", EMailUser=").append(DB.TO_STRING(mailUser)) + .append(", EMailUserPW=").append(DB.TO_STRING(mailUser)) + .append(" WHERE AD_User_ID IN (0,100)"); + no = DB.executeUpdate(sql.toString(), null); + // + try + { + env.setProperty("ADEMPIERE_MAIL_UPDATED", "Y"); + FileOutputStream out = new FileOutputStream(envFile); + env.store(out, ""); + out.flush(); + out.close(); + } + catch (Exception e) + { + } + + } // updateMail + + /************************************************************************** + * Set connection + * @param cc connection + */ + public static void setDBTarget (CConnection cc) + { + if (cc == null) + throw new IllegalArgumentException("Connection is NULL"); + + if (s_cc != null && s_cc.equals(cc)) + return; + + DB.closeTarget(); + // + if (s_cc == null) + s_cc = cc; + synchronized (s_cc) // use as mutex + { + s_cc = cc; + s_connections = null; + s_connectionRW = null; + s_connectionID = null; + } + s_cc.setDataSource(); + log.config(s_cc + " - DS=" + s_cc.isDataSource()); + // Trace.printStack(); + } // setDBTarget + + /** + * Connect to database and initialise all connections. + * @return True if success, false otherwise + */ + public static boolean connect() { + boolean success =false; + try + { + success = getConnectionRW() != null; + if (success) success = getConnectionRO() != null; + if (success) success = getConnectionID() != null; + s_cc.readInfo(getConnectionRW()); + } catch (Exception e) + { + success = false; + } + return success; + } + + /** + * Is there a connection to the database ? + * @return true, if connected to database + */ + public static boolean isConnected() + { + boolean success = false; + CLogErrorBuffer eb = CLogErrorBuffer.get(false); + if (eb != null && eb.isIssueError()) + eb.setIssueError(false); + else + eb = null; // don't reset + try + { + success = getConnectionRW() != null; // try to get a connection + } + catch (Exception e) + { + success = false; + } + if (eb != null) + eb.setIssueError(true); + return success; + } // isConnected + + /** + * Return (pooled) r/w AutoCommit, Serializable connection. + * For Transaction control use Trx.getConnection() + * @return Connection (r/w) + */ + public static Connection getConnectionRW () + { + // check health of connection + try + { + if (s_connectionRW == null) + ; + else if (s_connectionRW.isClosed()) + { + log.finest("Closed"); + s_connectionRW = null; + } + else if (s_connectionRW instanceof OracleConnection && ((OracleConnection)s_connectionRW).pingDatabase(1) < 0) + { + log.warning("No ping"); + s_connectionRW = null; + } + else + { + if (s_connectionRW.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + s_connectionRW.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + } + } + catch (Exception e) + { + s_connectionRW = null; + } + // Get new + if (s_connectionRW == null) + { + s_connectionRW = s_cc.getConnection (true, Connection.TRANSACTION_READ_COMMITTED); + log.finest("Con=" + s_connectionRW); + } + if (s_connectionRW == null) + throw new UnsupportedOperationException("No DBConnection"); + // + // System.err.println ("DB.getConnectionRW - " + s_connectionRW); + // Trace.printStack(); + return s_connectionRW; + } // getConnectionRW + + /** + * Return everytime a new r/w no AutoCommit, Serializable connection. + * To be used to ID + * @return Connection (r/w) + */ + public static Connection getConnectionID () + { + if (s_connectionID != null) + { + try + { + if (s_connectionID.isClosed()) + s_connectionID = null; + } + catch (Exception e) + { + s_connectionID = null; + } + } + if (s_connectionID == null) + { + s_connectionID = s_cc.getConnection (false, Connection.TRANSACTION_READ_COMMITTED); + } + if (s_connectionID == null) + throw new UnsupportedOperationException("No DBConnection"); + log.log(Level.ALL, s_connectionID.toString()); + return s_connectionID; + } // getConnectionID + + /** + * Return read committed, read/only from pool. + * @return Connection (r/o) + */ + public static Connection getConnectionRO () + { + try + { + synchronized (s_cc) // use as mutex as s_connection is null the first time + { + if (s_connections == null) + s_connections = createConnections (Connection.TRANSACTION_READ_COMMITTED); // see below + } + } + catch (Exception e) + { + log.log(Level.SEVERE, "RO", e); + } + + // check health of connection + int pos = s_conCount++; + int connectionNo = pos % s_conCacheSize; + Connection connection = s_connections[connectionNo]; + try + { + if (connection == null) + ; + else if (connection.isClosed()) + { + // RowSet.close also closes connection! + // System.out.println("DB.getConnectionRO - closed #" + connectionNo); + connection = null; + } + else if (connection instanceof OracleConnection && ((OracleConnection)connection).pingDatabase(1) < 0) + { + log.warning("No ping #" + connectionNo); + connection = null; + } + else + { + if (!connection.isReadOnly()) + connection.setReadOnly(true); + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + } + } + catch (Exception e) + { + log.severe("#" + connectionNo + " - " + e.toString()); + connection = null; + } + // Get new + if (connection == null) + { + log.finest("Replacing connection #" + connectionNo); + connection = s_cc.getConnection (true, Connection.TRANSACTION_READ_COMMITTED); // see above + try + { + if (connection != null) + connection.setReadOnly(true); + } + catch (Exception e) + { + log.severe("Cannot set to R/O - " + e); + } + s_connections[connectionNo] = connection; + } + if (connection == null) + throw new UnsupportedOperationException("DB.getConnectionRO - @NoDBConnection@"); + log.log(Level.ALL, "#" + connectionNo + " - " + connection); + // System.err.println ("DB.getConnectionRO - " + connection); + return connection; + } // getConnectionRO + + /** + * Create new Connection. + * The connection must be closed explicitly by the application + * + * @param autoCommit auto commit + * @param trxLevel - Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ, or Connection.TRANSACTION_READ_COMMITTED. + * @return Connection connection + */ + public static Connection createConnection (boolean autoCommit, int trxLevel) + { + Connection conn = s_cc.getConnection (autoCommit, trxLevel); + if (CLogMgt.isLevelFinest()) + { + /** + try + { + log.finest(s_cc.getConnectionURL() + + ", UserID=" + s_cc.getDbUid() + + ", AutoCommit=" + conn.getAutoCommit() + " (" + autoCommit + ")" + + ", TrxIso=" + conn.getTransactionIsolation() + "( " + trxLevel + ")"); + } + catch (Exception e) + { + } + **/ + } + return conn; + } // createConnection + + /** + * Create new set of r/o Connections. + * R/O connection might not be supported by DB + * + * @param trxLevel - Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ, or Connection.TRANSACTION_READ_COMMITTED. + * @return Array of Connections (size based on s_conCacheSize) + */ + private static Connection[] createConnections (int trxLevel) + { + log.finest("(" + s_conCacheSize + ") " + s_cc.getConnectionURL() + + ", UserID=" + s_cc.getDbUid() + + ", TrxLevel=" + CConnection.getTransactionIsolationInfo(trxLevel)); + Connection cons[] = new Connection[s_conCacheSize]; + try + { + for (int i = 0; i < s_conCacheSize; i++) + { + cons[i] = s_cc.getConnection (true, trxLevel); // auto commit + if (cons[i] == null) + log.warning("Connection is NULL"); // don't use log + } + } + catch (Exception e) + { + log.severe(e.getMessage()); + } + return cons; + } // createConnections + + /** + * Get Database Driver. + * Access to database specific functionality. + * @return Adempiere Database Driver + */ + public static AdempiereDatabase getDatabase() + { + if (s_cc != null) + return s_cc.getDatabase(); + log.severe("No Database Connection"); + return null; + } // getDatabase + + /** + * Get Database Driver. + * Access to database specific functionality. + * @param URL JDBC connection url + * @return Adempiere Database Driver + */ + public static AdempiereDatabase getDatabase(String URL) + { + if (URL == null) + { + log.severe("No Database URL"); + return null; + } + if (URL.indexOf("oracle") != -1) + return new DB_Oracle(); + /*if (URL.indexOf("derby") != -1) + return new DB_Derby();*/ + if (URL.indexOf("db2") != -1) + return new DB_DB2(); + log.severe("No Database for " + URL); + return null; + } // getDatabase + + /** + * Do we have an Oracle DB ? + * @return true if connected to Oracle + */ + public static boolean isOracle() + { + if (s_cc != null) + return s_cc.isOracle(); + log.severe("No Database Connection"); + return false; + } // isOracle + + /** + * Do we have a Derby DB ? + * @return true if connected to Derby + */ + public static boolean isDerby() + { + if (s_cc != null) + return s_cc.isDerby(); + log.severe("No Database Connection"); + return false; + } // isDerby + + //begin vpj-cd e-evolution 02/07/2005 PostgreSQL + /** + * Do we have a Postgre DB ? + * @return true if connected to PostgreSQL + */ + public static boolean isPostgreSQL() + { + if (s_cc != null) + return s_cc.isPostgreSQL(); + log.severe("No Database"); + return false; + } // isPostgreSQL + //begin vpj-cd e-evolution 02/07/2005 PostgreSQL + + public static boolean isDB2() + { + if (s_cc != null) + return s_cc.isDB2(); + log.severe("No Database"); + return false; + } + public static boolean isFyracle() + { + if (s_cc != null) + return s_cc.isFyracle(); + log.severe("No Database"); + return false; + } // isFyracle + + /** + * Do we have a Postgre DB ? + * @return true if connected to PostgreSQL + */ +// public static boolean isEDB() +// { +// if (s_cc != null) +// return s_cc.isEDB(); +// log.severe("No Database"); +// return false; +// } // isPostgreSQL + //end vpj-cd e-evolution 02/07/2005 PostgreSQL + + /** + * Get Database Info + * @return info + */ + public static String getDatabaseInfo() + { + if (s_cc != null) + return s_cc.getDBInfo(); + return "No Database"; + } // getDatabaseInfo + + + /************************************************************************** + * Check database Version with Code version + * @param ctx context + * @return true if Database version (date) is the same + */ + public static boolean isDatabaseOK (Properties ctx) + { + // Check Version + String version = "?"; + String sql = "SELECT Version FROM AD_System"; + try + { + PreparedStatement pstmt = prepareStatement(sql, null); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + version = rs.getString(1); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, "Problem with AD_System Table - Run system.sql script - " + e.toString()); + return false; + } + log.info("DB_Version=" + version); + // Identical DB version + if (Adempiere.DB_VERSION.equals(version)) + return true; + + String AD_Message = "DatabaseVersionError"; + String title = org.compiere.Adempiere.getName() + " " + Msg.getMsg(ctx, AD_Message, true); + // Code assumes Database version {0}, but Database has Version {1}. + String msg = Msg.getMsg(ctx, AD_Message); // complete message + msg = MessageFormat.format(msg, new Object[] {Adempiere.DB_VERSION, version}); + Object[] options = { UIManager.get("OptionPane.noButtonText"), "Migrate" }; + int no = JOptionPane.showOptionDialog (null, msg, + title, JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, + UIManager.getIcon("OptionPane.errorIcon"), options, options[0]); + if (no == 1) + { + JOptionPane.showMessageDialog (null, + "Start RUN_Migrate (in utils)\nSee: http://www.adempiere.com/maintain", + title, JOptionPane.INFORMATION_MESSAGE); + Env.exitEnv(1); + } + return false; + } // isDatabaseOK + + + /************************************************************************** + * Close Target + */ + public static void closeTarget() + { + boolean closed = false; + // RO connection + if (s_connections != null) + { + for (int i = 0; i < s_conCacheSize; i++) + { + try + { + if (s_connections[i] != null) + { + closed = true; + s_connections[i].close(); + } + } + catch (SQLException e) + { + log.warning("#" + i + " - " + e.getMessage()); + } + s_connections[i] = null; + } + } + s_connections = null; + // RW connection + try + { + if (s_connectionRW != null) + { + closed = true; + s_connectionRW.close(); + } + } + catch (SQLException e) + { + log.log(Level.SEVERE, "R/W", e); + } + s_connectionRW = null; + + //ID Connection + try + { + if (s_connectionID != null) + { + s_connectionID.close(); + } + } catch (SQLException e) + { + log.log(Level.SEVERE, "Id", e); + } + s_connectionID = null; + + // CConnection + if (s_cc != null) + { + closed = true; + s_cc.setDataSource(null); + } + s_cc = null; + if (closed) + log.fine("closed"); + } // closeTarget + + + /************************************************************************** + * Prepare Forward Read Only Call + * @param RO_SQL sql (RO) + * @return Callable Statement + */ + public static CallableStatement prepareCall(String RO_SQL) + { + if (RO_SQL == null || RO_SQL.length() == 0) + throw new IllegalArgumentException("Required parameter missing - " + RO_SQL); + // + String sql = getDatabase().convertStatement(RO_SQL); + try + { + return getConnectionRO().prepareCall + (sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + // throw new DBException(e); + } + return null; + } // prepareCall + + + /************************************************************************** + * Prepare Read Only Statement + * @param RO_SQL sql (RO) + * @return Prepared Statement + * @deprecated + */ + public static CPreparedStatement prepareStatement (String RO_SQL) + { + return prepareStatement(RO_SQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); + } // prepareStatement + + /** + * Prepare Read Only Statement + * @param RO_SQL sql (RO) + * @param trxName transaction + * @return Prepared Statement + */ + public static CPreparedStatement prepareStatement (String RO_SQL, String trxName) + { + return prepareStatement(RO_SQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, trxName); + } // prepareStatement + + /** + * Prepare Statement. + * @param sql sql statement + * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE + * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE + * @return Prepared Statement r/o or r/w depending on concur + * @deprecated + */ + public static CPreparedStatement prepareStatement (String sql, + int resultSetType, int resultSetConcurrency) + { + return prepareStatement(sql, resultSetType, resultSetConcurrency, null); + } // prepareStatement + + /** + * Prepare Statement. + * @param sql sql statement + * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE + * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE + * @param trxName transaction name + * @return Prepared Statement r/o or r/w depending on concur + */ + public static CPreparedStatement prepareStatement(String sql, + int resultSetType, int resultSetConcurrency, String trxName) + { + if (sql == null || sql.length() == 0) + throw new IllegalArgumentException("No SQL"); + // + return new CPreparedStatement(resultSetType, resultSetConcurrency, sql, trxName); + } // prepareStatement + + /** + * Create Read Only Statement + * @return Statement + */ + public static Statement createStatement() + { + return createStatement (ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); + } // createStatement + + /** + * Create Statement. + * @param resultSetType - ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE + * @param resultSetConcurrency - ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE + * @param trxName transaction name + * @return Statement - either r/w ir r/o depending on concur + */ + public static Statement createStatement(int resultSetType, int resultSetConcurrency, String trxName) + { + return new CStatement(resultSetType, resultSetConcurrency, trxName); + } // createStatement + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @return number of rows updated or -1 if error + * @deprecated + */ + public static int executeUpdate (String sql) + { + return executeUpdate(sql, null, false, null); + } // executeUpdate + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @param trxName optional transaction name + * @return number of rows updated or -1 if error + */ + public static int executeUpdate (String sql, String trxName) + { + return executeUpdate(sql, null, false, trxName); + } // executeUpdate + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @param ignoreError if true, no execution error is reported + * @return number of rows updated or -1 if error + * @deprecated + */ + public static int executeUpdate (String sql, boolean ignoreError) + { + return executeUpdate (sql, null, ignoreError, null); + } // executeUpdate + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @param ignoreError if true, no execution error is reported + * @param trxName transaction + * @return number of rows updated or -1 if error + */ + public static int executeUpdate (String sql, boolean ignoreError, String trxName) + { + return executeUpdate (sql, null, ignoreError, trxName); + } // executeUpdate + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @param param int param + * @param trxName transaction + * @return number of rows updated or -1 if error + */ + public static int executeUpdate (String sql, int param, String trxName) + { + return executeUpdate (sql, new Object[]{new Integer(param)}, false, trxName); + } // executeUpdate + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @param param int parameter + * @param ignoreError if true, no execution error is reported + * @param trxName transaction + * @return number of rows updated or -1 if error + */ + public static int executeUpdate (String sql, int param, boolean ignoreError, String trxName) + { + return executeUpdate (sql, new Object[]{new Integer(param)}, ignoreError, trxName); + } // executeUpdate + + /** + * Execute Update. + * saves "DBExecuteError" in Log + * @param sql sql + * @param params array of parameters + * @param ignoreError if true, no execution error is reported + * @param trxName optional transaction name + * @return number of rows updated or -1 if error + */ + public static int executeUpdate (String sql, Object[] params, boolean ignoreError, String trxName) + { + if (sql == null || sql.length() == 0) + throw new IllegalArgumentException("Required parameter missing - " + sql); + // + int no = -1; + CPreparedStatement cs = new CPreparedStatement(ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_UPDATABLE, sql, trxName); // converted in call + + try + { + // Set Parameter + if (params != null) + { + for (int i = 0; i < params.length; i++) + { + Object param = params[i]; + if (param instanceof String) + cs.setString(i+1, (String)param); + else if (param instanceof Integer) + cs.setInt(i+1, ((Integer)param).intValue()); + else if (param instanceof BigDecimal) + cs.setBigDecimal(i+1, (BigDecimal)param); + else if (param instanceof Timestamp) + cs.setTimestamp(i+1, (Timestamp)param); + } + } + // + no = cs.executeUpdate(); + // No Transaction - Commit + if (trxName == null) + { + cs.commit(); // Local commit + // Connection conn = cs.getConnection(); + // if (conn != null && !conn.getAutoCommit()) // is null for remote + // conn.commit(); + } + } + catch (SQLException e) + { + if (ignoreError) + log.log(Level.SEVERE, cs.getSql() + " [" + trxName + "] - " + e.getMessage()); + else + { + log.log(Level.SEVERE, cs.getSql() + " [" + trxName + "]", e); + log.saveError ("DBExecuteError", e); + } + // throw new DBException(e); + } + finally + { + // Always close cursor + try + { + cs.close(); + } + catch (SQLException e2) + { + log.log(Level.SEVERE, "Cannot close statement"); + } + } + return no; + } // executeUpdate + + /** + * Execute multiple Update statements. + * saves (last) "DBExecuteError" in Log + * @param sql multiple sql statements separated by "; " SQLSTATEMENT_SEPARATOR + * @param ignoreError if true, no execution error is reported + * @param trxName optional transaction name + * @return number of rows updated or -1 if error + */ + public static int executeUpdateMultiple (String sql, boolean ignoreError, String trxName) + { + if (sql == null || sql.length() == 0) + throw new IllegalArgumentException("Required parameter missing - " + sql); + int index = sql.indexOf(SQLSTATEMENT_SEPARATOR); + if (index == -1) + return executeUpdate(sql, null, ignoreError, trxName); + int no = 0; + // + String statements[] = sql.split(SQLSTATEMENT_SEPARATOR); + for (int i = 0; i < statements.length; i++) + { + log.fine(statements[i]); + no += executeUpdate(statements[i], null, ignoreError, trxName); + } + + return no; + } // executeUpdareMultiple + + /** + * Execute Update and throw exception. + * @param SQL sql + * @return number of rows updated or -1 if error + * @param trxName transaction + * @throws SQLException + */ + public static int executeUpdateEx (String SQL, String trxName) throws SQLException + { + if (SQL == null || SQL.length() == 0) + throw new IllegalArgumentException("Required parameter missing - " + SQL); + // + String sql = getDatabase().convertStatement(SQL); + int no = -1; + SQLException ex = null; + Connection conn = null; + Statement stmt = null; + try + { + Trx trx = trxName == null ? null : Trx.get(trxName, true); + if (trx != null) + conn = trx.getConnection(); + else + conn = DB.getConnectionRW (); + stmt = conn.createStatement(); + no = stmt.executeUpdate(sql); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql + " [" + trxName + "]", e); + ex = e; + } + finally + { + // Always close cursor + try + { + stmt.close(); + } + catch (SQLException e2) + { + log.log(Level.SEVERE, "Cannot close statement"); + } + } + if (ex != null) + throw new SQLException(ex.getMessage(), ex.getSQLState(), ex.getErrorCode()); + return no; + } // execute Update + + /** + * Commit - commit on RW connection. + * Is not required as RW connection is AutoCommit (exception: with transaction) + * @param throwException if true, re-throws exception + * @param trxName transaction name + * @return true if not needed or success + * @throws SQLException + */ + public static boolean commit (boolean throwException, String trxName) throws SQLException + { + try + { + Connection conn = null; + Trx trx = trxName == null ? null : Trx.get(trxName, true); + if (trx != null) + conn = trx.getConnection(); + else + conn = DB.getConnectionRW (); + // if (!conn.getAutoCommit()) + conn.commit(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, "[" + trxName + "]", e); + if (throwException) + throw e; + return false; + } + return true; + } // commit + + /** + * Rollback - rollback on RW connection. + * Is has no effect as RW connection is AutoCommit (exception: with transaction) + * @param throwException if true, re-throws exception + * @param trxName transaction name + * @return true if not needed or success + * @throws SQLException + */ + public static boolean rollback (boolean throwException, String trxName) throws SQLException + { + try + { + Connection conn = null; + Trx trx = trxName == null ? null : Trx.get(trxName, true); + if (trx != null) + conn = trx.getConnection(); + else + conn = DB.getConnectionRW (); + // if (!conn.getAutoCommit()) + conn.rollback(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, "[" + trxName + "]", e); + if (throwException) + throw e; + return false; + } + return true; + } // commit + + /** + * Get Row Set. + * When a Rowset is closed, it also closes the underlying connection. + * If the created RowSet is transfered by RMI, closing it makes no difference + * @param sql sql + * @param local local RowSet (own connection) + * @return row set or null + */ + public static RowSet getRowSet (String sql, boolean local) + { + RowSet retValue = null; + // Bugfix Gunther Hoppe, 02.09.2005 add vpj-cd e-evolution + // Begin + // CStatementVO info = new CStatementVO ( + // RowSet.TYPE_SCROLL_INSENSITIVE, RowSet.CONCUR_READ_ONLY, sql); + CStatementVO info = new CStatementVO (RowSet.TYPE_SCROLL_INSENSITIVE, RowSet.CONCUR_READ_ONLY, DB.getDatabase().convertStatement(sql)); + // End add vpj-cd e-evolution + CPreparedStatement stmt = new CPreparedStatement(info); + if (local) + { + retValue = stmt.local_getRowSet(); + } + else + { + retValue = stmt.remote_getRowSet(); + } + return retValue; + } // getRowSet + + /** + * Get Value from sql + * @param trxName trx + * @param sql sql + * @return first value or -1 + */ + public static int getSQLValue (String trxName, String sql) + { + int retValue = -1; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + else + log.fine("No Value " + sql); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValue + + /** + * Get Value from sql + * @param trxName trx + * @param sql sql + * @param int_param1 parameter 1 + * @return first value or -1 + */ + public static int getSQLValue (String trxName, String sql, int int_param1) + { + int retValue = -1; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + pstmt.setInt(1, int_param1); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + else + log.config("No Value " + sql + " - Param1=" + int_param1); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + " [" + trxName + "]", e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValue + + /** + * Get Value from sql + * @param trxName trx + * @param sql sql + * @param int_param1 parameter 1 + * @param int_param2 parameter 2 + * @return first value or -1 + */ + public static int getSQLValue (String trxName, String sql, int int_param1, int int_param2) + { + int retValue = -1; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + pstmt.setInt(1, int_param1); + pstmt.setInt(2, int_param2); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + else + log.info("No Value " + sql + + " - Param1=" + int_param1 + ",Param2=" + int_param2); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + ",Param2=" + int_param2 + + " [" + trxName + "]", e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValue + + /** + * Get Value from sql + * @param trxName trx + * @param sql sql + * @param str_param1 parameter 1 + * @return first value or -1 + */ + public static int getSQLValue (String trxName, String sql, String str_param1) + { + int retValue = -1; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + pstmt.setString(1, str_param1); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + else + log.info("No Value " + sql + " - Param1=" + str_param1); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql + " - Param1=" + str_param1, e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValue + + /** + * Get Value from sql + * @param trxName trx + * @param sql sql + * @param int_param1 parameter 1 + * @param s_param2 parameter 2 + * @return first value or -1 + */ + public static int getSQLValue (String trxName, String sql, int int_param1, String s_param2) + { + int retValue = -1; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + pstmt.setInt(1, int_param1); + pstmt.setString(2, s_param2); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + else + log.info("No Value: " + sql + " - Param1=" + int_param1 + ",Param2=" + s_param2); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + ",Param2=" + s_param2, e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValue + + /** + * Get String Value from sql + * @param trxName trx + * @param sql sql + * @param int_param1 parameter 1 + * @return first value or null + */ + public static String getSQLValueString (String trxName, String sql, int int_param1) + { + String retValue = null; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + pstmt.setInt(1, int_param1); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getString(1); + else + log.info("No Value " + sql + " - Param1=" + int_param1); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql + " - Param1=" + int_param1, e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValueString + + /** + * Get BigDecimal Value from sql + * @param trxName trx + * @param sql sql + * @param int_param1 parameter 1 + * @return first value or null + */ + public static BigDecimal getSQLValueBD (String trxName, String sql, int int_param1) + { + BigDecimal retValue = null; + PreparedStatement pstmt = null; + try + { + pstmt = prepareStatement(sql, trxName); + pstmt.setInt(1, int_param1); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getBigDecimal(1); + else + log.info("No Value " + sql + " - Param1=" + int_param1); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql + " - Param1=" + int_param1 + " [" + trxName + "]", e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return retValue; + } // getSQLValueBD + + + /** + * Get Array of Key Name Pairs + * @param sql select with id / name as first / second column + * @param optional if true (-1,"") is added + * @return array of key name pairs + */ + public static KeyNamePair[] getKeyNamePairs(String sql, boolean optional) + { + PreparedStatement pstmt = null; + ArrayList list = new ArrayList(); + if (optional) + list.add (new KeyNamePair(-1, "")); + try + { + pstmt = DB.prepareStatement(sql, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + list.add(new KeyNamePair(rs.getInt(1), rs.getString(2))); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + KeyNamePair[] retValue = new KeyNamePair[list.size()]; + list.toArray(retValue); + // s_log.fine("getKeyNamePairs #" + retValue.length); + return retValue; + } // getKeyNamePairs + + /** + * Is Sales Order Trx. + * Assumes Sales Order. Queries IsSOTrx of table with where clause + * @param TableName table + * @param whereClause where clause + * @return true (default) or false if tested that not SO + */ + public static boolean isSOTrx (String TableName, String whereClause) + { + if (TableName == null || TableName.length() == 0) + { + log.severe("No TableName"); + return true; + } + if (whereClause == null || whereClause.length() == 0) + { + log.severe("No Where Clause"); + return true; + } + // + boolean isSOTrx = true; + String sql = "SELECT IsSOTrx FROM " + TableName + + " WHERE " + whereClause; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + ResultSet rs = pstmt.executeQuery (); + if (rs.next ()) + isSOTrx = "Y".equals(rs.getString(1)); + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + if (TableName.endsWith("Line")) + { + String hdr = TableName.substring(0, TableName.indexOf("Line")); + sql = "SELECT IsSOTrx FROM " + hdr + + " h WHERE EXISTS (SELECT * FROM " + TableName + + " l WHERE h." + hdr + "_ID=l." + hdr + "_ID AND " + + whereClause + ")"; + PreparedStatement pstmt2 = null; + try + { + pstmt2 = DB.prepareStatement (sql, null); + ResultSet rs2 = pstmt2.executeQuery (); + if (rs2.next ()) + isSOTrx = "Y".equals(rs2.getString(1)); + rs2.close (); + pstmt2.close (); + pstmt2 = null; + } + catch (Exception ee) + { + log.finest(sql + " - " + e.getMessage()); + } + try + { + if (pstmt2 != null) + pstmt2.close (); + pstmt2 = null; + } + catch (Exception ee) + { + pstmt2 = null; + } + } + else + { + log.finest(TableName + " - No SOTrx"); + // log.finest(sql + " - " + e.getMessage()); + } + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + return isSOTrx; + } // isSOTrx + + + /************************************************************************** + * Get next number for Key column = 0 is Error. + * * @param ctx client + @param TableName table name + * @param trxName optionl transaction name + * @return next no + */ + public static int getNextID (Properties ctx, String TableName, String trxName) + { + if (ctx == null) + throw new IllegalArgumentException("Context missing"); + if (TableName == null || TableName.length() == 0) + throw new IllegalArgumentException("TableName missing"); + return getNextID(Env.getAD_Client_ID(ctx), TableName, trxName); + } // getNextID + + /** + * Get next number for Key column = 0 is Error. + * @param AD_Client_ID client + * @param TableName table name + * @param trxName optional Transaction Name + * @return next no + */ + public static int getNextID (int AD_Client_ID, String TableName, String trxName) + { + if ((trxName == null || trxName.length() == 0) && isRemoteObjects()) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + int id = server.getNextID(AD_Client_ID, TableName, null); + log.finest("server => " + id); + if (id < 0) + throw new DBException("No NextID"); + return id; + } + log.log(Level.SEVERE, "AppsServer not found - " + TableName); + } + catch (RemoteException ex) + { + log.log(Level.SEVERE, "AppsServer error", ex); + } + // Try locally + } + int id = MSequence.getNextID (AD_Client_ID, TableName, trxName); // tries 3 times + // if (id <= 0) + // throw new DBException("No NextID (" + id + ")"); + return id; + } // getNextID + + /** + * Get Document No based on Document Type + * @param C_DocType_ID document type + * @param trxName optional Transaction Name + * @return document no or null + */ + public static String getDocumentNo(int C_DocType_ID, String trxName) + { + if ((trxName == null || trxName.length() == 0) && isRemoteObjects()) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + String dn = server.getDocumentNo (C_DocType_ID, trxName); + log.finest("Server => " + dn); + if (dn != null) + return dn; + } + log.log(Level.SEVERE, "AppsServer not found - " + C_DocType_ID); + } + catch (RemoteException ex) + { + log.log(Level.SEVERE, "AppsServer error", ex); + } + } + // fallback + String dn = MSequence.getDocumentNo (C_DocType_ID, trxName); + if (dn == null) // try again + dn = MSequence.getDocumentNo (C_DocType_ID, trxName); + // if (dn == null) + // throw new DBException ("No DocumentNo"); + return dn; + } // getDocumentNo + + + /** + * Get Document No from table + * @param AD_Client_ID client + * @param TableName table name + * @param trxName optional Transaction Name + * @return document no or null + */ + public static String getDocumentNo (int AD_Client_ID, String TableName, String trxName) + { + if ((trxName == null || trxName.length() == 0) && isRemoteObjects()) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + String dn = server.getDocumentNo (AD_Client_ID, TableName, trxName); + log.finest("Server => " + dn); + if (dn != null) + return dn; + } + log.log(Level.SEVERE, "AppsServer not found - " + TableName); + } + catch (RemoteException ex) + { + log.log(Level.SEVERE, "AppsServer error", ex); + } + } + // fallback + String dn = MSequence.getDocumentNo (AD_Client_ID, TableName, trxName); + if (dn == null) // try again + dn = MSequence.getDocumentNo (AD_Client_ID, TableName, trxName); + if (dn == null) + throw new DBException ("No DocumentNo"); + return dn; + } // getDocumentNo + + /** + * Get Document Number for current document. + *
+ * - first search for DocType based Document No + * - then Search for DocumentNo based on TableName + * @param ctx context + * @param WindowNo window + * @param TableName table + * @param onlyDocType Do not search for document no based on TableName + * @param trxName optional Transaction Name + * @return DocumentNo or null, if no doc number defined + */ + public static String getDocumentNo (Properties ctx, int WindowNo, + String TableName, boolean onlyDocType, String trxName) + { + if (ctx == null || TableName == null || TableName.length() == 0) + throw new IllegalArgumentException("Required parameter missing"); + int AD_Client_ID = Env.getContextAsInt(ctx, WindowNo, "AD_Client_ID"); + + // Get C_DocType_ID from context - NO Defaults - + int C_DocType_ID = Env.getContextAsInt(ctx, WindowNo + "|C_DocTypeTarget_ID"); + if (C_DocType_ID == 0) + C_DocType_ID = Env.getContextAsInt(ctx, WindowNo + "|C_DocType_ID"); + if (C_DocType_ID == 0) + { + log.fine("Window=" + WindowNo + + " - Target=" + Env.getContextAsInt(ctx, WindowNo + "|C_DocTypeTarget_ID") + "/" + Env.getContextAsInt(ctx, WindowNo, "C_DocTypeTarget_ID") + + " - Actual=" + Env.getContextAsInt(ctx, WindowNo + "|C_DocType_ID") + "/" + Env.getContextAsInt(ctx, WindowNo, "C_DocType_ID")); + return getDocumentNo (AD_Client_ID, TableName, trxName); + } + + String retValue = getDocumentNo (C_DocType_ID, trxName); + if (!onlyDocType && retValue == null) + return getDocumentNo (AD_Client_ID, TableName, trxName); + return retValue; + } // getDocumentNo + + /** + * Is this a remote client connection + * @return true if client and RMI or Objects on Server + */ + public static boolean isRemoteObjects() + { + return CConnection.get().isServerObjects() + && CConnection.get().isAppsServerOK(false); + } // isRemoteObjects + + /** + * Is this a remote client connection + * @return true if client and RMI or Process on Server + */ + public static boolean isRemoteProcess() + { + return CConnection.get().isServerProcess() + && CConnection.get().isAppsServerOK(false); + } // isRemoteProcess + + + /************************************************************************** + * Print SQL Warnings. + *
+ * Usage: DB.printWarning("comment", rs.getWarnings()); + * @param comment comment + * @param warning warning + */ + public static void printWarning (String comment, SQLWarning warning) + { + if (comment == null || warning == null || comment.length() == 0) + throw new IllegalArgumentException("Required parameter missing"); + log.warning(comment); + if (warning == null) + return; + // + SQLWarning warn = warning; + while (warn != null) + { + StringBuffer buffer = new StringBuffer(); + buffer.append(warn.getMessage()) + .append("; State=").append(warn.getSQLState()) + .append("; ErrorCode=").append(warn.getErrorCode()); + log.warning(buffer.toString()); + warn = warn.getNextWarning(); + } + } // printWarning + + /** + * Create SQL TO Date String from Timestamp + * + * @param time Date to be converted + * @param dayOnly true if time set to 00:00:00 + * + * @return TO_DATE('2001-01-30 18:10:20',''YYYY-MM-DD HH24:MI:SS') + * or TO_DATE('2001-01-30',''YYYY-MM-DD') + */ + public static String TO_DATE (Timestamp time, boolean dayOnly) + { + return s_cc.getDatabase().TO_DATE(time, dayOnly); + } // TO_DATE + + /** + * Create SQL TO Date String from Timestamp + * @param day day time + * @return TO_DATE String (day only) + */ + public static String TO_DATE (Timestamp day) + { + return TO_DATE(day, true); + } // TO_DATE + + /** + * Create SQL for formatted Date, Number + * + * @param columnName the column name in the SQL + * @param displayType Display Type + * @param AD_Language 6 character language setting (from Env.LANG_*) + * + * @return TRIM(TO_CHAR(columnName,'9G999G990D00','NLS_NUMERIC_CHARACTERS='',.''')) + * or TRIM(TO_CHAR(columnName,'TM9')) depending on DisplayType and Language + * @see org.compiere.util.DisplayType + * @see org.compiere.util.Env + * + * */ + public static String TO_CHAR (String columnName, int displayType, String AD_Language) + { + if (columnName == null || AD_Language == null || columnName.length() == 0) + throw new IllegalArgumentException("Required parameter missing"); + return s_cc.getDatabase().TO_CHAR(columnName, displayType, AD_Language); + } // TO_CHAR + + /** + * Return number as string for INSERT statements with correct precision + * @param number number + * @param displayType display Type + * @return number as string + */ + public String TO_NUMBER (BigDecimal number, int displayType) + { + return s_cc.getDatabase().TO_NUMBER(number, displayType); + } // TO_NUMBER + + /** + * Package Strings for SQL command in quotes + * @param txt String with text + * @return escaped string for insert statement (NULL if null) + */ + public static String TO_STRING (String txt) + { + return TO_STRING (txt, 0); + } // TO_STRING + + /** + * Package Strings for SQL command in quotes. + *
+	 *		-	include in ' (single quotes)
+	 *		-	replace ' with ''
+	 *  
+ * @param txt String with text + * @param maxLength Maximum Length of content or 0 to ignore + * @return escaped string for insert statement (NULL if null) + */ + public static String TO_STRING (String txt, int maxLength) + { + if (txt == null || txt.length() == 0) + return "NULL"; + + // Length + String text = txt; + if (maxLength != 0 && text.length() > maxLength) + text = txt.substring(0, maxLength); + + // copy characters (we need to look through anyway) + StringBuffer out = new StringBuffer(); + out.append(QUOTE); // ' + for (int i = 0; i < text.length(); i++) + { + char c = text.charAt(i); + if (c == QUOTE) + out.append("''"); + else + out.append(c); + } + out.append(QUOTE); // ' + // + return out.toString(); + } // TO_STRING + + /** Quote */ + private static final char QUOTE = '\''; + + /** + * Run Post Migration manually + * @param args ignored + */ + public static void main (String[] args) + { + Adempiere.startup(true); + MSystem system = MSystem.get(Env.getCtx()); + system.setIsJustMigrated(true); + afterMigration(Env.getCtx()); + } // main +} // DB + diff --git a/dbPort/src/org/compiere/util/Env.java b/dbPort/src/org/compiere/util/Env.java index 28fada88dd..2ecc0ac9d7 100644 --- a/dbPort/src/org/compiere/util/Env.java +++ b/dbPort/src/org/compiere/util/Env.java @@ -3,23 +3,23 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.util; - -import java.awt.*; -import java.math.*; -import java.net.*; -import java.sql.*; + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.util; + +import java.awt.*; +import java.math.*; +import java.net.*; +import java.sql.*; import java.util.*; import java.util.logging.*; import javax.swing.*; @@ -27,1234 +27,1220 @@ import javax.swing.*; import org.compiere.*; import org.compiere.db.*; import org.compiere.model.*; -import org.compiere.swing.*; - - -/** - * System Environment and static variables - * - * @author Jorg Janke - * @version $Id: Env.java,v 1.3 2006/07/30 00:54:36 jjanke Exp $ - */ -public final class Env -{ - /** Logging */ - private static CLogger s_log = CLogger.getCLogger(Env.class); - - /** - * Exit System - * @param status System exit status (usually 0 for no error) - */ - public static void exitEnv (int status) - { - // End Session - MSession session = MSession.get(Env.getCtx(), false); // finish - if (session != null) - session.logout(); - // - reset(true); // final cache reset - s_log.info(""); - // - CLogMgt.shutdown(); - // - if (Ini.isClient()) - System.exit (status); +import org.compiere.swing.*; + + +/** + * System Environment and static variables + * + * @author Jorg Janke + * @version $Id: Env.java,v 1.3 2006/07/30 00:54:36 jjanke Exp $ + */ +public final class Env +{ + /** Logging */ + private static CLogger s_log = CLogger.getCLogger(Env.class); + + /** + * Exit System + * @param status System exit status (usually 0 for no error) + */ + public static void exitEnv (int status) + { + // End Session + MSession session = MSession.get(Env.getCtx(), false); // finish + if (session != null) + session.logout(); + // + reset(true); // final cache reset + s_log.info(""); + // + CLogMgt.shutdown(); + // + if (Ini.isClient()) + System.exit (status); } // close - /** - * Logout from the system - */ - public static void logout() - { - // End Session - MSession session = MSession.get(Env.getCtx(), false); // finish - if (session != null) - session.logout(); - // - reset(true); // final cache reset - // - } - /** * Reset Cache * @param finalCall everything otherwise login data remains */ - public static void reset (boolean finalCall) - { - s_log.info("finalCall=" + finalCall); - closeWindows(); - - // Dismantle windows - /** - for (int i = 0; i < s_windows.size(); i++) - { - Container win = (Container)s_windows.get(i); - if (win.getClass().getName().endsWith("AMenu")) // Null pointer - ; - else if (win instanceof Window) - ((Window)win).dispose(); - else - win.removeAll(); - } - **/ - s_windows.clear(); - - // Clear all Context - if (finalCall) - s_ctx.clear(); - else // clear window context only - { - Object[] keys = s_ctx.keySet().toArray(); - for (int i = 0; i < keys.length; i++) - { - String tag = keys[i].toString(); - if (Character.isDigit(tag.charAt(0))) - s_ctx.remove(keys[i]); - } - } - - // Cache - CacheMgt.get().reset(); - DB.closeTarget(); - // Reset Role Access - if (!finalCall) - { - DB.setDBTarget(CConnection.get()); - MRole defaultRole = MRole.getDefault(s_ctx, false); - if (defaultRole != null) - defaultRole.loadAccess(true); // Reload - } - } // resetAll - - - /************************************************************************** - * Application Context - */ - private static Properties s_ctx = new Properties(); - /** WindowNo for Find */ - public static final int WINDOW_FIND = 1110; - /** WinowNo for MLookup */ - public static final int WINDOW_MLOOKUP = 1111; - /** WindowNo for PrintCustomize */ - public static final int WINDOW_CUSTOMIZE = 1112; - /** WindowNo for PrintCustomize */ - public static final int WINDOW_INFO = 1113; - - /** Tab for Info */ - public static final int TAB_INFO = 1113; - - /** - * Get Context - * @return Properties - */ - public static final Properties getCtx() - { - return s_ctx; - } // getCtx - - /** - * Set Context - * @param ctx context - */ - public static void setCtx (Properties ctx) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - s_ctx.clear(); - s_ctx = ctx; - } // setCtx - - /** - * Set Global Context to Value - * @param ctx context - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, String context, String value) - { - if (ctx == null || context == null) - return; - s_log.finer("Context " + context + "==" + value); - // - if (value == null || value.length() == 0) - ctx.remove(context); - else - ctx.setProperty(context, value); - } // setContext - - /** - * Set Global Context to Value - * @param ctx context - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, String context, Timestamp value) - { - if (ctx == null || context == null) - return; - if (value == null) - { - ctx.remove(context); - s_log.finer("Context " + context + "==" + value); - } - else - { // JDBC Format 2005-05-09 00:00:00.0 - String stringValue = value.toString(); - // Chop off .0 - stringValue = stringValue.substring(0, stringValue.length()-2); - ctx.setProperty(context, stringValue); - s_log.finer("Context " + context + "==" + stringValue); - } - } // setContext - - /** - * Set Global Context to (int) Value - * @param ctx context - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, String context, int value) - { - if (ctx == null || context == null) - return; - s_log.finer("Context " + context + "==" + value); - // - ctx.setProperty(context, String.valueOf(value)); - } // setContext - - /** - * Set Global Context to Y/N Value - * @param ctx context - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, String context, boolean value) - { - setContext (ctx, context, value ? "Y" : "N"); - } // setContext - - /** - * Set Context for Window to Value - * @param ctx context - * @param WindowNo window no - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, int WindowNo, String context, String value) - { - if (ctx == null || context == null) - return; - if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP) - s_log.finer("Context("+WindowNo+") " + context + "==" + value); - // - if (value == null || value.equals("")) - ctx.remove(WindowNo+"|"+context); - else - ctx.setProperty(WindowNo+"|"+context, value); - } // setContext - - /** - * Set Context for Window to Value - * @param ctx context - * @param WindowNo window no - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, int WindowNo, String context, Timestamp value) - { - if (ctx == null || context == null) - return; - boolean logit = WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP; - if (value == null) - { - ctx.remove(WindowNo+"|"+context); - s_log.finer("Context("+WindowNo+") " + context + "==" + value); - } - else - { // JDBC Format 2005-05-09 00:00:00.0 - String stringValue = value.toString(); - // Chop off .0 - stringValue = stringValue.substring(0, stringValue.length()-2); - ctx.setProperty(WindowNo+"|"+context, stringValue); - s_log.finer("Context("+WindowNo+") " + context + "==" + stringValue); - } - } // setContext - - /** - * Set Context for Window to int Value - * @param ctx context - * @param WindowNo window no - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, int WindowNo, String context, int value) - { - if (ctx == null || context == null) - return; - if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP) - s_log.finer("Context("+WindowNo+") " + context + "==" + value); - // - ctx.setProperty(WindowNo+"|"+context, String.valueOf(value)); - } // setContext - - /** - * Set Context for Window to Y/N Value - * @param ctx context - * @param WindowNo window no - * @param context context key - * @param value context value - */ - public static void setContext (Properties ctx, int WindowNo, String context, boolean value) - { - setContext (ctx, WindowNo, context, value ? "Y" : "N"); - } // setContext - - /** - * Set Context for Window & Tab to Value - * @param ctx context - * @param WindowNo window no - * @param TabNo tab no - * @param context context key - * @param value context value - * */ - public static void setContext (Properties ctx, int WindowNo, int TabNo, String context, String value) - { - if (ctx == null || context == null) - return; - if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP) - s_log.finest("Context("+WindowNo+","+TabNo+") " + context + "==" + value); - // - if (value == null || value.equals("")) - ctx.remove(WindowNo+"|"+TabNo+"|"+context); - else - ctx.setProperty(WindowNo+"|"+TabNo+"|"+context, value); - } // setContext - - /** - * Set Auto Commit - * @param ctx context - * @param autoCommit auto commit (save) - */ - public static void setAutoCommit (Properties ctx, boolean autoCommit) - { - if (ctx == null) - return; - ctx.setProperty("AutoCommit", autoCommit ? "Y" : "N"); - } // setAutoCommit - - /** - * Set Auto Commit for Window - * @param ctx context - * @param WindowNo window no - * @param autoCommit auto commit (save) - */ - public static void setAutoCommit (Properties ctx, int WindowNo, boolean autoCommit) - { - if (ctx == null) - return; - ctx.setProperty(WindowNo+"|AutoCommit", autoCommit ? "Y" : "N"); - } // setAutoCommit - - /** - * Set Auto New Record - * @param ctx context - * @param autoNew auto new record - */ - public static void setAutoNew (Properties ctx, boolean autoNew) - { - if (ctx == null) - return; - ctx.setProperty("AutoNew", autoNew ? "Y" : "N"); - } // setAutoNew - - /** - * Set Auto New Record for Window - * @param ctx context - * @param WindowNo window no - * @param autoNew auto new record - */ - public static void setAutoNew (Properties ctx, int WindowNo, boolean autoNew) - { - if (ctx == null) - return; - ctx.setProperty(WindowNo+"|AutoNew", autoNew ? "Y" : "N"); - } // setAutoNew - - - /** - * Set SO Trx - * @param ctx context - * @param isSOTrx SO Context - */ - public static void setSOTrx (Properties ctx, boolean isSOTrx) - { - if (ctx == null) - return; - ctx.setProperty("IsSOTrx", isSOTrx ? "Y" : "N"); - } // setSOTrx - - /** - * Get global Value of Context - * @param ctx context - * @param context context key - * @return value or "" - */ - public static String getContext (Properties ctx, String context) - { - if (ctx == null || context == null) - throw new IllegalArgumentException ("Require Context"); - return ctx.getProperty(context, ""); - } // getContext - - /** - * Get Value of Context for Window. - * if not found global context if available and enabled - * @param ctx context - * @param WindowNo window - * @param context context key - * @param onlyWindow if true, no defaults are used unless explicitly asked for - * @return value or "" - */ - public static String getContext (Properties ctx, int WindowNo, String context, boolean onlyWindow) - { - if (ctx == null) - throw new IllegalArgumentException ("No Ctx"); - if (context == null) - throw new IllegalArgumentException ("Require Context"); - String s = ctx.getProperty(WindowNo+"|"+context); - if (s == null) - { - // Explicit Base Values - if (context.startsWith("#") || context.startsWith("$")) - return getContext(ctx, context); - if (onlyWindow) // no Default values - return ""; - return getContext(ctx, "#" + context); - } - return s; - } // getContext - - /** - * Get Value of Context for Window. - * if not found global context if available - * @param ctx context - * @param WindowNo window - * @param context context key - * @return value or "" - */ - public static String getContext (Properties ctx, int WindowNo, String context) - { - return getContext(ctx, WindowNo, context, false); - } // getContext - - /** - * Get Value of Context for Window & Tab, - * if not found global context if available - * @param ctx context - * @param WindowNo window no - * @param TabNo tab no - * @param context context key - * @return value or "" - */ - public static String getContext (Properties ctx, int WindowNo, int TabNo, String context) - { - if (ctx == null || context == null) - throw new IllegalArgumentException ("Require Context"); - String s = ctx.getProperty(WindowNo+"|"+TabNo+"|"+context); - if (s == null) - return getContext(ctx, WindowNo, context, false); - return s; - } // getContext - - /** - * Get Context and convert it to an integer (0 if error) - * @param ctx context - * @param context context key - * @return value - */ - public static int getContextAsInt(Properties ctx, String context) - { - if (ctx == null || context == null) - throw new IllegalArgumentException ("Require Context"); - String s = getContext(ctx, context); - if (s.length() == 0) - s = getContext(ctx, 0, context, false); // search 0 and defaults - if (s.length() == 0) - return 0; - // - try - { - return Integer.parseInt(s); - } - catch (NumberFormatException e) - { - s_log.log(Level.SEVERE, "(" + context + ") = " + s, e); - } - return 0; - } // getContextAsInt - - /** - * Get Context and convert it to an integer (0 if error) - * @param ctx context - * @param WindowNo window no - * @param context context key - * @return value or 0 - */ - public static int getContextAsInt(Properties ctx, int WindowNo, String context) - { - String s = getContext(ctx, WindowNo, context, false); - if (s.length() == 0) - return 0; - // - try - { - return Integer.parseInt(s); - } - catch (NumberFormatException e) - { - s_log.log(Level.SEVERE, "(" + context + ") = " + s, e); - } - return 0; - } // getContextAsInt - - /** - * Get Context and convert it to an integer (0 if error) - * @param ctx context - * @param WindowNo window no - * @param TabNo tab no - * @param context context key - * @return value or 0 - */ - public static int getContextAsInt (Properties ctx, int WindowNo, int TabNo, String context) - { - String s = getContext(ctx, WindowNo, TabNo, context); - if (s.length() == 0) - return 0; - // - try - { - return Integer.parseInt(s); - } - catch (NumberFormatException e) - { - s_log.log(Level.SEVERE, "(" + context + ") = " + s, e); - } - return 0; - } // getContextAsInt - - /** - * Is AutoCommit - * @param ctx context - * @return true if auto commit - */ - public static boolean isAutoCommit (Properties ctx) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - String s = getContext(ctx, "AutoCommit"); - if (s != null && s.equals("Y")) - return true; - return false; - } // isAutoCommit - - /** - * Is Window AutoCommit (if not set use default) - * @param ctx context - * @param WindowNo window no - * @return true if auto commit - */ - public static boolean isAutoCommit (Properties ctx, int WindowNo) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - String s = getContext(ctx, WindowNo, "AutoCommit", false); - if (s != null) - { - if (s.equals("Y")) - return true; - else - return false; - } - return isAutoCommit(ctx); - } // isAutoCommit - - - /** - * Is Auto New Record - * @param ctx context - * @return true if auto new - */ - public static boolean isAutoNew (Properties ctx) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - String s = getContext(ctx, "AutoNew"); - if (s != null && s.equals("Y")) - return true; - return false; - } // isAutoNew - - /** - * Is Window Auto New Record (if not set use default) - * @param ctx context - * @param WindowNo window no - * @return true if auto new record - */ - public static boolean isAutoNew (Properties ctx, int WindowNo) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - String s = getContext(ctx, WindowNo, "AutoNew", false); - if (s != null) - { - if (s.equals("Y")) - return true; - else - return false; - } - return isAutoNew(ctx); - } // isAutoNew - - - /** - * Is Sales Order Trx - * @param ctx context - * @return true if SO (default) - */ - public static boolean isSOTrx (Properties ctx) - { - String s = getContext(ctx, "IsSOTrx"); - if (s != null && s.equals("N")) - return false; - return true; - } // isSOTrx - - /** - * Is Sales Order Trx - * @param ctx context - * @param WindowNo window no - * @return true if SO (default) - */ - public static boolean isSOTrx (Properties ctx, int WindowNo) - { - String s = getContext(ctx, WindowNo, "IsSOTrx", true); - if (s != null && s.equals("N")) - return false; - return true; - } // isSOTrx - - /** - * Get Context and convert it to a Timestamp - * if error return today's date - * @param ctx context - * @param context context key - * @return Timestamp - */ - public static Timestamp getContextAsDate(Properties ctx, String context) - { - return getContextAsDate(ctx, 0, context); - } // getContextAsDate - - /** - * Get Context and convert it to a Timestamp - * if error return today's date - * @param ctx context - * @param WindowNo window no - * @param context context key - * @return Timestamp - */ - public static Timestamp getContextAsDate(Properties ctx, int WindowNo, String context) - { - if (ctx == null || context == null) - throw new IllegalArgumentException ("Require Context"); - String s = getContext(ctx, WindowNo, context, false); - // JDBC Format YYYY-MM-DD example 2000-09-11 00:00:00.0 - if (s == null || s.equals("")) - { - s_log.log(Level.SEVERE, "No value for: " + context); - return new Timestamp(System.currentTimeMillis()); - } - - // timestamp requires time - if (s.trim().length() == 10) - s = s.trim() + " 00:00:00.0"; - else if (s.indexOf('.') == -1) - s = s.trim() + ".0"; - - return Timestamp.valueOf(s); - } // getContextAsDate - - /** - * Get Login AD_Client_ID - * @param ctx context - * @return login AD_Client_ID - */ - public static int getAD_Client_ID (Properties ctx) - { - return Env.getContextAsInt(ctx, "#AD_Client_ID"); - } // getAD_Client_ID - - /** - * Get Login AD_Org_ID - * @param ctx context - * @return login AD_Org_ID - */ - public static int getAD_Org_ID (Properties ctx) - { - return Env.getContextAsInt(ctx, "#AD_Org_ID"); - } // getAD_Client_ID - - /** - * Get Login AD_User_ID - * @param ctx context - * @return login AD_User_ID - */ - public static int getAD_User_ID (Properties ctx) - { - return Env.getContextAsInt(ctx, "#AD_User_ID"); - } // getAD_User_ID - - /** - * Get Login AD_Role_ID - * @param ctx context - * @return login AD_Role_ID - */ - public static int getAD_Role_ID (Properties ctx) - { - return Env.getContextAsInt(ctx, "#AD_Role_ID"); - } // getAD_Role_ID - - /************************************************************************** - * Get Preference. - *
-	 *		0)	Current Setting
-	 *		1) 	Window Preference
-	 *		2) 	Global Preference
-	 *		3)	Login settings
-	 *		4)	Accounting settings
-	 *  
- * @param ctx context - * @param AD_Window_ID window no - * @param context Entity to search - * @param system System level preferences (vs. user defined) - * @return preference value - */ - public static String getPreference (Properties ctx, int AD_Window_ID, String context, boolean system) - { - if (ctx == null || context == null) - throw new IllegalArgumentException ("Require Context"); - String retValue = null; - // - if (!system) // User Preferences - { - retValue = ctx.getProperty("P"+AD_Window_ID+"|"+context);// Window Pref - if (retValue == null) - retValue = ctx.getProperty("P|"+context); // Global Pref - } - else // System Preferences - { - retValue = ctx.getProperty("#"+context); // Login setting - if (retValue == null) - retValue = ctx.getProperty("$"+context); // Accounting setting - } - // - return (retValue == null ? "" : retValue); - } // getPreference - - /************************************************************************** - * Language issues - */ - - /** Context Language identifier */ - static public final String LANGUAGE = "#AD_Language"; - - /** - * Check Base Language - * @param ctx context - * @param tableName table to be translated - * @return true if base language and table not translated - */ - public static boolean isBaseLanguage (Properties ctx, String tableName) - { - /** - if (isBaseTranslation(tableName)) - return Language.isBaseLanguage (getAD_Language(ctx)); - else // No AD Table - if (!isMultiLingualDocument(ctx)) - return true; // access base table - **/ - return Language.isBaseLanguage (getAD_Language(ctx)); - } // isBaseLanguage - - /** - * Check Base Language - * @param AD_Language language - * @param tableName table to be translated - * @return true if base language and table not translated - */ - public static boolean isBaseLanguage (String AD_Language, String tableName) - { - /** - if (isBaseTranslation(tableName)) - return Language.isBaseLanguage (AD_Language); - else // No AD Table - if (!isMultiLingualDocument(s_ctx)) // Base Context - return true; // access base table - **/ - return Language.isBaseLanguage (AD_Language); - } // isBaseLanguage - - /** - * Check Base Language - * @param language language - * @param tableName table to be translated - * @return true if base language and table not translated - */ - public static boolean isBaseLanguage (Language language, String tableName) - { - /** - if (isBaseTranslation(tableName)) - return language.isBaseLanguage(); - else // No AD Table - if (!isMultiLingualDocument(s_ctx)) // Base Context - return true; // access base table - **/ - return language.isBaseLanguage(); - } // isBaseLanguage - - /** - * Table is in Base Translation (AD) - * @param tableName table - * @return true if base trl - */ - public static boolean isBaseTranslation (String tableName) - { - if (tableName.startsWith("AD") - || tableName.equals("C_Country_Trl") ) - return true; - return false; - } // isBaseTranslation - - /** - * Do we have Multi-Lingual Documents. - * Set in DB.loadOrgs - * @param ctx context - * @return true if multi lingual documents - */ - public static boolean isMultiLingualDocument (Properties ctx) - { - return MClient.get(ctx).isMultiLingualDocument(); - } // isMultiLingualDocument - - /** - * Get System AD_Language - * @param ctx context - * @return AD_Language eg. en_US - */ - public static String getAD_Language (Properties ctx) - { - if (ctx != null) - { - String lang = getContext(ctx, LANGUAGE); - if (lang != null || lang.length() > 0) - return lang; - } - return Language.getBaseAD_Language(); - } // getAD_Language - - /** - * Get System Language - * @param ctx context - * @return Language - */ - public static Language getLanguage (Properties ctx) - { - if (ctx != null) - { - String lang = getContext(ctx, LANGUAGE); - if (lang != null || lang.length() > 0) - return Language.getLanguage(lang); - } - return Language.getBaseLanguage(); - } // getLanguage - - /** - * Get Login Language - * @param ctx context - * @return Language - */ - public static Language getLoginLanguage (Properties ctx) - { - return Language.getLoginLanguage(); - } // getLanguage - - /** - * Verify Language. - * Check that language is supported by the system - * @param ctx might be updated with new AD_Language - * @param language language - */ - public static void verifyLanguage (Properties ctx, Language language) - { - if (language.isBaseLanguage()) - return; - - boolean isSystemLanguage = false; - ArrayList AD_Languages = new ArrayList(); - String sql = "SELECT DISTINCT AD_Language FROM AD_Message_Trl"; - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - String AD_Language = rs.getString(1); - if (AD_Language.equals(language.getAD_Language())) - { - isSystemLanguage = true; - break; - } - AD_Languages.add(AD_Language); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, "", e); - } - // Found it - if (isSystemLanguage) - return; - // No Language - set to System - if (AD_Languages.size() == 0) - { - s_log.warning ("NO System Language - Set to Base " + Language.getBaseAD_Language()); - language.setAD_Language(Language.getBaseAD_Language()); - return; - } - - for (int i = 0; i < AD_Languages.size(); i++) - { - String AD_Language = (String)AD_Languages.get(i); // en_US - String lang = AD_Language.substring(0, 2); // en - // - String langCompare = language.getAD_Language().substring(0, 2); - if (lang.equals(langCompare)) - { - s_log.fine("Found similar Language " + AD_Language); - language.setAD_Language(AD_Language); - return; - } - } - - // We found same language - // if (!"0".equals(Msg.getMsg(AD_Language, "0"))) - - s_log.warning ("Not System Language=" + language - + " - Set to Base Language " + Language.getBaseAD_Language()); - language.setAD_Language(Language.getBaseAD_Language()); - } // verifyLanguage - - /************************************************************************** - * Get Context as String array with format: key == value - * @param ctx context - * @return context string - */ - public static String[] getEntireContext(Properties ctx) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - Iterator keyIterator = ctx.keySet().iterator(); - String[] sList = new String[ctx.size()]; - int i = 0; - while (keyIterator.hasNext()) - { - Object key = keyIterator.next(); - sList[i++] = key.toString() + " == " + ctx.get(key).toString(); - } - - return sList; - } // getEntireContext - - /** - * Get Header info (connection, org, user) - * @param ctx context - * @param WindowNo window - * @return Header String - */ - public static String getHeader(Properties ctx, int WindowNo) - { - StringBuffer sb = new StringBuffer(); - if (WindowNo > 0) - sb.append(getContext(ctx, WindowNo, "WindowName", false)).append(" "); - sb.append(getContext(ctx, "#AD_User_Name")).append("@") - .append(getContext(ctx, "#AD_Client_Name")).append(".") - .append(getContext(ctx, "#AD_Org_Name")) - .append(" [").append(CConnection.get().toString()).append("]"); - return sb.toString(); - } // getHeader - - /** - * Clean up context for Window (i.e. delete it) - * @param ctx context - * @param WindowNo window - */ - public static void clearWinContext(Properties ctx, int WindowNo) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - // - Object[] keys = ctx.keySet().toArray(); - for (int i = 0; i < keys.length; i++) - { - String tag = keys[i].toString(); - if (tag.startsWith(WindowNo+"|")) - ctx.remove(keys[i]); - } - // Clear Lookup Cache - MLookupCache.cacheReset(WindowNo); - // MLocator.cacheReset(WindowNo); - // - removeWindow(WindowNo); - } // clearWinContext - - /** - * Clean up all context (i.e. delete it) - * @param ctx context - */ - public static void clearContext(Properties ctx) - { - if (ctx == null) - throw new IllegalArgumentException ("Require Context"); - ctx.clear(); - } // clearContext - - - /** - * Parse Context replaces global or Window context @tag@ with actual value. - * - * @tag@ are ignored otherwise "" is returned - * @param ctx context - * @param WindowNo Number of Window - * @param value Message to be parsed - * @param onlyWindow if true, no defaults are used - * @param ignoreUnparsable if true, unsuccessful @return parsed String or "" if not successful and ignoreUnparsable - * @return parsed context - */ - public static String parseContext (Properties ctx, int WindowNo, String value, - boolean onlyWindow, boolean ignoreUnparsable) - { - if (value == null || value.length() == 0) - return ""; - - String token; - String inStr = new String(value); - StringBuffer outStr = new StringBuffer(); - - int i = inStr.indexOf('@'); - while (i != -1) - { - outStr.append(inStr.substring(0, i)); // up to @ - inStr = inStr.substring(i+1, inStr.length()); // from first @ - - int j = inStr.indexOf('@'); // next @ - if (j < 0) - { - s_log.log(Level.SEVERE, "No second tag: " + inStr); - return ""; // no second tag - } - - token = inStr.substring(0, j); - - String ctxInfo = getContext(ctx, WindowNo, token, onlyWindow); // get context - if (ctxInfo.length() == 0 && (token.startsWith("#") || token.startsWith("$")) ) - ctxInfo = getContext(ctx, token); // get global context - if (ctxInfo.length() == 0) - { - s_log.config("No Context Win=" + WindowNo + " for: " + token); - if (!ignoreUnparsable) - return ""; // token not found - } - else - outStr.append(ctxInfo); // replace context with Context - - inStr = inStr.substring(j+1, inStr.length()); // from second @ - i = inStr.indexOf('@'); - } - outStr.append(inStr); // add the rest of the string - - return outStr.toString(); - } // parseContext - - /** - * Parse Context replaces global or Window context @tag@ with actual value. - * - * @param ctx context - * @param WindowNo Number of Window - * @param value Message to be parsed - * @param onlyWindow if true, no defaults are used - * @return parsed String or "" if not successful - */ - public static String parseContext (Properties ctx, int WindowNo, String value, - boolean onlyWindow) - { - return parseContext(ctx, WindowNo, value, onlyWindow, false); - } // parseContext - - /*************************************************************************/ - - // Array of active Windows - private static ArrayList s_windows = new ArrayList(20); - - /** - * Add Container and return WindowNo. - * The container is a APanel, AWindow or JFrame/JDialog - * @param win window - * @return WindowNo used for context - */ - public static int createWindowNo(Container win) - { - int retValue = s_windows.size(); - s_windows.add(win); - return retValue; - } // createWindowNo - - /** - * Search Window by comparing the Frames - * @param container container - * @return WindowNo of container or 0 - */ - public static int getWindowNo (Container container) - { - if (container == null) - return 0; - JFrame winFrame = getFrame(container); - if (winFrame == null) - return 0; - - // loop through windows - for (int i = 0; i < s_windows.size(); i++) - { - Container cmp = (Container)s_windows.get(i); - if (cmp != null) - { - JFrame cmpFrame = getFrame(cmp); - if (winFrame.equals(cmpFrame)) - return i; - } - } - return 0; - } // getWindowNo - - /** - * Return the JFrame pointer of WindowNo - or null - * @param WindowNo window - * @return JFrame of WindowNo - */ - public static JFrame getWindow (int WindowNo) - { - JFrame retValue = null; - try - { - retValue = getFrame ((Container)s_windows.get(WindowNo)); - } - catch (Exception e) - { - s_log.log(Level.SEVERE, e.toString()); - } - return retValue; - } // getWindow - - /** - * Remove window from active list - * @param WindowNo window - */ - private static void removeWindow (int WindowNo) - { - if (WindowNo < s_windows.size()) - s_windows.set(WindowNo, null); - } // removeWindow - - /** - * Clean up context for Window (i.e. delete it) - * @param WindowNo window - */ - public static void clearWinContext(int WindowNo) - { - clearWinContext (s_ctx, WindowNo); - } // clearWinContext - - /** - * Clean up all context (i.e. delete it) - */ - public static void clearContext() - { - s_ctx.clear(); - } // clearContext - - - /************************************************************************** - * Get Frame of Window - * @param container Container - * @return JFrame of container or null - */ - public static JFrame getFrame (Container container) - { - Container element = container; - while (element != null) - { - if (element instanceof JFrame) - return (JFrame)element; - element = element.getParent(); - } - return null; - } // getFrame - - /** - * Get Graphics of container or its parent. - * The element may not have a Graphic if not displayed yet, - * but the parent might have. - * @param container Container - * @return Graphics of container or null - */ - public static Graphics getGraphics (Container container) - { - Container element = container; - while (element != null) - { - Graphics g = element.getGraphics(); - if (g != null) - return g; - element = element.getParent(); - } - return null; - } // getFrame - - /** - * Return JDialog or JFrame Parent - * @param container Container - * @return JDialog or JFrame of container - */ - public static Window getParent (Container container) - { - Container element = container; - while (element != null) - { - if (element instanceof JDialog || element instanceof JFrame) - return (Window)element; - if (element instanceof Window) - return (Window)element; - element = element.getParent(); - } - return null; - } // getParent - - /************************************************************************** - * Get Image with File name - * - * @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif) - * @return image + public static void reset (boolean finalCall) + { + s_log.info("finalCall=" + finalCall); + closeWindows(); + + // Dismantle windows + /** + for (int i = 0; i < s_windows.size(); i++) + { + Container win = (Container)s_windows.get(i); + if (win.getClass().getName().endsWith("AMenu")) // Null pointer + ; + else if (win instanceof Window) + ((Window)win).dispose(); + else + win.removeAll(); + } + **/ + s_windows.clear(); + + // Clear all Context + if (finalCall) + s_ctx.clear(); + else // clear window context only + { + Object[] keys = s_ctx.keySet().toArray(); + for (int i = 0; i < keys.length; i++) + { + String tag = keys[i].toString(); + if (Character.isDigit(tag.charAt(0))) + s_ctx.remove(keys[i]); + } + } + + // Cache + CacheMgt.get().reset(); + DB.closeTarget(); + // Reset Role Access + if (!finalCall) + { + DB.setDBTarget(CConnection.get()); + MRole defaultRole = MRole.getDefault(s_ctx, false); + if (defaultRole != null) + defaultRole.loadAccess(true); // Reload + } + } // resetAll + + + /************************************************************************** + * Application Context + */ + private static Properties s_ctx = new Properties(); + /** WindowNo for Find */ + public static final int WINDOW_FIND = 1110; + /** WinowNo for MLookup */ + public static final int WINDOW_MLOOKUP = 1111; + /** WindowNo for PrintCustomize */ + public static final int WINDOW_CUSTOMIZE = 1112; + /** WindowNo for PrintCustomize */ + public static final int WINDOW_INFO = 1113; + + /** Tab for Info */ + public static final int TAB_INFO = 1113; + + /** + * Get Context + * @return Properties + */ + public static final Properties getCtx() + { + return s_ctx; + } // getCtx + + /** + * Set Context + * @param ctx context + */ + public static void setCtx (Properties ctx) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + s_ctx.clear(); + s_ctx = ctx; + } // setCtx + + /** + * Set Global Context to Value + * @param ctx context + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, String context, String value) + { + if (ctx == null || context == null) + return; + s_log.finer("Context " + context + "==" + value); + // + if (value == null || value.length() == 0) + ctx.remove(context); + else + ctx.setProperty(context, value); + } // setContext + + /** + * Set Global Context to Value + * @param ctx context + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, String context, Timestamp value) + { + if (ctx == null || context == null) + return; + if (value == null) + { + ctx.remove(context); + s_log.finer("Context " + context + "==" + value); + } + else + { // JDBC Format 2005-05-09 00:00:00.0 + String stringValue = value.toString(); + // Chop off .0 + stringValue = stringValue.substring(0, stringValue.length()-2); + ctx.setProperty(context, stringValue); + s_log.finer("Context " + context + "==" + stringValue); + } + } // setContext + + /** + * Set Global Context to (int) Value + * @param ctx context + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, String context, int value) + { + if (ctx == null || context == null) + return; + s_log.finer("Context " + context + "==" + value); + // + ctx.setProperty(context, String.valueOf(value)); + } // setContext + + /** + * Set Global Context to Y/N Value + * @param ctx context + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, String context, boolean value) + { + setContext (ctx, context, value ? "Y" : "N"); + } // setContext + + /** + * Set Context for Window to Value + * @param ctx context + * @param WindowNo window no + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, int WindowNo, String context, String value) + { + if (ctx == null || context == null) + return; + if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP) + s_log.finer("Context("+WindowNo+") " + context + "==" + value); + // + if (value == null || value.equals("")) + ctx.remove(WindowNo+"|"+context); + else + ctx.setProperty(WindowNo+"|"+context, value); + } // setContext + + /** + * Set Context for Window to Value + * @param ctx context + * @param WindowNo window no + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, int WindowNo, String context, Timestamp value) + { + if (ctx == null || context == null) + return; + boolean logit = WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP; + if (value == null) + { + ctx.remove(WindowNo+"|"+context); + s_log.finer("Context("+WindowNo+") " + context + "==" + value); + } + else + { // JDBC Format 2005-05-09 00:00:00.0 + String stringValue = value.toString(); + // Chop off .0 + stringValue = stringValue.substring(0, stringValue.length()-2); + ctx.setProperty(WindowNo+"|"+context, stringValue); + s_log.finer("Context("+WindowNo+") " + context + "==" + stringValue); + } + } // setContext + + /** + * Set Context for Window to int Value + * @param ctx context + * @param WindowNo window no + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, int WindowNo, String context, int value) + { + if (ctx == null || context == null) + return; + if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP) + s_log.finer("Context("+WindowNo+") " + context + "==" + value); + // + ctx.setProperty(WindowNo+"|"+context, String.valueOf(value)); + } // setContext + + /** + * Set Context for Window to Y/N Value + * @param ctx context + * @param WindowNo window no + * @param context context key + * @param value context value + */ + public static void setContext (Properties ctx, int WindowNo, String context, boolean value) + { + setContext (ctx, WindowNo, context, value ? "Y" : "N"); + } // setContext + + /** + * Set Context for Window & Tab to Value + * @param ctx context + * @param WindowNo window no + * @param TabNo tab no + * @param context context key + * @param value context value + * */ + public static void setContext (Properties ctx, int WindowNo, int TabNo, String context, String value) + { + if (ctx == null || context == null) + return; + if (WindowNo != WINDOW_FIND && WindowNo != WINDOW_MLOOKUP) + s_log.finest("Context("+WindowNo+","+TabNo+") " + context + "==" + value); + // + if (value == null || value.equals("")) + ctx.remove(WindowNo+"|"+TabNo+"|"+context); + else + ctx.setProperty(WindowNo+"|"+TabNo+"|"+context, value); + } // setContext + + /** + * Set Auto Commit + * @param ctx context + * @param autoCommit auto commit (save) + */ + public static void setAutoCommit (Properties ctx, boolean autoCommit) + { + if (ctx == null) + return; + ctx.setProperty("AutoCommit", autoCommit ? "Y" : "N"); + } // setAutoCommit + + /** + * Set Auto Commit for Window + * @param ctx context + * @param WindowNo window no + * @param autoCommit auto commit (save) + */ + public static void setAutoCommit (Properties ctx, int WindowNo, boolean autoCommit) + { + if (ctx == null) + return; + ctx.setProperty(WindowNo+"|AutoCommit", autoCommit ? "Y" : "N"); + } // setAutoCommit + + /** + * Set Auto New Record + * @param ctx context + * @param autoNew auto new record + */ + public static void setAutoNew (Properties ctx, boolean autoNew) + { + if (ctx == null) + return; + ctx.setProperty("AutoNew", autoNew ? "Y" : "N"); + } // setAutoNew + + /** + * Set Auto New Record for Window + * @param ctx context + * @param WindowNo window no + * @param autoNew auto new record + */ + public static void setAutoNew (Properties ctx, int WindowNo, boolean autoNew) + { + if (ctx == null) + return; + ctx.setProperty(WindowNo+"|AutoNew", autoNew ? "Y" : "N"); + } // setAutoNew + + + /** + * Set SO Trx + * @param ctx context + * @param isSOTrx SO Context + */ + public static void setSOTrx (Properties ctx, boolean isSOTrx) + { + if (ctx == null) + return; + ctx.setProperty("IsSOTrx", isSOTrx ? "Y" : "N"); + } // setSOTrx + + /** + * Get global Value of Context + * @param ctx context + * @param context context key + * @return value or "" + */ + public static String getContext (Properties ctx, String context) + { + if (ctx == null || context == null) + throw new IllegalArgumentException ("Require Context"); + return ctx.getProperty(context, ""); + } // getContext + + /** + * Get Value of Context for Window. + * if not found global context if available and enabled + * @param ctx context + * @param WindowNo window + * @param context context key + * @param onlyWindow if true, no defaults are used unless explicitly asked for + * @return value or "" + */ + public static String getContext (Properties ctx, int WindowNo, String context, boolean onlyWindow) + { + if (ctx == null) + throw new IllegalArgumentException ("No Ctx"); + if (context == null) + throw new IllegalArgumentException ("Require Context"); + String s = ctx.getProperty(WindowNo+"|"+context); + if (s == null) + { + // Explicit Base Values + if (context.startsWith("#") || context.startsWith("$")) + return getContext(ctx, context); + if (onlyWindow) // no Default values + return ""; + return getContext(ctx, "#" + context); + } + return s; + } // getContext + + /** + * Get Value of Context for Window. + * if not found global context if available + * @param ctx context + * @param WindowNo window + * @param context context key + * @return value or "" + */ + public static String getContext (Properties ctx, int WindowNo, String context) + { + return getContext(ctx, WindowNo, context, false); + } // getContext + + /** + * Get Value of Context for Window & Tab, + * if not found global context if available + * @param ctx context + * @param WindowNo window no + * @param TabNo tab no + * @param context context key + * @return value or "" + */ + public static String getContext (Properties ctx, int WindowNo, int TabNo, String context) + { + if (ctx == null || context == null) + throw new IllegalArgumentException ("Require Context"); + String s = ctx.getProperty(WindowNo+"|"+TabNo+"|"+context); + if (s == null) + return getContext(ctx, WindowNo, context, false); + return s; + } // getContext + + /** + * Get Context and convert it to an integer (0 if error) + * @param ctx context + * @param context context key + * @return value + */ + public static int getContextAsInt(Properties ctx, String context) + { + if (ctx == null || context == null) + throw new IllegalArgumentException ("Require Context"); + String s = getContext(ctx, context); + if (s.length() == 0) + s = getContext(ctx, 0, context, false); // search 0 and defaults + if (s.length() == 0) + return 0; + // + try + { + return Integer.parseInt(s); + } + catch (NumberFormatException e) + { + s_log.log(Level.SEVERE, "(" + context + ") = " + s, e); + } + return 0; + } // getContextAsInt + + /** + * Get Context and convert it to an integer (0 if error) + * @param ctx context + * @param WindowNo window no + * @param context context key + * @return value or 0 + */ + public static int getContextAsInt(Properties ctx, int WindowNo, String context) + { + String s = getContext(ctx, WindowNo, context, false); + if (s.length() == 0) + return 0; + // + try + { + return Integer.parseInt(s); + } + catch (NumberFormatException e) + { + s_log.log(Level.SEVERE, "(" + context + ") = " + s, e); + } + return 0; + } // getContextAsInt + + /** + * Get Context and convert it to an integer (0 if error) + * @param ctx context + * @param WindowNo window no + * @param TabNo tab no + * @param context context key + * @return value or 0 + */ + public static int getContextAsInt (Properties ctx, int WindowNo, int TabNo, String context) + { + String s = getContext(ctx, WindowNo, TabNo, context); + if (s.length() == 0) + return 0; + // + try + { + return Integer.parseInt(s); + } + catch (NumberFormatException e) + { + s_log.log(Level.SEVERE, "(" + context + ") = " + s, e); + } + return 0; + } // getContextAsInt + + /** + * Is AutoCommit + * @param ctx context + * @return true if auto commit + */ + public static boolean isAutoCommit (Properties ctx) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + String s = getContext(ctx, "AutoCommit"); + if (s != null && s.equals("Y")) + return true; + return false; + } // isAutoCommit + + /** + * Is Window AutoCommit (if not set use default) + * @param ctx context + * @param WindowNo window no + * @return true if auto commit + */ + public static boolean isAutoCommit (Properties ctx, int WindowNo) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + String s = getContext(ctx, WindowNo, "AutoCommit", false); + if (s != null) + { + if (s.equals("Y")) + return true; + else + return false; + } + return isAutoCommit(ctx); + } // isAutoCommit + + + /** + * Is Auto New Record + * @param ctx context + * @return true if auto new + */ + public static boolean isAutoNew (Properties ctx) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + String s = getContext(ctx, "AutoNew"); + if (s != null && s.equals("Y")) + return true; + return false; + } // isAutoNew + + /** + * Is Window Auto New Record (if not set use default) + * @param ctx context + * @param WindowNo window no + * @return true if auto new record + */ + public static boolean isAutoNew (Properties ctx, int WindowNo) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + String s = getContext(ctx, WindowNo, "AutoNew", false); + if (s != null) + { + if (s.equals("Y")) + return true; + else + return false; + } + return isAutoNew(ctx); + } // isAutoNew + + + /** + * Is Sales Order Trx + * @param ctx context + * @return true if SO (default) + */ + public static boolean isSOTrx (Properties ctx) + { + String s = getContext(ctx, "IsSOTrx"); + if (s != null && s.equals("N")) + return false; + return true; + } // isSOTrx + + /** + * Is Sales Order Trx + * @param ctx context + * @param WindowNo window no + * @return true if SO (default) + */ + public static boolean isSOTrx (Properties ctx, int WindowNo) + { + String s = getContext(ctx, WindowNo, "IsSOTrx", true); + if (s != null && s.equals("N")) + return false; + return true; + } // isSOTrx + + /** + * Get Context and convert it to a Timestamp + * if error return today's date + * @param ctx context + * @param context context key + * @return Timestamp + */ + public static Timestamp getContextAsDate(Properties ctx, String context) + { + return getContextAsDate(ctx, 0, context); + } // getContextAsDate + + /** + * Get Context and convert it to a Timestamp + * if error return today's date + * @param ctx context + * @param WindowNo window no + * @param context context key + * @return Timestamp + */ + public static Timestamp getContextAsDate(Properties ctx, int WindowNo, String context) + { + if (ctx == null || context == null) + throw new IllegalArgumentException ("Require Context"); + String s = getContext(ctx, WindowNo, context, false); + // JDBC Format YYYY-MM-DD example 2000-09-11 00:00:00.0 + if (s == null || s.equals("")) + { + s_log.log(Level.SEVERE, "No value for: " + context); + return new Timestamp(System.currentTimeMillis()); + } + + // timestamp requires time + if (s.trim().length() == 10) + s = s.trim() + " 00:00:00.0"; + else if (s.indexOf('.') == -1) + s = s.trim() + ".0"; + + return Timestamp.valueOf(s); + } // getContextAsDate + + /** + * Get Login AD_Client_ID + * @param ctx context + * @return login AD_Client_ID + */ + public static int getAD_Client_ID (Properties ctx) + { + return Env.getContextAsInt(ctx, "#AD_Client_ID"); + } // getAD_Client_ID + + /** + * Get Login AD_Org_ID + * @param ctx context + * @return login AD_Org_ID + */ + public static int getAD_Org_ID (Properties ctx) + { + return Env.getContextAsInt(ctx, "#AD_Org_ID"); + } // getAD_Client_ID + + /** + * Get Login AD_User_ID + * @param ctx context + * @return login AD_User_ID + */ + public static int getAD_User_ID (Properties ctx) + { + return Env.getContextAsInt(ctx, "#AD_User_ID"); + } // getAD_User_ID + + /** + * Get Login AD_Role_ID + * @param ctx context + * @return login AD_Role_ID + */ + public static int getAD_Role_ID (Properties ctx) + { + return Env.getContextAsInt(ctx, "#AD_Role_ID"); + } // getAD_Role_ID + + /************************************************************************** + * Get Preference. + *
+	 *		0)	Current Setting
+	 *		1) 	Window Preference
+	 *		2) 	Global Preference
+	 *		3)	Login settings
+	 *		4)	Accounting settings
+	 *  
+ * @param ctx context + * @param AD_Window_ID window no + * @param context Entity to search + * @param system System level preferences (vs. user defined) + * @return preference value + */ + public static String getPreference (Properties ctx, int AD_Window_ID, String context, boolean system) + { + if (ctx == null || context == null) + throw new IllegalArgumentException ("Require Context"); + String retValue = null; + // + if (!system) // User Preferences + { + retValue = ctx.getProperty("P"+AD_Window_ID+"|"+context);// Window Pref + if (retValue == null) + retValue = ctx.getProperty("P|"+context); // Global Pref + } + else // System Preferences + { + retValue = ctx.getProperty("#"+context); // Login setting + if (retValue == null) + retValue = ctx.getProperty("$"+context); // Accounting setting + } + // + return (retValue == null ? "" : retValue); + } // getPreference + + /************************************************************************** + * Language issues + */ + + /** Context Language identifier */ + static public final String LANGUAGE = "#AD_Language"; + + /** + * Check Base Language + * @param ctx context + * @param tableName table to be translated + * @return true if base language and table not translated + */ + public static boolean isBaseLanguage (Properties ctx, String tableName) + { + /** + if (isBaseTranslation(tableName)) + return Language.isBaseLanguage (getAD_Language(ctx)); + else // No AD Table + if (!isMultiLingualDocument(ctx)) + return true; // access base table + **/ + return Language.isBaseLanguage (getAD_Language(ctx)); + } // isBaseLanguage + + /** + * Check Base Language + * @param AD_Language language + * @param tableName table to be translated + * @return true if base language and table not translated + */ + public static boolean isBaseLanguage (String AD_Language, String tableName) + { + /** + if (isBaseTranslation(tableName)) + return Language.isBaseLanguage (AD_Language); + else // No AD Table + if (!isMultiLingualDocument(s_ctx)) // Base Context + return true; // access base table + **/ + return Language.isBaseLanguage (AD_Language); + } // isBaseLanguage + + /** + * Check Base Language + * @param language language + * @param tableName table to be translated + * @return true if base language and table not translated + */ + public static boolean isBaseLanguage (Language language, String tableName) + { + /** + if (isBaseTranslation(tableName)) + return language.isBaseLanguage(); + else // No AD Table + if (!isMultiLingualDocument(s_ctx)) // Base Context + return true; // access base table + **/ + return language.isBaseLanguage(); + } // isBaseLanguage + + /** + * Table is in Base Translation (AD) + * @param tableName table + * @return true if base trl + */ + public static boolean isBaseTranslation (String tableName) + { + if (tableName.startsWith("AD") + || tableName.equals("C_Country_Trl") ) + return true; + return false; + } // isBaseTranslation + + /** + * Do we have Multi-Lingual Documents. + * Set in DB.loadOrgs + * @param ctx context + * @return true if multi lingual documents + */ + public static boolean isMultiLingualDocument (Properties ctx) + { + return MClient.get(ctx).isMultiLingualDocument(); + } // isMultiLingualDocument + + /** + * Get System AD_Language + * @param ctx context + * @return AD_Language eg. en_US + */ + public static String getAD_Language (Properties ctx) + { + if (ctx != null) + { + String lang = getContext(ctx, LANGUAGE); + if (lang != null || lang.length() > 0) + return lang; + } + return Language.getBaseAD_Language(); + } // getAD_Language + + /** + * Get System Language + * @param ctx context + * @return Language + */ + public static Language getLanguage (Properties ctx) + { + if (ctx != null) + { + String lang = getContext(ctx, LANGUAGE); + if (lang != null || lang.length() > 0) + return Language.getLanguage(lang); + } + return Language.getBaseLanguage(); + } // getLanguage + + /** + * Get Login Language + * @param ctx context + * @return Language + */ + public static Language getLoginLanguage (Properties ctx) + { + return Language.getLoginLanguage(); + } // getLanguage + + /** + * Verify Language. + * Check that language is supported by the system + * @param ctx might be updated with new AD_Language + * @param language language + */ + public static void verifyLanguage (Properties ctx, Language language) + { + if (language.isBaseLanguage()) + return; + + boolean isSystemLanguage = false; + ArrayList AD_Languages = new ArrayList(); + String sql = "SELECT DISTINCT AD_Language FROM AD_Message_Trl"; + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + String AD_Language = rs.getString(1); + if (AD_Language.equals(language.getAD_Language())) + { + isSystemLanguage = true; + break; + } + AD_Languages.add(AD_Language); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, "", e); + } + // Found it + if (isSystemLanguage) + return; + // No Language - set to System + if (AD_Languages.size() == 0) + { + s_log.warning ("NO System Language - Set to Base " + Language.getBaseAD_Language()); + language.setAD_Language(Language.getBaseAD_Language()); + return; + } + + for (int i = 0; i < AD_Languages.size(); i++) + { + String AD_Language = (String)AD_Languages.get(i); // en_US + String lang = AD_Language.substring(0, 2); // en + // + String langCompare = language.getAD_Language().substring(0, 2); + if (lang.equals(langCompare)) + { + s_log.fine("Found similar Language " + AD_Language); + language.setAD_Language(AD_Language); + return; + } + } + + // We found same language + // if (!"0".equals(Msg.getMsg(AD_Language, "0"))) + + s_log.warning ("Not System Language=" + language + + " - Set to Base Language " + Language.getBaseAD_Language()); + language.setAD_Language(Language.getBaseAD_Language()); + } // verifyLanguage + + /************************************************************************** + * Get Context as String array with format: key == value + * @param ctx context + * @return context string + */ + public static String[] getEntireContext(Properties ctx) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + Iterator keyIterator = ctx.keySet().iterator(); + String[] sList = new String[ctx.size()]; + int i = 0; + while (keyIterator.hasNext()) + { + Object key = keyIterator.next(); + sList[i++] = key.toString() + " == " + ctx.get(key).toString(); + } + + return sList; + } // getEntireContext + + /** + * Get Header info (connection, org, user) + * @param ctx context + * @param WindowNo window + * @return Header String + */ + public static String getHeader(Properties ctx, int WindowNo) + { + StringBuffer sb = new StringBuffer(); + if (WindowNo > 0) + sb.append(getContext(ctx, WindowNo, "WindowName", false)).append(" "); + sb.append(getContext(ctx, "#AD_User_Name")).append("@") + .append(getContext(ctx, "#AD_Client_Name")).append(".") + .append(getContext(ctx, "#AD_Org_Name")) + .append(" [").append(CConnection.get().toString()).append("]"); + return sb.toString(); + } // getHeader + + /** + * Clean up context for Window (i.e. delete it) + * @param ctx context + * @param WindowNo window + */ + public static void clearWinContext(Properties ctx, int WindowNo) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + // + Object[] keys = ctx.keySet().toArray(); + for (int i = 0; i < keys.length; i++) + { + String tag = keys[i].toString(); + if (tag.startsWith(WindowNo+"|")) + ctx.remove(keys[i]); + } + // Clear Lookup Cache + MLookupCache.cacheReset(WindowNo); + // MLocator.cacheReset(WindowNo); + // + removeWindow(WindowNo); + } // clearWinContext + + /** + * Clean up all context (i.e. delete it) + * @param ctx context + */ + public static void clearContext(Properties ctx) + { + if (ctx == null) + throw new IllegalArgumentException ("Require Context"); + ctx.clear(); + } // clearContext + + + /** + * Parse Context replaces global or Window context @tag@ with actual value. + * + * @tag@ are ignored otherwise "" is returned + * @param ctx context + * @param WindowNo Number of Window + * @param value Message to be parsed + * @param onlyWindow if true, no defaults are used + * @param ignoreUnparsable if true, unsuccessful @return parsed String or "" if not successful and ignoreUnparsable + * @return parsed context + */ + public static String parseContext (Properties ctx, int WindowNo, String value, + boolean onlyWindow, boolean ignoreUnparsable) + { + if (value == null || value.length() == 0) + return ""; + + String token; + String inStr = new String(value); + StringBuffer outStr = new StringBuffer(); + + int i = inStr.indexOf('@'); + while (i != -1) + { + outStr.append(inStr.substring(0, i)); // up to @ + inStr = inStr.substring(i+1, inStr.length()); // from first @ + + int j = inStr.indexOf('@'); // next @ + if (j < 0) + { + s_log.log(Level.SEVERE, "No second tag: " + inStr); + return ""; // no second tag + } + + token = inStr.substring(0, j); + + String ctxInfo = getContext(ctx, WindowNo, token, onlyWindow); // get context + if (ctxInfo.length() == 0 && (token.startsWith("#") || token.startsWith("$")) ) + ctxInfo = getContext(ctx, token); // get global context + if (ctxInfo.length() == 0) + { + s_log.config("No Context Win=" + WindowNo + " for: " + token); + if (!ignoreUnparsable) + return ""; // token not found + } + else + outStr.append(ctxInfo); // replace context with Context + + inStr = inStr.substring(j+1, inStr.length()); // from second @ + i = inStr.indexOf('@'); + } + outStr.append(inStr); // add the rest of the string + + return outStr.toString(); + } // parseContext + + /** + * Parse Context replaces global or Window context @tag@ with actual value. + * + * @param ctx context + * @param WindowNo Number of Window + * @param value Message to be parsed + * @param onlyWindow if true, no defaults are used + * @return parsed String or "" if not successful + */ + public static String parseContext (Properties ctx, int WindowNo, String value, + boolean onlyWindow) + { + return parseContext(ctx, WindowNo, value, onlyWindow, false); + } // parseContext + + /*************************************************************************/ + + // Array of active Windows + private static ArrayList s_windows = new ArrayList(20); + + /** + * Add Container and return WindowNo. + * The container is a APanel, AWindow or JFrame/JDialog + * @param win window + * @return WindowNo used for context + */ + public static int createWindowNo(Container win) + { + int retValue = s_windows.size(); + s_windows.add(win); + return retValue; + } // createWindowNo + + /** + * Search Window by comparing the Frames + * @param container container + * @return WindowNo of container or 0 + */ + public static int getWindowNo (Container container) + { + if (container == null) + return 0; + JFrame winFrame = getFrame(container); + if (winFrame == null) + return 0; + + // loop through windows + for (int i = 0; i < s_windows.size(); i++) + { + Container cmp = (Container)s_windows.get(i); + if (cmp != null) + { + JFrame cmpFrame = getFrame(cmp); + if (winFrame.equals(cmpFrame)) + return i; + } + } + return 0; + } // getWindowNo + + /** + * Return the JFrame pointer of WindowNo - or null + * @param WindowNo window + * @return JFrame of WindowNo + */ + public static JFrame getWindow (int WindowNo) + { + JFrame retValue = null; + try + { + retValue = getFrame ((Container)s_windows.get(WindowNo)); + } + catch (Exception e) + { + s_log.log(Level.SEVERE, e.toString()); + } + return retValue; + } // getWindow + + /** + * Remove window from active list + * @param WindowNo window + */ + private static void removeWindow (int WindowNo) + { + if (WindowNo < s_windows.size()) + s_windows.set(WindowNo, null); + } // removeWindow + + /** + * Clean up context for Window (i.e. delete it) + * @param WindowNo window + */ + public static void clearWinContext(int WindowNo) + { + clearWinContext (s_ctx, WindowNo); + } // clearWinContext + + /** + * Clean up all context (i.e. delete it) + */ + public static void clearContext() + { + s_ctx.clear(); + } // clearContext + + + /************************************************************************** + * Get Frame of Window + * @param container Container + * @return JFrame of container or null + */ + public static JFrame getFrame (Container container) + { + Container element = container; + while (element != null) + { + if (element instanceof JFrame) + return (JFrame)element; + element = element.getParent(); + } + return null; + } // getFrame + + /** + * Get Graphics of container or its parent. + * The element may not have a Graphic if not displayed yet, + * but the parent might have. + * @param container Container + * @return Graphics of container or null + */ + public static Graphics getGraphics (Container container) + { + Container element = container; + while (element != null) + { + Graphics g = element.getGraphics(); + if (g != null) + return g; + element = element.getParent(); + } + return null; + } // getFrame + + /** + * Return JDialog or JFrame Parent + * @param container Container + * @return JDialog or JFrame of container + */ + public static Window getParent (Container container) + { + Container element = container; + while (element != null) + { + if (element instanceof JDialog || element instanceof JFrame) + return (Window)element; + if (element instanceof Window) + return (Window)element; + element = element.getParent(); + } + return null; + } // getParent + + /************************************************************************** + * Get Image with File name + * + * @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif) + * @return image */ public static Image getImage (String fileNameInImageDir) { @@ -1262,258 +1248,189 @@ public final class Env if (url == null) { s_log.log(Level.SEVERE, "Not found: " + fileNameInImageDir); - return null; - } - Toolkit tk = Toolkit.getDefaultToolkit(); - return tk.getImage(url); - } // getImage - - /** - * Get ImageIcon. - * - * @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif) - * @return image + return null; + } + Toolkit tk = Toolkit.getDefaultToolkit(); + return tk.getImage(url); + } // getImage + + /** + * Get ImageIcon. + * + * @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif) + * @return image */ public static ImageIcon getImageIcon (String fileNameInImageDir) { URL url = Adempiere.class.getResource("images/" + fileNameInImageDir); if (url == null) { - s_log.log(Level.WARNING, "Not found: " + fileNameInImageDir); + s_log.log(Level.SEVERE, "Not found: " + fileNameInImageDir); return null; } return new ImageIcon(url); } // getImageIcon - /** - * Get ImageIcon. This method different from getImageIcon - * where the fileName parameter is without extension. The - * method will first try .gif and then .png if .gif does not - * exists. - * - * @param fileName file name in imgaes folder without the extension(e.g. Bean16) - * @return image - */ - public static ImageIcon getImageIcon2 (String fileName) - { - URL url = Adempiere.class.getResource("images/" + fileName+".gif"); - if (url == null) - url = Adempiere.class.getResource("images/" + fileName+".png"); - if (url == null) - { - s_log.log(Level.WARNING, "GIF/PNG Not found: " + fileName); - return null; - } - return new ImageIcon(url); - } // getImageIcon2 - /*************************************************************************** * Start Browser - * @param url url - */ - public static void startBrowser (String url) - { - s_log.info(url); - // OS command - String cmd = "explorer "; - if (!isWindows()) - cmd = "netscape "; - // - String execute = cmd + url; - try - { - Runtime.getRuntime().exec(execute); - } - catch (Exception e) - { - s_log.severe(execute + " - " + e); - } - } // startBrowser - - /** - * Do we run on Apple - * @return true if Mac - */ - public static boolean isMac() - { - String osName = System.getProperty ("os.name"); - osName = osName.toLowerCase(); - return osName.indexOf ("mac") != -1; - } // isMac - - /** - * Do we run on Windows - * @return true if windows - */ - public static boolean isWindows() - { - String osName = System.getProperty ("os.name"); - osName = osName.toLowerCase(); - return osName.indexOf ("windows") != -1; - } // isWindows - - - /** Array of hidden Windows */ - private static ArrayList s_hiddenWindows = new ArrayList(); - /** Closing Window Indicator */ - private static boolean s_closingWindows = false; - - /** - * Hide Window - * @param window window - * @return true if window is hidden, otherwise close it - */ - static public boolean hideWindow(CFrame window) - { - if (!Ini.isCacheWindow() || s_closingWindows) - return false; - for (int i = 0; i < s_hiddenWindows.size(); i++) - { - CFrame hidden = s_hiddenWindows.get(i); - s_log.info(i + ": " + hidden); - if (hidden.getAD_Window_ID() == window.getAD_Window_ID()) - return false; // already there - } - if (window.getAD_Window_ID() != 0) // workbench - { - if (s_hiddenWindows.add(window)) - { + * @param url url + */ + public static void startBrowser (String url) + { + s_log.info(url); + // OS command + String cmd = "explorer "; + if (!isWindows()) + cmd = "netscape "; + // + String execute = cmd + url; + try + { + Runtime.getRuntime().exec(execute); + } + catch (Exception e) + { + s_log.severe(execute + " - " + e); + } + } // startBrowser + + /** + * Do we run on Apple + * @return true if Mac + */ + public static boolean isMac() + { + String osName = System.getProperty ("os.name"); + osName = osName.toLowerCase(); + return osName.indexOf ("mac") != -1; + } // isMac + + /** + * Do we run on Windows + * @return true if windows + */ + public static boolean isWindows() + { + String osName = System.getProperty ("os.name"); + osName = osName.toLowerCase(); + return osName.indexOf ("windows") != -1; + } // isWindows + + + /** Array of hidden Windows */ + private static ArrayList s_hiddenWindows = new ArrayList(); + /** Closing Window Indicator */ + private static boolean s_closingWindows = false; + + /** + * Hide Window + * @param window window + * @return true if window is hidden, otherwise close it + */ + static public boolean hideWindow(CFrame window) + { + if (!Ini.isCacheWindow() || s_closingWindows) + return false; + for (int i = 0; i < s_hiddenWindows.size(); i++) + { + CFrame hidden = s_hiddenWindows.get(i); + s_log.info(i + ": " + hidden); + if (hidden.getAD_Window_ID() == window.getAD_Window_ID()) + return false; // already there + } + if (window.getAD_Window_ID() != 0) // workbench + { + if (s_hiddenWindows.add(window)) + { window.setVisible(false); s_log.info(window.toString()); // window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_ICONIFIED)); - if (s_hiddenWindows.size() > 10) { - CFrame toClose = s_hiddenWindows.remove(0); // sort of lru - try { - s_closingWindows = true; - toClose.dispose(); - } finally { - s_closingWindows = false; - } - } + if (s_hiddenWindows.size() > 10) + s_hiddenWindows.remove(0); // sort of lru return true; } } - return false; - } // hideWindow - - /** - * Show Window - * @param AD_Window_ID window - * @return true if window re-displayed - */ - static public CFrame showWindow (int AD_Window_ID) - { - for (int i = 0; i < s_hiddenWindows.size(); i++) - { - CFrame hidden = s_hiddenWindows.get(i); - if (hidden.getAD_Window_ID() == AD_Window_ID) - { - s_hiddenWindows.remove(i); - s_log.info(hidden.toString()); - hidden.setVisible(true); - hidden.toFront(); - return hidden; - } - } - return null; - } // showWindow - - /** - * Clode Windows - */ - static void closeWindows () - { - s_closingWindows = true; - for (int i = 0; i < s_hiddenWindows.size(); i++) - { - CFrame hidden = s_hiddenWindows.get(i); - hidden.dispose(); - } - s_hiddenWindows.clear(); - s_closingWindows = false; - } // closeWindows - - /** - * Sleep - * @param sec seconds - */ - public static void sleep (int sec) - { - s_log.info("Start - Seconds=" + sec); - try - { - Thread.sleep(sec*1000); - } - catch (Exception e) - { - s_log.log(Level.WARNING, "", e); - } + return false; + } // hideWindow + + /** + * Show Window + * @param AD_Window_ID window + * @return true if window re-displayed + */ + static public boolean showWindow (int AD_Window_ID) + { + for (int i = 0; i < s_hiddenWindows.size(); i++) + { + CFrame hidden = s_hiddenWindows.get(i); + if (hidden.getAD_Window_ID() == AD_Window_ID) + { + s_hiddenWindows.remove(i); + s_log.info(hidden.toString()); + hidden.setVisible(true); + hidden.toFront(); + return true; + } + } + return false; + } // showWindow + + /** + * Clode Windows + */ + static void closeWindows () + { + s_closingWindows = true; + for (int i = 0; i < s_hiddenWindows.size(); i++) + { + CFrame hidden = s_hiddenWindows.get(i); + hidden.dispose(); + } + s_hiddenWindows.clear(); + s_closingWindows = false; + } // closeWindows + + /** + * Sleep + * @param sec seconds + */ + public static void sleep (int sec) + { + s_log.info("Start - Seconds=" + sec); + try + { + Thread.sleep(sec*1000); + } + catch (Exception e) + { + s_log.log(Level.WARNING, "", e); + } s_log.info("End"); } // sleep - /** - * Update all windows after look and feel changes. - * @since 2006-11-27 - */ - public static SetupdateUI() - { - Set updated = new HashSet(); - for (Container c : s_windows) - { - Window w = getFrame(c); - if (w == null) continue; - if (updated.contains(w)) continue; - SwingUtilities.updateComponentTreeUI(w); - w.validate(); - RepaintManager mgr = RepaintManager.currentManager(w); - Component childs[] = w.getComponents(); - for (Component child : childs) { - if (child instanceof JComponent) - mgr.markCompletelyDirty((JComponent)child); - } - w.repaint(); - updated.add(w); - } - for (Window w : s_hiddenWindows) - { - if (updated.contains(w)) continue; - SwingUtilities.updateComponentTreeUI(w); - w.validate(); - RepaintManager mgr = RepaintManager.currentManager(w); - Component childs[] = w.getComponents(); - for (Component child : childs) { - if (child instanceof JComponent) - mgr.markCompletelyDirty((JComponent)child); - } - w.repaint(); - updated.add(w); - } - return updated; - } - /************************************************************************** * Static Variables - */ - - /** Big Decimal 0 */ - static final public BigDecimal ZERO = new BigDecimal(0.0); - /** Big Decimal 1 */ - static final public BigDecimal ONE = new BigDecimal(1.0); - /** Big Decimal 100 */ - static final public BigDecimal ONEHUNDRED = new BigDecimal(100.0); - - /** New Line */ - public static final String NL = System.getProperty("line.separator"); - - - /** - * Static initializer - */ - static - { - // Set English as default Language + */ + + /** Big Decimal 0 */ + static final public BigDecimal ZERO = new BigDecimal(0.0); + /** Big Decimal 1 */ + static final public BigDecimal ONE = new BigDecimal(1.0); + /** Big Decimal 100 */ + static final public BigDecimal ONEHUNDRED = new BigDecimal(100.0); + + /** New Line */ + public static final String NL = System.getProperty("line.separator"); + + + /** + * Static initializer + */ + static + { + // Set English as default Language s_ctx.put(LANGUAGE, Language.getBaseAD_Language()); } // static diff --git a/dbPort/src/org/compiere/util/GenerateModel.java b/dbPort/src/org/compiere/util/GenerateModel.java index 3c7140bce1..79843cbcc2 100644 --- a/dbPort/src/org/compiere/util/GenerateModel.java +++ b/dbPort/src/org/compiere/util/GenerateModel.java @@ -1,826 +1,834 @@ -/****************************************************************************** - * Product: Adempiere ERP & CRM Smart Business Solution * - * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * - * This program is free software; you can redistribute it and/or modify it * - * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.util; - -import java.io.*; -import java.math.*; -import java.sql.*; -import java.util.logging.*; -import org.compiere.*; - -/** - * Generate Model Classes extending PO. - * Base class for CMP interface - will be extended to create byte code directly - * - * @author Jorg Janke - * @version $Id: GenerateModel.java,v 1.5 2006/07/30 00:54:36 jjanke Exp $ - */ -public class GenerateModel -{ - /** - * Generate PO Class - * @param AD_Table_ID table id - * @param directory directory with \ or / at the end. - * @param packageName package name - */ - public GenerateModel (int AD_Table_ID, String directory, String packageName) - { - // create column access methods - StringBuffer mandatory = new StringBuffer(); - StringBuffer sb = createColumns(AD_Table_ID, mandatory); - // add header stuff - String tableName = createHeader(AD_Table_ID, sb, mandatory, packageName); - // Save it - writeToFile (sb, directory + tableName + ".java"); - } // GenerateModel - - /** File Header */ - public static final String COPY = - "/******************************************************************************\n" - +" * Product: Adempiere ERP & CRM Smart Business Solution *\n" - +" * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *\n" - +" * This program is free software; you can redistribute it and/or modify it *\n" - +" * under the terms version 2 of the GNU General Public License as published *\n" - +" * by the Free Software Foundation. This program is distributed in the hope *\n" - +" * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *\n" - +" * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n" - +" * See the GNU General Public License for more details. *\n" - +" * You should have received a copy of the GNU General Public License along *\n" - +" * with this program; if not, write to the Free Software Foundation, Inc., *\n" - +" * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *\n" - +" * For the text or an alternative of this public license, you may reach us *\n" - +" * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *\n" - +" * or via info@compiere.org or http://www.compiere.org/license.html *\n" - +" *****************************************************************************/\n"; - - /** Generated on */ - private Timestamp s_run = new Timestamp(System.currentTimeMillis()); - - /** Logger */ - private static CLogger log = CLogger.getCLogger (GenerateModel.class); - - /** - * Add Header info to buffer - * @param AD_Table_ID table - * @param sb buffer - * @param mandatory init call for mandatory columns - * @param packageName package name - * @return class name - */ - private String createHeader (int AD_Table_ID, StringBuffer sb, StringBuffer mandatory, String packageName) - { - String tableName = ""; - int accessLevel = 0; - String sql = "SELECT TableName, AccessLevel FROM AD_Table WHERE AD_Table_ID=?"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Table_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - tableName = rs.getString(1); - accessLevel = rs.getInt(2); - } - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - if (tableName == null) - throw new RuntimeException ("TableName not found for ID=" + AD_Table_ID); - // - String accessLevelInfo = accessLevel + " "; - if (accessLevel >= 4 ) - accessLevelInfo += "- System "; - if (accessLevel == 2 || accessLevel == 3 || accessLevel == 6 || accessLevel == 7) - accessLevelInfo += "- Client "; - if (accessLevel == 1 || accessLevel == 3 || accessLevel == 5 || accessLevel == 7) - accessLevelInfo += "- Org "; - - String keyColumn = tableName + "_ID"; - String className = "X_" + tableName; - // - StringBuffer start = new StringBuffer () - .append (COPY) - .append ("package " + packageName + ";\n" - + "/** Generated Model - DO NOT CHANGE */\n"); - if (!packageName.equals("org.compiere.model")) - start.append("import org.compiere.model.*;"); - start.append("import java.util.*;" - + "import java.sql.*;" - + "import java.math.*;" - + "import org.compiere.util.*;" - // Class - + "/** Generated Model for ").append(tableName).append("\n" - + " * @author Jorg Janke (generated) \n" - + " * @version ").append(Adempiere.MAIN_VERSION).append(" - ").append(s_run).append(" */\n" - + "public class ").append(className).append(" extends PO" - + "{" - // Standard Constructor - + "/** Standard Constructor\n@param ctx context\n@param " - + keyColumn + " id\n@param trxName transaction\n*/\n" - + "public ").append(className).append(" (Properties ctx, int ").append(keyColumn) - .append(", String trxName)" - + "{" - + "super (ctx, ").append(keyColumn).append(", trxName);" - + "/** if (").append(keyColumn).append(" == 0)" - + "{").append(mandatory).append("} */\n" - + "}" // Constructor End - // Short Constructor -// + "/** Short Constructor */\n" -// + "public ").append(className).append(" (Properties ctx, int ").append(keyColumn).append(")" -// + "{" -// + "this (ctx, ").append(keyColumn).append(", null);" -// + "}" // Constructor End - - // Load Constructor - + "/** Load Constructor \n@param ctx context\n@param rs result set \n@param trxName transaction\n*/\n" - + "public ").append(className).append(" (Properties ctx, ResultSet rs, String trxName)" - + "{" - + "super (ctx, rs, trxName);" - + "}" // Load Constructor End - // - + "/** AD_Table_ID=").append(AD_Table_ID).append(" */\n" - + "public static final int Table_ID=").append(AD_Table_ID).append(";\n" - // - + "/** TableName=").append(tableName).append(" */\n" - + "public static final String Table_Name=\"").append(tableName).append("\";\n" - + "protected static KeyNamePair Model = new KeyNamePair(").append(AD_Table_ID).append(",\"").append(tableName).append("\");\n" - // - + "protected BigDecimal accessLevel = new BigDecimal(").append(accessLevel).append(");" - + "/** AccessLevel\n@return ").append(accessLevelInfo).append("\n*/\n" - + "protected int get_AccessLevel()" - + "{" - + "return accessLevel.intValue();" - + "}" - // - + "/** Load Meta Data\n@param ctx context\n@return PO Info\n*/\n" - + "protected POInfo initPO (Properties ctx)" - + "{" - + "POInfo poi = POInfo.getPOInfo (ctx, Table_ID);" - + "return poi;" - + "}" // initPO - // - + "/** Info\n@return info\n*/\n" - + "public String toString()" - + "{" - + "StringBuffer sb = new StringBuffer (\"").append(className).append("[\")" - + ".append(get_ID()).append(\"]\");" - + "return sb.toString();" - + "}"); - - StringBuffer end = new StringBuffer ("}"); - // - sb.insert(0, start); - sb.append(end); - - return className; - } // createHeader - - - /** - * Create Column access methods - * @param AD_Table_ID table - * @param mandatory init call for mandatory columns - * @return set/get method - */ - private StringBuffer createColumns (int AD_Table_ID, StringBuffer mandatory) - { - StringBuffer sb = new StringBuffer(); - String sql = "SELECT c.ColumnName, c.IsUpdateable, c.IsMandatory," // 1..3 - + " c.AD_Reference_ID, c.AD_Reference_Value_ID, DefaultValue, SeqNo, " // 4..7 - + " c.FieldLength, c.ValueMin, c.ValueMax, c.VFormat, c.Callout, " // 8..12 - + " c.Name, c.Description, c.ColumnSQL, c.IsEncrypted " - + "FROM AD_Column c " - + "WHERE c.AD_Table_ID=?" - + " AND c.IsActive='Y'" - + " AND c.ColumnName <> 'AD_Client_ID'" - + " AND c.ColumnName <> 'AD_Org_ID'" - + " AND c.ColumnName <> 'IsActive'" - + " AND c.ColumnName NOT LIKE 'Created%'" - + " AND c.ColumnName NOT LIKE 'Updated%' " - + "ORDER BY c.ColumnName"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Table_ID); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - String columnName = rs.getString(1); - boolean isUpdateable = "Y".equals(rs.getString(2)); - boolean isMandatory = "Y".equals(rs.getString(3)); - int displayType = rs.getInt(4); - int AD_Reference_Value_ID = rs.getInt(5); - String defaultValue = rs.getString(6); - int seqNo = rs.getInt(7); - int fieldLength = rs.getInt(8); - String ValueMin = rs.getString(9); - String ValueMax = rs.getString(10); - String VFormat = rs.getString(11); - String Callout = rs.getString(12); - String Name = rs.getString(13); - String Description = rs.getString(14); - String ColumnSQL = rs.getString(15); - boolean virtualColumn = ColumnSQL != null && ColumnSQL.length() > 0; - boolean IsEncrypted = "Y".equals(rs.getString(16)); - // - sb.append(createColumnMethods (mandatory, - columnName, isUpdateable, isMandatory, - displayType, AD_Reference_Value_ID, fieldLength, - defaultValue, ValueMin, ValueMax, VFormat, - Callout, Name, Description, virtualColumn, IsEncrypted)); - // - if (seqNo == 1) - sb.append(createKeyNamePair(columnName, displayType)); - } - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - return sb; - } // createColumns - - /** - * Create set/get methods for column - * @param mandatory init call for mandatory columns - * @param columnName column name - * @param isUpdateable updateable - * @param isMandatory mandatory - * @param displayType display type - * @param AD_Reference_ID validation reference - * @param fieldLength int - * @param defaultValue default value - * @param ValueMin String - * @param ValueMax String - * @param VFormat String - * @param Callout String - * @param Name String - * @param Description String - * @param virtualColumn virtual column - * @param IsEncrypted stored encrypted - @return set/get method - */ - private String createColumnMethods (StringBuffer mandatory, - String columnName, boolean isUpdateable, boolean isMandatory, - int displayType, int AD_Reference_ID, int fieldLength, - String defaultValue, String ValueMin, String ValueMax, String VFormat, - String Callout, String Name, String Description, - boolean virtualColumn, boolean IsEncrypted) - { - // Clazz - Class clazz = DisplayType.getClass(displayType, true); - if (defaultValue == null) - defaultValue = ""; - if (DisplayType.isLOB(displayType)) // No length check for LOBs - fieldLength = 0; - - // Handle Posted - if (columnName.equalsIgnoreCase("Posted") - || columnName.equalsIgnoreCase("Processed") - || columnName.equalsIgnoreCase("Processing")) - { - clazz = Boolean.class; - AD_Reference_ID = 0; - } - // Record_ID - else if (columnName.equalsIgnoreCase("Record_ID")) - { - clazz = Integer.class; - AD_Reference_ID = 0; - } - // String Key - else if (columnName.equalsIgnoreCase("AD_Language") - || columnName.equalsIgnoreCase("EntityType")) - { - clazz = String.class; - } - // Data Type - String dataType = clazz.getName(); - dataType = dataType.substring(dataType.lastIndexOf('.')+1); - if (dataType.equals("Boolean")) - dataType = "boolean"; - else if (dataType.equals("Integer")) - dataType = "int"; - else if (displayType == DisplayType.Binary) - dataType = "byte[]"; - - - StringBuffer sb = new StringBuffer(); - // ****** Set Comment ****** - sb.append("/** Set ").append(Name); - sb.append(".\n@param ").append(columnName).append(" "); - if (Description != null && Description.length() > 0) - sb.append(Description); - else - sb.append(Name); - sb.append(" */\n"); - - // Set ******** - String setValue = "set_Value"; - if (IsEncrypted) - setValue = "set_ValueE"; - // public void setColumn (xxx variable) - sb.append("public "); - if (!isUpdateable) - { - setValue = "set_ValueNoCheck"; - if (IsEncrypted) - setValue = "set_ValueNoCheckE"; - } - sb.append("void set").append(columnName).append(" (").append(dataType).append(" ").append(columnName).append(")" - + "{"); - // List Validation - if (AD_Reference_ID != 0) - { - String staticVar = addListValidation (sb, AD_Reference_ID, columnName, !isMandatory); - sb.insert(0, staticVar); // first check - } - // setValue ("ColumnName", xx); - if (virtualColumn) - { - sb.append ("throw new IllegalArgumentException (\"").append(columnName).append(" is virtual column\");"); - } - else if (clazz.equals(Integer.class)) - { - if (columnName.endsWith("_ID")) - { - if (isMandatory) // check mandatory ID - { - int firstOK = 1; // Valid ID 0 - if (columnName.equals("AD_Client_ID") || columnName.equals("AD_Org_ID") - || columnName.equals("Record_ID") || columnName.equals("C_DocType_ID") - || columnName.equals("Node_ID") || columnName.equals("AD_Role_ID") - || columnName.equals("M_AttributeSet_ID") || columnName.equals("M_AttributeSetInstance_ID")) - firstOK = 0; - sb.append("if (").append (columnName) - .append (" < ").append(firstOK).append(") throw new IllegalArgumentException (\"") - .append(columnName).append(" is mandatory.\");"); - } - else // set optional _ID to null if 0 - sb.append("if (").append (columnName).append (" <= 0) ") - .append(setValue).append(" (\"").append(columnName).append("\", null); else \n"); - } - sb.append(setValue).append(" (\"").append(columnName).append("\", new Integer(").append(columnName).append("));"); - } - else if (clazz.equals(Boolean.class)) - sb.append(setValue).append(" (\"").append(columnName).append("\", new Boolean(").append(columnName).append("));"); - else - { - if (isMandatory && AD_Reference_ID == 0) // does not apply to int/boolean - { - sb.append("if (") - .append (columnName).append (" == null)" - + " throw new IllegalArgumentException (\"") - .append(columnName).append(" is mandatory.\");"); - } - // String length check - if (clazz.equals(String.class) && fieldLength > 0) - { - sb.append ("if ("); - if (!isMandatory) - sb.append(columnName).append(" != null && "); - sb.append(columnName).append(".length() > ").append(fieldLength) - .append("){log.warning(\"Length > ") - .append(fieldLength).append(" - truncated\");") - .append(columnName).append(" = ") - .append(columnName).append(".substring(0,").append(fieldLength-1).append(");}"); - } - - // - sb.append (setValue).append(" (\"").append (columnName).append ("\", ") - .append (columnName).append (");"); - } - sb.append("}"); - - // Mandatory call in constructor - if (isMandatory) - { - mandatory.append("set").append(columnName).append(" ("); - if (clazz.equals(Integer.class)) - mandatory.append("0"); - else if (clazz.equals(Boolean.class)) - { - if (defaultValue.indexOf('Y') != -1) - mandatory.append(true); - else - mandatory.append("false"); - } - else if (clazz.equals(BigDecimal.class)) - mandatory.append("Env.ZERO"); - else if (clazz.equals(Timestamp.class)) - mandatory.append("new Timestamp(System.currentTimeMillis())"); - else - mandatory.append("null"); - mandatory.append(");"); - if (defaultValue.length() > 0) - mandatory.append("// ").append(defaultValue).append(Env.NL); - } - - - // ****** Get Comment ****** - sb.append("/** Get ").append(Name); - if (Description != null && Description.length() > 0) - sb.append(".\n@return ").append(Description); - else - sb.append(".\n@return ").append(Name); - sb.append(" */\n"); - - // Get ******** - String getValue = "get_Value"; - if (IsEncrypted) - getValue = "get_ValueE"; - sb.append("public ").append(dataType); - if (clazz.equals(Boolean.class)) - { - sb.append(" is"); - if (columnName.toLowerCase().startsWith("is")) - sb.append(columnName.substring(2)); - else - sb.append(columnName); - } - else - sb.append(" get").append(columnName); - sb.append("() {"); - if (clazz.equals(Integer.class)) - sb.append("Integer ii = (Integer)") - .append(getValue).append("(\"").append(columnName).append("\");" - + "if (ii == null)" - + " return 0;" - + "return ii.intValue();"); - else if (clazz.equals(BigDecimal.class)) - sb.append("BigDecimal bd = (BigDecimal)").append(getValue) - .append("(\"").append(columnName).append("\");" - + "if (bd == null)" - + " return Env.ZERO;" - + "return bd;"); - else if (clazz.equals(Boolean.class)) - sb.append("Object oo = ").append(getValue) - .append("(\"").append(columnName).append("\");" - + "if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return \"Y\".equals(oo);}" - + "return false;"); - else if (dataType.equals("Object")) - sb.append("return ").append(getValue) - .append("(\"").append(columnName).append("\");"); - else - sb.append("return (").append(dataType).append(")").append(getValue) - .append("(\"").append(columnName).append("\");"); - sb.append("}"); - // - return sb.toString(); - } // createColumnMethods - - - /** - * Add List Validation - * @param sb buffer - example: - if (NextAction.equals("N") || NextAction.equals("F")); - else throw new IllegalArgumentException ("NextAction Invalid value - Reference_ID=219 - N - F"); - * @param AD_Reference_ID reference - * @param columnName column - * @param nullable the validation must allow null values - * @return static parameter - Example: - public static final int NEXTACTION_AD_Reference_ID=219; - public static final String NEXTACTION_None = "N"; - public static final String NEXTACTION_FollowUp = "F"; - */ - private String addListValidation (StringBuffer sb, int AD_Reference_ID, - String columnName, boolean nullable) - { - StringBuffer retValue = new StringBuffer(); - retValue.append("\n/** ").append(columnName).append(" AD_Reference_ID=").append(AD_Reference_ID) .append(" */\n") - .append("public static final int ").append(columnName.toUpperCase()) - .append("_AD_Reference_ID=").append(AD_Reference_ID).append(";"); - // - boolean found = false; - StringBuffer values = new StringBuffer("Reference_ID=") - .append(AD_Reference_ID); - StringBuffer statement = new StringBuffer(); - if (nullable) - statement.append("if (").append(columnName).append(" == null"); - // - String sql = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=?"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Reference_ID); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - String value = rs.getString(1); - values.append(" - ").append(value); - if (statement.length() == 0) - statement.append("if (").append(columnName) - .append(".equals(\"").append(value).append("\")"); - else - statement.append(" || ").append(columnName) - .append(".equals(\"").append(value).append("\")"); - if (!found) - { - found = true; - sb.append("if (") - .append (columnName).append (" == null)" - + " throw new IllegalArgumentException (\"") - .append(columnName).append(" is mandatory\");"); - } - // Name (SmallTalkNotation) - String name = rs.getString(2); - char[] nameArray = name.toCharArray(); - StringBuffer nameClean = new StringBuffer(); - boolean initCap = true; - for (int i = 0; i < nameArray.length; i++) - { - char c = nameArray[i]; - if (Character.isJavaIdentifierPart(c)) - { - if (initCap) - nameClean.append(Character.toUpperCase(c)); - else - nameClean.append(c); - initCap = false; - } - else - { - if (c == '+') - nameClean.append("Plus"); - else if (c == '-') - nameClean.append("_"); - else if (c == '>') - { - if (name.indexOf('<') == -1) // ignore - nameClean.append("Gt"); - } - else if (c == '<') - { - if (name.indexOf('>') == -1) // ignore - nameClean.append("Le"); - } - else if (c == '!') - nameClean.append("Not"); - else if (c == '=') - nameClean.append("Eq"); - else if (c == '~') - nameClean.append("Like"); - initCap = true; - } - } - retValue.append("/** ").append(name).append(" = ").append(value).append(" */\n"); - retValue.append("public static final String ").append(columnName.toUpperCase()) - .append("_").append(nameClean) - .append(" = \"").append(value).append("\";"); - } - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - found = false; - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - statement.append(")" - + "; " - + "else " - + "throw new IllegalArgumentException (\"").append(columnName) - .append(" Invalid value - \" + ").append(columnName) - .append(" + \" - ").append(values).append("\");"); - // - if (found && !columnName.equals("EntityType")) - sb.append (statement); - return retValue.toString(); - } // addListValidation - - /** - * Create getKeyNamePair() method with first identifier - * @param columnName name - * * @param displayType int - @return method code - */ - private StringBuffer createKeyNamePair (String columnName, int displayType) - { - String method = "get" + columnName + "()"; - if (displayType != DisplayType.String) - method = "String.valueOf(" + method + ")"; - StringBuffer sb = new StringBuffer("/** Get Record ID/ColumnName\n@return ID/ColumnName pair\n*/" - + "public KeyNamePair getKeyNamePair() " - + "{return new KeyNamePair(get_ID(), ").append(method).append(");}"); - return sb; - } // createKeyNamePair - - - /************************************************************************** - * Write to file - * @param sb string buffer - * @param fileName file name - */ - private void writeToFile (StringBuffer sb, String fileName) - { - try - { - File out = new File (fileName); - FileWriter fw = new FileWriter (out); - for (int i = 0; i < sb.length(); i++) - { - char c = sb.charAt(i); - // after - if (c == ';' || c == '}') - { - fw.write (c); - if (sb.substring(i+1).startsWith("//")) - fw.write('\t'); - else - fw.write(Env.NL); - } - // before & after - else if (c == '{') - { - fw.write(Env.NL); - fw.write (c); - fw.write(Env.NL); - } - else - fw.write (c); - } - fw.flush (); - fw.close (); - float size = out.length(); - size /= 1024; - log.info(out.getAbsolutePath() + " - " + size + " kB"); - } - catch (Exception ex) - { - log.log(Level.SEVERE, fileName, ex); - } - } // writeToFile - - /** - * String representation - * @return string representation - */ - public String toString() - { - StringBuffer sb = new StringBuffer ("GenerateModel[") - .append("]"); - return sb.toString(); - } // toString - - - - /************************************************************************** - * Generate PO Model Class. - *
-	 * 	Example: java GenerateModel.class mydirectory myPackage 'U','A'
-	 * 	would generate entity type User and Application classes into mydirectory.
-	 * 	Without parameters, the default is used:
-	 * 	C:\Adempiere\adempiere-all\extend\src\adempiere\model\ adempiere.model 'U','A'
-	 * 	
- * @param args directory package entityType - * - directory where to save the generated file - * - package of the classes to be generated - * - entityType to be generated - */ - public static void main (String[] args) - { - org.compiere.Adempiere.startupEnvironment(true); - CLogMgt.setLevel(Level.FINE); - // CLogMgt.setLevel(Level.ALL); - log.info("Generate Model $Revision: 1.5 $"); - log.info("----------------------------------"); - // first parameter - String directory = "C:\\Adempiere\\adempiere-all\\extend\\src\\adempiere\\model\\"; - if (args.length > 0) - directory = args[0]; - if (directory == null || directory.length() == 0) - { - System.err.println("No Directory"); - System.exit(1); - } - log.info("Directory: " + directory); - - // second parameter - String packageName = "adempiere.model"; - if (args.length > 1) - packageName = args[1]; - if (packageName == null || packageName.length() == 0) - { - System.err.println("No package"); - System.exit(1); - } - log.info("Package: " + packageName); - - // third parameter - String entityType = "'U','A'"; // User, Application - if (args.length > 2) - entityType = args[2]; - if (entityType == null || entityType.length() == 0) - { - System.err.println("No EntityType"); - System.exit(1); - } - StringBuffer sql = new StringBuffer("EntityType IN (") - .append(entityType).append(")"); - log.info(sql.toString()); - log.info("----------------------------------"); - - // complete sql - sql.insert(0, "SELECT AD_Table_ID " - + "FROM AD_Table " - + "WHERE (TableName IN ('RV_WarehousePrice','RV_BPartner')" // special views - + " OR IsView='N')" - + " AND TableName NOT LIKE '%_Trl' AND "); - sql.append(" ORDER BY TableName"); - - // - int count = 0; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql.toString(), null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - new GenerateModel(rs.getInt(1), directory, packageName); - count++; - } - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - log.severe("main - " + e); - } - finally - { - try - { - if (pstmt != null) - pstmt.close (); - } - catch (Exception e) - {} - pstmt = null; - } - log.info("Generated = " + count); - - } // main - -} // GenerateModel +/****************************************************************************** + * Product: Adempiere ERP & CRM Smart Business Solution * + * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * + * This program is free software; you can redistribute it and/or modify it * + * under the terms version 2 of the GNU General Public License as published * + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.util; + +import java.io.*; +import java.math.*; +import java.sql.*; +import java.util.logging.*; +import org.compiere.*; + +/** + * Generate Model Classes extending PO. + * Base class for CMP interface - will be extended to create byte code directly + * + * @author Jorg Janke + * @version $Id: GenerateModel.java,v 1.5 2006/07/30 00:54:36 jjanke Exp $ + */ +public class GenerateModel +{ + /** + * Generate PO Class + * @param AD_Table_ID table id + * @param directory directory with \ or / at the end. + * @param packageName package name + */ + public GenerateModel (int AD_Table_ID, String directory, String packageName) + { + // create column access methods + StringBuffer mandatory = new StringBuffer(); + StringBuffer sb = createColumns(AD_Table_ID, mandatory); + // add header stuff + String tableName = createHeader(AD_Table_ID, sb, mandatory, packageName); + // Save it + writeToFile (sb, directory + tableName + ".java"); + } // GenerateModel + + /** File Header */ + public static final String COPY = + "/******************************************************************************\n" + +" * Product: Adempiere ERP & CRM Smart Business Solution *\n" + +" * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *\n" + +" * This program is free software; you can redistribute it and/or modify it *\n" + +" * under the terms version 2 of the GNU General Public License as published *\n" + +" * by the Free Software Foundation. This program is distributed in the hope *\n" + +" * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *\n" + +" * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n" + +" * See the GNU General Public License for more details. *\n" + +" * You should have received a copy of the GNU General Public License along *\n" + +" * with this program; if not, write to the Free Software Foundation, Inc., *\n" + +" * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *\n" + +" * For the text or an alternative of this public license, you may reach us *\n" + +" * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *\n" + +" * or via info@compiere.org or http://www.compiere.org/license.html *\n" + +" *****************************************************************************/\n"; + + /** Generated on */ + private Timestamp s_run = new Timestamp(System.currentTimeMillis()); + + /** Logger */ + private static CLogger log = CLogger.getCLogger (GenerateModel.class); + + /** + * Add Header info to buffer + * @param AD_Table_ID table + * @param sb buffer + * @param mandatory init call for mandatory columns + * @param packageName package name + * @return class name + */ + private String createHeader (int AD_Table_ID, StringBuffer sb, StringBuffer mandatory, String packageName) + { + String tableName = ""; + int accessLevel = 0; + String sql = "SELECT TableName, AccessLevel FROM AD_Table WHERE AD_Table_ID=?"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Table_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + tableName = rs.getString(1); + accessLevel = rs.getInt(2); + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + if (tableName == null) + throw new RuntimeException ("TableName not found for ID=" + AD_Table_ID); + // + String accessLevelInfo = accessLevel + " "; + if (accessLevel >= 4 ) + accessLevelInfo += "- System "; + if (accessLevel == 2 || accessLevel == 3 || accessLevel == 6 || accessLevel == 7) + accessLevelInfo += "- Client "; + if (accessLevel == 1 || accessLevel == 3 || accessLevel == 5 || accessLevel == 7) + accessLevelInfo += "- Org "; + + String keyColumn = tableName + "_ID"; + String className = "X_" + tableName; + // + StringBuffer start = new StringBuffer () + .append (COPY) + .append ("package " + packageName + ";\n" + + "/** Generated Model - DO NOT CHANGE */\n"); + if (!packageName.equals("org.compiere.model")) + start.append("import org.compiere.model.*;"); + start.append("import java.util.*;" + + "import java.sql.*;" + + "import java.math.*;" + + "import org.compiere.util.*;" + // Class + + "/** Generated Model for ").append(tableName).append("\n" + + " * @author Jorg Janke (generated) \n" + + " * @version ").append(Adempiere.MAIN_VERSION).append(" - $Id$") + // .append(s_run) // Timestamp + .append(" */\n" + + "public class ").append(className).append(" extends PO" + + "{" + // Standard Constructor + + "/** Standard Constructor\n@param ctx context\n@param " + + keyColumn + " id\n@param trxName transaction\n*/\n" + + "public ").append(className).append(" (Properties ctx, int ").append(keyColumn) + .append(", String trxName)" + + "{" + + "super (ctx, ").append(keyColumn).append(", trxName);" + + "/** if (").append(keyColumn).append(" == 0)" + + "{").append(mandatory).append("} */\n" + + "}" // Constructor End + // Short Constructor +// + "/** Short Constructor */\n" +// + "public ").append(className).append(" (Properties ctx, int ").append(keyColumn).append(")" +// + "{" +// + "this (ctx, ").append(keyColumn).append(", null);" +// + "}" // Constructor End + + // Load Constructor + + "/** Load Constructor \n@param ctx context\n@param rs result set \n@param trxName transaction\n*/\n" + + "public ").append(className).append(" (Properties ctx, ResultSet rs, String trxName)" + + "{" + + "super (ctx, rs, trxName);" + + "}" // Load Constructor End + // + + "/** AD_Table_ID=").append(AD_Table_ID).append(" */\n" + + "public static final int Table_ID=").append(AD_Table_ID).append(";\n" + // + + "/** TableName=").append(tableName).append(" */\n" + + "public static final String Table_Name=\"").append(tableName).append("\";\n" + + "protected static KeyNamePair Model = new KeyNamePair(").append(AD_Table_ID).append(",\"").append(tableName).append("\");\n" + // + + "protected BigDecimal accessLevel = new BigDecimal(").append(accessLevel).append(");" + + "/** AccessLevel\n@return ").append(accessLevelInfo).append("\n*/\n" + + "protected int get_AccessLevel()" + + "{" + + "return accessLevel.intValue();" + + "}" + // + + "/** Load Meta Data\n@param ctx context\n@return PO Info\n*/\n" + + "protected POInfo initPO (Properties ctx)" + + "{" + + "POInfo poi = POInfo.getPOInfo (ctx, Table_ID);" + + "return poi;" + + "}" // initPO + // + + "/** Info\n@return info\n*/\n" + + "public String toString()" + + "{" + + "StringBuffer sb = new StringBuffer (\"").append(className).append("[\")" + + ".append(get_ID()).append(\"]\");" + + "return sb.toString();" + + "}"); + + StringBuffer end = new StringBuffer ("}"); + // + sb.insert(0, start); + sb.append(end); + + return className; + } // createHeader + + + /** + * Create Column access methods + * @param AD_Table_ID table + * @param mandatory init call for mandatory columns + * @return set/get method + */ + private StringBuffer createColumns (int AD_Table_ID, StringBuffer mandatory) + { + StringBuffer sb = new StringBuffer(); + String sql = "SELECT c.ColumnName, c.IsUpdateable, c.IsMandatory," // 1..3 + + " c.AD_Reference_ID, c.AD_Reference_Value_ID, DefaultValue, SeqNo, " // 4..7 + + " c.FieldLength, c.ValueMin, c.ValueMax, c.VFormat, c.Callout, " // 8..12 + + " c.Name, c.Description, c.ColumnSQL, c.IsEncrypted " + + "FROM AD_Column c " + + "WHERE c.AD_Table_ID=?" + + " AND c.IsActive='Y'" + + " AND c.ColumnName <> 'AD_Client_ID'" + + " AND c.ColumnName <> 'AD_Org_ID'" + + " AND c.ColumnName <> 'IsActive'" + + " AND c.ColumnName NOT LIKE 'Created%'" + + " AND c.ColumnName NOT LIKE 'Updated%' " + + "ORDER BY c.ColumnName"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Table_ID); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + String columnName = rs.getString(1); + boolean isUpdateable = "Y".equals(rs.getString(2)); + boolean isMandatory = "Y".equals(rs.getString(3)); + int displayType = rs.getInt(4); + int AD_Reference_Value_ID = rs.getInt(5); + String defaultValue = rs.getString(6); + int seqNo = rs.getInt(7); + int fieldLength = rs.getInt(8); + String ValueMin = rs.getString(9); + String ValueMax = rs.getString(10); + String VFormat = rs.getString(11); + String Callout = rs.getString(12); + String Name = rs.getString(13); + String Description = rs.getString(14); + String ColumnSQL = rs.getString(15); + boolean virtualColumn = ColumnSQL != null && ColumnSQL.length() > 0; + boolean IsEncrypted = "Y".equals(rs.getString(16)); + // + sb.append(createColumnMethods (mandatory, + columnName, isUpdateable, isMandatory, + displayType, AD_Reference_Value_ID, fieldLength, + defaultValue, ValueMin, ValueMax, VFormat, + Callout, Name, Description, virtualColumn, IsEncrypted)); + // + if (seqNo == 1) + sb.append(createKeyNamePair(columnName, displayType)); + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + return sb; + } // createColumns + + /** + * Create set/get methods for column + * @param mandatory init call for mandatory columns + * @param columnName column name + * @param isUpdateable updateable + * @param isMandatory mandatory + * @param displayType display type + * @param AD_Reference_ID validation reference + * @param fieldLength int + * @param defaultValue default value + * @param ValueMin String + * @param ValueMax String + * @param VFormat String + * @param Callout String + * @param Name String + * @param Description String + * @param virtualColumn virtual column + * @param IsEncrypted stored encrypted + @return set/get method + */ + private String createColumnMethods (StringBuffer mandatory, + String columnName, boolean isUpdateable, boolean isMandatory, + int displayType, int AD_Reference_ID, int fieldLength, + String defaultValue, String ValueMin, String ValueMax, String VFormat, + String Callout, String Name, String Description, + boolean virtualColumn, boolean IsEncrypted) + { + // Clazz + Class clazz = DisplayType.getClass(displayType, true); + if (defaultValue == null) + defaultValue = ""; + if (DisplayType.isLOB(displayType)) // No length check for LOBs + fieldLength = 0; + + // Handle Posted + if (columnName.equalsIgnoreCase("Posted") + || columnName.equalsIgnoreCase("Processed") + || columnName.equalsIgnoreCase("Processing")) + { + clazz = Boolean.class; + AD_Reference_ID = 0; + } + // Record_ID + else if (columnName.equalsIgnoreCase("Record_ID")) + { + clazz = Integer.class; + AD_Reference_ID = 0; + } + // String Key + else if (columnName.equalsIgnoreCase("AD_Language") + || columnName.equalsIgnoreCase("EntityType")) + { + clazz = String.class; + } + // Data Type + String dataType = clazz.getName(); + dataType = dataType.substring(dataType.lastIndexOf('.')+1); + if (dataType.equals("Boolean")) + dataType = "boolean"; + else if (dataType.equals("Integer")) + dataType = "int"; + else if (displayType == DisplayType.Binary) + dataType = "byte[]"; + + + StringBuffer sb = new StringBuffer(); + // ****** Set Comment ****** + sb.append("/** Set ").append(Name); + sb.append(".\n@param ").append(columnName).append(" "); + if (Description != null && Description.length() > 0) + sb.append(Description); + else + sb.append(Name); + sb.append(" */\n"); + + // Set ******** + String setValue = "set_Value"; + if (IsEncrypted) + setValue = "set_ValueE"; + // public void setColumn (xxx variable) + sb.append("public "); + if (!isUpdateable) + { + setValue = "set_ValueNoCheck"; + if (IsEncrypted) + setValue = "set_ValueNoCheckE"; + } + sb.append("void set").append(columnName).append(" (").append(dataType).append(" ").append(columnName).append(")" + + "{"); + // List Validation + if (AD_Reference_ID != 0) + { + String staticVar = addListValidation (sb, AD_Reference_ID, columnName, !isMandatory); + sb.insert(0, staticVar); // first check + } + // setValue ("ColumnName", xx); + if (virtualColumn) + { + sb.append ("throw new IllegalArgumentException (\"").append(columnName).append(" is virtual column\");"); + } + // Integer + else if (clazz.equals(Integer.class)) + { + if (columnName.endsWith("_ID")) + { + if (isMandatory) // check mandatory ID + { + int firstOK = 1; // Valid ID 0 + if (columnName.equals("AD_Client_ID") || columnName.equals("AD_Org_ID") + || columnName.equals("Record_ID") || columnName.equals("C_DocType_ID") + || columnName.equals("Node_ID") || columnName.equals("AD_Role_ID") + || columnName.equals("M_AttributeSet_ID") || columnName.equals("M_AttributeSetInstance_ID")) + firstOK = 0; + sb.append("if (").append (columnName) + .append (" < ").append(firstOK).append(") throw new IllegalArgumentException (\"") + .append(columnName).append(" is mandatory.\");"); + } + else // set optional _ID to null if 0 + sb.append("if (").append (columnName).append (" <= 0) ") + .append(setValue).append(" (\"").append(columnName).append("\", null); else \n"); + } + sb.append(setValue).append(" (\"").append(columnName).append("\", new Integer(").append(columnName).append("));"); + } + // Boolean + else if (clazz.equals(Boolean.class)) + sb.append(setValue).append(" (\"").append(columnName).append("\", new Boolean(").append(columnName).append("));"); + else + { + if (isMandatory && AD_Reference_ID == 0) // does not apply to int/boolean + { + sb.append("if (") + .append (columnName).append (" == null)" + + " throw new IllegalArgumentException (\"") + .append(columnName).append(" is mandatory.\");"); + } + // String length check + if (clazz.equals(String.class) && fieldLength > 0) + { + sb.append ("if ("); + if (!isMandatory) + sb.append(columnName).append(" != null && "); + sb.append(columnName).append(".length() > ").append(fieldLength) + .append("){log.warning(\"Length > ") + .append(fieldLength).append(" - truncated\");") + .append(columnName).append(" = ") + .append(columnName).append(".substring(0,").append(fieldLength-1).append(");}"); + } + + // + sb.append (setValue).append(" (\"").append (columnName).append ("\", ") + .append (columnName).append (");"); + } + sb.append("}"); + + // Mandatory call in constructor + if (isMandatory) + { + mandatory.append("set").append(columnName).append(" ("); + if (clazz.equals(Integer.class)) + mandatory.append("0"); + else if (clazz.equals(Boolean.class)) + { + if (defaultValue.indexOf('Y') != -1) + mandatory.append(true); + else + mandatory.append("false"); + } + else if (clazz.equals(BigDecimal.class)) + mandatory.append("Env.ZERO"); + else if (clazz.equals(Timestamp.class)) + mandatory.append("new Timestamp(System.currentTimeMillis())"); + else + mandatory.append("null"); + mandatory.append(");"); + if (defaultValue.length() > 0) + mandatory.append("// ").append(defaultValue).append(Env.NL); + } + + + // ****** Get Comment ****** + sb.append("/** Get ").append(Name); + if (Description != null && Description.length() > 0) + sb.append(".\n@return ").append(Description); + else + sb.append(".\n@return ").append(Name); + sb.append(" */\n"); + + // Get ******** + String getValue = "get_Value"; + if (IsEncrypted) + getValue = "get_ValueE"; + sb.append("public ").append(dataType); + if (clazz.equals(Boolean.class)) + { + sb.append(" is"); + if (columnName.toLowerCase().startsWith("is")) + sb.append(columnName.substring(2)); + else + sb.append(columnName); + } + else + sb.append(" get").append(columnName); + sb.append("() {"); + if (clazz.equals(Integer.class)) + sb.append("Integer ii = (Integer)") + .append(getValue).append("(\"").append(columnName).append("\");" + + "if (ii == null)" + + " return 0;" + + "return ii.intValue();"); + else if (clazz.equals(BigDecimal.class)) + sb.append("BigDecimal bd = (BigDecimal)").append(getValue) + .append("(\"").append(columnName).append("\");" + + "if (bd == null)" + + " return Env.ZERO;" + + "return bd;"); + else if (clazz.equals(Boolean.class)) + sb.append("Object oo = ").append(getValue) + .append("(\"").append(columnName).append("\");" + + "if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return \"Y\".equals(oo);}" + + "return false;"); + else if (dataType.equals("Object")) + sb.append("return ").append(getValue) + .append("(\"").append(columnName).append("\");"); + else + sb.append("return (").append(dataType).append(")").append(getValue) + .append("(\"").append(columnName).append("\");"); + sb.append("}"); + // + return sb.toString(); + } // createColumnMethods + + + /** + * Add List Validation + * @param sb buffer - example: + if (NextAction.equals("N") || NextAction.equals("F")); + else throw new IllegalArgumentException ("NextAction Invalid value - Reference_ID=219 - N - F"); + * @param AD_Reference_ID reference + * @param columnName column + * @param nullable the validation must allow null values + * @return static parameter - Example: + public static final int NEXTACTION_AD_Reference_ID=219; + public static final String NEXTACTION_None = "N"; + public static final String NEXTACTION_FollowUp = "F"; + */ + private String addListValidation (StringBuffer sb, int AD_Reference_ID, + String columnName, boolean nullable) + { + StringBuffer retValue = new StringBuffer(); + retValue.append("\n/** ").append(columnName).append(" AD_Reference_ID=").append(AD_Reference_ID) .append(" */\n") + .append("public static final int ").append(columnName.toUpperCase()) + .append("_AD_Reference_ID=").append(AD_Reference_ID).append(";"); + // + boolean found = false; + StringBuffer values = new StringBuffer("Reference_ID=") + .append(AD_Reference_ID); + StringBuffer statement = new StringBuffer(); + if (nullable) + statement.append("if (").append(columnName).append(" == null"); + // + String sql = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=?"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Reference_ID); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + String value = rs.getString(1); + values.append(" - ").append(value); + if (statement.length() == 0) + statement.append("if (").append(columnName) + .append(".equals(\"").append(value).append("\")"); + else + statement.append(" || ").append(columnName) + .append(".equals(\"").append(value).append("\")"); + // + if (!found) + { + found = true; + if (!nullable) + sb.append("if (") + .append (columnName).append (" == null)" + + " throw new IllegalArgumentException (\"") + .append(columnName).append(" is mandatory\");"); + } + + + // Name (SmallTalkNotation) + String name = rs.getString(2); + char[] nameArray = name.toCharArray(); + StringBuffer nameClean = new StringBuffer(); + boolean initCap = true; + for (int i = 0; i < nameArray.length; i++) + { + char c = nameArray[i]; + if (Character.isJavaIdentifierPart(c)) + { + if (initCap) + nameClean.append(Character.toUpperCase(c)); + else + nameClean.append(c); + initCap = false; + } + else + { + if (c == '+') + nameClean.append("Plus"); + else if (c == '-') + nameClean.append("_"); + else if (c == '>') + { + if (name.indexOf('<') == -1) // ignore + nameClean.append("Gt"); + } + else if (c == '<') + { + if (name.indexOf('>') == -1) // ignore + nameClean.append("Le"); + } + else if (c == '!') + nameClean.append("Not"); + else if (c == '=') + nameClean.append("Eq"); + else if (c == '~') + nameClean.append("Like"); + initCap = true; + } + } + retValue.append("/** ").append(name).append(" = ").append(value).append(" */\n"); + retValue.append("public static final String ").append(columnName.toUpperCase()) + .append("_").append(nameClean) + .append(" = \"").append(value).append("\";"); + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + found = false; + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + statement.append(")" + + "; " + + "else " + + "throw new IllegalArgumentException (\"").append(columnName) + .append(" Invalid value - \" + ").append(columnName) + .append(" + \" - ").append(values).append("\");"); + // + if (found && !columnName.equals("EntityType")) + sb.append (statement); + return retValue.toString(); + } // addListValidation + + /** + * Create getKeyNamePair() method with first identifier + * @param columnName name + * * @param displayType int + @return method code + */ + private StringBuffer createKeyNamePair (String columnName, int displayType) + { + String method = "get" + columnName + "()"; + if (displayType != DisplayType.String) + method = "String.valueOf(" + method + ")"; + StringBuffer sb = new StringBuffer("/** Get Record ID/ColumnName\n@return ID/ColumnName pair\n*/" + + "public KeyNamePair getKeyNamePair() " + + "{return new KeyNamePair(get_ID(), ").append(method).append(");}"); + return sb; + } // createKeyNamePair + + + /************************************************************************** + * Write to file + * @param sb string buffer + * @param fileName file name + */ + private void writeToFile (StringBuffer sb, String fileName) + { + try + { + File out = new File (fileName); + FileWriter fw = new FileWriter (out); + for (int i = 0; i < sb.length(); i++) + { + char c = sb.charAt(i); + // after + if (c == ';' || c == '}') + { + fw.write (c); + if (sb.substring(i+1).startsWith("//")) + fw.write('\t'); + else + fw.write(Env.NL); + } + // before & after + else if (c == '{') + { + fw.write(Env.NL); + fw.write (c); + fw.write(Env.NL); + } + else + fw.write (c); + } + fw.flush (); + fw.close (); + float size = out.length(); + size /= 1024; + log.info(out.getAbsolutePath() + " - " + size + " kB"); + } + catch (Exception ex) + { + log.log(Level.SEVERE, fileName, ex); + } + } // writeToFile + + /** + * String representation + * @return string representation + */ + public String toString() + { + StringBuffer sb = new StringBuffer ("GenerateModel[") + .append("]"); + return sb.toString(); + } // toString + + + + /************************************************************************** + * Generate PO Model Class. + *
+	 * 	Example: java GenerateModel.class mydirectory myPackage 'U','A'
+	 * 	would generate entity type User and Application classes into mydirectory.
+	 * 	Without parameters, the default is used:
+	 * 	C:\Adempiere\adempiere-all\extend\src\adempiere\model\ adempiere.model 'U','A'
+	 * 	
+ * @param args directory package entityType + * - directory where to save the generated file + * - package of the classes to be generated + * - entityType to be generated + */ + public static void main (String[] args) + { + org.compiere.Adempiere.startupEnvironment(true); + CLogMgt.setLevel(Level.FINE); + // CLogMgt.setLevel(Level.ALL); + log.info("Generate Model $Revision: 1.5 $"); + log.info("----------------------------------"); + // first parameter + String directory = "C:\\Adempiere\\adempiere-all\\extend\\src\\adempiere\\model\\"; + if (args.length > 0) + directory = args[0]; + if (directory == null || directory.length() == 0) + { + System.err.println("No Directory"); + System.exit(1); + } + log.info("Directory: " + directory); + + // second parameter + String packageName = "adempiere.model"; + if (args.length > 1) + packageName = args[1]; + if (packageName == null || packageName.length() == 0) + { + System.err.println("No package"); + System.exit(1); + } + log.info("Package: " + packageName); + + // third parameter + String entityType = "'U','A'"; // User, Application + if (args.length > 2) + entityType = args[2]; + if (entityType == null || entityType.length() == 0) + { + System.err.println("No EntityType"); + System.exit(1); + } + StringBuffer sql = new StringBuffer("EntityType IN (") + .append(entityType).append(")"); + log.info(sql.toString()); + log.info("----------------------------------"); + + // complete sql + sql.insert(0, "SELECT AD_Table_ID " + + "FROM AD_Table " + + "WHERE (TableName IN ('RV_WarehousePrice','RV_BPartner')" // special views + + " OR IsView='N')" + + " AND TableName NOT LIKE '%_Trl' AND "); + sql.append(" ORDER BY TableName"); + + // + int count = 0; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql.toString(), null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + new GenerateModel(rs.getInt(1), directory, packageName); + count++; + } + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + log.severe("main - " + e); + } + finally + { + try + { + if (pstmt != null) + pstmt.close (); + } + catch (Exception e) + {} + pstmt = null; + } + log.info("Generated = " + count); + + } // main + +} // GenerateModel diff --git a/dbPort/src/org/compiere/util/Login.java b/dbPort/src/org/compiere/util/Login.java index eb6df324cd..8eb9a28e5e 100644 --- a/dbPort/src/org/compiere/util/Login.java +++ b/dbPort/src/org/compiere/util/Login.java @@ -3,43 +3,43 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.util; - -import java.security.*; -import java.sql.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; -// -import org.compiere.*; -import org.compiere.db.*; -import org.compiere.model.*; - - -/** - * Login Manager - * - * @author Jorg Janke - * @version $Id: Login.java,v 1.6 2006/10/02 05:19:06 jjanke Exp $ - */ -public class Login -{ - /** - * Test Init - Set Environment for tests - * @param isClient client session - * @return Context - */ + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.util; + +import java.security.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; +// +import org.compiere.*; +import org.compiere.db.*; +import org.compiere.model.*; + + +/** + * Login Manager + * + * @author Jorg Janke + * @version $Id: Login.java,v 1.6 2006/10/02 05:19:06 jjanke Exp $ + */ +public class Login +{ + /** + * Test Init - Set Environment for tests + * @param isClient client session + * @return Context + */ public static Properties initTest (boolean isClient) { // logger.entering("Env", "initTest"); @@ -47,39 +47,39 @@ public class Login // Test Context Properties ctx = Env.getCtx(); Login login = new Login(ctx); - KeyNamePair[] roles = login.getRoles(CConnection.get(), - "System", "System", true); - // load role - if (roles != null && roles.length > 0) - { - KeyNamePair[] clients = login.getClients (roles[0]); - // load client - if (clients != null && clients.length > 0) - { - KeyNamePair[] orgs = login.getOrgs(clients[0]); - // load org - if (orgs != null && orgs.length > 0) - { - KeyNamePair[] whs = login.getWarehouses(orgs[0]); - // - login.loadPreferences(orgs[0], null, null, null); - } - } - } - // - Env.setContext(ctx, "#Date", "2000-01-01"); - // logger.exiting("Env", "initTest"); - return ctx; - } // testInit - - /** - * Java Version Test - * @param isClient client connection - * @return true if Java Version is OK - */ - public static boolean isJavaOK (boolean isClient) - { - // Java System version check + KeyNamePair[] roles = login.getRoles(CConnection.get(), + "System", "System", true); + // load role + if (roles != null && roles.length > 0) + { + KeyNamePair[] clients = login.getClients (roles[0]); + // load client + if (clients != null && clients.length > 0) + { + KeyNamePair[] orgs = login.getOrgs(clients[0]); + // load org + if (orgs != null && orgs.length > 0) + { + KeyNamePair[] whs = login.getWarehouses(orgs[0]); + // + login.loadPreferences(orgs[0], null, null, null); + } + } + } + // + Env.setContext(ctx, "#Date", "2000-01-01"); + // logger.exiting("Env", "initTest"); + return ctx; + } // testInit + + /** + * Java Version Test + * @param isClient client connection + * @return true if Java Version is OK + */ + public static boolean isJavaOK (boolean isClient) + { + // Java System version check String jVersion = System.getProperty("java.version"); if (jVersion.startsWith("1.5.0")) return true; @@ -90,15 +90,15 @@ public class Login // Warning boolean ok = false; // if (jVersion.startsWith("1.4") - // || jVersion.startsWith("1.5.1")) // later/earlier release - // ok = true; - - // Error Message - StringBuffer msg = new StringBuffer(); - msg.append(System.getProperty("java.vm.name")).append(" - ").append(jVersion); - if (ok) - msg.append("(untested)"); - msg.append(" <> 1.5.0"); + // || jVersion.startsWith("1.5.1")) // later/earlier release + // ok = true; + + // Error Message + StringBuffer msg = new StringBuffer(); + msg.append(System.getProperty("java.vm.name")).append(" - ").append(jVersion); + if (ok) + msg.append("(untested)"); + msg.append(" <> 1.5.0"); // if (isClient) JOptionPane.showMessageDialog(null, msg.toString(), @@ -106,845 +106,846 @@ public class Login ok ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE); else log.severe(msg.toString()); - return ok; - } // isJavaOK - - - /************************************************************************** - * Login - * @param ctx context - */ - public Login (Properties ctx) - { - if (ctx == null) - throw new IllegalArgumentException("Context missing"); - m_ctx = ctx; - } // Login - - /** Logger */ - private static CLogger log = CLogger.getCLogger(Login.class); - /** Context */ - private Properties m_ctx = null; - /** Connection Profile */ - private String m_connectionProfile = null; - - - /** - * (Test) Client Login. - *

- * - Get Connection - * - Compare User info - *

- * Sets Conext with login info - * @param cc connection - * @param app_user user - * @param app_pwd pwd - * @param force ignore pwd - * @return Array of Role KeyNamePair or null if error - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log - */ - protected KeyNamePair[] getRoles (CConnection cc, - String app_user, String app_pwd, boolean force) - { - // Establish connection - DB.setDBTarget(cc); - Env.setContext(m_ctx, "#Host", cc.getAppsHost()); - Env.setContext(m_ctx, "#Database", cc.getDbName()); - - if (DB.getConnectionRO() == null) - { - log.saveError("NoDatabase", ""); - return null; - } - if (app_pwd == null) - return null; - // - return getRoles (app_user, app_pwd, force); - } // getRoles - - /** - * (Web) Client Login. - *

- * Compare User Info - *

- * Sets Conext with login info - * @param app_user Principal - * @return role array or null if in error. - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log - */ - public KeyNamePair[] getRoles (Principal app_user) - { - if (app_user == null) - return null; - // login w/o password as previously authorized - return getRoles (app_user.getName(), null, false); - } // getRoles - - /** - * Client Login. - *

- * Compare User Info - *

- * Sets Conext with login info - * @param app_user user id - * @param app_pwd password - * @return role array or null if in error. - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log - */ - public KeyNamePair[] getRoles (String app_user, String app_pwd) - { - return getRoles (app_user, app_pwd, false); - } // login - - /** - * Actual DB login procedure. - * @param app_user user - * @param app_pwd pwd - * @param force ignore pwd - * @return role array or null if in error. - * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log - */ - private KeyNamePair[] getRoles (String app_user, String app_pwd, boolean force) - { - log.info("User=" + app_user); - long start = System.currentTimeMillis(); - if (app_user == null) - { - log.warning("No Apps User"); - return null; - } - - // Authentification - boolean authenticated = false; - MSystem system = MSystem.get(m_ctx); - if (system.isLDAP()) - { - authenticated = system.isLDAP(app_user, app_pwd); - if (authenticated) - app_pwd = null; - // if not authenticated, use AD_User as backup - } - else if (app_pwd == null || app_pwd.length() == 0) - { - log.warning("No Apps Password"); - return null; - } - - KeyNamePair[] retValue = null; - ArrayList list = new ArrayList(); - // - StringBuffer sql = new StringBuffer("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name,") - .append(" u.ConnectionProfile ") - .append("FROM AD_User u") - .append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')") - .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') ") - .append("WHERE COALESCE(u.LDAPUser,u.Name)=?") // #1 - .append(" AND u.IsActive='Y'") - .append(" AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); - if (app_pwd != null) - sql.append(" AND (u.Password=? OR u.Password=?)"); // #2/3 - sql.append(" ORDER BY r.Name"); - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql.toString(), null); - pstmt.setString(1, app_user); - if (app_pwd != null) - { - pstmt.setString(2, app_pwd); - pstmt.setString(3, SecureEngine.encrypt(app_pwd)); - } - // execute a query - ResultSet rs = pstmt.executeQuery(); - - if (!rs.next()) // no record found - if (force) - { - Env.setContext(m_ctx, "#AD_User_Name", "System"); - Env.setContext(m_ctx, "#AD_User_ID", "0"); - Env.setContext(m_ctx, "#AD_User_Description", "System Forced Login"); - Env.setContext(m_ctx, "#User_Level", "S "); // Format 'SCO' - Env.setContext(m_ctx, "#User_Client", "0"); // Format c1, c2, ... - Env.setContext(m_ctx, "#User_Org", "0"); // Format o1, o2, ... - rs.close(); - pstmt.close(); - retValue = new KeyNamePair[] {new KeyNamePair(0, "System Administrator")}; - return retValue; - } - else - { - rs.close(); - pstmt.close(); - log.saveError("UserPwdError", app_user, false); - return null; - } - - Env.setContext(m_ctx, "#AD_User_Name", app_user); - Env.setContext(m_ctx, "#AD_User_ID", rs.getInt(1)); - Env.setContext(m_ctx, "#SalesRep_ID", rs.getInt(1)); - // - Ini.setProperty(Ini.P_UID, app_user); - if (Ini.isPropertyBool(Ini.P_STORE_PWD)) - Ini.setProperty(Ini.P_PWD, app_pwd); - - m_connectionProfile = rs.getString(4); // User Based - if (m_connectionProfile != null) - { - CConnection cc = CConnection.get(); - if (!cc.getConnectionProfile().equals(m_connectionProfile)) - { - cc.setConnectionProfile(m_connectionProfile); - Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong()); - Ini.saveProperties(false); - } - } - - do // read all roles - { - int AD_Role_ID = rs.getInt(2); - if (AD_Role_ID == 0) - Env.setContext(m_ctx, "#SysAdmin", "Y"); - String Name = rs.getString(3); - KeyNamePair p = new KeyNamePair(AD_Role_ID, Name); - list.add(p); - } - while (rs.next()); - - rs.close(); - pstmt.close(); - pstmt = null; - // - retValue = new KeyNamePair[list.size()]; - list.toArray(retValue); - log.fine("User=" + app_user + " - roles #" + retValue.length); - } - catch (SQLException ex) - { - log.log(Level.SEVERE, sql.toString(), ex); - log.saveError("DBLogin", ex); - retValue = null; - } - // - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) + return ok; + } // isJavaOK + + + /************************************************************************** + * Login + * @param ctx context + */ + public Login (Properties ctx) + { + if (ctx == null) + throw new IllegalArgumentException("Context missing"); + m_ctx = ctx; + } // Login + + /** Logger */ + private static CLogger log = CLogger.getCLogger(Login.class); + /** Context */ + private Properties m_ctx = null; + /** Connection Profile */ + private String m_connectionProfile = null; + + + /** + * (Test) Client Login. + *

+ * - Get Connection + * - Compare User info + *

+ * Sets Conext with login info + * @param cc connection + * @param app_user user + * @param app_pwd pwd + * @param force ignore pwd + * @return Array of Role KeyNamePair or null if error + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + */ + protected KeyNamePair[] getRoles (CConnection cc, + String app_user, String app_pwd, boolean force) + { + // Establish connection + DB.setDBTarget(cc); + Env.setContext(m_ctx, "#Host", cc.getAppsHost()); + Env.setContext(m_ctx, "#Database", cc.getDbName()); + + if (DB.getConnectionRO() == null) + { + log.saveError("NoDatabase", ""); + return null; + } + if (app_pwd == null) + return null; + // + return getRoles (app_user, app_pwd, force); + } // getRoles + + /** + * (Web) Client Login. + *

+ * Compare User Info + *

+ * Sets Conext with login info + * @param app_user Principal + * @return role array or null if in error. + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + */ + public KeyNamePair[] getRoles (Principal app_user) + { + if (app_user == null) + return null; + // login w/o password as previously authorized + return getRoles (app_user.getName(), null, false); + } // getRoles + + /** + * Client Login. + *

+ * Compare User Info + *

+ * Sets Conext with login info + * @param app_user user id + * @param app_pwd password + * @return role array or null if in error. + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + */ + public KeyNamePair[] getRoles (String app_user, String app_pwd) + { + return getRoles (app_user, app_pwd, false); + } // login + + /** + * Actual DB login procedure. + * @param app_user user + * @param app_pwd pwd + * @param force ignore pwd + * @return role array or null if in error. + * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log + */ + private KeyNamePair[] getRoles (String app_user, String app_pwd, boolean force) + { + log.info("User=" + app_user); + long start = System.currentTimeMillis(); + if (app_user == null) + { + log.warning("No Apps User"); + return null; + } + + // Authentification + boolean authenticated = false; + MSystem system = MSystem.get(m_ctx); + if (system.isLDAP()) + { + authenticated = system.isLDAP(app_user, app_pwd); + if (authenticated) + app_pwd = null; + // if not authenticated, use AD_User as backup + } + else if (app_pwd == null || app_pwd.length() == 0) + { + log.warning("No Apps Password"); + return null; + } + + KeyNamePair[] retValue = null; + ArrayList list = new ArrayList(); + // + StringBuffer sql = new StringBuffer("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name,") + .append(" u.ConnectionProfile ") + .append("FROM AD_User u") + .append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')") + .append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') ") + .append("WHERE COALESCE(u.LDAPUser,u.Name)=?") // #1 + .append(" AND u.IsActive='Y'") + .append(" AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')"); + if (app_pwd != null) + sql.append(" AND (u.Password=? OR u.Password=?)"); // #2/3 + sql.append(" ORDER BY r.Name"); + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql.toString(), null); + pstmt.setString(1, app_user); + if (app_pwd != null) + { + pstmt.setString(2, app_pwd); + pstmt.setString(3, SecureEngine.encrypt(app_pwd)); + } + // execute a query + ResultSet rs = pstmt.executeQuery(); + + if (!rs.next()) // no record found + if (force) + { + Env.setContext(m_ctx, "#AD_User_Name", "System"); + Env.setContext(m_ctx, "#AD_User_ID", "0"); + Env.setContext(m_ctx, "#AD_User_Description", "System Forced Login"); + Env.setContext(m_ctx, "#User_Level", "S "); // Format 'SCO' + Env.setContext(m_ctx, "#User_Client", "0"); // Format c1, c2, ... + Env.setContext(m_ctx, "#User_Org", "0"); // Format o1, o2, ... + rs.close(); + pstmt.close(); + retValue = new KeyNamePair[] {new KeyNamePair(0, "System Administrator")}; + return retValue; + } + else + { + rs.close(); + pstmt.close(); + log.saveError("UserPwdError", app_user, false); + return null; + } + + Env.setContext(m_ctx, "#AD_User_Name", app_user); + Env.setContext(m_ctx, "#AD_User_ID", rs.getInt(1)); + Env.setContext(m_ctx, "#SalesRep_ID", rs.getInt(1)); + // + Ini.setProperty(Ini.P_UID, app_user); + if (Ini.isPropertyBool(Ini.P_STORE_PWD)) + Ini.setProperty(Ini.P_PWD, app_pwd); + + m_connectionProfile = rs.getString(4); // User Based + if (m_connectionProfile != null) + { + CConnection cc = CConnection.get(); + if (!cc.getConnectionProfile().equals(m_connectionProfile)) + { + cc.setConnectionProfile(m_connectionProfile); + Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong()); + Ini.saveProperties(false); + } + } + + do // read all roles + { + int AD_Role_ID = rs.getInt(2); + if (AD_Role_ID == 0) + Env.setContext(m_ctx, "#SysAdmin", "Y"); + String Name = rs.getString(3); + KeyNamePair p = new KeyNamePair(AD_Role_ID, Name); + list.add(p); + } + while (rs.next()); + + rs.close(); + pstmt.close(); + pstmt = null; + // + retValue = new KeyNamePair[list.size()]; + list.toArray(retValue); + log.fine("User=" + app_user + " - roles #" + retValue.length); + } + catch (SQLException ex) + { + log.log(Level.SEVERE, sql.toString(), ex); + log.saveError("DBLogin", ex); + retValue = null; + } + // + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) { pstmt = null; } + long ms = System.currentTimeMillis () - start; return retValue; } // getRoles - - /************************************************************************** - * Load Clients. - *

- * Sets Role info in context and loads its clients - * @param role role information - * @return list of valid client KeyNodePairs or null if in error - */ - public KeyNamePair[] getClients (KeyNamePair role) - { - if (role == null) - throw new IllegalArgumentException("Role missing"); - - // s_log.fine("loadClients - Role: " + role.toStringX()); - - ArrayList list = new ArrayList(); - KeyNamePair[] retValue = null; - String sql = "SELECT DISTINCT r.UserLevel, r.ConnectionProfile, " // 1/2 - + " c.AD_Client_ID,c.Name " // 3/4 - + "FROM AD_Role r" - + " INNER JOIN AD_Client c ON (r.AD_Client_ID=c.AD_Client_ID) " - + "WHERE r.AD_Role_ID=?" // #1 - + " AND r.IsActive='Y' AND c.IsActive='Y'"; - - PreparedStatement pstmt = null; - // get Role details - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, role.getKey()); - ResultSet rs = pstmt.executeQuery(); - - if (!rs.next()) - { - rs.close(); - pstmt.close(); - log.log(Level.SEVERE, "No Clients for Role: " + role.toStringX()); - return null; - } - - // Role Info - Env.setContext(m_ctx, "#AD_Role_ID", role.getKey()); - Env.setContext(m_ctx, "#AD_Role_Name", role.getName()); - Ini.setProperty(Ini.P_ROLE, role.getName()); - // User Level - Env.setContext(m_ctx, "#User_Level", rs.getString(1)); // Format 'SCO' - - // ConnectionProfile - CConnection cc = CConnection.get(); - if (m_connectionProfile == null) // No User Based - { - m_connectionProfile = rs.getString(2); // Role Based - if (m_connectionProfile != null - && !cc.getConnectionProfile().equals(m_connectionProfile)) - { - cc.setConnectionProfile(m_connectionProfile); - Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong()); - Ini.saveProperties(false); - } - } - - // load Clients - do - { - int AD_Client_ID = rs.getInt(3); - String Name = rs.getString(4); - KeyNamePair p = new KeyNamePair(AD_Client_ID, Name); - list.add(p); - } - while (rs.next()); - rs.close(); - pstmt.close(); - pstmt = null; - // - retValue = new KeyNamePair[list.size()]; - list.toArray(retValue); - log.fine("Role: " + role.toStringX() + " - clients #" + retValue.length); - } - catch (SQLException ex) - { - log.log(Level.SEVERE, sql, ex); - retValue = null; - } - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - return retValue; - } // getClients - - /** - * Load Organizations. - *

- * Sets Client info in context and loads its organization, the role has access to - * @param client client information - * @return list of valid Org KeyNodePairs or null if in error - */ - public KeyNamePair[] getOrgs (KeyNamePair client) - { - if (client == null) - throw new IllegalArgumentException("Client missing"); - if (Env.getContext(m_ctx,"#AD_Role_ID").length() == 0) // could be number 0 - throw new UnsupportedOperationException("Missing Context #AD_Role_ID"); - - int AD_Role_ID = Env.getContextAsInt(m_ctx,"#AD_Role_ID"); - int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); - // s_log.fine("Client: " + client.toStringX() + ", AD_Role_ID=" + AD_Role_ID); - - // get Client details for role - ArrayList list = new ArrayList(); - KeyNamePair[] retValue = null; - // - String sql = "SELECT o.AD_Org_ID,o.Name,o.IsSummary " // 1..3 - + "FROM AD_Role r, AD_Client c" - + " INNER JOIN AD_Org o ON (c.AD_Client_ID=o.AD_Client_ID OR o.AD_Org_ID=0) " - + "WHERE r.AD_Role_ID=?" // #1 - + " AND c.AD_Client_ID=?" // #2 - + " AND o.IsActive='Y' AND o.IsSummary='N'" - + " AND (r.IsAccessAllOrgs='Y' " - + "OR (r.IsUseUserOrgAccess='N' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ra " - + "WHERE ra.AD_Role_ID=r.AD_Role_ID AND ra.IsActive='Y')) " - + "OR (r.IsUseUserOrgAccess='Y' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_User_OrgAccess ua " - + "WHERE ua.AD_User_ID=? AND ua.IsActive='Y'))" // #3 - + ") " - + "ORDER BY o.Name"; - // - PreparedStatement pstmt = null; - MRole role = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Role_ID); - pstmt.setInt(2, client.getKey()); - pstmt.setInt(3, AD_User_ID); - ResultSet rs = pstmt.executeQuery(); - // load Orgs - while (rs.next()) - { - int AD_Org_ID = rs.getInt(1); - String Name = rs.getString(2); - boolean summary = "Y".equals(rs.getString(3)); - if (summary) - { - if (role == null) - role = MRole.get(m_ctx, AD_Role_ID); - getOrgsAddSummary (list, AD_Org_ID, Name, role); - } - else - { - KeyNamePair p = new KeyNamePair(AD_Org_ID, Name); - if (!list.contains(p)) - list.add(p); - } - } - rs.close(); - pstmt.close(); - pstmt = null; - // - retValue = new KeyNamePair[list.size()]; - list.toArray(retValue); - log.fine("Client: " + client.toStringX() - + ", AD_Role_ID=" + AD_Role_ID - + ", AD_User_ID=" + AD_User_ID - + " - orgs #" + retValue.length); - } - catch (SQLException ex) - { - log.log(Level.SEVERE, sql, ex); - retValue = null; - } - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - // No Orgs - if (retValue == null || retValue.length == 0) - { - log.log(Level.WARNING, "No Org for Client: " + client.toStringX() - + ", AD_Role_ID=" + AD_Role_ID - + ", AD_User_ID=" + AD_User_ID); - return null; - } - - // Client Info - Env.setContext(m_ctx, "#AD_Client_ID", client.getKey()); - Env.setContext(m_ctx, "#AD_Client_Name", client.getName()); - Ini.setProperty(Ini.P_CLIENT, client.getName()); - return retValue; - } // getOrgs - - /** - * Get Orgs - Add Summary Org - * @param list list - * @param Summary_Org_ID summary org - * @param Summary_Name name - * @param role role - * @see org.compiere.model.MRole#loadOrgAccessAdd - */ - private void getOrgsAddSummary (ArrayList list, int Summary_Org_ID, - String Summary_Name, MRole role) - { - if (role == null) - { - log.warning("Summary Org=" + Summary_Name + "(" + Summary_Org_ID + ") - No Role"); - return; - } - // Do we look for trees? - if (role.getAD_Tree_Org_ID() == 0) - { - log.config("Summary Org=" + Summary_Name + "(" + Summary_Org_ID + ") - No Org Tree: " + role); - return; - } - // Summary Org - Get Dependents - MTree_Base tree = MTree_Base.get(m_ctx, role.getAD_Tree_Org_ID(), null); - String sql = "SELECT AD_Client_ID, AD_Org_ID, Name, IsSummary FROM AD_Org " - + "WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " - + tree.getNodeTableName() - + " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y') " - + "ORDER BY Name"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement (sql, null); - pstmt.setInt (1, tree.getAD_Tree_ID()); - pstmt.setInt (2, Summary_Org_ID); - ResultSet rs = pstmt.executeQuery (); - while (rs.next ()) - { - int AD_Client_ID = rs.getInt(1); - int AD_Org_ID = rs.getInt(2); - String Name = rs.getString(3); - boolean summary = "Y".equals(rs.getString(4)); - // - if (summary) - getOrgsAddSummary (list, AD_Org_ID, Name, role); - else - { - KeyNamePair p = new KeyNamePair(AD_Org_ID, Name); - if (!list.contains(p)) - list.add(p); - } - } - rs.close (); - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - log.log (Level.SEVERE, sql, e); - } - try - { - if (pstmt != null) - pstmt.close (); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - } // getOrgAddSummary - - - /** - * Load Warehouses - * @param org organization - * @return Array of Warehouse Info - */ - public KeyNamePair[] getWarehouses (KeyNamePair org) - { - if (org == null) - throw new IllegalArgumentException("Org missing"); - - // s_log.info("loadWarehouses - Org: " + org.toStringX()); - - ArrayList list = new ArrayList(); - KeyNamePair[] retValue = null; - String sql = "SELECT M_Warehouse_ID, Name FROM M_Warehouse " - + "WHERE AD_Org_ID=? AND IsActive='Y' " - + "ORDER BY Name"; - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, org.getKey()); - ResultSet rs = pstmt.executeQuery(); - - if (!rs.next()) - { - rs.close(); - pstmt.close(); - log.info("No Warehouses for Org: " + org.toStringX()); - return null; - } - - // load Warehousess - do - { - int AD_Warehouse_ID = rs.getInt(1); - String Name = rs.getString(2); - KeyNamePair p = new KeyNamePair(AD_Warehouse_ID, Name); - list.add(p); - } - while (rs.next()); - - rs.close(); - pstmt.close(); - pstmt = null; - // - retValue = new KeyNamePair[list.size()]; - list.toArray(retValue); - log.fine("Org: " + org.toStringX() - + " - warehouses #" + retValue.length); - } - catch (SQLException ex) - { - log.log(Level.SEVERE, "getWarehouses", ex); - retValue = null; - } - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - return retValue; - } // getWarehouses - - /** - * Validate Login - * @param org log-in org - * @return error message - */ - public String validateLogin (KeyNamePair org) - { - int AD_Client_ID = Env.getAD_Client_ID(m_ctx); - int AD_Org_ID = org.getKey(); - int AD_Role_ID = Env.getAD_Role_ID(m_ctx); - int AD_User_ID = Env.getAD_User_ID(m_ctx); - String error = ModelValidationEngine.get().loginComplete(AD_Client_ID, AD_Org_ID, AD_Role_ID, AD_User_ID); - if (error != null && error.length() > 0) - { - log.severe("Refused: " + error); - return error; - } - return null; - } // validateLogin - - /** - * Load Preferences into Context for selected client. - *

- * Sets Org info in context and loads relevant field from - * - AD_Client/Info, - * - C_AcctSchema, - * - C_AcctSchema_Elements - * - AD_Preference - *

- * Assumes that the context is set for #AD_Client_ID, #AD_User_ID, #AD_Role_ID - * - * @param org org information - * @param warehouse optional warehouse information - * @param timestamp optional date - * @param printerName optional printer info - * @return AD_Message of error (NoValidAcctInfo) or "" - */ - public String loadPreferences (KeyNamePair org, - KeyNamePair warehouse, java.sql.Timestamp timestamp, String printerName) - { - log.info("Org: " + org.toStringX()); - - if (m_ctx == null || org == null) - throw new IllegalArgumentException("Required parameter missing"); - if (Env.getContext(m_ctx,"#AD_Client_ID").length() == 0) - throw new UnsupportedOperationException("Missing Context #AD_Client_ID"); - if (Env.getContext(m_ctx,"#AD_User_ID").length() == 0) - throw new UnsupportedOperationException("Missing Context #AD_User_ID"); - if (Env.getContext(m_ctx,"#AD_Role_ID").length() == 0) - throw new UnsupportedOperationException("Missing Context #AD_Role_ID"); - - // Org Info - assumes that it is valid - Env.setContext(m_ctx, "#AD_Org_ID", org.getKey()); - Env.setContext(m_ctx, "#AD_Org_Name", org.getName()); - Ini.setProperty(Ini.P_ORG, org.getName()); - - // Warehouse Info - if (warehouse != null) - { - Env.setContext(m_ctx, "#M_Warehouse_ID", warehouse.getKey()); - Ini.setProperty(Ini.P_WAREHOUSE, warehouse.getName()); - } - - // Date (default today) - long today = System.currentTimeMillis(); - if (timestamp != null) - today = timestamp.getTime(); - Env.setContext(m_ctx, "#Date", new java.sql.Timestamp(today)); - - // Optional Printer - if (printerName == null) - printerName = ""; - Env.setContext(m_ctx, "#Printer", printerName); - Ini.setProperty(Ini.P_PRINTER, printerName); - - // Load Role Info - MRole.getDefault(m_ctx, true); - - // Other - Env.setAutoCommit(m_ctx, Ini.isPropertyBool(Ini.P_A_COMMIT)); - Env.setAutoNew(m_ctx, Ini.isPropertyBool(Ini.P_A_NEW)); - if (MRole.getDefault(m_ctx, false).isShowAcct()) - Env.setContext(m_ctx, "#ShowAcct", Ini.getProperty(Ini.P_SHOW_ACCT)); - else - Env.setContext(m_ctx, "#ShowAcct", "N"); - Env.setContext(m_ctx, "#ShowTrl", Ini.getProperty(Ini.P_SHOW_TRL)); - Env.setContext(m_ctx, "#ShowAdvanced", Ini.getProperty(Ini.P_SHOW_ADVANCED)); - - String retValue = ""; - int AD_Client_ID = Env.getContextAsInt(m_ctx, "#AD_Client_ID"); - int AD_Org_ID = org.getKey(); - int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); - int AD_Role_ID = Env.getContextAsInt(m_ctx, "#AD_Role_ID"); - - // Other Settings - Env.setContext(m_ctx, "#YYYY", "Y"); - Env.setContext(m_ctx, "#StdPrecision", 2); - - // AccountSchema Info (first) - String sql = "SELECT * " - + "FROM C_AcctSchema a, AD_ClientInfo c " - + "WHERE a.C_AcctSchema_ID=c.C_AcctSchema1_ID " - + "AND c.AD_Client_ID=?"; - PreparedStatement pstmt = null; - try - { - int C_AcctSchema_ID = 0; - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Client_ID); - ResultSet rs = pstmt.executeQuery(); - - if (!rs.next()) - { - // No Warning for System - if (AD_Role_ID != 0) - retValue = "NoValidAcctInfo"; - } - else - { - // Accounting Info - C_AcctSchema_ID = rs.getInt("C_AcctSchema_ID"); - Env.setContext(m_ctx, "$C_AcctSchema_ID", C_AcctSchema_ID); - Env.setContext(m_ctx, "$C_Currency_ID", rs.getInt("C_Currency_ID")); - Env.setContext(m_ctx, "$HasAlias", rs.getString("HasAlias")); - } - rs.close(); - pstmt.close(); - - // Accounting Elements - sql = "SELECT ElementType " - + "FROM C_AcctSchema_Element " - + "WHERE C_AcctSchema_ID=?" - + " AND IsActive='Y'"; - pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, C_AcctSchema_ID); - rs = pstmt.executeQuery(); - while (rs.next()) - Env.setContext(m_ctx, "$Element_" + rs.getString("ElementType"), "Y"); - rs.close(); - pstmt.close(); - - // This reads all relevant window neutral defaults - // overwriting superseeded ones. Window specific is read in Mainain - sql = "SELECT Attribute, Value, AD_Window_ID " - + "FROM AD_Preference " - + "WHERE AD_Client_ID IN (0, @#AD_Client_ID@)" - + " AND AD_Org_ID IN (0, @#AD_Org_ID@)" - + " AND (AD_User_ID IS NULL OR AD_User_ID=0 OR AD_User_ID=@#AD_User_ID@)" - + " AND IsActive='Y' " - + "ORDER BY Attribute, AD_Client_ID, AD_User_ID DESC, AD_Org_ID"; - // the last one overwrites - System - Client - User - Org - Window - sql = Env.parseContext(m_ctx, 0, sql, false); - if (sql.length() == 0) - log.log(Level.SEVERE, "loadPreferences - Missing Environment"); - else - { - pstmt = DB.prepareStatement(sql, null); - rs = pstmt.executeQuery(); - while (rs.next()) - { - int AD_Window_ID = rs.getInt(3); - String at = ""; - if (rs.wasNull()) - at = "P|" + rs.getString(1); - else - at = "P" + AD_Window_ID + "|" + rs.getString(1); - String va = rs.getString(2); - Env.setContext(m_ctx, at, va); - } - rs.close(); - pstmt.close(); - } - - // Default Values - log.info("Default Values ..."); - sql = "SELECT t.TableName, c.ColumnName " - + "FROM AD_Column c " - + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID) " - + "WHERE c.IsKey='Y' AND t.IsActive='Y'" - + " AND EXISTS (SELECT * FROM AD_Column cc " - + " WHERE ColumnName = 'IsDefault' AND t.AD_Table_ID=cc.AD_Table_ID AND cc.IsActive='Y')"; - pstmt = DB.prepareStatement(sql, null); - rs = pstmt.executeQuery(); - while (rs.next()) - loadDefault (rs.getString(1), rs.getString(2)); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (SQLException e) - { - log.log(Level.SEVERE, "loadPreferences", e); - } - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - // - Ini.saveProperties(Ini.isClient()); - // Country - Env.setContext(m_ctx, "#C_Country_ID", MCountry.getDefault(m_ctx).getC_Country_ID()); - return retValue; - } // loadPreferences - - /** - * Load Default Value for Table into Context. - * @param TableName table name - * @param ColumnName column name - */ - private void loadDefault (String TableName, String ColumnName) - { - if (TableName.startsWith("AD_Window") - || TableName.startsWith("AD_PrintFormat") - || TableName.startsWith("AD_Workflow") ) - return; - String value = null; - // - String sql = "SELECT " + ColumnName + " FROM " + TableName // most specific first - + " WHERE IsDefault='Y' AND IsActive='Y' ORDER BY AD_Client_ID DESC, AD_Org_ID DESC"; - sql = MRole.getDefault(m_ctx, false).addAccessSQL(sql, - TableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - PreparedStatement pstmt = null; - try - { - pstmt = DB.prepareStatement(sql, null); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - value = rs.getString(1); - rs.close(); - pstmt.close(); - pstmt = null; - } - catch (SQLException e) - { - log.log(Level.SEVERE, TableName + " (" + sql + ")", e); - return; - } - try - { - if (pstmt != null) - pstmt.close(); - pstmt = null; - } - catch (Exception e) - { - pstmt = null; - } - // Set Context Value - if (value != null && value.length() != 0) - { - if (TableName.equals("C_DocType")) - Env.setContext(m_ctx, "#C_DocTypeTarget_ID", value); - else - Env.setContext(m_ctx, "#" + ColumnName, value); - } - } // loadDefault - + + /************************************************************************** + * Load Clients. + *

+ * Sets Role info in context and loads its clients + * @param role role information + * @return list of valid client KeyNodePairs or null if in error + */ + public KeyNamePair[] getClients (KeyNamePair role) + { + if (role == null) + throw new IllegalArgumentException("Role missing"); + + // s_log.fine("loadClients - Role: " + role.toStringX()); + + ArrayList list = new ArrayList(); + KeyNamePair[] retValue = null; + String sql = "SELECT DISTINCT r.UserLevel, r.ConnectionProfile, " // 1/2 + + " c.AD_Client_ID,c.Name " // 3/4 + + "FROM AD_Role r" + + " INNER JOIN AD_Client c ON (r.AD_Client_ID=c.AD_Client_ID) " + + "WHERE r.AD_Role_ID=?" // #1 + + " AND r.IsActive='Y' AND c.IsActive='Y'"; + + PreparedStatement pstmt = null; + // get Role details + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, role.getKey()); + ResultSet rs = pstmt.executeQuery(); + + if (!rs.next()) + { + rs.close(); + pstmt.close(); + log.log(Level.SEVERE, "No Clients for Role: " + role.toStringX()); + return null; + } + + // Role Info + Env.setContext(m_ctx, "#AD_Role_ID", role.getKey()); + Env.setContext(m_ctx, "#AD_Role_Name", role.getName()); + Ini.setProperty(Ini.P_ROLE, role.getName()); + // User Level + Env.setContext(m_ctx, "#User_Level", rs.getString(1)); // Format 'SCO' + + // ConnectionProfile + CConnection cc = CConnection.get(); + if (m_connectionProfile == null) // No User Based + { + m_connectionProfile = rs.getString(2); // Role Based + if (m_connectionProfile != null + && !cc.getConnectionProfile().equals(m_connectionProfile)) + { + cc.setConnectionProfile(m_connectionProfile); + Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong()); + Ini.saveProperties(false); + } + } + + // load Clients + do + { + int AD_Client_ID = rs.getInt(3); + String Name = rs.getString(4); + KeyNamePair p = new KeyNamePair(AD_Client_ID, Name); + list.add(p); + } + while (rs.next()); + rs.close(); + pstmt.close(); + pstmt = null; + // + retValue = new KeyNamePair[list.size()]; + list.toArray(retValue); + log.fine("Role: " + role.toStringX() + " - clients #" + retValue.length); + } + catch (SQLException ex) + { + log.log(Level.SEVERE, sql, ex); + retValue = null; + } + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + return retValue; + } // getClients + + /** + * Load Organizations. + *

+ * Sets Client info in context and loads its organization, the role has access to + * @param client client information + * @return list of valid Org KeyNodePairs or null if in error + */ + public KeyNamePair[] getOrgs (KeyNamePair client) + { + if (client == null) + throw new IllegalArgumentException("Client missing"); + if (Env.getContext(m_ctx,"#AD_Role_ID").length() == 0) // could be number 0 + throw new UnsupportedOperationException("Missing Context #AD_Role_ID"); + + int AD_Role_ID = Env.getContextAsInt(m_ctx,"#AD_Role_ID"); + int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); + // s_log.fine("Client: " + client.toStringX() + ", AD_Role_ID=" + AD_Role_ID); + + // get Client details for role + ArrayList list = new ArrayList(); + KeyNamePair[] retValue = null; + // + String sql = "SELECT o.AD_Org_ID,o.Name,o.IsSummary " // 1..3 + + "FROM AD_Role r, AD_Client c" + + " INNER JOIN AD_Org o ON (c.AD_Client_ID=o.AD_Client_ID OR o.AD_Org_ID=0) " + + "WHERE r.AD_Role_ID=?" // #1 + + " AND c.AD_Client_ID=?" // #2 + + " AND o.IsActive='Y' AND o.IsSummary='N'" + + " AND (r.IsAccessAllOrgs='Y' " + + "OR (r.IsUseUserOrgAccess='N' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ra " + + "WHERE ra.AD_Role_ID=r.AD_Role_ID AND ra.IsActive='Y')) " + + "OR (r.IsUseUserOrgAccess='Y' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_User_OrgAccess ua " + + "WHERE ua.AD_User_ID=? AND ua.IsActive='Y'))" // #3 + + ") " + + "ORDER BY o.Name"; + // + PreparedStatement pstmt = null; + MRole role = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Role_ID); + pstmt.setInt(2, client.getKey()); + pstmt.setInt(3, AD_User_ID); + ResultSet rs = pstmt.executeQuery(); + // load Orgs + while (rs.next()) + { + int AD_Org_ID = rs.getInt(1); + String Name = rs.getString(2); + boolean summary = "Y".equals(rs.getString(3)); + if (summary) + { + if (role == null) + role = MRole.get(m_ctx, AD_Role_ID); + getOrgsAddSummary (list, AD_Org_ID, Name, role); + } + else + { + KeyNamePair p = new KeyNamePair(AD_Org_ID, Name); + if (!list.contains(p)) + list.add(p); + } + } + rs.close(); + pstmt.close(); + pstmt = null; + // + retValue = new KeyNamePair[list.size()]; + list.toArray(retValue); + log.fine("Client: " + client.toStringX() + + ", AD_Role_ID=" + AD_Role_ID + + ", AD_User_ID=" + AD_User_ID + + " - orgs #" + retValue.length); + } + catch (SQLException ex) + { + log.log(Level.SEVERE, sql, ex); + retValue = null; + } + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + // No Orgs + if (retValue == null || retValue.length == 0) + { + log.log(Level.WARNING, "No Org for Client: " + client.toStringX() + + ", AD_Role_ID=" + AD_Role_ID + + ", AD_User_ID=" + AD_User_ID); + return null; + } + + // Client Info + Env.setContext(m_ctx, "#AD_Client_ID", client.getKey()); + Env.setContext(m_ctx, "#AD_Client_Name", client.getName()); + Ini.setProperty(Ini.P_CLIENT, client.getName()); + return retValue; + } // getOrgs + + /** + * Get Orgs - Add Summary Org + * @param list list + * @param Summary_Org_ID summary org + * @param Summary_Name name + * @param role role + * @see org.compiere.model.MRole#loadOrgAccessAdd + */ + private void getOrgsAddSummary (ArrayList list, int Summary_Org_ID, + String Summary_Name, MRole role) + { + if (role == null) + { + log.warning("Summary Org=" + Summary_Name + "(" + Summary_Org_ID + ") - No Role"); + return; + } + // Do we look for trees? + if (role.getAD_Tree_Org_ID() == 0) + { + log.config("Summary Org=" + Summary_Name + "(" + Summary_Org_ID + ") - No Org Tree: " + role); + return; + } + // Summary Org - Get Dependents + MTree_Base tree = MTree_Base.get(m_ctx, role.getAD_Tree_Org_ID(), null); + String sql = "SELECT AD_Client_ID, AD_Org_ID, Name, IsSummary FROM AD_Org " + + "WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + + tree.getNodeTableName() + + " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y') " + + "ORDER BY Name"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement (sql, null); + pstmt.setInt (1, tree.getAD_Tree_ID()); + pstmt.setInt (2, Summary_Org_ID); + ResultSet rs = pstmt.executeQuery (); + while (rs.next ()) + { + int AD_Client_ID = rs.getInt(1); + int AD_Org_ID = rs.getInt(2); + String Name = rs.getString(3); + boolean summary = "Y".equals(rs.getString(4)); + // + if (summary) + getOrgsAddSummary (list, AD_Org_ID, Name, role); + else + { + KeyNamePair p = new KeyNamePair(AD_Org_ID, Name); + if (!list.contains(p)) + list.add(p); + } + } + rs.close (); + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + log.log (Level.SEVERE, sql, e); + } + try + { + if (pstmt != null) + pstmt.close (); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + } // getOrgAddSummary + + + /** + * Load Warehouses + * @param org organization + * @return Array of Warehouse Info + */ + public KeyNamePair[] getWarehouses (KeyNamePair org) + { + if (org == null) + throw new IllegalArgumentException("Org missing"); + + // s_log.info("loadWarehouses - Org: " + org.toStringX()); + + ArrayList list = new ArrayList(); + KeyNamePair[] retValue = null; + String sql = "SELECT M_Warehouse_ID, Name FROM M_Warehouse " + + "WHERE AD_Org_ID=? AND IsActive='Y' " + + "ORDER BY Name"; + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, org.getKey()); + ResultSet rs = pstmt.executeQuery(); + + if (!rs.next()) + { + rs.close(); + pstmt.close(); + log.info("No Warehouses for Org: " + org.toStringX()); + return null; + } + + // load Warehousess + do + { + int AD_Warehouse_ID = rs.getInt(1); + String Name = rs.getString(2); + KeyNamePair p = new KeyNamePair(AD_Warehouse_ID, Name); + list.add(p); + } + while (rs.next()); + + rs.close(); + pstmt.close(); + pstmt = null; + // + retValue = new KeyNamePair[list.size()]; + list.toArray(retValue); + log.fine("Org: " + org.toStringX() + + " - warehouses #" + retValue.length); + } + catch (SQLException ex) + { + log.log(Level.SEVERE, "getWarehouses", ex); + retValue = null; + } + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + return retValue; + } // getWarehouses + + /** + * Validate Login + * @param org log-in org + * @return error message + */ + public String validateLogin (KeyNamePair org) + { + int AD_Client_ID = Env.getAD_Client_ID(m_ctx); + int AD_Org_ID = org.getKey(); + int AD_Role_ID = Env.getAD_Role_ID(m_ctx); + int AD_User_ID = Env.getAD_User_ID(m_ctx); + String error = ModelValidationEngine.get().loginComplete(AD_Client_ID, AD_Org_ID, AD_Role_ID, AD_User_ID); + if (error != null && error.length() > 0) + { + log.severe("Refused: " + error); + return error; + } + return null; + } // validateLogin + + /** + * Load Preferences into Context for selected client. + *

+ * Sets Org info in context and loads relevant field from + * - AD_Client/Info, + * - C_AcctSchema, + * - C_AcctSchema_Elements + * - AD_Preference + *

+ * Assumes that the context is set for #AD_Client_ID, #AD_User_ID, #AD_Role_ID + * + * @param org org information + * @param warehouse optional warehouse information + * @param timestamp optional date + * @param printerName optional printer info + * @return AD_Message of error (NoValidAcctInfo) or "" + */ + public String loadPreferences (KeyNamePair org, + KeyNamePair warehouse, java.sql.Timestamp timestamp, String printerName) + { + log.info("Org: " + org.toStringX()); + + if (m_ctx == null || org == null) + throw new IllegalArgumentException("Required parameter missing"); + if (Env.getContext(m_ctx,"#AD_Client_ID").length() == 0) + throw new UnsupportedOperationException("Missing Context #AD_Client_ID"); + if (Env.getContext(m_ctx,"#AD_User_ID").length() == 0) + throw new UnsupportedOperationException("Missing Context #AD_User_ID"); + if (Env.getContext(m_ctx,"#AD_Role_ID").length() == 0) + throw new UnsupportedOperationException("Missing Context #AD_Role_ID"); + + // Org Info - assumes that it is valid + Env.setContext(m_ctx, "#AD_Org_ID", org.getKey()); + Env.setContext(m_ctx, "#AD_Org_Name", org.getName()); + Ini.setProperty(Ini.P_ORG, org.getName()); + + // Warehouse Info + if (warehouse != null) + { + Env.setContext(m_ctx, "#M_Warehouse_ID", warehouse.getKey()); + Ini.setProperty(Ini.P_WAREHOUSE, warehouse.getName()); + } + + // Date (default today) + long today = System.currentTimeMillis(); + if (timestamp != null) + today = timestamp.getTime(); + Env.setContext(m_ctx, "#Date", new java.sql.Timestamp(today)); + + // Optional Printer + if (printerName == null) + printerName = ""; + Env.setContext(m_ctx, "#Printer", printerName); + Ini.setProperty(Ini.P_PRINTER, printerName); + + // Load Role Info + MRole.getDefault(m_ctx, true); + + // Other + Env.setAutoCommit(m_ctx, Ini.isPropertyBool(Ini.P_A_COMMIT)); + Env.setAutoNew(m_ctx, Ini.isPropertyBool(Ini.P_A_NEW)); + if (MRole.getDefault(m_ctx, false).isShowAcct()) + Env.setContext(m_ctx, "#ShowAcct", Ini.getProperty(Ini.P_SHOW_ACCT)); + else + Env.setContext(m_ctx, "#ShowAcct", "N"); + Env.setContext(m_ctx, "#ShowTrl", Ini.getProperty(Ini.P_SHOW_TRL)); + Env.setContext(m_ctx, "#ShowAdvanced", Ini.getProperty(Ini.P_SHOW_ADVANCED)); + + String retValue = ""; + int AD_Client_ID = Env.getContextAsInt(m_ctx, "#AD_Client_ID"); + int AD_Org_ID = org.getKey(); + int AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); + int AD_Role_ID = Env.getContextAsInt(m_ctx, "#AD_Role_ID"); + + // Other Settings + Env.setContext(m_ctx, "#YYYY", "Y"); + Env.setContext(m_ctx, "#StdPrecision", 2); + + // AccountSchema Info (first) + String sql = "SELECT * " + + "FROM C_AcctSchema a, AD_ClientInfo c " + + "WHERE a.C_AcctSchema_ID=c.C_AcctSchema1_ID " + + "AND c.AD_Client_ID=?"; + PreparedStatement pstmt = null; + try + { + int C_AcctSchema_ID = 0; + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Client_ID); + ResultSet rs = pstmt.executeQuery(); + + if (!rs.next()) + { + // No Warning for System + if (AD_Role_ID != 0) + retValue = "NoValidAcctInfo"; + } + else + { + // Accounting Info + C_AcctSchema_ID = rs.getInt("C_AcctSchema_ID"); + Env.setContext(m_ctx, "$C_AcctSchema_ID", C_AcctSchema_ID); + Env.setContext(m_ctx, "$C_Currency_ID", rs.getInt("C_Currency_ID")); + Env.setContext(m_ctx, "$HasAlias", rs.getString("HasAlias")); + } + rs.close(); + pstmt.close(); + + // Accounting Elements + sql = "SELECT ElementType " + + "FROM C_AcctSchema_Element " + + "WHERE C_AcctSchema_ID=?" + + " AND IsActive='Y'"; + pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, C_AcctSchema_ID); + rs = pstmt.executeQuery(); + while (rs.next()) + Env.setContext(m_ctx, "$Element_" + rs.getString("ElementType"), "Y"); + rs.close(); + pstmt.close(); + + // This reads all relevant window neutral defaults + // overwriting superseeded ones. Window specific is read in Mainain + sql = "SELECT Attribute, Value, AD_Window_ID " + + "FROM AD_Preference " + + "WHERE AD_Client_ID IN (0, @#AD_Client_ID@)" + + " AND AD_Org_ID IN (0, @#AD_Org_ID@)" + + " AND (AD_User_ID IS NULL OR AD_User_ID=0 OR AD_User_ID=@#AD_User_ID@)" + + " AND IsActive='Y' " + + "ORDER BY Attribute, AD_Client_ID, AD_User_ID DESC, AD_Org_ID"; + // the last one overwrites - System - Client - User - Org - Window + sql = Env.parseContext(m_ctx, 0, sql, false); + if (sql.length() == 0) + log.log(Level.SEVERE, "loadPreferences - Missing Environment"); + else + { + pstmt = DB.prepareStatement(sql, null); + rs = pstmt.executeQuery(); + while (rs.next()) + { + int AD_Window_ID = rs.getInt(3); + String at = ""; + if (rs.wasNull()) + at = "P|" + rs.getString(1); + else + at = "P" + AD_Window_ID + "|" + rs.getString(1); + String va = rs.getString(2); + Env.setContext(m_ctx, at, va); + } + rs.close(); + pstmt.close(); + } + + // Default Values + log.info("Default Values ..."); + sql = "SELECT t.TableName, c.ColumnName " + + "FROM AD_Column c " + + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID) " + + "WHERE c.IsKey='Y' AND t.IsActive='Y'" + + " AND EXISTS (SELECT * FROM AD_Column cc " + + " WHERE ColumnName = 'IsDefault' AND t.AD_Table_ID=cc.AD_Table_ID AND cc.IsActive='Y')"; + pstmt = DB.prepareStatement(sql, null); + rs = pstmt.executeQuery(); + while (rs.next()) + loadDefault (rs.getString(1), rs.getString(2)); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (SQLException e) + { + log.log(Level.SEVERE, "loadPreferences", e); + } + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + // + Ini.saveProperties(Ini.isClient()); + // Country + Env.setContext(m_ctx, "#C_Country_ID", MCountry.getDefault(m_ctx).getC_Country_ID()); + return retValue; + } // loadPreferences + + /** + * Load Default Value for Table into Context. + * @param TableName table name + * @param ColumnName column name + */ + private void loadDefault (String TableName, String ColumnName) + { + if (TableName.startsWith("AD_Window") + || TableName.startsWith("AD_PrintFormat") + || TableName.startsWith("AD_Workflow") ) + return; + String value = null; + // + String sql = "SELECT " + ColumnName + " FROM " + TableName // most specific first + + " WHERE IsDefault='Y' AND IsActive='Y' ORDER BY AD_Client_ID DESC, AD_Org_ID DESC"; + sql = MRole.getDefault(m_ctx, false).addAccessSQL(sql, + TableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); + PreparedStatement pstmt = null; + try + { + pstmt = DB.prepareStatement(sql, null); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + value = rs.getString(1); + rs.close(); + pstmt.close(); + pstmt = null; + } + catch (SQLException e) + { + log.log(Level.SEVERE, TableName + " (" + sql + ")", e); + return; + } + try + { + if (pstmt != null) + pstmt.close(); + pstmt = null; + } + catch (Exception e) + { + pstmt = null; + } + // Set Context Value + if (value != null && value.length() != 0) + { + if (TableName.equals("C_DocType")) + Env.setContext(m_ctx, "#C_DocTypeTarget_ID", value); + else + Env.setContext(m_ctx, "#" + ColumnName, value); + } + } // loadDefault + /** * Batch Login using Ini values * @@ -952,168 +953,168 @@ public class Login Ini.setProperty(Ini.P_UID,"SuperUser"); Ini.setProperty(Ini.P_PWD,"System"); Ini.setProperty(Ini.P_ROLE,"GardenAdmin"); - Ini.setProperty(Ini.P_CLIENT, "Garden World"); - Ini.setProperty(Ini.P_ORG,"HQ"); - Ini.setProperty(Ini.P_WAREHOUSE,"HQ"); - Ini.setProperty(Ini.P_LANGUAGE,"English"); - Ini.setProperty(Ini.P_PRINTER,"MyPrinter"); - Login login = new Login(Env.getCtx()); - login.batchLogin(); - * - * @param loginDate optional login date - * @return true if logged in using Ini values - */ - public boolean batchLogin(java.sql.Timestamp loginDate) - { - // User Login - String uid = Ini.getProperty(Ini.P_UID); - String pwd = Ini.getProperty(Ini.P_PWD); - KeyNamePair[] roles = getRoles (uid, pwd); - if (roles == null || roles.length == 0) - { - log.severe("User/Password invalid: " + uid); - return false; - } - log.info("User: " + uid); - - // Role - String role = Ini.getProperty(Ini.P_ROLE); - KeyNamePair rolePP = null; - for (int i = 0; i < roles.length; i++) - { - KeyNamePair pair = roles[i]; - if (pair.getName().equalsIgnoreCase(role)) - { - rolePP = pair; - break; - } - } - if (rolePP == null) - { - log.severe("Role invalid: " + role); - for (int i = 0; i < roles.length; i++) - log.info("Option: " + roles[i]); - return false; - } - log.info("Role: " + role); - - // Clients - String client = Ini.getProperty(Ini.P_CLIENT); - KeyNamePair[] clients = getClients(rolePP); - if (clients == null || clients.length == 0) - { - log.severe("No Clients for Role: " + role); - return false; - } - KeyNamePair clientPP = null; - for (int i = 0; i < clients.length; i++) - { - KeyNamePair pair = clients[i]; - if (pair.getName().equalsIgnoreCase(client)) - { - clientPP = pair; - break; - } - } - if (clientPP == null) - { - log.severe("Client invalid: " + client); - for (int i = 0; i < clients.length; i++) - log.info("Option: " + clients[i]); - return false; - } - - // Organization - String org = Ini.getProperty(Ini.P_ORG); - KeyNamePair[] orgs = getOrgs(clientPP); - if (orgs == null || orgs.length == 0) - { - log.severe("No Orgs for Client: " + client); - return false; - } - KeyNamePair orgPP = null; - for (int i = 0; i < orgs.length; i++) - { - KeyNamePair pair = orgs[i]; - if (pair.getName().equalsIgnoreCase(org)) - { - orgPP = pair; - break; - } - } - if (orgPP == null) - { - log.severe("Org invalid: " + org); - for (int i = 0; i < orgs.length; i++) - log.info("Option: " + orgs[i]); - return false; - } - String error = validateLogin(orgPP); - if (error != null && error.length() > 0) - return false; - - // Warehouse - String wh = Ini.getProperty(Ini.P_WAREHOUSE); - KeyNamePair[] whs = getWarehouses(orgPP); - if (whs == null || whs.length == 0) - { - log.severe("No Warehouses for Org: " + org); - return false; - } - KeyNamePair whPP = null; - for (int i = 0; i < whs.length; i++) - { - KeyNamePair pair = whs[i]; - if (pair.getName().equalsIgnoreCase(wh)) - { - whPP = pair; - break; - } - } - if (whPP == null) - { - log.severe("Warehouse invalid: " + wh); - for (int i = 0; i < whs.length; i++) - log.info("Option: " + whs[i]); - return false; - } - - // Language - String langName = Ini.getProperty(Ini.P_LANGUAGE); - Language language = Language.getLanguage(langName); - Language.setLoginLanguage(language); - Env.verifyLanguage (m_ctx, language); - Env.setContext(m_ctx, Env.LANGUAGE, language.getAD_Language()); - Locale loc = language.getLocale(); - Locale.setDefault(loc); - Msg.getMsg(m_ctx, "0"); - - // Preferences - String printerName = Ini.getProperty(Ini.P_PRINTER); - if (loginDate == null) - loginDate = new java.sql.Timestamp(System.currentTimeMillis()); - loadPreferences(orgPP, whPP, loginDate, printerName); - // - log.info("complete"); - return true; - } // batchLogin - - /** - * Batch Login with system date - * @return true if logged in - */ - public boolean batchLogin() - { - return batchLogin(new java.sql.Timestamp (System.currentTimeMillis())); - } // batchLogin - - /** - * Get SSO Principal - * @return principal - */ - public Principal getPrincipal() - { - return null; - } // getPrincipal - -} // Login + Ini.setProperty(Ini.P_CLIENT, "Garden World"); + Ini.setProperty(Ini.P_ORG,"HQ"); + Ini.setProperty(Ini.P_WAREHOUSE,"HQ"); + Ini.setProperty(Ini.P_LANGUAGE,"English"); + Ini.setProperty(Ini.P_PRINTER,"MyPrinter"); + Login login = new Login(Env.getCtx()); + login.batchLogin(); + * + * @param loginDate optional login date + * @return true if logged in using Ini values + */ + public boolean batchLogin(java.sql.Timestamp loginDate) + { + // User Login + String uid = Ini.getProperty(Ini.P_UID); + String pwd = Ini.getProperty(Ini.P_PWD); + KeyNamePair[] roles = getRoles (uid, pwd); + if (roles == null || roles.length == 0) + { + log.severe("User/Password invalid: " + uid); + return false; + } + log.info("User: " + uid); + + // Role + String role = Ini.getProperty(Ini.P_ROLE); + KeyNamePair rolePP = null; + for (int i = 0; i < roles.length; i++) + { + KeyNamePair pair = roles[i]; + if (pair.getName().equalsIgnoreCase(role)) + { + rolePP = pair; + break; + } + } + if (rolePP == null) + { + log.severe("Role invalid: " + role); + for (int i = 0; i < roles.length; i++) + log.info("Option: " + roles[i]); + return false; + } + log.info("Role: " + role); + + // Clients + String client = Ini.getProperty(Ini.P_CLIENT); + KeyNamePair[] clients = getClients(rolePP); + if (clients == null || clients.length == 0) + { + log.severe("No Clients for Role: " + role); + return false; + } + KeyNamePair clientPP = null; + for (int i = 0; i < clients.length; i++) + { + KeyNamePair pair = clients[i]; + if (pair.getName().equalsIgnoreCase(client)) + { + clientPP = pair; + break; + } + } + if (clientPP == null) + { + log.severe("Client invalid: " + client); + for (int i = 0; i < clients.length; i++) + log.info("Option: " + clients[i]); + return false; + } + + // Organization + String org = Ini.getProperty(Ini.P_ORG); + KeyNamePair[] orgs = getOrgs(clientPP); + if (orgs == null || orgs.length == 0) + { + log.severe("No Orgs for Client: " + client); + return false; + } + KeyNamePair orgPP = null; + for (int i = 0; i < orgs.length; i++) + { + KeyNamePair pair = orgs[i]; + if (pair.getName().equalsIgnoreCase(org)) + { + orgPP = pair; + break; + } + } + if (orgPP == null) + { + log.severe("Org invalid: " + org); + for (int i = 0; i < orgs.length; i++) + log.info("Option: " + orgs[i]); + return false; + } + String error = validateLogin(orgPP); + if (error != null && error.length() > 0) + return false; + + // Warehouse + String wh = Ini.getProperty(Ini.P_WAREHOUSE); + KeyNamePair[] whs = getWarehouses(orgPP); + if (whs == null || whs.length == 0) + { + log.severe("No Warehouses for Org: " + org); + return false; + } + KeyNamePair whPP = null; + for (int i = 0; i < whs.length; i++) + { + KeyNamePair pair = whs[i]; + if (pair.getName().equalsIgnoreCase(wh)) + { + whPP = pair; + break; + } + } + if (whPP == null) + { + log.severe("Warehouse invalid: " + wh); + for (int i = 0; i < whs.length; i++) + log.info("Option: " + whs[i]); + return false; + } + + // Language + String langName = Ini.getProperty(Ini.P_LANGUAGE); + Language language = Language.getLanguage(langName); + Language.setLoginLanguage(language); + Env.verifyLanguage (m_ctx, language); + Env.setContext(m_ctx, Env.LANGUAGE, language.getAD_Language()); + Locale loc = language.getLocale(); + Locale.setDefault(loc); + Msg.getMsg(m_ctx, "0"); + + // Preferences + String printerName = Ini.getProperty(Ini.P_PRINTER); + if (loginDate == null) + loginDate = new java.sql.Timestamp(System.currentTimeMillis()); + loadPreferences(orgPP, whPP, loginDate, printerName); + // + log.info("complete"); + return true; + } // batchLogin + + /** + * Batch Login with system date + * @return true if logged in + */ + public boolean batchLogin() + { + return batchLogin(new java.sql.Timestamp (System.currentTimeMillis())); + } // batchLogin + + /** + * Get SSO Principal + * @return principal + */ + public Principal getPrincipal() + { + return null; + } // getPrincipal + +} // Login diff --git a/dbPort/src/org/compiere/util/Msg.java b/dbPort/src/org/compiere/util/Msg.java index 4a9c5f4400..3738cfbd21 100644 --- a/dbPort/src/org/compiere/util/Msg.java +++ b/dbPort/src/org/compiere/util/Msg.java @@ -3,214 +3,214 @@ * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * - * by the Free Software Foundation. This program is distributed in the hope * - * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * - * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along * - * with this program; if not, write to the Free Software Foundation, Inc., * - * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * - * For the text or an alternative of this public license, you may reach us * - * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * - * or via info@compiere.org or http://www.compiere.org/license.html * - *****************************************************************************/ -package org.compiere.util; - -import java.io.*; -import java.sql.*; -import java.text.*; -import java.util.*; -import java.util.logging.*; -import org.compiere.*; - -/** - * Reads all Messages and stores them in a HashMap - * - * @author Jorg Janke - * @version $Id: Msg.java,v 1.2 2006/07/30 00:54:36 jjanke Exp $ - */ -public final class Msg -{ - /** Initial size of HashMap */ - private static final int MAP_SIZE = 750; - /** Separator between Msg and optional Tip */ - private static final String SEPARATOR = Env.NL + Env.NL; - - /** Singleton */ - private static Msg s_msg = null; - - /** Logger */ - private static CLogger s_log = CLogger.getCLogger (Msg.class); - - /** - * Get Message Object - * @return Mag - */ - private static Msg get() - { - if (s_msg == null) - s_msg = new Msg(); - return s_msg; - } // get - - - /************************************************************************** - * Constructor - */ - private Msg() - { - } // Mag - - /** The Map */ - private CCache> m_languages - = new CCache>("msg_lang", 2, 0); - - /** - * Get Language specific Message Map - * @param ad_language Language Key - * @return HashMap of Language - */ - private CCache getMsgMap (String ad_language) - { - String AD_Language = ad_language; - if (AD_Language == null || AD_Language.length() == 0) - AD_Language = Language.getBaseAD_Language(); - // Do we have the language ? - CCache retValue = (CCache)m_languages.get(AD_Language); - if (retValue != null && retValue.size() > 0) - return retValue; - - // Load Language - retValue = initMsg(AD_Language); - if (retValue != null) - { - m_languages.put(AD_Language, retValue); - return retValue; - } - return retValue; - } // getMsgMap - - - /** - * Init message HashMap. - * The initial call is from ALogin (ConfirmPanel init). - * The second from Env.verifyLanguage. - * @param AD_Language Language - * @return Cache HashMap - */ - private CCache initMsg (String AD_Language) - { - // Trace.printStack(); - CCache msg = new CCache("AD_Message", MAP_SIZE, 0); - // - if (!DB.isConnected()) - { - s_log.log(Level.SEVERE, "No DB Connection"); - return null; - } - try - { - PreparedStatement pstmt = null; - if (AD_Language == null || AD_Language.length() == 0 || Env.isBaseLanguage(AD_Language, "AD_Language")) - pstmt = DB.prepareStatement("SELECT Value, MsgText, MsgTip FROM AD_Message", null); - else - { - pstmt = DB.prepareStatement("SELECT m.Value, t.MsgText, t.MsgTip " - + "FROM AD_Message_Trl t, AD_Message m " - + "WHERE m.AD_Message_ID=t.AD_Message_ID" - + " AND t.AD_Language=?", null); - pstmt.setString(1, AD_Language); - } - ResultSet rs = pstmt.executeQuery(); - - // get values - while (rs.next()) - { - String AD_Message = rs.getString(1); - StringBuffer MsgText = new StringBuffer(); - MsgText.append(rs.getString(2)); - String MsgTip = rs.getString(3); - // - if (MsgTip != null) // messageTip on next line, if exists - MsgText.append(" ").append(SEPARATOR).append(MsgTip); - msg.put(AD_Message, MsgText.toString()); - } - - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, "initMsg", e); - return null; - } - // - if (msg.size() < 100) - { - s_log.log(Level.SEVERE, "Too few (" + msg.size() + ") Records found for " + AD_Language); - return null; - } - s_log.info("Records=" + msg.size() + " - " + AD_Language); - return msg; - } // initMsg - - /** - * Reset Message cache - */ - public void reset() - { - if (m_languages == null) - return; - - // clear all languages - Iterator iterator = m_languages.values().iterator(); - while (iterator.hasNext()) - { - HashMap hm = (HashMap)iterator.next(); - hm.clear(); - } - m_languages.clear(); - } // reset - - /** - * Return an array of the installed Languages - * @return Array of loaded Languages or null - */ - public String[] getLanguages() - { - if (m_languages == null) - return null; - String[] retValue = new String[m_languages.size()]; - m_languages.keySet().toArray(retValue); - return retValue; - } // getLanguages - - /** - * Check if Language is loaded - * @param language Language code - * @return true, if language is loaded - */ - public boolean isLoaded (String language) - { - if (m_languages == null) - return false; - return m_languages.containsKey(language); - } // isLoaded - - /** - * Lookup term - * @param AD_Language language - * @param text text - * @return translated term or null - */ - private String lookup (String AD_Language, String text) - { - if (text == null) - return null; - if (AD_Language == null || AD_Language.length() == 0) - return text; - // hardcoded trl - if (text.equals("/") || text.equals("\\")) + * by the Free Software Foundation. This program is distributed in the hope * + * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * + * See the GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License along * + * with this program; if not, write to the Free Software Foundation, Inc., * + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * + * For the text or an alternative of this public license, you may reach us * + * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * + * or via info@compiere.org or http://www.compiere.org/license.html * + *****************************************************************************/ +package org.compiere.util; + +import java.io.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; +import org.compiere.*; + +/** + * Reads all Messages and stores them in a HashMap + * + * @author Jorg Janke + * @version $Id: Msg.java,v 1.2 2006/07/30 00:54:36 jjanke Exp $ + */ +public final class Msg +{ + /** Initial size of HashMap */ + private static final int MAP_SIZE = 750; + /** Separator between Msg and optional Tip */ + private static final String SEPARATOR = Env.NL + Env.NL; + + /** Singleton */ + private static Msg s_msg = null; + + /** Logger */ + private static CLogger s_log = CLogger.getCLogger (Msg.class); + + /** + * Get Message Object + * @return Mag + */ + private static Msg get() + { + if (s_msg == null) + s_msg = new Msg(); + return s_msg; + } // get + + + /************************************************************************** + * Constructor + */ + private Msg() + { + } // Mag + + /** The Map */ + private CCache> m_languages + = new CCache>("msg_lang", 2, 0); + + /** + * Get Language specific Message Map + * @param ad_language Language Key + * @return HashMap of Language + */ + private CCache getMsgMap (String ad_language) + { + String AD_Language = ad_language; + if (AD_Language == null || AD_Language.length() == 0) + AD_Language = Language.getBaseAD_Language(); + // Do we have the language ? + CCache retValue = (CCache)m_languages.get(AD_Language); + if (retValue != null && retValue.size() > 0) + return retValue; + + // Load Language + retValue = initMsg(AD_Language); + if (retValue != null) + { + m_languages.put(AD_Language, retValue); + return retValue; + } + return retValue; + } // getMsgMap + + + /** + * Init message HashMap. + * The initial call is from ALogin (ConfirmPanel init). + * The second from Env.verifyLanguage. + * @param AD_Language Language + * @return Cache HashMap + */ + private CCache initMsg (String AD_Language) + { + // Trace.printStack(); + CCache msg = new CCache("AD_Message", MAP_SIZE, 0); + // + if (!DB.isConnected()) + { + s_log.log(Level.SEVERE, "No DB Connection"); + return null; + } + try + { + PreparedStatement pstmt = null; + if (AD_Language == null || AD_Language.length() == 0 || Env.isBaseLanguage(AD_Language, "AD_Language")) + pstmt = DB.prepareStatement("SELECT Value, MsgText, MsgTip FROM AD_Message", null); + else + { + pstmt = DB.prepareStatement("SELECT m.Value, t.MsgText, t.MsgTip " + + "FROM AD_Message_Trl t, AD_Message m " + + "WHERE m.AD_Message_ID=t.AD_Message_ID" + + " AND t.AD_Language=?", null); + pstmt.setString(1, AD_Language); + } + ResultSet rs = pstmt.executeQuery(); + + // get values + while (rs.next()) + { + String AD_Message = rs.getString(1); + StringBuffer MsgText = new StringBuffer(); + MsgText.append(rs.getString(2)); + String MsgTip = rs.getString(3); + // + if (MsgTip != null) // messageTip on next line, if exists + MsgText.append(" ").append(SEPARATOR).append(MsgTip); + msg.put(AD_Message, MsgText.toString()); + } + + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, "initMsg", e); + return null; + } + // + if (msg.size() < 100) + { + s_log.log(Level.SEVERE, "Too few (" + msg.size() + ") Records found for " + AD_Language); + return null; + } + s_log.info("Records=" + msg.size() + " - " + AD_Language); + return msg; + } // initMsg + + /** + * Reset Message cache + */ + public void reset() + { + if (m_languages == null) + return; + + // clear all languages + Iterator iterator = m_languages.values().iterator(); + while (iterator.hasNext()) + { + HashMap hm = (HashMap)iterator.next(); + hm.clear(); + } + m_languages.clear(); + } // reset + + /** + * Return an array of the installed Languages + * @return Array of loaded Languages or null + */ + public String[] getLanguages() + { + if (m_languages == null) + return null; + String[] retValue = new String[m_languages.size()]; + m_languages.keySet().toArray(retValue); + return retValue; + } // getLanguages + + /** + * Check if Language is loaded + * @param language Language code + * @return true, if language is loaded + */ + public boolean isLoaded (String language) + { + if (m_languages == null) + return false; + return m_languages.containsKey(language); + } // isLoaded + + /** + * Lookup term + * @param AD_Language language + * @param text text + * @return translated term or null + */ + private String lookup (String AD_Language, String text) + { + if (text == null) + return null; + if (AD_Language == null || AD_Language.length() == 0) + return text; + // hardcoded trl + if (text.equals("/") || text.equals("\\")) return File.separator; if (text.equals(";") || text.equals(":")) return File.pathSeparator; @@ -219,7 +219,7 @@ public final class Msg if (text.equals("bat") || text.equals("sh")) { if (System.getProperty("os.name").startsWith("Win")) - return "bat"; + return "bat"; return "sh"; } if (text.equals("CopyRight")) @@ -227,431 +227,431 @@ public final class Msg // HashMap langMap = getMsgMap(AD_Language); if (langMap == null) - return null; - return (String)langMap.get(text); - } // lookup - - - /************************************************************************** - * Get translated text for AD_Message - * @param ad_language - Language - * @param AD_Message - Message Key - * @return translated text - */ - public static String getMsg (String ad_language, String AD_Message) - { - if (AD_Message == null || AD_Message.length() == 0) - return ""; - // - String AD_Language = ad_language; - if (AD_Language == null || AD_Language.length() == 0) - AD_Language = Language.getBaseAD_Language(); - // - String retStr = get().lookup (AD_Language, AD_Message); - // - if (retStr == null || retStr.length() == 0) - { - s_log.warning("NOT found: " + AD_Message); - return AD_Message; - } - - return retStr; - } // getMsg - - /** - * Get translated text message for AD_Message - * @param ctx Context to retrieve language - * @param AD_Message - Message Key - * @return translated text - */ - public static String getMsg (Properties ctx, String AD_Message) - { - return getMsg (Env.getAD_Language(ctx), AD_Message); - } // getMeg - - /** - * Get translated text message for AD_Message - * @param language Language - * @param AD_Message - Message Key - * @return translated text - */ - public static String getMsg (Language language, String AD_Message) - { - return getMsg (language.getAD_Language(), AD_Message); - } // getMeg - - /** - * Get translated text message for AD_Message - * @param ad_language - Language - * @param AD_Message - Message Key - * @param getText if true only return Text, if false only return Tip - * @return translated text - */ - public static String getMsg (String ad_language, String AD_Message, boolean getText) - { - String retStr = getMsg (ad_language, AD_Message); - int pos = retStr.indexOf(SEPARATOR); - // No Tip - if (pos == -1) - { - if (getText) - return retStr; - else - return ""; - } - else // with Tip - { - if (getText) - retStr = retStr.substring (0, pos); + return null; + return (String)langMap.get(text); + } // lookup + + + /************************************************************************** + * Get translated text for AD_Message + * @param ad_language - Language + * @param AD_Message - Message Key + * @return translated text + */ + public static String getMsg (String ad_language, String AD_Message) + { + if (AD_Message == null || AD_Message.length() == 0) + return ""; + // + String AD_Language = ad_language; + if (AD_Language == null || AD_Language.length() == 0) + AD_Language = Language.getBaseAD_Language(); + // + String retStr = get().lookup (AD_Language, AD_Message); + // + if (retStr == null || retStr.length() == 0) + { + s_log.warning("NOT found: " + AD_Message); + return AD_Message; + } + + return retStr; + } // getMsg + + /** + * Get translated text message for AD_Message + * @param ctx Context to retrieve language + * @param AD_Message - Message Key + * @return translated text + */ + public static String getMsg (Properties ctx, String AD_Message) + { + return getMsg (Env.getAD_Language(ctx), AD_Message); + } // getMeg + + /** + * Get translated text message for AD_Message + * @param language Language + * @param AD_Message - Message Key + * @return translated text + */ + public static String getMsg (Language language, String AD_Message) + { + return getMsg (language.getAD_Language(), AD_Message); + } // getMeg + + /** + * Get translated text message for AD_Message + * @param ad_language - Language + * @param AD_Message - Message Key + * @param getText if true only return Text, if false only return Tip + * @return translated text + */ + public static String getMsg (String ad_language, String AD_Message, boolean getText) + { + String retStr = getMsg (ad_language, AD_Message); + int pos = retStr.indexOf(SEPARATOR); + // No Tip + if (pos == -1) + { + if (getText) + return retStr; + else + return ""; + } + else // with Tip + { + if (getText) + retStr = retStr.substring (0, pos); else { int start = pos + SEPARATOR.length(); - int end = retStr.length(); + // int end = retStr.length(); retStr = retStr.substring (start); } } - return retStr; - } // getMsg - - /** - * Get translated text message for AD_Message - * @param ctx Context to retrieve language - * @param AD_Message Message Key - * @param getText if true only return Text, if false only return Tip - * @return translated text - */ - public static String getMsg (Properties ctx, String AD_Message, boolean getText) - { - return getMsg (Env.getAD_Language(ctx), AD_Message, getText); - } // getMsg - - /** - * Get translated text message for AD_Message - * @param language Language - * @param AD_Message Message Key - * @param getText if true only return Text, if false only return Tip - * @return translated text - */ - public static String getMsg (Language language, String AD_Message, boolean getText) - { - return getMsg (language.getAD_Language(), AD_Message, getText); - } // getMsg - - /** - * Get clear text for AD_Message with parameters - * @param ctx Context to retrieve language - * @param AD_Message Message yey - * @param args MessageFormat arguments - * @return translated text - * @see java.text.MessageFormat for formatting options - */ - public static String getMsg(Properties ctx, String AD_Message, Object[] args) - { - return getMsg (Env.getAD_Language(ctx), AD_Message, args); - } // getMsg - - /** - * Get clear text for AD_Message with parameters - * @param language Language - * @param AD_Message Message yey - * @param args MessageFormat arguments - * @return translated text - * @see java.text.MessageFormat for formatting options - */ - public static String getMsg(Language language, String AD_Message, Object[] args) - { - return getMsg (language.getAD_Language(), AD_Message, args); - } // getMsg - - /** - * Get clear text for AD_Message with parameters - * @param ad_language Language - * @param AD_Message Message yey - * @param args MessageFormat arguments - * @return translated text - * @see java.text.MessageFormat for formatting options - */ - public static String getMsg (String ad_language, String AD_Message, Object[] args) - { - String msg = getMsg(ad_language, AD_Message); - String retStr = msg; - try - { - retStr = MessageFormat.format(msg, args); // format string - } - catch (Exception e) - { - s_log.log(Level.SEVERE, msg, e); - } - return retStr; - } // getMsg - - - /************************************************************************** - * Get Amount in Words - * @param language language - * @param amount numeric amount (352.80) - * @return amount in words (three*five*two 80/100) - */ - public static String getAmtInWords (Language language, String amount) - { - if (amount == null || language == null) - return amount; - // Try to find Class - String className = "org.compiere.util.AmtInWords_"; - try - { - className += language.getLanguageCode().toUpperCase(); - Class clazz = Class.forName(className); - AmtInWords aiw = (AmtInWords)clazz.newInstance(); - return aiw.getAmtInWords(amount); - } - catch (ClassNotFoundException e) - { - s_log.log(Level.FINER, "Class not found: " + className); - } - catch (Exception e) - { - s_log.log(Level.SEVERE, className, e); - } - - // Fallback - StringBuffer sb = new StringBuffer(); - int pos = amount.lastIndexOf('.'); - int pos2 = amount.lastIndexOf(','); - if (pos2 > pos) - pos = pos2; - for (int i = 0; i < amount.length(); i++) - { - if (pos == i) // we are done - { - String cents = amount.substring(i+1); - sb.append(' ').append(cents).append("/100"); - break; - } - else - { - char c = amount.charAt(i); - if (c == ',' || c == '.') // skip thousand separator - continue; - if (sb.length() > 0) - sb.append("*"); - sb.append(getMsg(language, String.valueOf(c))); - } - } - return sb.toString(); - } // getAmtInWords - - - /************************************************************************** - * Get Translation for Element - * @param ad_language language - * @param ColumnName column name - * @param isSOTrx if false PO terminology is used (if exists) - * @return Name of the Column or "" if not found - */ - public static String getElement (String ad_language, String ColumnName, boolean isSOTrx) - { - if (ColumnName == null || ColumnName.equals("")) - return ""; - String AD_Language = ad_language; - if (AD_Language == null || AD_Language.length() == 0) - AD_Language = Language.getBaseAD_Language(); - - // Check AD_Element - String retStr = ""; - try - { - PreparedStatement pstmt = null; - try - { - if (AD_Language == null || AD_Language.length() == 0 || Env.isBaseLanguage(AD_Language, "AD_Element")) - pstmt = DB.prepareStatement("SELECT Name, PO_Name FROM AD_Element WHERE UPPER(ColumnName)=?", null); - else - { - pstmt = DB.prepareStatement("SELECT t.Name, t.PO_Name FROM AD_Element_Trl t, AD_Element e " - + "WHERE t.AD_Element_ID=e.AD_Element_ID AND UPPER(e.ColumnName)=? " - + "AND t.AD_Language=?", null); - pstmt.setString(2, AD_Language); - } - } - catch (Exception e) - { - return ColumnName; - } - pstmt.setString(1, ColumnName.toUpperCase()); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - retStr = rs.getString(1); - if (!isSOTrx) - { - String temp = rs.getString(2); - if (temp != null && temp.length() > 0) - retStr = temp; - } - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - s_log.log(Level.SEVERE, "getElement", e); - return ""; - } - if (retStr != null) - return retStr.trim(); - return retStr; - } // getElement - - /** - * Get Translation for Element using Sales terminology - * @param ctx context - * @param ColumnName column name - * @return Name of the Column or "" if not found - */ - public static String getElement (Properties ctx, String ColumnName) - { - return getElement (Env.getAD_Language(ctx), ColumnName, true); - } // getElement - - /** - * Get Translation for Element - * @param ctx context - * @param ColumnName column name - * @param isSOTrx sales transaction - * @return Name of the Column or "" if not found - */ - public static String getElement (Properties ctx, String ColumnName, boolean isSOTrx) - { - return getElement (Env.getAD_Language(ctx), ColumnName, isSOTrx); - } // getElement - - - /************************************************************************** - * "Translate" text. - *

-	 *		- Check AD_Message.AD_Message 	->	MsgText
-	 *		- Check AD_Element.ColumnName	->	Name
-	 *  
- * If checking AD_Element, the SO terminology is used. - * @param ad_language Language - * @param isSOTrx sales order context - * @param text Text - MsgText or Element Name - * @return translated text or original text if not found - */ - public static String translate(String ad_language, boolean isSOTrx, String text) - { - if (text == null || text.equals("")) - return ""; - String AD_Language = ad_language; - if (AD_Language == null || AD_Language.length() == 0) - AD_Language = Language.getBaseAD_Language(); - - // Check AD_Message - String retStr = get().lookup (AD_Language, text); - if (retStr != null) - return retStr; - - // Check AD_Element - retStr = getElement(AD_Language, text, isSOTrx); - if (!retStr.equals("")) - return retStr.trim(); - - // Nothing found - if (!text.startsWith("*")) - s_log.warning("NOT found: " + text); - return text; - } // translate - - /*** - * "Translate" text (SO Context). - *
-	 *		- Check AD_Message.AD_Message 	->	MsgText
-	 *		- Check AD_Element.ColumnName	->	Name
-	 *  
- * If checking AD_Element, the SO terminology is used. - * @param ad_language Language - * @param text Text - MsgText or Element Name - * @return translated text or original text if not found - */ - public static String translate(String ad_language, String text) - { - return translate (ad_language, true, text); - } // translate - - /** - * "Translate" text. - *
-	 *		- Check AD_Message.AD_Message 	->	MsgText
-	 *		- Check AD_Element.ColumnName	->	Name
-	 *  
- * @param ctx Context - * @param text Text - MsgText or Element Name - * @return translated text or original text if not found - */ - public static String translate(Properties ctx, String text) - { - if (text == null || text.length() == 0) - return text; - String s = (String)ctx.get(text); - if (s != null && s.length() > 0) - return s; - return translate (Env.getAD_Language(ctx), Env.isSOTrx(ctx), text); - } // translate - - /** - * "Translate" text. - *
-	 *		- Check AD_Message.AD_Message 	->	MsgText
-	 *		- Check AD_Element.ColumnName	->	Name
-	 *  
- * @param language Language - * @param text Text - * @return translated text or original text if not found - */ - public static String translate(Language language, String text) - { - return translate (language.getAD_Language(), false, text); - } // translate - - /** - * Translate elements enclosed in "@" (at sign) - * @param ctx Context - * @param text Text - * @return translated text or original text if not found - */ - public static String parseTranslation(Properties ctx, String text) - { - if (text == null || text.length() == 0) - return text; - - String inStr = text; - String token; - StringBuffer outStr = new StringBuffer(); - - int i = inStr.indexOf("@"); - while (i != -1) - { - outStr.append(inStr.substring(0, i)); // up to @ - inStr = inStr.substring(i+1, inStr.length()); // from first @ - - int j = inStr.indexOf("@"); // next @ - if (j < 0) // no second tag - { - inStr = "@" + inStr; - break; - } - - token = inStr.substring(0, j); - outStr.append(translate(ctx, token)); // replace context - - inStr = inStr.substring(j+1, inStr.length()); // from second @ - i = inStr.indexOf("@"); - } - - outStr.append(inStr); // add remainder - return outStr.toString(); - } // parseTranslation - -} // Msg + return retStr; + } // getMsg + + /** + * Get translated text message for AD_Message + * @param ctx Context to retrieve language + * @param AD_Message Message Key + * @param getText if true only return Text, if false only return Tip + * @return translated text + */ + public static String getMsg (Properties ctx, String AD_Message, boolean getText) + { + return getMsg (Env.getAD_Language(ctx), AD_Message, getText); + } // getMsg + + /** + * Get translated text message for AD_Message + * @param language Language + * @param AD_Message Message Key + * @param getText if true only return Text, if false only return Tip + * @return translated text + */ + public static String getMsg (Language language, String AD_Message, boolean getText) + { + return getMsg (language.getAD_Language(), AD_Message, getText); + } // getMsg + + /** + * Get clear text for AD_Message with parameters + * @param ctx Context to retrieve language + * @param AD_Message Message yey + * @param args MessageFormat arguments + * @return translated text + * @see java.text.MessageFormat for formatting options + */ + public static String getMsg(Properties ctx, String AD_Message, Object[] args) + { + return getMsg (Env.getAD_Language(ctx), AD_Message, args); + } // getMsg + + /** + * Get clear text for AD_Message with parameters + * @param language Language + * @param AD_Message Message yey + * @param args MessageFormat arguments + * @return translated text + * @see java.text.MessageFormat for formatting options + */ + public static String getMsg(Language language, String AD_Message, Object[] args) + { + return getMsg (language.getAD_Language(), AD_Message, args); + } // getMsg + + /** + * Get clear text for AD_Message with parameters + * @param ad_language Language + * @param AD_Message Message yey + * @param args MessageFormat arguments + * @return translated text + * @see java.text.MessageFormat for formatting options + */ + public static String getMsg (String ad_language, String AD_Message, Object[] args) + { + String msg = getMsg(ad_language, AD_Message); + String retStr = msg; + try + { + retStr = MessageFormat.format(msg, args); // format string + } + catch (Exception e) + { + s_log.log(Level.SEVERE, msg, e); + } + return retStr; + } // getMsg + + + /************************************************************************** + * Get Amount in Words + * @param language language + * @param amount numeric amount (352.80) + * @return amount in words (three*five*two 80/100) + */ + public static String getAmtInWords (Language language, String amount) + { + if (amount == null || language == null) + return amount; + // Try to find Class + String className = "org.compiere.util.AmtInWords_"; + try + { + className += language.getLanguageCode().toUpperCase(); + Class clazz = Class.forName(className); + AmtInWords aiw = (AmtInWords)clazz.newInstance(); + return aiw.getAmtInWords(amount); + } + catch (ClassNotFoundException e) + { + s_log.log(Level.FINER, "Class not found: " + className); + } + catch (Exception e) + { + s_log.log(Level.SEVERE, className, e); + } + + // Fallback + StringBuffer sb = new StringBuffer(); + int pos = amount.lastIndexOf('.'); + int pos2 = amount.lastIndexOf(','); + if (pos2 > pos) + pos = pos2; + for (int i = 0; i < amount.length(); i++) + { + if (pos == i) // we are done + { + String cents = amount.substring(i+1); + sb.append(' ').append(cents).append("/100"); + break; + } + else + { + char c = amount.charAt(i); + if (c == ',' || c == '.') // skip thousand separator + continue; + if (sb.length() > 0) + sb.append("*"); + sb.append(getMsg(language, String.valueOf(c))); + } + } + return sb.toString(); + } // getAmtInWords + + + /************************************************************************** + * Get Translation for Element + * @param ad_language language + * @param ColumnName column name + * @param isSOTrx if false PO terminology is used (if exists) + * @return Name of the Column or "" if not found + */ + public static String getElement (String ad_language, String ColumnName, boolean isSOTrx) + { + if (ColumnName == null || ColumnName.equals("")) + return ""; + String AD_Language = ad_language; + if (AD_Language == null || AD_Language.length() == 0) + AD_Language = Language.getBaseAD_Language(); + + // Check AD_Element + String retStr = ""; + try + { + PreparedStatement pstmt = null; + try + { + if (AD_Language == null || AD_Language.length() == 0 || Env.isBaseLanguage(AD_Language, "AD_Element")) + pstmt = DB.prepareStatement("SELECT Name, PO_Name FROM AD_Element WHERE UPPER(ColumnName)=?", null); + else + { + pstmt = DB.prepareStatement("SELECT t.Name, t.PO_Name FROM AD_Element_Trl t, AD_Element e " + + "WHERE t.AD_Element_ID=e.AD_Element_ID AND UPPER(e.ColumnName)=? " + + "AND t.AD_Language=?", null); + pstmt.setString(2, AD_Language); + } + } + catch (Exception e) + { + return ColumnName; + } + pstmt.setString(1, ColumnName.toUpperCase()); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + retStr = rs.getString(1); + if (!isSOTrx) + { + String temp = rs.getString(2); + if (temp != null && temp.length() > 0) + retStr = temp; + } + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + s_log.log(Level.SEVERE, "getElement", e); + return ""; + } + if (retStr != null) + return retStr.trim(); + return retStr; + } // getElement + + /** + * Get Translation for Element using Sales terminology + * @param ctx context + * @param ColumnName column name + * @return Name of the Column or "" if not found + */ + public static String getElement (Properties ctx, String ColumnName) + { + return getElement (Env.getAD_Language(ctx), ColumnName, true); + } // getElement + + /** + * Get Translation for Element + * @param ctx context + * @param ColumnName column name + * @param isSOTrx sales transaction + * @return Name of the Column or "" if not found + */ + public static String getElement (Properties ctx, String ColumnName, boolean isSOTrx) + { + return getElement (Env.getAD_Language(ctx), ColumnName, isSOTrx); + } // getElement + + + /************************************************************************** + * "Translate" text. + *
+	 *		- Check AD_Message.AD_Message 	->	MsgText
+	 *		- Check AD_Element.ColumnName	->	Name
+	 *  
+ * If checking AD_Element, the SO terminology is used. + * @param ad_language Language + * @param isSOTrx sales order context + * @param text Text - MsgText or Element Name + * @return translated text or original text if not found + */ + public static String translate(String ad_language, boolean isSOTrx, String text) + { + if (text == null || text.equals("")) + return ""; + String AD_Language = ad_language; + if (AD_Language == null || AD_Language.length() == 0) + AD_Language = Language.getBaseAD_Language(); + + // Check AD_Message + String retStr = get().lookup (AD_Language, text); + if (retStr != null) + return retStr; + + // Check AD_Element + retStr = getElement(AD_Language, text, isSOTrx); + if (!retStr.equals("")) + return retStr.trim(); + + // Nothing found + if (!text.startsWith("*")) + s_log.warning("NOT found: " + text); + return text; + } // translate + + /*** + * "Translate" text (SO Context). + *
+	 *		- Check AD_Message.AD_Message 	->	MsgText
+	 *		- Check AD_Element.ColumnName	->	Name
+	 *  
+ * If checking AD_Element, the SO terminology is used. + * @param ad_language Language + * @param text Text - MsgText or Element Name + * @return translated text or original text if not found + */ + public static String translate(String ad_language, String text) + { + return translate (ad_language, true, text); + } // translate + + /** + * "Translate" text. + *
+	 *		- Check AD_Message.AD_Message 	->	MsgText
+	 *		- Check AD_Element.ColumnName	->	Name
+	 *  
+ * @param ctx Context + * @param text Text - MsgText or Element Name + * @return translated text or original text if not found + */ + public static String translate(Properties ctx, String text) + { + if (text == null || text.length() == 0) + return text; + String s = (String)ctx.get(text); + if (s != null && s.length() > 0) + return s; + return translate (Env.getAD_Language(ctx), Env.isSOTrx(ctx), text); + } // translate + + /** + * "Translate" text. + *
+	 *		- Check AD_Message.AD_Message 	->	MsgText
+	 *		- Check AD_Element.ColumnName	->	Name
+	 *  
+ * @param language Language + * @param text Text + * @return translated text or original text if not found + */ + public static String translate(Language language, String text) + { + return translate (language.getAD_Language(), false, text); + } // translate + + /** + * Translate elements enclosed in "@" (at sign) + * @param ctx Context + * @param text Text + * @return translated text or original text if not found + */ + public static String parseTranslation(Properties ctx, String text) + { + if (text == null || text.length() == 0) + return text; + + String inStr = text; + String token; + StringBuffer outStr = new StringBuffer(); + + int i = inStr.indexOf("@"); + while (i != -1) + { + outStr.append(inStr.substring(0, i)); // up to @ + inStr = inStr.substring(i+1, inStr.length()); // from first @ + + int j = inStr.indexOf("@"); // next @ + if (j < 0) // no second tag + { + inStr = "@" + inStr; + break; + } + + token = inStr.substring(0, j); + outStr.append(translate(ctx, token)); // replace context + + inStr = inStr.substring(j+1, inStr.length()); // from second @ + i = inStr.indexOf("@"); + } + + outStr.append(inStr); // add remainder + return outStr.toString(); + } // parseTranslation + +} // Msg