I need to get the JDBC connection id(UUID) with Connection object. Is there is any way to get the connection id?
Well, if you meen "sql-connection to sql-server", then jdbc has no standard instruments for this. Here is handmade example for jdbc:mysql (beware - Reflection and restricted characters):
private long getJdbcConnectionId(Connection conn) {
long cid = 0;
try {
Field f_conn__conn = conn.getClass().getSuperclass().getDeclaredField("_conn");
f_conn__conn.setAccessible(true);
Object o_conn__conn = f_conn__conn.get(conn);
Field f_conn__conn__conn = o_conn__conn.getClass().getSuperclass().getDeclaredField("_conn");
f_conn__conn__conn.setAccessible(true);
Object o_conn__conn__conn = f_conn__conn__conn.get(o_conn__conn);
Field f_connectionId = o_conn__conn__conn.getClass().getSuperclass().getDeclaredField("connectionId");
f_connectionId.setAccessible(true);
cid = f_connectionId.getLong(o_conn__conn__conn);
f_connectionId.setAccessible(false);
f_conn__conn__conn.setAccessible(false);
f_conn__conn.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
return cid;
}
EDIT:
ok this way to avoid compile-time coupling, using reflection
import java.sql.Connection;
import java.sql.DriverManager;
...
public String getMysqlConnectionId()
{
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://host:3306/schema", "myuser", "mypassword");
Class<?> clazz = Class.forName("com.mysql.jdbc.MySQLConnection");
Object o = connection.unwrap(clazz);
return (String) clazz.getMethod("getId").invoke(o).toString();
} catch ( Exception e ) {
return e.getMessage();
}
}
By casting your java.sql.Connection object to com.mysql.jdbc.MySQLConnection and using getId()
import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.MySQLConnection;
...
public long getMysqlConnectionId()
{
Connection connection = DriverManager.getConnection("jdbc:mysql://host:3306/schema", "myuser", "mypassword");
// would throw a ClassCastException in case this is not a mysql one, of course
return ((MySQLConnection) connection).getId();
}
But this is sort of terribly coupling your project to MySQL at compile time
note: I won't be offended when I get down-voted for this, it is sort of deserved ;-)
<!-- pom.xml -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>x.y.z</version>
</dependency>
Some other people apparently are using connection.unwrap(com.mysql.jdbc.MySQLConnection) which might feels a bit more appropriate, yet does not remove the compile-time coupling to com.mysql
https://github.com/prestodb/presto/issues/9425
Here is my example how to get Oracle SID:
public int getConnectionSid() {
try {
if (connection == null || connection.isClosed())
return -1;
if (connectionSid == -1) {
try {
Method method = connection.getClass().getDeclaredMethod("getSessionId", null);
method.setAccessible(true);
connectionSid = (Integer)method.invoke(nativeConnection, null);
method.setAccessible(false);
} catch (NoSuchMethodException e) {
return -1;
} catch (IllegalAccessException e) {
return -1;
} catch (InvocationTargetException e) {
return -1;
}
}
return connectionSid;
} catch (SQLException e) {
return -1;
}
Related
I am trying to set up Dead Letter Queue monitoring for a system. So far, I can get it to be thrown in the DLQ queue without problems when the message consumption fails on the consumer. Now I'm having some trouble with getting the reason why it failed;
currently I get the following
java.lang.Throwable: Delivery[2] exceeds redelivery policy imit:RedeliveryPolicy
{destination = queue://*,
collisionAvoidanceFactor = 0.15,
maximumRedeliveries = 1,
maximumRedeliveryDelay = -1,
initialRedeliveryDelay = 10000,
useCollisionAvoidance = false,
useExponentialBackOff = true,
backOffMultiplier = 5.0,
redeliveryDelay = 10000,
preDispatchCheck = true},
cause:null
I do not know why cause is coming back as null. I'm using Spring with ActiveMQ. I'm using the DefaultJmsListenerContainerFactory, which creates a DefaultMessageListenerContainer. I would like cause to be filled with the exception that happened on my consumer but I can't get it to work. Apparently there's something on Spring that's not bubbling up the exception correctly, but I'm not sure what it is. I'm using spring-jms:4.3.10. I would really appreciate the help.
I am using spring-boot-starter-activemq:2.2.2.RELEASE (spring-jms:5.2.2, activemq-client-5.15.11) and I have the same behavior.
(links point to the versions I use)
The rollback cause is added here for the POSION_ACK_TYPE (sic!).
Its assignment to the MessageDispatch is only happening in one place: when dealing with a RuntimeException in the case there is a javax.jms.MessageListener registered.
Unfortunately (for this particular case), Spring doesn't register one, because it prefers to deal with its own hierarchy. So, long story short, there is no chance to make it happen with Spring out-of-the-box.
However, I managed to write an hack-ish way of getting an access to the MessageDispatch instance dealt with, inject the exception as the rollback cause, and it works!
package com.example;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import javax.jms.*;
public class MyJmsMessageListenerContainer extends DefaultMessageListenerContainer {
private final MessageDeliveryFailureCauseEnricher messageDeliveryFailureCauseEnricher = new MessageDeliveryFailureCauseEnricher();
private MessageConsumer messageConsumer; // Keep for later introspection
#Override
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
this.messageConsumer = super.createConsumer(session, destination);
return this.messageConsumer;
}
#Override
protected void invokeListener(Session session, Message message) throws JMSException {
try {
super.invokeListener(session, message);
} catch (Throwable throwable) {
messageDeliveryFailureCauseEnricher.enrich(throwable, this.messageConsumer);
throw throwable;
}
}
}
Note: don't deal with the Throwable by overriding the protected void handleListenerException(Throwable ex) method, because at that moment some cleanup already happened in the ActiveMQMessageConsumer instance.
package com.example;
import org.apache.activemq.ActiveMQMessageConsumer;
import org.apache.activemq.command.MessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import javax.jms.MessageConsumer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
class MessageDeliveryFailureCauseEnricher {
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryFailureCauseEnricher.class);
private final Map<Class<?>, Field> accessorFields = new HashMap<>();
private final Field targetField;
public MessageDeliveryFailureCauseEnricher() {
this.targetField = register(ActiveMQMessageConsumer.class, "deliveredMessages");
// Your mileage may vary; here is mine:
register("brave.jms.TracingMessageConsumer", "delegate");
register("org.springframework.jms.connection.CachedMessageConsumer", "target");
}
private Field register(String className, String fieldName) {
Field result = null;
if (className == null) {
logger.warn("Can't register a field from a missing class name");
} else {
try {
Class<?> clazz = Class.forName(className);
result = register(clazz, fieldName);
} catch (ClassNotFoundException e) {
logger.warn("Class not found on classpath: {}", className);
}
}
return result;
}
private Field register(Class<?> clazz, String fieldName) {
Field result = null;
if (fieldName == null) {
logger.warn("Can't register a missing class field name");
} else {
Field field = ReflectionUtils.findField(clazz, fieldName);
if (field != null) {
ReflectionUtils.makeAccessible(field);
accessorFields.put(clazz, field);
}
result = field;
}
return result;
}
void enrich(Throwable throwable, MessageConsumer messageConsumer) {
if (throwable != null) {
if (messageConsumer == null) {
logger.error("Can't enrich the MessageDispatch with rollback cause '{}' if no MessageConsumer is provided", throwable.getMessage());
} else {
LinkedList<MessageDispatch> deliveredMessages = lookupFrom(messageConsumer);
if (deliveredMessages != null && !deliveredMessages.isEmpty()) {
deliveredMessages.getLast().setRollbackCause(throwable); // Might cause problems if we prefetch more than 1 message
}
}
}
}
private LinkedList<MessageDispatch> lookupFrom(Object object) {
LinkedList<MessageDispatch> result = null;
if (object != null) {
Field field = accessorFields.get(object.getClass());
if (field != null) {
Object fieldValue = ReflectionUtils.getField(field, object);
if (fieldValue != null) {
if (targetField == field) {
result = (LinkedList<MessageDispatch>) fieldValue;
} else {
result = lookupFrom(fieldValue);
}
}
}
}
return result;
}
}
The magic happen in the second class:
At construction time we make some private fields accessible.
When a Throwable is caught, we traverse these fields to end up with the appropriate MessageDispatch instance (beware if you prefetch more than 1 message), and inject it the throwable we want to be part of the dlqDeliveryFailureCause JMS property.
I crafted this solution this afternoon, after hours of debugging (thanks OSS!) and many trials and errors. It works, but I have the feeling it's more of an hack than a real, solid solution.
With that in mind, I made my best to avoid side effects, so the worst that can happen is no trace of the original Throwable in the message ending in the Dead Letter Queue.
If I missed the point somewhere, I'b be glad to learn more about this.
I want to verify that session in JBoss 5 is still active and in logged in state. to implement a JWT (json web token).
for this, I need to get session by id.
to debug it: JBoss uses a special version of tomcat called JBoss web.
then I searched "jboss web 2* jar" and added it as source for sources to eclipse then I could debug it. also in eclipse, I have installed from eclipse marketplace FernFlower decompiler (* I took the actual version from https://developer.jboss.org/wiki/VersionOfTomcatInJBossAS)
I referenced those sources
how to refresh JSESSIONID cookie after login
https://github.com/auth0/java-jwt
my solution may help other pseudo tomcat serverlet servers
package com.mysoftware.controller.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mysoftware.util.SqlInjectionAndXSSRequestWrapper;
import com.mysoftware.model.User;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.jboss.seam.security.Identity;
import org.jboss.seam.web.ServletContexts;
import org.jboss.util.Base64;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
public class JWTAuthorization {
public static String isSessionIdLoggedIn(String requestedSessionId) {
try {
// get the request
HttpServletRequest request =ServletContexts.instance().getRequest();
ServletRequest serverletRequest = ((ServletRequestWrapper)request).getRequest();
// first need to unwrap the request until the core - org.apache.catalina.connector.Request.
// i had additional wrapper around the request SqlInjectionAndXSSRequestWrapper. (you probably wont have it)
// for simplicity i added SqlInjectionAndXSSRequestWrapper.request to my class, just saved the constructor argument.
SqlInjectionAndXSSRequestWrapper injectionRequest = (SqlInjectionAndXSSRequestWrapper) serverletRequest;
// code may start here, I run it and cast it and debug it and when I see it crash: "can't convert class x to y'. I understand which class it is and unwrap it accordingly.
RequestFacade requestFacade = (RequestFacade) injectionRequest.request;
Field catalinaRequestField;
//Getting actual catalina request using reflection
catalinaRequestField = requestFacade.getClass().getDeclaredField( "request" );
catalinaRequestField.setAccessible( true ); // grant access to (protected) field
Request realRequest = (Request)catalinaRequestField.get( requestFacade );
Manager manager = realRequest.getContext().getManager();
HttpSession session = null;
try {
session=(HttpSession) manager.findSession(requestedSessionId);
} catch (IOException var7) {}
if (session != null && !((Session) session).isValid()) {session = null;}
if (session != null) {((Session) session).access();} // mark usage
if (session != null && session.isNew()) return "new";
if (session != null )
{
Identity identity = (Identity)session.getAttribute("org.jboss.seam.security.identity");
if (identity != null && identity.isLoggedIn()) return "login";
}
return "not login";
} catch (Exception e1) {
e1.printStackTrace();
return "exception";
}
}
protected final static String sessionidencryptionkey="1234567890ghdg";
protected final static String jwtsecret="1234567890sdghsg";
public static String getTokenForCRM(User user)
{
try {
Algorithm algorithm = Algorithm.HMAC256(jwtsecret);
String token = JWT.create()
.withSubject(user.getId().toString())
.withArrayClaim("CRM", new String[]{ user.getAccount().getCrm() } )
.withClaim("SessionID", encrypt( ServletContexts.instance().getRequest().getSession().getId() , sessionidencryptionkey) )
.sign(algorithm);
return token;
} catch (Exception exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
return "ERROR_CREATEING_TOKEN";
}
public static String getSessionId(DecodedJWT token)
{
try {
return decrypt( token.getClaim("SessionID").asString() , sessionidencryptionkey) ;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
public static DecodedJWT verifyToken(String token)
{
try {
Algorithm algorithm = Algorithm.HMAC256(jwtsecret);
JWTVerifier verifier = JWT.require(algorithm)
//.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
return jwt;
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
return null;
}
public static String encrypt(String strClearText,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
byte[] encrypted=cipher.doFinal(strClearText.getBytes());
strData=new String(encrypted);
//strData=Base64.encodeBytes(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
public static String decrypt(String strEncrypted,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeyspec);
final byte[] strEncryptedBytes=strEncrypted.getBytes();
// final byte[] strEncryptedBytes==Base64.encode(strEncrypted)
byte[] decrypted=cipher.doFinal(strEncryptedBytes);
strData=new String(decrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
}
my testing code was.
inside a controller i had:
call it without wuery on different browsers,
then add parameter of the other session id in one of the browsers
#GET
#Path("testJWTSessionCheck")
#Produces("application/json")
public String testJWTSessionCheck( #QueryParam("s") String requestedSessionId) {
if(requestedSessionId!=null && requestedSessionId.length()>5) {
JWTAuthorization.isSessionIdLoggedIn(requestedSessionId);
}
HttpSession session1 = ServletContexts.instance().getRequest().getSession(false);
return session1.getId();
}
This code below creates JMS queue at run time in Wildfly 9.0.1 with no problem. In Wildfly 10 and 11 hornetq-server was replaced with activemq. How properly migrate it to Wildfly 10/11?
Thank you.
private boolean createQueue(String operationName, String queueName) {
boolean result = false;
ModelControllerClient client = qService.getModelControllerClient();
if(client != null){
ModelNode operation = new ModelNode();
ModelNode address = operation.get(ClientConstants.OP_ADDR);
address.add("subsystem", "messaging");
address.add("hornetq-server", "default");
address.add("jms-queue", queueName);
ModelNode entries = operation.get("entries");
entries.add("jms/queue/" + queueName);
operation.get(ClientConstants.OP).set(operationName);
try {
ModelNode returnVal = client.execute(operation);
return returnVal.get("outcome").asString().equalsIgnoreCase("success");
} catch (Exception e) {
DLOG.error(ExceptionUtils.getStackTrace(e));
} finally {
try {
client.close();
} catch (IOException ex) {
DLOG.error(ExceptionUtils.getStackTrace(ex));
}
}
}
return result;
}
With Wildfly 10 the JMS-Implementation changed from HornetQ to Apache ActiveMQ Artemis.The following example is tested with Wildfly 10.
You could prepare the command to create a queue like this:
public void createQueue() throws Exception {
ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9990);
if (client != null) {
ModelNode op = new ModelNode();
op.get(ClientConstants.OP_ADDR).add(ClientConstants.SUBSYSTEM, "messaging-activemq");
op.get(ClientConstants.OP_ADDR).add(ClientConstants.SERVER, "default");
op.get(ClientConstants.OP_ADDR).add("jms-queue", "HelloWorldQueue");
op.get("entries").add("queue/HelloWorldQueue");
op.get("entries").add("java:jboss/exported/queue/HelloWorldQueue");
op.get(ClientConstants.OP).set("add");
applyUpdate(op, client);
}
}
And execute the operation with this method:
private static void applyUpdate(ModelNode update, final ModelControllerClient client) throws IOException {
LOG.info("Execute: " + update.toString());
ModelNode result = client.execute(new OperationBuilder(update).build());
if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) {
if (result.hasDefined("result")) {
LOG.info(result.get("result").toString());
}
} else if (result.hasDefined("failure-description")) {
throw new RuntimeException(result.get("failure-description").toString());
} else {
throw new RuntimeException("Operation not successful; outcome = " + result.get("outcome"));
}
}
The code runs inside a WAR with the following maven dependency:
<dependency>
<groupId>org.wildfly.core</groupId>
<artifactId>wildfly-controller-client</artifactId>
<version>3.0.10.Final</version>
</dependency>
With Java EE 7 and JMS 2.0 there is as well the annotation #JMSDestinationDefinitions which allows automatic creation of JMS resources at deployment time. For some use cases this could already be good enough.
I am receiving an error that I did see on your site, but as a novice java coder I think that I flubbed my implementation of the solution.
I am getting a message
"SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3"
I am using Eclipse Mars 1
The database is a sql server 2000, so I downloaded sqljdbc.jar from the Microsoft site as suggested by an earlier question. I loaded it to c:\temp and added that to the CLASSPATH and rebooted.
code snippet reads:
package texasLAMPConversion;
import java.sql.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TexasLAMPConversion {
public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "jdbc:sqlserver://serverName\\instanceName";
String uName = "*********";
String uPass = "*********";
Connection conn = null;
try {
conn = DriverManager.getConnection(host, uName,uPass);
if (conn != null) { System.out.println("Connected to the database");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage() );
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
FileWriter fw= null;
File file =null;
try {
file=new File("C:/temp/generated_stmts_update_t_customer_master.sql");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
}catch (IOException e) {
e.printStackTrace();
}
String oldKey = "8000001234", newKey = "8";
int lenAcct = 10;
oldKey = ReformatOldAcct(lenAcct, oldKey );
newKey = leftZeroAcct(lenAcct, newKey);
System.out.println("oldkey = " + oldKey + " and newKey = " + newKey);
}
private static String ReformatOldAcct(int lenAcct, String oldKey) {
// TODO Auto-generated method stub
String reformatedAcct = "";
reformatedAcct = "0" + oldKey.substring(2, lenAcct);
return (reformatedAcct);
}
private static String leftZeroAcct(int lenAcct, String acctNo) {
// TODO Auto-generated method stub
int index =0;
int currentLengthAcct;
String leadingZero = "";
currentLengthAcct = acctNo.length();
while (index < (lenAcct -currentLengthAcct) ) {
leadingZero = '0' + leadingZero;
index ++;
}
return (leadingZero + acctNo);
}
}
and it is throwing this complete message
Apr 19, 2016 11:29:44 AM com.microsoft.sqlserver.jdbc.SQLServerConnection Prelogin
WARNING: ConnectionID:1 ClientConnectionId: 602d619d-c033-41d0-9109-80f56e3ab9b3 Server major version:8 is not supported by this driver.
Apr 19, 2016 11:29:44 AM com.microsoft.sqlserver.jdbc.SQLServerConnection Prelogin
WARNING: ConnectionID:1 ClientConnectionId: 602d619d-c033-41d0-9109-80f56e3ab9b3 Server major version:8 is not supported by this driver.
com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2226) at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2226)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2210)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2210)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.Prelogin(SQLServerConnection.java:2095)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.Prelogin(SQLServerConnection.java:2095)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1799)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1799)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1454)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1285)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1285)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1131)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1131)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at texasLAMPConversion.TexasLAMPConversion.main(TexasLAMPConversion.java:20)
at texasLAMPConversion.TexasLAMPConversion.main(TexasLAMPConversion.java:20)
SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3
SQL Server version 8 is not supported by this driver. ClientConnectionId:602d619d-c033-41d0-9109-80f56e3ab9b3
Any thoughts for a novice java programmer moving away from PowerBuilder?
I'm trying to develop an adf mobile app using jDeveloper and oracle sql developer.
I have connected jDev and sql. I want to populate selectOneChoice comp. that I m gonna fetch datas.
this is my connection method;
package salesorder.application;
import groovy.sql.Sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import oracle.adf.share.jndi.InitialContextFactoryImpl;
import oracle.adfmf.framework.api.AdfmfJavaUtilities;
import oracle.jbo.server.InitialContextImpl;
import oracle.jdbc.connector.OracleConnectionManager;
import oracle.jdbc.pool.OracleDataSource;
public class DBConnection {
public DBConnection() {
super();
}
private static String jdbcUrl = "jdbc:oracle:thin:#10.172.105.37:1521:VIS";
private static String userid = "***";
private static String password = "***";
protected static Connection conn = null;
public static Connection getConnection()throws Exception{
if (conn == null) {
try {
OracleDataSource ds; ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn=ds.getConnection(userid,password);
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
}
return conn;
}
}
and this, my method to fetch data;
private void Execute() {
Trace.log(Utility.ApplicationLogger, Level.INFO, Customers.class, "Execute",
"!!!!!!!!!!!!!!!!!In COUNTRY Execute!!!!!!!!!!!!!!!!!!!!!!!!!");
try{
Connection conn = DBConnection.getConnection();
customers.clear();
conn.setAutoCommit(false);
PreparedStatement stat= conn.prepareStatement("select cust_account_id,account_name from hz_cust_accounts_all where account_name is not null order by account_name asc");
// fetching customers name
ResultSet rs = stat.executeQuery();
Trace.log(Utility.ApplicationLogger, Level.INFO, Customers.class, "Execute",
"!!!!!!!!!!!!!!!!!Query Executed!!!!!!!!!!!!!!!!!!!!!!!!!");
while(rs.next()){
int id = rs.getInt("CUST_ACCOUNT_ID"); // customer id
String name = rs.getString("ACCOUNT_NAME"); // customer name
Customer c = new Customer(id,name);
customers.add(c);
}
rs.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
when i try to start application, an error comes up like that.
i cant use an image. so
Error
oracle.jdbc.pool.OracleDataSource
I dont know how Im gonna solve that, i cannot figure out why . Any help ?
Just to clarify - are you trying to use ADF Mobile (AMX pages)?
If so then you can't connect with JDBC to a remote database from the client.
You can only connect with JDBC to the local SQLite DB on your device.
To access data from remote servers you'll need to expose this data with web services and call those.