Adempiere 3.1.2

This commit is contained in:
vpj-cd 2006-12-07 03:23:16 +00:00
parent 8a0bf1e3c7
commit b4c4d18be1
6 changed files with 3042 additions and 3128 deletions

View File

@ -98,6 +98,15 @@ public abstract class Config
p_data.p_properties.setProperty(key, value);
} // setProperty
/**
* Get Configuration Property
* @param key key
* @return value or ""
*/
protected String getProperty(String key)
{
return p_data.p_properties.getProperty(key, "");
} // getProperty
/**
* UI Signal OK

View File

@ -3,53 +3,53 @@
* 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.install;
import java.io.*;
import java.net.*;
import java.sql.*;
import org.compiere.db.*;
import org.compiere.util.*;
import com.ibm.db2.jcc.*;
/**
* DB/2 Configuration Test
*
* @author Jorg Janke
* @version $Id: ConfigDB2.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $
*/
public class ConfigDB2 extends Config
{
/**
* ConfigOracle
* @param data configuration
*/
public ConfigDB2 (ConfigurationData data)
{
super (data);
} // ConfigOracle
/** DB/2 Driver */
private static DB2Driver s_db2Driver = null;
/** Last Connection */
private Connection m_con = null;
/**
* Init
*/
* 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.install;
import java.io.*;
import java.net.*;
import java.sql.*;
import org.compiere.db.*;
import org.compiere.util.*;
import com.ibm.db2.jcc.*;
/**
* DB/2 Configuration Test
*
* @author Jorg Janke
* @version $Id: ConfigDB2.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $
*/
public class ConfigDB2 extends Config
{
/**
* ConfigOracle
* @param data configuration
*/
public ConfigDB2 (ConfigurationData data)
{
super (data);
} // ConfigOracle
/** DB/2 Driver */
private static DB2Driver s_db2Driver = null;
/** Last Connection */
private Connection m_con = null;
/**
* Init
*/
public void init()
{
p_data.setDatabasePort(String.valueOf(DB_DB2.DEFAULT_PORT_0));
@ -57,30 +57,30 @@ public class ConfigDB2 extends Config
p_data.setDatabaseSystemPassword(true);
} // init
/**************************************************************************
* Test
* @return error message or null if OK
*/
public String test()
{
// Database Server
String server = p_data.getDatabaseServer();
boolean pass = server != null && server.length() > 0
&& server.toLowerCase().indexOf("localhost") == -1
&& !server.equals("127.0.0.1");
String error = "Not correct: DB Server = " + server;
InetAddress databaseServer = null;
try
{
if (pass)
databaseServer = InetAddress.getByName(server);
}
catch (Exception e)
{
error += " - " + e.getMessage();
pass = false;
}
/**************************************************************************
* Test
* @return error message or null if OK
*/
public String test()
{
// Database Server
String server = p_data.getDatabaseServer();
boolean pass = server != null && server.length() > 0
&& server.toLowerCase().indexOf("localhost") == -1
&& !server.equals("127.0.0.1");
String error = "Not correct: DB Server = " + server;
InetAddress databaseServer = null;
try
{
if (pass)
databaseServer = InetAddress.getByName(server);
}
catch (Exception e)
{
error += " - " + e.getMessage();
pass = false;
}
signalOK(getPanel().okDatabaseServer, "ErrorDatabaseServer",
pass, true, error);
log.info("OK: Database Server = " + databaseServer);
@ -89,10 +89,10 @@ public class ConfigDB2 extends Config
// Database Port
int databasePort = p_data.getDatabasePort();
pass = p_data.testPort (databaseServer, databasePort, true);
error = "DB Server Port = " + databasePort;
signalOK(getPanel().okDatabaseServer, "ErrorDatabasePort",
pass, true, error);
pass = p_data.testPort (databaseServer, databasePort, true);
error = "DB Server Port = " + databasePort;
signalOK(getPanel().okDatabaseServer, "ErrorDatabasePort",
pass, true, error);
if (!pass)
return error;
log.info("OK: Database Port = " + databasePort);
@ -100,24 +100,24 @@ public class ConfigDB2 extends Config
// JDBC Database Info
String databaseName = p_data.getDatabaseName(); // Service Name
String systemPassword = p_data.getDatabaseSystemPassword();
pass = systemPassword != null && systemPassword.length() > 0;
error = "No Database System Password entered";
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
//
// URL (derived) jdbc:oracle:thin:@//prod1:1521/prod1
String url = "jdbc:db2://" + databaseServer.getHostName()
+ ":" + databasePort
+ "/" + databaseName;
pass = testJDBC(url, "db2admin", systemPassword);
error = "Error connecting: " + url
+ " - as db2admin/" + systemPassword;
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
String databaseName = p_data.getDatabaseName(); // Service Name
String systemPassword = p_data.getDatabaseSystemPassword();
pass = systemPassword != null && systemPassword.length() > 0;
error = "No Database System Password entered";
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
//
// URL (derived) jdbc:oracle:thin:@//prod1:1521/prod1
String url = "jdbc:db2://" + databaseServer.getHostName()
+ ":" + databasePort
+ "/" + databaseName;
pass = testJDBC(url, "db2admin", systemPassword);
error = "Error connecting: " + url
+ " - as db2admin/" + systemPassword;
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
log.info("OK: Connection = " + url);
@ -128,20 +128,20 @@ public class ConfigDB2 extends Config
// Database User Info
String databaseUser = p_data.getDatabaseUser(); // UID
String databasePassword = p_data.getDatabasePassword(); // PWD
pass = databasePassword != null && databasePassword.length() > 0;
error = "Invalid Database User Password";
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
// Ignore result as it might not be imported
pass = testJDBC(url, databaseUser, databasePassword);
error = "Database imported? Cannot connect to User: " + databaseUser + "/" + databasePassword;
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, false, error);
if (pass)
String databaseUser = p_data.getDatabaseUser(); // UID
String databasePassword = p_data.getDatabasePassword(); // PWD
pass = databasePassword != null && databasePassword.length() > 0;
error = "Invalid Database User Password";
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
// Ignore result as it might not be imported
pass = testJDBC(url, databaseUser, databasePassword);
error = "Database imported? Cannot connect to User: " + databaseUser + "/" + databasePassword;
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, false, error);
if (pass)
{
log.info("OK: Database User = " + databaseUser);
if (m_con != null)
@ -154,99 +154,99 @@ public class ConfigDB2 extends Config
if (!p_data.getAppsServerType().equals(ConfigurationData.APPSTYPE_TOMCAT))
{
String cmd = "db2 ";
if (Env.isWindows())
cmd = "db2cmd -c -w -i db2 ";
String sqlcmd1 = cmd + "connect to xx";
String sqlcmd2 = cmd + "-f utils/db2/Test.sql";
log.config(sqlcmd2);
pass = testSQL(sqlcmd2);
error = "Error connecting via: " + sqlcmd2;
signalOK(getPanel().okDatabaseSQL, "ErrorTNS",
pass, true, error);
if (pass)
log.info("OK: Database SQL Connection");
}
m_con = null;
return null;
} // test
/**
* Test JDBC Connection to Server
* @param url connection string
* @param uid user id
* @param pwd password
* @return true if OK
*/
private boolean testJDBC (String url, String uid, String pwd)
{
log.fine("Url=" + url + ", UID=" + uid);
try
{
if (s_db2Driver == null)
{
s_db2Driver = new DB2Driver();
DriverManager.registerDriver(s_db2Driver);
}
m_con = DriverManager.getConnection(url, uid, pwd);
String cmd = "db2 ";
if (Env.isWindows())
cmd = "db2cmd -c -w -i db2 ";
String sqlcmd1 = cmd + "connect to xx";
String sqlcmd2 = cmd + "-f utils/db2/Test.sql";
log.config(sqlcmd2);
pass = testSQL(sqlcmd2);
error = "Error connecting via: " + sqlcmd2;
signalOK(getPanel().okDatabaseSQL, "ErrorTNS",
pass, true, error);
if (pass)
log.info("OK: Database SQL Connection");
}
m_con = null;
return null;
} // test
/**
* Test JDBC Connection to Server
* @param url connection string
* @param uid user id
* @param pwd password
* @return true if OK
*/
private boolean testJDBC (String url, String uid, String pwd)
{
log.fine("Url=" + url + ", UID=" + uid);
try
{
if (s_db2Driver == null)
{
s_db2Driver = new DB2Driver();
DriverManager.registerDriver(s_db2Driver);
}
m_con = DriverManager.getConnection(url, uid, pwd);
}
catch (Exception e)
{
log.severe(e.toString());
log.warning(e.toString());
return false;
}
return true;
} // testJDBC
/**
* Test Command Line Connection
* @param sqlcmd sql command line
* @return true if OK
*/
private boolean testSQL (String sqlcmd)
{
if (true)
return true;
//
StringBuffer sbOut = new StringBuffer();
StringBuffer sbErr = new StringBuffer();
int result = -1;
try
{
Process p = Runtime.getRuntime().exec (sqlcmd);
InputStream in = p.getInputStream();
int c;
while ((c = in.read()) != -1)
{
sbOut.append((char)c);
System.out.print((char)c);
}
in.close();
in = p.getErrorStream();
while ((c = in.read()) != -1)
sbErr.append((char)c);
in.close();
// Get result
try
{
Thread.yield();
result = p.exitValue();
}
catch (Exception e) // Timing issue on Solaris.
{
Thread.sleep(200); // .2 sec
result = p.exitValue();
}
} // testJDBC
/**
* Test Command Line Connection
* @param sqlcmd sql command line
* @return true if OK
*/
private boolean testSQL (String sqlcmd)
{
if (true)
return true;
//
StringBuffer sbOut = new StringBuffer();
StringBuffer sbErr = new StringBuffer();
int result = -1;
try
{
Process p = Runtime.getRuntime().exec (sqlcmd);
InputStream in = p.getInputStream();
int c;
while ((c = in.read()) != -1)
{
sbOut.append((char)c);
System.out.print((char)c);
}
in.close();
in = p.getErrorStream();
while ((c = in.read()) != -1)
sbErr.append((char)c);
in.close();
// Get result
try
{
Thread.yield();
result = p.exitValue();
}
catch (Exception e) // Timing issue on Solaris.
{
Thread.sleep(200); // .2 sec
result = p.exitValue();
}
}
catch (Exception ex)
{
log.severe(ex.toString());
log.warning(ex.toString());
}
log.finer(sbOut.toString());
if (sbErr.length() > 0)
log.warning(sbErr.toString());
return result == 0;
} // testSQL
} // ConfigDB2
log.warning(sbErr.toString());
return result == 0;
} // testSQL
} // ConfigDB2

View File

@ -1,466 +1,416 @@
/******************************************************************************
* 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.install;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import org.compiere.db.*;
import oracle.jdbc.*;
/**
* Oracle Confguration
*
* @author Jorg Janke
* @version $Id: ConfigOracle.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $
*/
public class ConfigOracle extends Config
{
/**
* ConfigOracle
* @param data configuration
*/
public ConfigOracle (ConfigurationData data)
{
super (data);
} // ConfigOracle
/** Oracle Driver */
private static OracleDriver s_oracleDriver = null;
/** Discovered TNS */
private String[] p_discovered = null;
/** Discovered Database Name */
private String[] p_dbname = null;
/** Last Connection */
private Connection m_con = null;
/**
* Init
*/
public void init()
{
p_data.setDatabasePort(String.valueOf(DB_Oracle.DEFAULT_PORT));
//
p_data.setDatabaseSystemPassword(true);
} // init
/**
* Discover Databases.
* To be overwritten by database configs
* @param selected selected database
* @return array of databases
*/
public String[] discoverDatabases(String selected)
{
if (p_discovered != null)
return p_discovered;
//
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> dblist = new ArrayList<String>();
// default value to lowercase or null
String def = selected;
if (def != null && def.trim().length() == 0)
def = null;
if (def != null) {
list.add(def.toLowerCase());
dblist.add(def.toLowerCase());
}
String path = System.getenv("ORACLE_HOME");
if (path == null)
{
// Search for Oracle Info
path = System.getProperty("java.library.path");
String[] entries = path.split(File.pathSeparator);
for (int e = 0; e < entries.length; e++)
{
String entry = entries[e].toLowerCase();
if (entry.indexOf("ora") != -1 && entry.endsWith("bin"))
{
StringBuffer sb = getTNS_File (entries[e].substring(0, entries[e].length()-4));
String[] tnsnames = getTNS_Names (sb, true);
String[] dbNames = getTNS_Names (sb, false);
if (tnsnames != null)
{
for (int i = 0; i < tnsnames.length; i++)
{
String tns = tnsnames[i]; // is lower case
String db = dbNames[i];
if (!tns.equals(def)) {
list.add(tns);
dblist.add(db);
} else {
dblist.remove(0);
dblist.add(0, db);
}
}
break;
}
}
} // for all path entries
}
else
{
StringBuffer sb = getTNS_File (path);
String[] tnsnames = getTNS_Names (sb, true);
String[] dbNames = getTNS_Names (sb, false);
if (tnsnames != null)
{
for (int i = 0; i < tnsnames.length; i++)
{
String tns = tnsnames[i]; // is lower case
String db = dbNames[i];
if (!tns.equals(def)) {
list.add(tns);
dblist.add(db);
} else {
dblist.remove(0);
dblist.add(0, db);
}
}
}
}
p_discovered = new String[list.size()];
list.toArray(p_discovered);
p_dbname = new String[dblist.size()];
dblist.toArray(p_dbname);
return p_discovered;
} // discoverDatabases
@Override
public String getDatabaseName(String nativeConnectioName)
{
int idx = -1;
if (p_discovered == null) return nativeConnectioName;
for (int i = 0; i < p_discovered.length; i++)
{
if (p_discovered[i].equals(nativeConnectioName))
{
idx = i;
break;
}
}
if (idx >= 0
&& p_dbname != null
&& idx < p_dbname.length)
return p_dbname[idx];
else
return nativeConnectioName;
}
/**
* Get File tnmsnames.ora in StringBuffer
* @param oraHome ORACLE_HOME
* @return tnsnames.ora or null
*/
private StringBuffer getTNS_File (String oraHome)
{
String tnsnames = oraHome + File.separator
+ "network" + File.separator
+ "admin" + File.separator
+ "tnsnames.ora";
File tnsfile = new File (tnsnames);
if (!tnsfile.exists())
return null;
log.fine(tnsnames);
StringBuffer sb = new StringBuffer();
try
{
FileReader fr = new FileReader (tnsfile);
int c;
while ((c = fr.read()) != -1)
sb.append((char)c);
}
catch (IOException ex)
{
log.severe("Error Reading " + tnsnames);
ex.printStackTrace();
return null;
}
if (sb.length() == 0)
return null;
return sb;
} // getTNS_File
/**
* Get TNS Names entries.
* Assumes standard tnsmanes.ora formatting of NetMgr
* @param tnsnames content of tnsnames.ora
* @return tns names or null
*/
private String[] getTNS_Names (StringBuffer tnsnames, boolean tns)
{
if (tnsnames == null)
return null;
ArrayList<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile("$", Pattern.MULTILINE);
String[] lines = pattern.split(tnsnames);
for (int i = 0; i < lines.length; i++)
{
String line = lines[i].trim();
log.finest(i + ": " + line);
if (tns) // get TNS Name
{
if (line.length() > 0
&& Character.isLetter(line.charAt(0)) // no # (
&& line.indexOf("=") != -1
&& line.indexOf("EXTPROC_") == -1
&& line.indexOf("_HTTP") == -1)
{
String entry = line.substring(0, line.indexOf('=')).trim().toLowerCase();
log.fine(entry);
list.add(entry);
}
}
else // search service names
{
if (line.length() > 0
&& line.toUpperCase().indexOf("SERVICE_NAME") != -1)
{
String entry = line.substring(line.indexOf('=')+1).trim().toLowerCase();
int index = entry.indexOf(')');
if (index != 0)
entry = entry.substring(0, index).trim();
log.fine(entry);
list.add(entry);
}
}
}
// Convert to Array
if (list.size() == 0)
return null;
String[] retValue = new String[list.size()];
list.toArray(retValue);
return retValue;
} // getTNS_Names
/**************************************************************************
* Test
* @return error message or null if OK
*/
public String test()
{
// Database Server
String server = p_data.getDatabaseServer();
boolean pass = server != null && server.length() > 0
&& server.toLowerCase().indexOf("localhost") == -1
&& !server.equals("127.0.0.1");
String error = "Not correct: DB Server = " + server;
InetAddress databaseServer = null;
try
{
if (pass)
databaseServer = InetAddress.getByName(server);
}
catch (Exception e)
{
error += " - " + e.getMessage();
pass = false;
}
signalOK(getPanel().okDatabaseServer, "ErrorDatabaseServer",
pass, true, error);
log.info("OK: Database Server = " + databaseServer);
setProperty(ConfigurationData.ADEMPIERE_DB_SERVER, databaseServer.getHostName());
setProperty(ConfigurationData.ADEMPIERE_DB_TYPE, p_data.getDatabaseType());
// Database Port
int databasePort = p_data.getDatabasePort();
pass = p_data.testPort (databaseServer, databasePort, true);
error = "DB Server Port = " + databasePort;
signalOK(getPanel().okDatabaseServer, "ErrorDatabasePort",
pass, true, error);
if (!pass)
return error;
log.info("OK: Database Port = " + databasePort);
setProperty(ConfigurationData.ADEMPIERE_DB_PORT, String.valueOf(databasePort));
// JDBC Database Info
String databaseName = p_data.getDatabaseName(); // Service Name
String systemPassword = p_data.getDatabaseSystemPassword();
pass = systemPassword != null && systemPassword.length() > 0;
error = "No Database System Password entered";
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
//
// URL (derived) jdbc:oracle:thin:@//prod1:1521/prod1
String url = "jdbc:oracle:thin:@//" + databaseServer.getHostName()
+ ":" + databasePort
+ "/" + databaseName;
pass = testJDBC(url, "system", systemPassword);
error = "Error connecting: " + url
+ " - as system/" + systemPassword;
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
log.info("OK: Connection = " + url);
setProperty(ConfigurationData.ADEMPIERE_DB_URL, url);
log.info("OK: Database System User " + databaseName);
setProperty(ConfigurationData.ADEMPIERE_DB_NAME, databaseName);
setProperty(ConfigurationData.ADEMPIERE_DB_SYSTEM, systemPassword);
// Database User Info
String databaseUser = p_data.getDatabaseUser(); // UID
String databasePassword = p_data.getDatabasePassword(); // PWD
pass = databasePassword != null && databasePassword.length() > 0;
error = "Invalid Database User Password";
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
// Ignore result as it might not be imported
pass = testJDBC(url, databaseUser, databasePassword);
error = "Database imported? Cannot connect to User: " + databaseUser + "/" + databasePassword;
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, false, error);
if (pass)
{
log.info("OK: Database User = " + databaseUser);
if (m_con != null)
setProperty(ConfigurationData.ADEMPIERE_WEBSTORES, getWebStores(m_con));
}
else
log.warning(error);
setProperty(ConfigurationData.ADEMPIERE_DB_USER, databaseUser);
setProperty(ConfigurationData.ADEMPIERE_DB_PASSWORD, databasePassword);
// TNS Name Info via sqlplus - if not tomcat
if (!p_data.getAppsServerType().equals(ConfigurationData.APPSTYPE_TOMCAT))
{
String sqlplus = "sqlplus system/" + systemPassword + "@"
+ databaseServer.getHostName() + "/" + databaseName
+ " @utils/oracle/Test.sql";
log.config(sqlplus);
pass = testSQL(sqlplus);
error = "Error connecting via: " + sqlplus;
signalOK(getPanel().okDatabaseSQL, "ErrorTNS",
pass, true, error);
if (pass)
log.info("OK: Database SQL Connection");
}
// OCI Test
if (System.getProperty("TestOCI", "N").equals("Y"))
{
url = "jdbc:oracle:oci8:@" + databaseName;
pass = testJDBC(url, "system", systemPassword);
if (pass)
log.info("OK: Connection = " + url);
else
log.warning("Cannot connect via Net8: " + url);
}
log.info("OCI Test Skipped");
//
m_con = null;
return null;
} // test
/**
* Test JDBC Connection to Server
* @param url connection string
* @param uid user id
* @param pwd password
* @return true if OK
*/
private boolean testJDBC (String url, String uid, String pwd)
{
log.fine("Url=" + url + ", UID=" + uid);
try
{
if (s_oracleDriver == null)
{
s_oracleDriver = new OracleDriver();
DriverManager.registerDriver(s_oracleDriver);
}
m_con = DriverManager.getConnection(url, uid, pwd);
}
catch (UnsatisfiedLinkError ule)
{
log.warning("Check [ORACLE_HOME]/jdbc/Readme.txt for (OCI) driver setup");
log.warning(ule.toString());
}
catch (Exception e)
{
log.severe(e.toString());
return false;
}
return true;
} // testJDBC
/**
* Test TNS Connection
* @param sqlplus sqlplus command line
* @return true if OK
*/
private boolean testSQL (String sqlplus)
{
StringBuffer sbOut = new StringBuffer();
StringBuffer sbErr = new StringBuffer();
int result = -1;
try
{
Process p = Runtime.getRuntime().exec (sqlplus);
InputStream in = p.getInputStream();
int c;
while ((c = in.read()) != -1)
{
sbOut.append((char)c);
System.out.print((char)c);
}
in.close();
in = p.getErrorStream();
while ((c = in.read()) != -1)
sbErr.append((char)c);
in.close();
// Get result
try
{
Thread.yield();
result = p.exitValue();
}
catch (Exception e) // Timing issue on Solaris.
{
Thread.sleep(200); // .2 sec
result = p.exitValue();
}
}
catch (Exception ex)
{
log.severe(ex.toString());
}
log.finer(sbOut.toString());
if (sbErr.length() > 0)
log.warning(sbErr.toString());
return result == 0;
} // testSQL
} // ConfigOracle
/******************************************************************************
* 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.install;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import org.compiere.db.*;
import oracle.jdbc.*;
/**
* Oracle Confguration
*
* @author Jorg Janke
* @version $Id: ConfigOracle.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $
*/
public class ConfigOracle extends Config
{
/**
* ConfigOracle
* @param data configuration
* @param XE express edition
*/
public ConfigOracle (ConfigurationData data, boolean XE)
{
super (data);
m_XE = XE;
} // ConfigOracle
/** Oracle Driver */
private static OracleDriver s_oracleDriver = null;
/** Discoverd TNS */
private String[] p_discovered = null;
/** Last Connection */
private Connection m_con = null;
/** Express Edition */
private boolean m_XE = false;
/**
* Init
*/
public void init()
{
p_data.setDatabasePort(String.valueOf(DB_Oracle.DEFAULT_PORT));
//
p_data.setDatabaseSystemPassword(true);
} // init
/**
* Discover Databases.
* To be overwritten by database configs
* @param selected selected database
* @return array of databases
*/
public String[] discoverDatabases(String selected)
{
if (p_discovered != null)
return p_discovered;
//
ArrayList<String> list = new ArrayList<String>();
// default value to lowercase or null
String def = selected;
if (def != null && def.trim().length() == 0)
def = null;
if (def != null)
list.add(def.toLowerCase());
if (m_XE)
{
String serviceName = "xe";
if (!list.contains(serviceName))
list.add(serviceName);
}
// Search for Oracle Info
String path = System.getProperty("java.library.path");
String[] entries = path.split(File.pathSeparator);
for (int e = 0; e < entries.length; e++)
{
String entry = entries[e].toLowerCase();
if (entry.indexOf("ora") != -1 && entry.endsWith("bin"))
{
StringBuffer sb = getTNS_File (entries[e].substring(0, entries[e].length()-4));
String[] serviceNames = getTNS_Names (sb);
if (serviceNames != null)
{
for (int i = 0; i < serviceNames.length; i++)
{
String serviceName = serviceNames[i].toLowerCase();
if (!list.contains(serviceName))
list.add(serviceName);
}
break;
}
}
} // for all path entries
p_discovered = new String[list.size()];
list.toArray(p_discovered);
return p_discovered;
} // discoverDatabases
/**
* Get File tnmsnames.ora in StringBuffer
* @param oraHome ORACLE_HOME
* @return tnsnames.ora or null
*/
private StringBuffer getTNS_File (String oraHome)
{
String tnsnames = oraHome + File.separator
+ "network" + File.separator
+ "admin" + File.separator
+ "tnsnames.ora";
File tnsfile = new File (tnsnames);
if (!tnsfile.exists())
return null;
log.fine(tnsnames);
StringBuffer sb = new StringBuffer();
try
{
FileReader fr = new FileReader (tnsfile);
int c;
while ((c = fr.read()) != -1)
sb.append((char)c);
}
catch (IOException ex)
{
log.warning("Error Reading " + tnsnames);
ex.printStackTrace();
return null;
}
if (sb.length() == 0)
return null;
return sb;
} // getTNS_File
/**
* Get TNS Names entries.
* Assumes standard tnsmanes.ora formatting of NetMgr
* @param tnsnames content of tnsnames.ora
* @return service names or null
*/
private String[] getTNS_Names (StringBuffer tnsnames)
{
if (tnsnames == null)
return null;
ArrayList<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile("$", Pattern.MULTILINE);
String[] lines = pattern.split(tnsnames);
for (int i = 0; i < lines.length; i++)
{
String line = lines[i].trim();
log.finest(i + ": " + line);
if (false) // get TNS Name
{
if (line.length() > 0
&& Character.isLetter(line.charAt(0)) // no # (
&& line.indexOf("=") != -1
&& line.indexOf("EXTPROC_") == -1
&& line.indexOf("_HTTP") == -1)
{
String entry = line.substring(0, line.indexOf('=')).trim().toLowerCase();
log.fine(entry);
list.add(entry);
}
}
else // search service names
{
if (line.length() > 0
&& line.toUpperCase().indexOf("SERVICE_NAME") != -1)
{
String entry = line.substring(line.indexOf('=')+1).trim().toLowerCase();
int index = entry.indexOf(')');
if (index != 0)
entry = entry.substring(0, index).trim();
log.fine(entry);
list.add(entry);
}
}
}
// Convert to Array
if (list.size() == 0)
return null;
String[] retValue = new String[list.size()];
list.toArray(retValue);
return retValue;
} // getTNS_Names
/**************************************************************************
* Test
* @return error message or null if OK
*/
public String test()
{
// Database Server
String server = p_data.getDatabaseServer();
boolean pass = server != null && server.length() > 0
&& server.toLowerCase().indexOf("localhost") == -1
&& !server.equals("127.0.0.1");
String error = "Not correct: DB Server = " + server;
InetAddress databaseServer = null;
try
{
if (pass)
databaseServer = InetAddress.getByName(server);
}
catch (Exception e)
{
error += " - " + e.getMessage();
pass = false;
}
signalOK(getPanel().okDatabaseServer, "ErrorDatabaseServer",
pass, true, error);
log.info("OK: Database Server = " + databaseServer);
setProperty(ConfigurationData.ADEMPIERE_DB_SERVER, databaseServer.getHostName());
setProperty(ConfigurationData.ADEMPIERE_DB_TYPE, p_data.getDatabaseType());
setProperty(ConfigurationData.ADEMPIERE_DB_PATH, "oracle");
// Database Port
int databasePort = p_data.getDatabasePort();
pass = p_data.testPort (databaseServer, databasePort, true);
error = "DB Server Port = " + databasePort;
signalOK(getPanel().okDatabaseServer, "ErrorDatabasePort",
pass, true, error);
if (!pass)
return error;
log.info("OK: Database Port = " + databasePort);
setProperty(ConfigurationData.ADEMPIERE_DB_PORT, String.valueOf(databasePort));
// JDBC Database Info
String databaseName = p_data.getDatabaseName(); // Service Name
String systemPassword = p_data.getDatabaseSystemPassword();
pass = systemPassword != null && systemPassword.length() > 0;
error = "No Database System Password entered";
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
//
// URL (derived) jdbc:oracle:thin:@//prod1:1521/prod1
String url = "jdbc:oracle:thin:@//" + databaseServer.getHostName()
+ ":" + databasePort
+ "/" + databaseName;
pass = testJDBC(url, "system", systemPassword);
error = "Error connecting: " + url
+ " - as system/" + systemPassword;
signalOK(getPanel().okDatabaseSystem, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
log.info("OK: Connection = " + url);
setProperty(ConfigurationData.ADEMPIERE_DB_URL, url);
log.info("OK: Database System User " + databaseName);
setProperty(ConfigurationData.ADEMPIERE_DB_NAME, databaseName);
setProperty(ConfigurationData.ADEMPIERE_DB_SYSTEM, systemPassword);
// Database User Info
String databaseUser = p_data.getDatabaseUser(); // UID
String databasePassword = p_data.getDatabasePassword(); // PWD
pass = databasePassword != null && databasePassword.length() > 0;
error = "Invalid Database User Password";
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, true, error);
if (!pass)
return error;
// Ignore result as it might not be imported
pass = testJDBC(url, databaseUser, databasePassword);
error = "Cannot connect to User: " + databaseUser + "/" + databasePassword + " - Database may not be imported yet (OK on initial run).";
signalOK(getPanel().okDatabaseUser, "ErrorJDBC",
pass, false, error);
if (pass)
{
log.info("OK: Database User = " + databaseUser);
if (m_con != null)
setProperty(ConfigurationData.ADEMPIERE_WEBSTORES, getWebStores(m_con));
}
else
log.warning(error);
setProperty(ConfigurationData.ADEMPIERE_DB_USER, databaseUser);
setProperty(ConfigurationData.ADEMPIERE_DB_PASSWORD, databasePassword);
// TNS Name Info via sqlplus - if not tomcat
if (!p_data.getAppsServerType().equals(ConfigurationData.APPSTYPE_TOMCAT))
{
String sqlplus = "sqlplus system/" + systemPassword + "@" + databaseName
+ " @" + getProperty(ConfigurationData.ADEMPIERE_HOME)
+ "/utils/oracle/Test.sql";
log.config(sqlplus);
pass = testSQL(sqlplus);
error = "Error connecting via: " + sqlplus;
signalOK(getPanel().okDatabaseSQL, "ErrorTNS",
pass, true, error);
if (pass)
log.info("OK: Database SQL Connection");
}
// OCI Test
if (System.getProperty("TestOCI", "N").equals("Y"))
{
url = "jdbc:oracle:oci8:@" + databaseName;
pass = testJDBC(url, "system", systemPassword);
if (pass)
log.info("OK: Connection = " + url);
else
log.warning("Cannot connect via Net8: " + url);
}
log.info("OCI Test Skipped");
//
m_con = null;
return null;
} // test
/**
* Test JDBC Connection to Server
* @param url connection string
* @param uid user id
* @param pwd password
* @return true if OK
*/
private boolean testJDBC (String url, String uid, String pwd)
{
log.fine("Url=" + url + ", UID=" + uid);
try
{
if (s_oracleDriver == null)
{
s_oracleDriver = new OracleDriver();
DriverManager.registerDriver(s_oracleDriver);
}
m_con = DriverManager.getConnection(url, uid, pwd);
}
catch (UnsatisfiedLinkError ule)
{
log.warning("Check [ORACLE_HOME]/jdbc/Readme.txt for (OCI) driver setup");
log.warning(ule.toString());
}
catch (Exception e)
{
log.warning(e.toString());
return false;
}
return true;
} // testJDBC
/**
* Test TNS Connection
* @param sqlplus sqlplus command line
* @return true if OK
*/
private boolean testSQL (String sqlplus)
{
StringBuffer sbOut = new StringBuffer();
StringBuffer sbErr = new StringBuffer();
int result = -1;
try
{
Process p = Runtime.getRuntime().exec (sqlplus);
InputStream in = p.getInputStream();
int c;
while ((c = in.read()) != -1)
{
sbOut.append((char)c);
System.out.print((char)c);
}
in.close();
in = p.getErrorStream();
while ((c = in.read()) != -1)
sbErr.append((char)c);
in.close();
// Get result
try
{
Thread.yield();
result = p.exitValue();
}
catch (Exception e) // Timing issue on Solaris.
{
Thread.sleep(200); // .2 sec
result = p.exitValue();
}
}
catch (Exception ex)
{
log.warning(ex.toString());
}
log.finer(sbOut.toString());
if (sbErr.length() > 0)
log.warning(sbErr.toString());
return result == 0;
} // testSQL
} // ConfigOracle

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,426 +1,433 @@
/******************************************************************************
* 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.install;
import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.Certificate;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import org.compiere.*;
import org.compiere.util.*;
import sun.security.tools.*;
/**
* Class to manage SSL KeyStore
*
* @author Jorg Janke
* @version $Id: KeyStoreMgt.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $
*/
public class KeyStoreMgt
{
/**
* Constructor.
* @param fileName key store file name
* @param password - same password for key store and certificate
*/
public KeyStoreMgt (String fileName, char[] password)
{
log.info(fileName);
m_file = new File (fileName);
m_password = password;
} // KeyStoreMgt
/** Logger */
private static CLogger log = CLogger.getCLogger(KeyStoreMgt.class);
/** KeyStore File */
private File m_file = null;
/** KeyStore Password */
private char[] m_password = null;
/** KeyStore */
private KeyStore m_keyStore = null;
/** Directory below ADEMPIERE_HOME */
public static String KEYSTORE_DIRECTORY = "keystore";
/** Name of KeyStore */
public static String KEYSTORE_NAME = "myKeystore";
/** Certificate Alias */
public static String CERTIFICATE_ALIAS = "adempiere";
/**
* Verify/Create Key Store
* @param parent frame
* @return null or error message
*/
public String verify (JFrame parent)
{
KeyStore ks = null;
try
{
ks = getKeyStore();
}
catch (Exception e)
{
log.log(Level.SEVERE, "get KeyStore", e);
return e.getMessage();
}
// No KeyStore
if (ks == null)
{
createCertificate(CERTIFICATE_ALIAS, parent);
try
{
ks = getKeyStore();
}
catch (Exception e)
{
log.log(Level.SEVERE, "new KeyStore", e);
return e.getMessage();
}
} // new key store
// No KeyStore
if (ks == null)
return "No Key Store";
// Verify Certificate
Certificate cert = null;
try
{
cert = getCertificate(CERTIFICATE_ALIAS);
}
catch (Exception e)
{
log.log(Level.SEVERE, "certificate", e);
return e.getMessage();
}
if (cert == null)
return "No Certificate found";
return null; // OK
} // verify
/**
* Get KeyStore
* @return KeyStore or null
* @throws Exception
*/
public KeyStore getKeyStore() throws Exception
{
try
{
m_keyStore = KeyStore.getInstance("JKS");
}
catch (Exception e)
{
log.log(Level.SEVERE, "Instance", e);
}
// Load Existing
if (m_file.exists())
{
log.fine(m_file.toString());
InputStream is = null;
try
{
is = new FileInputStream (m_file);
}
catch (Exception e)
{
log.log(Level.SEVERE, "load", e);
return null;
}
m_keyStore.load(is, m_password);
}
else
return null; // does not exist
//
log.fine("Provider=" + m_keyStore.getProvider()
+ " - Type=" + m_keyStore.getType());
//
return m_keyStore;
} // getKeyStore
/**
* Get Certificate
* @param alias alias
* @return certificate or null
* @throws Exception
*/
public Certificate getCertificate (String alias) throws Exception
{
log.config("Alias=" + alias);
Date date = m_keyStore.getCreationDate(alias);
if (date == null) // no certificate
return null;
log.fine("Created=" + date);
//
Key key = m_keyStore.getKey(alias, m_password);
if (CLogMgt.isLevelFinest())
log.info("Key=" + key); // Multiple lines
else
log.fine(key.getAlgorithm());
//
Certificate cert = m_keyStore.getCertificate(alias);
if (CLogMgt.isLevelFinest())
log.info("Certificate = " + cert); // Multiple lines
else
log.fine(cert.getType());
// log.fine("Certificate - Type=" + cert.getType()
// + " - PublicKey=" + cert.getPublicKey());
return cert;
} // getCertificate
/**************************************************************************
* Create Certificate
* @param alias alias
* @param parent interactive dialog
*/
private void createCertificate (String alias, JFrame parent)
{
log.info("");
try
{
File dir = m_file.getParentFile();
if (!dir.exists())
dir.mkdir();
}
catch (Exception e)
{
log.log(Level.SEVERE, "directory", e);
}
String dname = getDname(parent);
if (dname == null)
return;
//
try
{
genkey (alias, m_password, m_file.getAbsolutePath(), dname);
selfcert (alias, m_password, m_file.getAbsolutePath(), dname);
}
catch (Exception e)
{
log.log(Level.SEVERE, "certificate", e);
}
} // createCertificate
/**
* Get Distinguised Name
* @param parent interactive dialog
* @return dname or null
*/
public static String getDname(JFrame parent)
{
String cn = null;
try
{
InetAddress address = InetAddress.getLocalHost();
cn = address.getCanonicalHostName();
}
catch (Exception e)
{
}
String ou = System.getProperty("user.name");
String o = "AdempiereUser";
String l = "MyTown";
String s = "";
String c = System.getProperty("user.country");
//
if (parent != null)
{
KeyStoreDialog skd = new KeyStoreDialog(parent,
cn, ou, o, l, s, c);
if (!skd.isOK())
return null;
cn = skd.getCN();
ou = skd.getOU();
o = skd.getO();
l = skd.getL();
s = skd.getS();
c = skd.getC();
}
//
if (cn == null || cn.length() == 0)
{
log.severe("No Common Name (CN)");
return null;
}
if (ou == null || ou.length() == 0)
{
log.severe("No Organization Unit (OU)");
return null;
}
if (o == null || o.length() == 0)
{
log.severe("No Organization (O)");
return null;
}
if (c == null || c.length() == 0)
{
log.severe("No Country (C)");
return null;
}
// Escape commas
StringBuffer dname = new StringBuffer();
dname.append("CN=").append(escapeCommas(cn)); // common name
dname.append(", OU=").append(escapeCommas(ou)); // org unit
dname.append(", O=").append(escapeCommas(o)); // org
if (l != null && l.length() > 0)
dname.append(", L=").append(escapeCommas(l)); // locality
if (s != null && s.length() > 0)
dname.append(", S=").append(escapeCommas(s)); // state
dname.append(", C=").append(escapeCommas(c)); // country
return dname.toString();
} // getDname
/**
* Escape Commas
* @param in input string
* @return excaped string
*/
public static String escapeCommas(String in)
{
if (in == null || in.indexOf(",") == -1)
return in;
StringBuffer out = new StringBuffer();
char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++)
{
if (chars[i] == ',')
out.append('\\').append(',');
else
out.append(chars[i]);
}
return out.toString();
} // escapeCommas
/**
* Generate Key
* @param alias adempiere
* @param password password
* @param fileName key store file name (may have spaces)
* @param dname distinguished name
*/
public static void genkey (String alias, char[] password, String fileName, String dname)
{
StringBuffer cmd = new StringBuffer ("-genkey -keyalg rsa");
cmd.append(" -alias ").append(alias);
cmd.append(" -dname \"").append(dname).append("\"");
cmd.append(" -keypass ").append(password).append(" -validity 365");
if (fileName.indexOf(' ') != -1)
cmd.append(" -keystore \"").append(fileName).append("\" -storepass ").append(password);
else
cmd.append(" -keystore ").append(fileName).append(" -storepass ").append(password);
keytool (cmd.toString());
} // genkey
/**
* Generate Key
* @param alias adempiere
* @param password password
* @param fileName key store file name (may have spaces)
* @param dname distinguished name
*/
public static void selfcert (String alias, char[] password, String fileName, String dname)
{
StringBuffer cmd = new StringBuffer ("-selfcert");
cmd.append(" -alias ").append(alias);
cmd.append(" -dname \"").append(dname).append("\"");
cmd.append(" -keypass ").append(password).append(" -validity 180");
if (fileName.indexOf(' ') != -1)
cmd.append(" -keystore \"").append(fileName).append("\" -storepass ").append(password);
else
cmd.append(" -keystore ").append(fileName).append(" -storepass ").append(password);
keytool (cmd.toString());
} // selfcert
/**
* Submit Command to Key Tool
* @param cmd command
*/
public static void keytool(String cmd)
{
log.info("keytool " + cmd);
ArrayList<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(cmd, " ");
String quoteBuffer = null;
while (st.hasMoreTokens())
{
String token = st.nextToken();
// System.out.println("= " + token + " = quoteBuffer=" + quoteBuffer + " - Size=" + list.size() );
if (quoteBuffer == null)
{
if (token.startsWith("\""))
quoteBuffer = token.substring(1);
else
list.add(token);
}
else
quoteBuffer += " " + token;
if (token.endsWith("\""))
{
String str = quoteBuffer.substring(0, quoteBuffer.length()-1);
// System.out.println(" Buffer= " + str );
list.add(str);
quoteBuffer = null;
}
} // all tokens
//
String[] args = new String[list.size()];
list.toArray(args);
// System.out.println(" args #" + args.length);
KeyTool.main(args);
} // ketyool
/**
* Get Keystore File Name
* @param baseDir ADEMPIERE_HOME
* @return file name
*/
public static String getKeystoreFileName (String baseDir)
{
String fileName = baseDir;
if (fileName == null)
fileName = "";
else if (!fileName.endsWith(File.separator))
fileName += File.separator;
fileName += KEYSTORE_DIRECTORY + File.separator + KEYSTORE_NAME;
return fileName;
} // getKeystoreFileName
/**************************************************************************
* Test
* @param args ignored
*/
public static void main (String[] args)
{
Adempiere.startupEnvironment(true);
System.out.println(new KeyStoreMgt (
"C:/Adempiere/keystore/myKeystore2", "myPassword".toCharArray()).verify(null));
} // main
} // MyKeyStore
/******************************************************************************
* 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.install;
import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.Certificate;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import org.compiere.*;
import org.compiere.util.*;
import sun.security.tools.*;
/**
* Class to manage SSL KeyStore
*
* @author Jorg Janke
* @version $Id: KeyStoreMgt.java,v 1.3 2006/07/30 00:57:42 jjanke Exp $
*/
public class KeyStoreMgt
{
/**
* Constructor.
* @param fileName key store file name
* @param password - same password for key store and certificate
*/
public KeyStoreMgt (String fileName, char[] password)
{
log.info(fileName);
m_file = new File (fileName);
m_password = password;
} // KeyStoreMgt
/** Logger */
private static CLogger log = CLogger.getCLogger(KeyStoreMgt.class);
/** KeyStore File */
private File m_file = null;
/** KeyStore Password */
private char[] m_password = null;
/** KeyStore */
private KeyStore m_keyStore = null;
/** Directory below ADEMPIERE_HOME */
public static String KEYSTORE_DIRECTORY = "keystore";
/** Name of KeyStore */
public static String KEYSTORE_NAME = "myKeystore";
/** Certificate Alias */
public static String CERTIFICATE_ALIAS = "adempiere";
/**
* Verify/Create Key Store
* @param parent frame
* @return null or error message
*/
public String verify (JFrame parent)
{
KeyStore ks = null;
try
{
ks = getKeyStore();
}
catch (Exception e)
{
log.log(Level.SEVERE, "get KeyStore", e);
return e.getMessage();
}
// No KeyStore
if (ks == null)
{
createCertificate(CERTIFICATE_ALIAS, parent);
try
{
ks = getKeyStore();
}
catch (Exception e)
{
log.log(Level.SEVERE, "new KeyStore", e);
return e.getMessage();
}
} // new key store
// No KeyStore
if (ks == null)
return "No Key Store";
// Verify Certificate
Certificate cert = null;
try
{
cert = getCertificate(CERTIFICATE_ALIAS);
}
catch (Exception e)
{
log.log(Level.SEVERE, "certificate", e);
return e.getMessage();
}
if (cert == null)
return "No Certificate found";
return null; // OK
} // verify
/**
* Get KeyStore
* @return KeyStore or null
* @throws Exception
*/
public KeyStore getKeyStore() throws Exception
{
try
{
m_keyStore = KeyStore.getInstance("JKS");
}
catch (Exception e)
{
log.log(Level.SEVERE, "Instance", e);
}
// Load Existing
if (m_file.exists())
{
log.fine(m_file.toString());
InputStream is = null;
try
{
is = new FileInputStream (m_file);
}
catch (Exception e)
{
log.log(Level.SEVERE, "load", e);
return null;
}
m_keyStore.load(is, m_password);
}
else
return null; // does not exist
//
log.fine("Provider=" + m_keyStore.getProvider()
+ " - Type=" + m_keyStore.getType());
//
return m_keyStore;
} // getKeyStore
/**
* Get Certificate
* @param alias alias
* @return certificate or null
* @throws Exception
*/
public Certificate getCertificate (String alias) throws Exception
{
log.config("Alias=" + alias);
Date date = m_keyStore.getCreationDate(alias);
if (date == null) // no certificate
return null;
log.fine("Created=" + date);
//
Key key = m_keyStore.getKey(alias, m_password);
if (CLogMgt.isLevelFinest())
log.info("Key=" + key); // Multiple lines
else
log.fine(key.getAlgorithm());
//
Certificate cert = m_keyStore.getCertificate(alias);
if (CLogMgt.isLevelFinest())
log.info("Certificate = " + cert); // Multiple lines
else
log.fine(cert.getType());
// log.fine("Certificate - Type=" + cert.getType()
// + " - PublicKey=" + cert.getPublicKey());
return cert;
} // getCertificate
/**************************************************************************
* Create Certificate
* @param alias alias
* @param parent interactive dialog
*/
private void createCertificate (String alias, JFrame parent)
{
log.info("");
try
{
File dir = m_file.getParentFile();
if (!dir.exists())
dir.mkdir();
}
catch (Exception e)
{
log.log(Level.SEVERE, "directory", e);
}
String dname = getDname(parent);
if (dname == null)
return;
//
try
{
genkey (alias, m_password, m_file.getAbsolutePath(), dname);
selfcert (alias, m_password, m_file.getAbsolutePath(), dname);
}
catch (Exception e)
{
log.log(Level.SEVERE, "certificate", e);
}
} // createCertificate
/**
* Get Distinguised Name
* @param parent interactive dialog
* @return dname or null
*/
public static String getDname(JFrame parent)
{
String cn = null;
try
{
InetAddress address = InetAddress.getLocalHost();
cn = address.getCanonicalHostName();
}
catch (Exception e)
{
}
String ou = System.getProperty("user.name");
String o = "AdempiereUser";
String l = "MyTown";
String s = "";
String c = System.getProperty("user.country");
//
if (parent != null)
{
KeyStoreDialog skd = new KeyStoreDialog(parent,
cn, ou, o, l, s, c);
if (!skd.isOK())
return null;
cn = skd.getCN();
ou = skd.getOU();
o = skd.getO();
l = skd.getL();
s = skd.getS();
c = skd.getC();
}
//
if (cn == null || cn.length() == 0)
{
log.warning("No Common Name (CN)");
return null;
}
if (ou == null || ou.length() == 0)
{
log.warning("No Organization Unit (OU)");
return null;
}
if (o == null || o.length() == 0)
{
log.warning("No Organization (O)");
return null;
}
if (c == null || c.length() == 0)
{
log.warning("No Country (C)");
return null;
}
// Escape commas
StringBuffer dname = new StringBuffer();
dname.append("CN=").append(escapeCommas(cn)); // common name
dname.append(", OU=").append(escapeCommas(ou)); // org unit
dname.append(", O=").append(escapeCommas(o)); // org
if (l != null && l.length() > 0)
dname.append(", L=").append(escapeCommas(l)); // locality
if (s != null && s.length() > 0)
dname.append(", S=").append(escapeCommas(s)); // state
dname.append(", C=").append(escapeCommas(c)); // country
return dname.toString();
} // getDname
/**
* Escape Commas
* @param in input string
* @return excaped string
*/
public static String escapeCommas(String in)
{
if (in == null || in.indexOf(",") == -1)
return in;
StringBuffer out = new StringBuffer();
char[] chars = in.toCharArray();
for (int i = 0; i < chars.length; i++)
{
if (chars[i] == ',')
out.append('\\').append(',');
else
out.append(chars[i]);
}
return out.toString();
} // escapeCommas
/**
* Generate Key
* @param alias adempiere
* @param password password
* @param fileName key store file name (may have spaces)
* @param dname distinguished name
*/
public static void genkey (String alias, char[] password, String fileName, String dname)
{
StringBuffer cmd = new StringBuffer ("-genkey -keyalg rsa");
cmd.append(" -alias ").append(alias);
cmd.append(" -dname \"").append(dname).append("\"");
cmd.append(" -keypass ").append(password).append(" -validity 365");
if (fileName.indexOf(' ') != -1)
cmd.append(" -keystore \"").append(fileName).append("\" -storepass ").append(password);
else
cmd.append(" -keystore ").append(fileName).append(" -storepass ").append(password);
keytool (cmd.toString());
} // genkey
/**
* Generate Key
* @param alias adempiere
* @param password password
* @param fileName key store file name (may have spaces)
* @param dname distinguished name
*/
public static void selfcert (String alias, char[] password, String fileName, String dname)
{
StringBuffer cmd = new StringBuffer ("-selfcert");
cmd.append(" -alias ").append(alias);
cmd.append(" -dname \"").append(dname).append("\"");
cmd.append(" -keypass ").append(password).append(" -validity 180");
if (fileName.indexOf(' ') != -1)
cmd.append(" -keystore \"").append(fileName).append("\" -storepass ").append(password);
else
cmd.append(" -keystore ").append(fileName).append(" -storepass ").append(password);
keytool (cmd.toString());
} // selfcert
/**
* Submit Command to Key Tool
* @param cmd command
*/
public static void keytool(String cmd)
{
log.info("keytool " + cmd);
ArrayList<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(cmd, " ");
String quoteBuffer = null;
while (st.hasMoreTokens())
{
String token = st.nextToken();
// System.out.println("= " + token + " = quoteBuffer=" + quoteBuffer + " - Size=" + list.size() );
if (quoteBuffer == null)
{
if (token.startsWith("\""))
quoteBuffer = token.substring(1);
else
list.add(token);
}
else
quoteBuffer += " " + token;
if (token.endsWith("\""))
{
String str = quoteBuffer.substring(0, quoteBuffer.length()-1);
// System.out.println(" Buffer= " + str );
list.add(str);
quoteBuffer = null;
}
} // all tokens
//
String[] args = new String[list.size()];
list.toArray(args);
// System.out.println(" args #" + args.length);
//vpj-cd add support java 6
try
{
KeyTool.main(args);
}
catch (Exception e)
{
}
} // ketyool
/**
* Get Keystore File Name
* @param baseDir ADEMPIERE_HOME
* @return file name
*/
public static String getKeystoreFileName (String baseDir)
{
String fileName = baseDir;
if (fileName == null)
fileName = "";
else if (!fileName.endsWith(File.separator))
fileName += File.separator;
fileName += KEYSTORE_DIRECTORY + File.separator + KEYSTORE_NAME;
return fileName;
} // getKeystoreFileName
/**************************************************************************
* Test
* @param args ignored
*/
public static void main (String[] args)
{
Adempiere.startupEnvironment(true);
System.out.println(new KeyStoreMgt (
"C:/Adempiere/keystore/myKeystore2", "myPassword".toCharArray()).verify(null));
} // main
} // MyKeyStore