JDBC connection error - jdbc

I have created a JDBC Connection Pool in Glassfish and use it as a JDBC Resource "jdbc/__default". I can ping this connection pool successfully in the Administration Console interface.
Then, I am trying to run the following program:
package de.java2enterprise.onlineshop;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import javax.annotation.Resource;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
#WebServlet("/test")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// #Resource(name="jdbc/__default")
// private DataSource ds;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
writer.println("<!DOCTYPE html>");
writer.println("<html><body>");
Connection con = null;
DataSource ds;
try {
ds = (DataSource) InitialContext.doLookup("jdbc/__default");
con = ds.getConnection();
if (con.isValid(10)) {
writer.println("<BR>Connected!");
}
con.close();
} catch (Exception ex) {
writer.println(ex.getMessage());
} finally {
if (con != null){
try{
con.close();
} catch (Exception ex){
}
}
}
writer.println("<BR>Test finished!</body></html>");
writer.close();
}
}
However, then I receive the following error in the web browser:
Error in allocating a connection. Cause: Connection could not be allocated because: Listener refused the connection with the following error: ORA-12518, TNS:listener could not hand off client connection
Test finished!
In the server log, I get the following error:
2015-04-08T08:15:20.540+0200|Information: Loading application [onlineshop#onlineshop-war.war] at [onlineshop-war]
2015-04-08T08:15:20.636+0200|Information: onlineshop was successfully deployed in 611 milliseconds.
2015-04-08T08:15:38.552+0200|Warnung: Context path from ServletContext: /onlineshop-war differs from path from bundle: onlineshop-war
2015-04-08T08:15:38.802+0200|Information: visiting unvisited references
2015-04-08T08:15:39.519+0200|Information: Successfully got INSTRUMENTATION: sun.instrument.InstrumentationImpl#2d618042
2015-04-08T08:15:41.471+0200|Warnung: RAR5038:Unexpected exception while creating resource for pool Onlineshop. Exception : javax.resource.spi.ResourceAllocationException: Connection could not be allocated because: Listener refused the connection with the following error:
ORA-12516, TNS:listener could not find available handler with matching protocol stack
2015-04-08T08:15:41.471+0200|Warnung: RAR5117 : Failed to obtain/create connection from connection pool [ Onlineshop ]. Reason : com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: Listener refused the connection with the following error:
ORA-12516, TNS:listener could not find available handler with matching protocol stack
2015-04-08T08:15:41.486+0200|Warnung: RAR5114 : Error allocating connection : [Error in allocating a connection. Cause: Connection could not be allocated because: Listener refused the connection with the following error:
ORA-12516, TNS:listener could not find available handler with matching protocol stack
]
After that, I can not ping the connection pool again and receive more or less the same error in the Administration Console.
I use the following configuration: JDK 1.8.0_25, GlassFish Server Open Source Edition 4.1 (build 13), Oracle Database XE 11.2.
In Glassfish administration console, I've created the following JDBC Resource: JNDI Name: jdbc/__default, Logical JNDI Name: java:comp/DefaultDataSource, Connection Pool: Onlineshop.
The JDBC Connection Pool Name is Onlineshop, Resource Type: javax.sql.DataSource, Classname: oracle.jdbc.pool.OracleDataSource.
I've a minimal pool size of 800 connections, maximum of 3200 connections. The other parameters I've kept as they were, I've only added user and password at JDBC Connection Pool Properties.
Anyone an idea? :-)

Close your connection in a finally block or in try-with-resources if you use jdk7+ as it should be done in Java. See if it helps

Related

Oracle Database JDBC driver cannot read wallet file from Spark

Objective
I'm trying to write to Oracle's ADWC (basically oracle database) from a Spark application running on Yarn. The only way to connect to this database is by using an Oracle Wallet file, which is basically a Java keystore.
Problem
The problem arises when the JDBC driver tries to read the wallet from HDFS. If I include the hdfs:// prefix the parser in the JDBC driver throws an error and if I don't then it cannot find the file.
Previous Attempts
including the directory in the connect string (prefixed and non) jdbc:oracle:thin:#luigi_low?TNS_ADMIN=/user/spark/wallet_LUIGI
including the directory as an spark.driver.extraJavaOptions with -Doracle.net.tns_admin and -Doracle.net.wallet_location
All the code is on GitHub, and specifically, the error messages are here https://github.com/sblack4/kafka-scala-jdbc/blob/master/ERROR.md
I've got a working example of the same connection here https://github.com/sblack4/scala-jdbc-adwc
help me StackOverflow. you are my only hope
If you need any more clarification don't hesitate :)
update (SparkFiles attempt)
the code is on a separate branch of the same repository, https://github.com/sblack4/kafka-scala-jdbc/tree/sparkfiles
This error message mystifies me as it seems my JDBC library has stopped trying to read the wallet files. It may be unrelated to the previous problem
Exception in thread "main" java.sql.SQLRecoverableException: IO Error: Invalid connection string format, a valid format is: "host:port:sid"
I've deleted the other JDBC libraries from my classpath through Ambari as this error could be related to spark picking up an older version of my JDBC library
Here's some code that will help diagnose what the issues is.
It checks and configures everything required to connect.
JDBC Driver version
JCE Installed
Classpath dependencies
Configures
tns_admin
ssl settings
trust/key stores
This is a slimmed down version of what's in sqldev/sqlcl
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Properties;
import javax.crypto.Cipher;
import oracle.jdbc.OracleConnection;
public class JDBCTest {
public static void fail(String msg){
System.err.println(String.join("", Collections.nCopies(20, "*")));
System.err.println(msg);
System.err.println(String.join("", Collections.nCopies(20, "*")));
System.exit(1);
}
public static void main(String[] args) throws SQLException {
System.out.println("JDBC Driver Version:" + oracle.jdbc.OracleDriver.getDriverVersion());
// Check JDBC Driver Version
if (!oracle.jdbc.OracleDriver.getDriverVersion().startsWith("18.")) {
fail(" DRIVER TOOO OLD!!!");
}
// Check JCE Installed
int maxKeySize = 0;
try {
maxKeySize = Cipher.getMaxAllowedKeyLength("AES");
} catch (NoSuchAlgorithmException e) {
}
if (maxKeySize < 129 ) {
fail(" JCE Policy not unlimited!!!");
}
// Check Classpath
String cp = System.getProperty("java.class.path");
String[] cpFiles = {"ojdbc8.jar","oraclepki.jar","osdt_cert.jar","osdt_core.jar"};
for (String file:cpFiles){
if ( cp.indexOf(file) == -1 ){
fail("CLASSPATH Missing:" + file);
}
}
// Wallet unziped location
String unzippedWalletLocation = "/Users/klrice/workspace/12.2JDBC/wallet";
String conString = "jdbc:oracle:thin:#sqldev_medium";
Properties props = new Properties();
props.setProperty("oracle.net.wallet_location",unzippedWalletLocation);
props.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_NET_CONNECT_TIMEOUT, "2000");
// unzipped includes a tnsnames.ora
props.setProperty("oracle.net.tns_admin",unzippedWalletLocation);
props.setProperty("javax.net.ssl.trustStore","truststore.jks");
props.setProperty("javax.net.ssl.trustStorePassword","<password>");
props.setProperty("javax.net.ssl.keyStore","keystore.jks");
props.setProperty("javax.net.ssl.keyStorePassword","<password>");
props.setProperty("oracle.net.ssl_server_dn_match","true");
props.setProperty("oracle.net.ssl_version","1.2");
props.setProperty("user", "ADMIN");
props.setProperty("password", "<password>");
try {
// now Connect
Connection conn = DriverManager.getConnection(conString,props);
} catch (Exception e){
e.printStackTrace();
fail(e.getLocalizedMessage());
}
System.out.println("SUCCESS!!");
}
}
Are you using 18.3 JDBC drivers? Passing TNS_ADMIN as part of the connection URL requires 18.3 JDBC driver. Also, are you attempting to connect within the corporate network. In that case, you will need to pass HTTPS_PROXY and HTTPS_PROXY_PORT in the connection URL. Let us know. Happy to help with the problem.

phoenix jdbc doesn't work, no exceptions and stuck

I'm new to phoenix and hbase.hbase table and phoenix view works well and i can fetch data through phoenix. when I access jdbc to phoenix,it stucks.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Phoenix {
private static String driver = "org.apache.phoenix.jdbc.PhoenixDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Statement stmt = null;
ResultSet rs = null;
System.out.println("start...");
Connection con = DriverManager.getConnection("jdbc:phoenix:[my_cloud_server_ip]:2181");
System.out.println(con);
con.close();
}
}
(only one zookeeper server has public internet ip,so i write this ip there,does it matters?)
it prints "start..." and no response any more
BUT when when the url is "jdbc:phoenix:ip:2181" or "jdbc:phoenix:ip:2181/hbase"
i got no response
when i add some other words ,for example "jdbc:phoenix:ip:2181/balabala"
i got NULL POINTER EXCEPTION
why ?
I hope u can understand what i say:)
Reproducing your example, I am getting a java.net.SocketTimeoutException after 60 seconds, caused by java.net.UnknownHostException: unknown host: <hostname_of_my_zk_server>. But maybe that's what you called "no response" if you were in a hurry (or if you have a custom hbase-site.xml with a larger timeout client-side).
This error seems like the one explained in this article (section Zookeeper at the end) :
As in our case CDH was running in a test VM, we encountered this issue: http://stackoverflow.com/questions/18428722/hbase-java-client-unknown-host-localhost-localdomain
That was worked around by adding localhost.localdomain to the existing /etc/hosts entry for cluster1, which was already pointing to the right IP address.
This answer on SO summarizes the solution.
Basically, you need to add an entry to your /etc/hosts client-side :
<my_cloud_server_ip> <hostname_of_my_cloud_server_ip>
Moreover, you need to have an hbase-site.xml client-side (you can use the one on your server as a basis).

Connection is not established between Eclipse Paho and IBM Websphere MQ

I am novice user to IBM MQ. Basically I want to establish the connection between Client(Eclipse Paho) and IBM MQ Queue Manager.
I have performed the following steps:
I have installed the IBM MQ v.9.0
Created a Queue Manager
Started a Queue Manager as a service with the port number(1414)
Create a Server channel and assigns this with created Queue Manager.
At Client side:
Downloadd Eclipse Paho, which is MQTT Java client.
try to small program to connect with started Queue Manager.
Followinig is the program.
import java.util.logging.Logger;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MQMTTFactory {
private static Logger log = Logger.getLogger(MQMTTFactory.class.getName());
private MQMTTFactory() {
}
static final String BROKER_URL = "tcp://<<Ipaddress>>:1234";
static final String M2MIO_DOMAIN = "<Insert m2m.io domain here>";
static final String M2MIO_STUFF = "things";
static final String M2MIO_USERNAME = "Guest";
static final String M2MIO_PASSWORD_MD5 = "<m2m.io password (MD5 sum of password)>";
static MqttClient myClient = null;
public static MqttClient getMqttClient() {
MqttConnectOptions connOpt;
if (myClient == null) {
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(true);
connOpt.setKeepAliveInterval(3000);
connOpt.setUserName(M2MIO_USERNAME);
// connOpt.setPassword(M2MIO_PASSWORD_MD5.toCharArray());
// Connect to Broker
try {
myClient = new MqttClient(BROKER_URL,
MqttAsyncClient.generateClientId(), new MemoryPersistence());
myClient.connect(connOpt);
} catch (MqttException e) {
log.severe("Client connection to the MQTT Broker is failed");
e.printStackTrace();
System.exit(-1);
}
}
return myClient;
}
}
But the above program is failed to establish the connection with the server.
the following is the error while running the above program.
Unable to connect to server (32103) - java.net.ConnectException: Connection refused: connect
Could any body tell me what might be the wrong? or Any suggestions.
The Eclipse Paho client only works with the MQTT Protocol. This is a topic based pub/sub protocol and does not support Message Queues.
While IBM-MQ can support MQTT it is not enabled by default.
I suggest you read the following 2 articles to get a better understanding
https://www.ibm.com/developerworks/community/blogs/aimsupport/entry/what_is_mqtt_and_how_does_it_work_with_websphere_mq?lang=en
https://www.ibm.com/support/knowledgecenter/en/SS9D84_1.0.0/com.ibm.mm.tc.doc/tc00110_.htm

Unable to connect to database through Eclipse

I have been trying to run this code for hours, to get no success. I have Oracle 11g Enterprise Edition. Does anyone know the code to get port number from sql * plus cmd prompt?
The code doesn't run and I am not able to view the output over eclipse. Please guide me.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Testt {
public static void main(String[] args) throws Exception {
try{
//Driver registration
Class.forName("oracle.jdbc.driver.OracleDriver");
//Create connection
Connection c =DriverManager.getConnection("jdbc:oracle:thin:
#localhost:1521:EE","scott","tiger");
//Create statement
Statement stmt=c.createStatement();
//Execute query
ResultSet rs=stmt.executeQuery("select * from emp;");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
c.close();
}
catch(Exception e){e.printStackTrace();}
}
}
Output:
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

SQL exception while creating connection to SQL Server using jdbc

I am getting the following error while creating a connection to SQL Server using jdbc. THe error is :
java.sql.SQLException: No suitable driver found for jdbc:sqlserver//D-PC//SQLEXPRESS;integratedSecurity=true
Failed to make connection!
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement;
/** * * #author Jatin */ public class SQLConnect {
public Connection sqlcon(Connection conn){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
Statement stmt = null;
try{
conn = DriverManager.getConnection("jdbc:sqlserver//D-PC//SQLEXPRESS;integratedSecurity=true");
stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE Students");
System.out.println("Database Created");
}
catch(SQLException e){
e.printStackTrace();
}
if (conn != null) { System.out.println("You made it, take control your database now!"); } else { System.out.println("Failed to make connection!"); }
return(conn);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con =null;
SQLConnect sqlcon = new SQLConnect();
con = sqlcon.sqlcon(con);
}
}
The connection to the host GUNA, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:237)
how to resolve this

Resources