Cannot connect to oracle database - sqlexception

I am trying to connect to oracle database 12c using java in eclipse.
This is the exception that keeps getting caught.
Exception in thread "main" java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:666)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:566)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBHelper.makeConnection(DBHelper.java:31)
at Main.main(Main.java:37)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
at oracle.net.ns.NSProtocolStream.negotiateConnection(NSProtocolStream.java:246)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:264)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
... 7 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:161)
at oracle.net.nt.ConnOption.connect(ConnOption.java:159)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428)
... 13 more
Below is what i've done
main.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] arg) throws SQLException{
DBHelper dbconn = new DBHelper("system", "reborn78");
Connection conn = dbconn.makeConnection();
ResultSet result = dbconn.runQuery(conn, "SELECT A,B FROM NEWS");
System.out.println(result);
}
}
DBHelper.java
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBHelper {
private String userName;
private String passWord;
private final String url = "jdbc:oracle:thin:#localhost:1521/ORCL";
public DBHelper(String userName, String passWord) throws SQLException{
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
this.userName = userName;
this.passWord = passWord;
}
public Connection makeConnection() throws SQLException{
Properties props = new Properties();
props.setProperty("user", this.userName);
props.setProperty("password", this.passWord);
return DriverManager.getConnection(this.url,props);
}
public ResultSet runQuery(Connection conn, String sqlQuery) throws SQLException{
PreparedStatement preStatement;
ResultSet result;
Statement statement = conn.createStatement();
preStatement = conn.prepareStatement(sqlQuery);
statement.execute(sqlQuery);
result = preStatement.executeQuery();
return result;
}
}
below is my listener.ora file
# listener.ora Network Configuration File: E:\app\Usama\product\12.1.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = CLRExtProc)
(ORACLE_HOME = E:\app\Usama\product\12.1.0\dbhome_1)
(PROGRAM = extproc)
(ENVS = "EXTPROC_DLLS=ONLY:E:\app\Usama\product\12.1.0\dbhome_1\bin\oraclr12.dll")
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
)
below is my tnsnames.ora file
# tnsnames.ora Network Configuration File: E:\app\Usama\product\12.1.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.
LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(CONNECT_DATA =
(SID = CLRExtProc)
(PRESENTATION = RO)
)
)
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
SQL is connected using sqlplus and the listener running and connected to sql developer as well!
Below is the link to pictures
https://www.dropbox.com/sh/vbv0gkfcz2g59t5/AACtIVR1-bIen99DNN4HDsWaa?dl=0
I have wasted three days getting this right, i was able to get it to work yesterday but today when i restarted my system, the same error is back. I have tried everything available but nothing seems to work today.
Thanks in advance

SOLVED.
I was able to get it to run by re-configuring the database using database configuration assistant and then configuring the net services by net configuration assistant.
Turns out, as I understand, it is the only way to start the services needed to connect via a listener. I have to do it manually and test the net connection in the net configuration assistant every time i restart the system.
Thank you for your support.

Related

How to fix "No suitable driver found for jdbc:mysql//localhost:3306/gaming_site" error

I'm setting up a new database connection but ended with "java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/gaming_site" error!
Please help me to fix this!
I'm using mysql v8.0
Therefore I added mysql connector v8.0.12 in java build path's libraries
Code for establishing database connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String dbDriver = "com.mysql.jdbc.Driver";
String dbURL = "jdbc:mysql//localhost:3306/gaming_site";
String dbUserName = "root";
String dbPassword = "root";
Class.forName(dbDriver);
Connection con = DriverManager.getConnection(dbURL,dbUserName,dbPassword);
return con;
}
}
You're missing a colon in the JDBC URL:
jdbc:mysql://localhost:3306/gaming_site
^
Add this.
See the syntax at https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-jdbc-url-format.html

Apache calcite:parse failed: Encountered "from \""

I am currently attempting to connect mysql using calcite.
However, I had problems executing SQL statements
When I use this sql to excute,it works.
ResultSet resultSet = statement.executeQuery(
"select * from ex.depts");
But I would like to access a table named like this "primary_test",it failed.
Exception in thread "main" java.sql.SQLException: Error while executing SQL "select * from ex.primary_test": From line 1, column 15 to line 1, column 29: Object 'primary_test' not found within 'ex'
at org.apache.calcite.avatica.Helper.createException(Helper.java:56)
at org.apache.calcite.avatica.Helper.createException(Helper.java:41)
at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:163)
at org.apache.calcite.avatica.AvaticaStatement.executeQuery(AvaticaStatement.java:227)
at CalciteMysqlConnectionIns.main(CalciteMysqlConnectionIns.java:44)
Caused by: org.apache.calcite.runtime.CalciteContextException: From line 1, column 15 to line 1, column 29: Object 'primary_test' not found within 'ex'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.calcite.runtime.Resources$ExInstWithCause.ex(Resources.java:463)
at org.apache.calcite.sql.SqlUtil.newContextException(SqlUtil.java:787)
at org.apache.calcite.sql.SqlUtil.newContextException(SqlUtil.java:772)
at org.apache.calcite.sql.validate.SqlValidatorImpl.newValidationError(SqlValidatorImpl.java:4788)
at org.apache.calcite.sql.validate.IdentifierNamespace.resolveImpl(IdentifierNamespace.java:166)
at org.apache.calcite.sql.validate.IdentifierNamespace.validateImpl(IdentifierNamespace.java:177)
at org.apache.calcite.sql.validate.AbstractNamespace.validate(AbstractNamespace.java:84)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateNamespace(SqlValidatorImpl.java:977)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateQuery(SqlValidatorImpl.java:953)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateFrom(SqlValidatorImpl.java:3050)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateFrom(SqlValidatorImpl.java:3032)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateSelect(SqlValidatorImpl.java:3302)
at org.apache.calcite.sql.validate.SelectNamespace.validateImpl(SelectNamespace.java:60)
at org.apache.calcite.sql.validate.AbstractNamespace.validate(AbstractNamespace.java:84)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateNamespace(SqlValidatorImpl.java:977)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateQuery(SqlValidatorImpl.java:953)
at org.apache.calcite.sql.SqlSelect.validate(SqlSelect.java:216)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validateScopedExpression(SqlValidatorImpl.java:928)
at org.apache.calcite.sql.validate.SqlValidatorImpl.validate(SqlValidatorImpl.java:632)
at org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(SqlToRelConverter.java:556)
at org.apache.calcite.prepare.Prepare.prepareSql(Prepare.java:265)
at org.apache.calcite.prepare.Prepare.prepareSql(Prepare.java:231)
at org.apache.calcite.prepare.CalcitePrepareImpl.prepare2_(CalcitePrepareImpl.java:772)
at org.apache.calcite.prepare.CalcitePrepareImpl.prepare_(CalcitePrepareImpl.java:636)
at org.apache.calcite.prepare.CalcitePrepareImpl.prepareSql(CalcitePrepareImpl.java:606)
at org.apache.calcite.jdbc.CalciteConnectionImpl.parseQuery(CalciteConnectionImpl.java:229)
at org.apache.calcite.jdbc.CalciteMetaImpl.prepareAndExecute(CalciteMetaImpl.java:550)
at org.apache.calcite.avatica.AvaticaConnection.prepareAndExecuteInternal(AvaticaConnection.java:675)
at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:156)
... 2 more
Caused by: org.apache.calcite.sql.validate.SqlValidatorException: Object 'primary_test' not found within 'ex'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.calcite.runtime.Resources$ExInstWithCause.ex(Resources.java:463)
at org.apache.calcite.runtime.Resources$ExInst.ex(Resources.java:572)
... 30 more
I have used many different query like
ResultSet resultSet = statement.executeQuery(
"select * from ex.\"primary_test\"");
but it doesn't work.
Could someone help me with this question?
my code is like following:
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.apache.calcite.adapter.jdbc.JdbcSchema;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.commons.dbcp2.BasicDataSource;
public class CalciteMysqlConnectionIns {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.apache.calcite.jdbc.Driver");
Properties info = new Properties();
info.setProperty("lex", "JAVA");
Connection connection = DriverManager.getConnection("jdbc:calcite:", info);
CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = calciteConnection.getRootSchema();
// 本地Schema.
// Schema schema = ReflectiveSchema.create(calciteConnection, rootSchema, "hr",
// new HrSchema());
Class.forName("com.mysql.jdbc.Driver");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:mysql://192.168.130.7/hr");
dataSource.setUsername("root");
dataSource.setPassword("123456");
Schema schema = JdbcSchema.create(rootSchema, "ex", dataSource, null, "sql_learn");
rootSchema.add("ex", schema);
// System.out.println(calciteConnection.getMetaData());
DatabaseMetaData databaseMetaData = calciteConnection.getMetaData();
// ResultSet rs = databaseMetaData.getTables(null, null, "%", new String[]{"TABLE"});
Statement statement = calciteConnection.createStatement();
ResultSet resultSet = statement.executeQuery(
"select * from ex.\"primary_test\"");
output(resultSet, System.out);
resultSet.close();
statement.close();
connection.close();
}
private static void output(ResultSet resultSet, PrintStream out) throws SQLException {
final ResultSetMetaData metaData = resultSet.getMetaData();
final int columnCount = metaData.getColumnCount();
// out.println(metaData.getColumnLabel(1) + " " + metaData.getColumnLabel(2));
// out.println(metaData.getColumnTypeName(1) + " " + metaData.getColumnTypeName(2));
while (resultSet.next()) {
for (int i = 1; ; i++) {
out.print(resultSet.getString(i));
if (i < columnCount) {
out.print(", ");
} else {
out.println();
break;
}
}
}
}
}
you can try this:
select * from ex.`primary_test`

Unable to get the hive remote metastore table information over thrift

I can get the metastore table information on my local mysql metastore setup with hive using the below program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
public class MetaStoreTest {
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
HiveConf conf = new HiveConf();
conf.addResource(new Path("/home/hadoop/hive-0.12.0/conf/hive-site.xml"));
Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
conn = DriverManager.getConnection(
conf.getVar(ConfVars.METASTORECONNECTURLKEY),
conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
conf.getVar(ConfVars.METASTOREPWD));
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(
"select t.tbl_name, s.location from TBLS t " +
"join SDS s on t.sd_id = s.sd_id");
while (rs.next()) {
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
}
finally {
if (conn != null) {
conn.close();
}
}
}
}
Currently am trying the above program to get the metastore tables from a remote metastore using thrift.In my current hive-site.xml i have these params,
hive.metastore.uris = thrift://host1:9083, thrift://host2:9083
hive.metastore.local = false
There is no params for :
javax.jdo.option.ConnectionDriverName, javax.jdo.option.ConnectionUserName, javax.jdo.option.ConnectionPassword
So, how can i fetch the metatable information over thrift protocol. I am running the above code on host2. Please suggest.
Also when i run the above code, it shows information on :
METASTORE_CONNECTION_DRIVER as derby connection embedded driver,
METASTORECONNECTURLKEY as jdbc:mysql://<host name>/<database name>?createDatabaseIfNotExist=true,
METASTORE_CONNECTION_USER_NAME as "APP" and
METASTOREPWD as "mine"
replace this section of your code :
conf.addResource(new Path("/home/hadoop/hive-0.12.0/conf/hive-site.xml"));
Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
conn = DriverManager.getConnection(
conf.getVar(ConfVars.METASTORECONNECTURLKEY),
conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
conf.getVar(ConfVars.METASTOREPWD));
with the below :
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://host2:3306/metastore", "urusername", "urpassword");
[note :Change the metastore dbname, user and password accordingly as per your setup.]
now :
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("show tables");
while (rs.next()) {
System.out.println("Tables:" +rs.getString(1));
}
See are you getting the metastore table names or not.

SSL Server Exception: javax.net.ssl.SSLException

I am creating a SSL Server and Client in Java. The point of the program is to mimic a movie theater program. I can establish the connection but when I attempt to "reserve" a seat the program crashes. I get the following error:
Server aborted: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is my Server Code
// SSL Server
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class SSL_Server {
public static void main(String[] args) {
int port = 2018;
System.setProperty("javax.net.ssl.keyStore","mySrvKeystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = null;
System.out.println("SSL_Server started");
final ExecutorService threadPool = Executors.newCachedThreadPool();
try {
ssocket = ssocketFactory.createServerSocket(port);
InetAddress myIP =InetAddress.getLocalHost();
System.out.println(myIP.getHostAddress());
while(true){
Socket aClient = ssocket.accept();
//create a new thread for every client
threadPool.submit(new SSL_ClientHandler(aClient));
}
}
catch(Exception e) {
System.err.println("Server aborted:" + e);
} finally {
try{
ssocket.close();
} catch (Exception e){
System.err.println("could not close connection properly" + e);
}
}
System.out.println("connection was closed successfully");
}
}
The following is my client code
//SSL Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class TCP_Client {
public static void main(String[] args) throws IOException{
// SSL_Client newClient = new SSL_Client();
// Lock lock = new ReentrantLock();
boolean validInput = false;
BufferedReader din;
PrintStream pout;
int port = 2018;
BufferedReader stdinp = new BufferedReader(new InputStreamReader(System.in));
String line = "done";
StringTokenizer st;
String hostname;
String task = "done";
if(args.length>0)
hostname = args[0];
else
hostname = "localhost";
SocketFactory socketFactory = SSLSocketFactory.getDefault();
//Socket socket = socketFactory.createSocket(hostname, port);
while(true)
{
try{
//read input
while(!validInput)
{
System.out.println("Please enter a valid command or 'done' to finish.");
line = stdinp.readLine();
st = new StringTokenizer(line);
task = st.nextToken();
if(task.equals("reserve") || task.equals("search") || task.equals("delete") || task.equals("getinfo") || task.equals("done"))
{
validInput =true;
break;
}
System.out.println("Invalid command. Please enter another command or 'done' to escape.");
}
if(task.equals("done"))
{
break;
}
validInput = false;//reset for next line read in
//create a new socket every time
//Socket socket = new Socket(hostname, port);
Socket socket = socketFactory.createSocket(hostname, port);
din = new BufferedReader (new InputStreamReader (socket.getInputStream()));
pout = new PrintStream (socket.getOutputStream());
pout.println(line);
pout.flush();
//print out response from server
System.out.println(din.readLine());
} catch (Exception e){
System.err.println("Server aborted: " + e);
}
}
}
}
"Unable to find valid certification path to requested target" means that your truststore doesn't trust the server certificate. Import it into your truststore, or have it signed by a recognized CA.

How to use a JNDI Resource in a JAX-RS (Jersey) Application?

I'm trying to set up a connection to my database through a Tomcat JNDI resource. I've been looking at many articles today and I can't seem to find an answer.
In my server.xml I have:
<GlobalNamingResources>
<Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="tomcat" password="...."
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>
.....
</GlobalNamingResources>
In my web service, I attempt to access the resource with:
InitialContext ctx = new InitialContext();
DataSource data = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDB");
Connection conn = data.getConnection();
When I run the code, I get this exception:
Nov 2, 2011 1:06:20 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
...
I have the newest mysql-connector-java-5.1.18-bin.jar in both my web-app's lib and my tomcat lib.
Can you please help me get this working?
I use this code, with only the name of the resource, and it works:
private Connection getConnection(){
final Context ctx = new InitialContext();
final DataSource ds = (DataSource) ctx.lookup("jdbc/MyDB");
if (ds != null)
{
return ds.getConnection();
}
else
{
}
}
We just need to mention the jndi name after java:
In your case:
InitialContext ctx = new InitialContext();
DataSource data = (DataSource)ctx.lookup("java:/jdbc/MyDB");
Connection conn = data.getConnection();
Because you configured in your server.xml as below:
<GlobalNamingResources>
<Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="tomcat" password="...."
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>
.....
</GlobalNamingResources>
My solution was to switch to a properties file for the database information and then utilize it with entity manager.
import java.io.FileReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import org.eclipse.persistence.config.EntityManagerProperties;
import org.eclipse.persistence.config.PersistenceUnitProperties;
...
Properties properties = new Properties();
FileReader fr = new FileReader(Constants.Config.getPropertiesFile());
properties.load(fr);
// connect to the database
Map<String,String> emMap = new HashMap<String,String>();
emMap.put(PersistenceUnitProperties.APP_LOCATION, Constants.Config.getAppDir());
emMap.put(EntityManagerProperties.JDBC_USER, properties.getProperty("db.username"));
emMap.put(EntityManagerProperties.JDBC_PASSWORD, properties.getProperty("db.password"));
// iterate over these properties attempting to read them in and connect to the url
List<?> dbProps = Collections.list(properties.keys());
Collections.sort(dbProps, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(((String)o2));
}
});
for(Object propKey : dbProps){
// support multiple database key/values in the eform db.url, db.url1, ... db.urlN
if(!propKey.toString().matches("db.url\\d*")){
continue;
}
String dbLocation = properties.getProperty(propKey.toString());
try {
if(dbLocation == null) continue;
emMap.put(EntityManagerProperties.JDBC_URL, dbLocation);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("db", emMap);
em = entityManagerFactory.createEntityManager();
// ensure we're connected by executing a no-op query
em.createNativeQuery("select current_database()").getSingleResult(); // will only work for postgresql
properties.put("db.connected", dbLocation);
break;
}
catch (javax.persistence.PersistenceException e) {
Utility.logger(DataHolder.class).error("Couldn't connect to " + dbLocation);
}
}