im trying to connect my java to db2 database but im getting an error :
"Execution failed due to a distribution protocol error that will affect the successful execution of subsequent DDM commands or SQL statements.
A connection could not be established to the database because manager 0x2407 at level 0x3 is not supported."
What do you think im doing wrong? Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class conUrl {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://host:50000/test";
String user="dbuser";
String password="passwrod";
Connection connection = null;
//Statement st = null;
//Result rs = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Related
I'm working on migrating my existing EJB application from Jersey 1.x to 2.x. facing many challenges related to EJB and JMS queue concepts. I'm facing an Null pointer exception when the below code is executed.
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
public class SessionImpl implements SessionLocal {
#Resource(mappedName = "java:/RemoteJmsXA")
private QueueConnectionFactory queueConnectionFactory;
#Inject
private ConvRequestSessionLocal convRequestSession;
private RequestSessionLocal asyncSession;
#PostConstruct
public void initialize() {
QueueConnection connection = null;
QueueSession queueSession = null;
try {
connection = queueConnectionFactory.createQueueConnection();
queueSession = connection.createQueueSession(true, QueueSession.SESSION_TRANSACTED);
asyncSession = AsyncUtils.mixinAsync(convRequestSession);
} catch (JMSException e) {
LOG.error("Error ocurred while connecting to remote queues. " + e.getLocalizedMessage());
throw new RuntimeException("Error occured while connecting to remote queues.", e);
} finally {
try {
if (queueSession != null) {
queueSession.close();
}
if (connection != null) {
connection.close();
}
} catch (JMSException e) {
LOG.error("Error occured while closing connection to remote queues. " + e.getLocalizedMessage());
}
}
}
}
Exception:
2017-01-18 20:08:44,317 WARNING [org.glassfish.jersey.internal.Errors] (http-127.0.0.1-8080-4) The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 2
java.lang.NullPointerException
at com.ejb.session.impl.SessionImpl.initialize(SessionImpl.java:809)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
stack trace shows that exception throws exactly in this line
connection = queueConnectionFactory.createQueueConnection();
I have a problem with syntax SQL. When i mvn jetty:run then occur following error:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "user" at
line 1, co lumn 14.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknow
n Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source
)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException
(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Un
known Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown So
urce)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown So
urce)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
reateTableNotExist(CustomContextLoaderListener.java:68)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
reateTable(CustomContextLoaderListener.java:48)
at edu.java.spring.service.user.controller.CustomContextLoaderListener.c
ontextInitialized(CustomContextLoaderListener.java:36)
Here file CustomContextLoaderListene which encouter error:
package edu.java.spring.service.user.controller;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import org.springframework.web.context.ContextLoaderListener;
public class CustomContextLoaderListener extends ContextLoaderListener{
#Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("hibernate shutdown database");
try {
DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/userdb;shutdown=true");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n Spring-MVC application destroyed \n");
super.contextDestroyed(event);
}
#Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("\n Spring-MVC application inited \n");
try {
createTable();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.contextInitialized(event);
}
public void createTable() throws SQLException{
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection connection = DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/subjectdb;create=true");
createTableNotExist(connection,"user", "create table user"
+ "(username varchar(1000) primary key,"
+ "password varchar(1000),birthday date,"
+ "age integer,gender varchar(100))");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createTableNotExist(Connection connection,
String tableName,String createTableSQL) throws SQLException{
DatabaseMetaData dbmd = connection.getMetaData();
ResultSet rs = dbmd.getTables(null, null,tableName.toUpperCase(), null);
if (rs.next()){
System.out.println("Table" + rs.getString("TABLE_NAME") + "already exists");
return;
}
Statement statement = connection.createStatement();
statement.execute(createTableSQL);
System.out.println("\n\n executed" + createTableSQL + "\n\n");
statement.close();
}
}
"user" it is a built-in function in derby. Enter another table name and it should start work
I have activemq5.3.2 running and I wanted to subscribe existing advisory topics using my java program. while, `jndi` lookup I am getting following error:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:657)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:259)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:296)
at javax.naming.InitialContext.lookup(InitialContext.java:363)
at jmsclient.Consumer.<init>(Consumer.java:38)
at jmsclient.Consumer.main(Consumer.java:74)
Exception occurred: javax.jms.InvalidDestinationException: Don't understand null destinations
Please suggest where the problem is, or how could I use my topic name to look for?
package jmsclient;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Consumer implements MessageListener {
private static int ackMode;
private static String clientTopicName;
private boolean transacted = false;
//private MessageConsumer messageConsumer;
static {
clientTopicName = "ActiveMQ.Advisory.Consumer.Queue.example.A";
ackMode = Session.AUTO_ACKNOWLEDGE;
}
#SuppressWarnings("null")
public Consumer()
{// TODO Auto-generated method stub
TextMessage message = null;
Context jndiContext;
//TopicConnectionFactory topicConnectionFactory = null;
TopicConnection topicConnection = null;
TopicSession topicSession = null;
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://usaxwas012ccxra.ccmp.ibm.lab:61616");
try{
Topic myTopic = null;
try { jndiContext = new InitialContext();
myTopic = (Topic) jndiContext.lookup(clientTopicName);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
topicConnection = connectionFactory.createTopicConnection();
topicConnection.start();
topicSession = topicConnection.createTopicSession(transacted, ackMode);
TopicSubscriber topicSubscriber = topicSession.createSubscriber(myTopic);
Message m = topicSubscriber.receive(1000);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " + message.getText());
}
}
} //try ends
catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
} finally {
if (topicConnection != null) {
try {
topicConnection.close();
} catch (JMSException e) {}
}}}
public void onMessage(Message arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new Consumer();
}
}
When I use Windows to run eclipse Android emulator to connect socket,it was successful.
However, when I use Mac os lion to run the "Same" code ,the emulator shows"unfortunately
client test was stop!!"please help me solve this.And I already add the permission to internet!
package com.example.testclientokok;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Socket socket=new Socket(InetAddress.getLocalHost(), 8888);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
server part
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
If I understand correctly, you are executing MyServer on your machine, where you also run the emulator. If the Activity running in the emulator wants to establish a connection with MyServer, then it should use the following IP address : 10.0.2.2 (and not localhost, which references the emualor loopback interface).
See http://developer.android.com/tools/devices/emulator.html#networkaddresses
THE PROBLEM
Simple sql that returns about 500 rows takes:
40 ms in Toad (this return the first 500 rows)
500-600 ms in Java with connection obtained from an instance of
oracle.jdbc.pool.OracleDataSource class.
2100-2500 ms in Java with connection obtained from the data
source configured in Weblogic on looked up via JNDI
The above timings exclude getting the connection instance.
Problem: slow performance of option 3. Why? How can it be made more reasonable?
THE SETUP
Weblogic 10.3.5
Oracle 11g RDMBS
THE TEST CODE
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.pool.OracleDataSource;
import Facility;
import BrowserSQL;
public class JDBCTest {
public static Connection conn;
public static Connection getConnection(){
String url= "localhost:1521:testdb";
String usr="test";
String pswd="test";
Connection conn = null;
try {
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:#" + url);
ods.setUser(usr);
ods.setPassword(pswd);
conn = ods.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static Connection getConnectionWeblogicJndi(){
Connection conn = null;
try {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
Context ctx = new InitialContext(ht);
DataSource ods = (DataSource)ctx.lookup("jdbc/test");
conn = ods.getConnection();
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
return conn;
}
//get the next val from given sequence.
public static void runQuery(Connection conn, String sql){
ResultSet rs=null;
Statement stmt=null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){}
}catch(SQLException ex){
ex.printStackTrace();
}
finally{
close(rs,stmt,conn);
}
}
public static void close(ResultSet rs, Statement ps, Connection conn){
if (rs!=null) {
try { rs.close(); } catch(SQLException ex) { ex.printStackTrace(); }
}
if (ps != null) {
try { ps.close(); } catch (SQLException ex) { ex.printStackTrace(); }
}
if(conn !=null){
try{ conn.close(); }catch(SQLException ex){ ex.printStackTrace(); }
}
}
public static void main(String[]arg) throws SQLException {
//Connection conn = JDBCTest.getConnectionWeblogicJndi();
Connection conn = JDBCTest.getConnection();
((OracleConnection)conn).setDefaultRowPrefetch(1000);
long a = GregorianCalendar.getInstance().getTimeInMillis();
System.out.println("Stating testGetAllFacilityByQuery..."+a);
runQuery(conn, BrowserSQL.getAllFacilities());
long b = GregorianCalendar.getInstance().getTimeInMillis();
System.out.println("End testGetAllFacilityByQuery..."+b + " -------- total time: "+(b-a)+" ms");
}
}