No suitable driver found for ucanaccess - java

I've a .mdb access file and I'm indexing the datas to my solr core. I wrote this java class to index them in solr core. When I'm running this java class as java application, it works fine but when I'm running server side it's not working.
package org.solr;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.applet.*;
import java.awt.*;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.CoreAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.CoreAdminResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CollectionAdminParams;
import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.ContentStreamBase.ByteArrayStream;
import org.apache.solr.handler.dataimport.DateFormatTransformer;
import org.apache.solr.schema.DateValueFieldType;
public class dbJava {
public void main(String args[]) throws SolrServerException, IOException {
Statement state;
Connection connect;
try {
connect = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\FTK1187\\Desktop/eArchiveMaster.mdb","FTEC198","");
state = connect.createStatement();
ResultSet rs = state.executeQuery("SELECT * FROM TableArchive ORDER BY ID" );
//System.out.println(count);
String urlString="http://localhost:8983/solr/archiveCore";
HttpSolrClient solr=new HttpSolrClient.Builder(urlString).build();
((HttpSolrClient) solr).setParser(new XMLResponseParser());
//SolrInputDocument document=new SolrInputDocument();
final String contentStream = "extract this text ...";
final String contentType = "text/csv;charset=UTF-8";
final ByteArrayStream byteArrayStream = new ByteArrayStream(contentStream.getBytes(StandardCharsets.UTF_8), null);
byteArrayStream.setContentType(contentType);
final ModifiableSolrParams modifiableSolrParams = new ModifiableSolrParams();
modifiableSolrParams.add(CollectionAdminParams.COLLECTION, "archiveCore");
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
req.addContentStream(byteArrayStream);
req.setParams(modifiableSolrParams);
req.setMethod(METHOD.POST);
solr.deleteByQuery("*");
solr.commit();
long startTime=System.nanoTime();
while(rs.next()){
req.setParam("literal.id", String.valueOf(rs.getInt("ID")));
req.setParam("literal.NameAdded", String.valueOf(rs.getString("NameAdded")));
req.setParam("literal.DateAdded", String.valueOf(rs.getString("DateAdded")));
req.setParam("literal.NameModified", String.valueOf(rs.getString("NameModified")));
req.setParam("literal.DateModified", String.valueOf(rs.getString("DateModified")));
req.setParam("literal.strSO", String.valueOf(rs.getString("strSO")));
req.setParam("literal.strCust", String.valueOf(rs.getString("strCust")));
req.setParam("literal.strOperator", String.valueOf(rs.getString("strOperator")));
req.setParam("literal.PackName", String.valueOf(rs.getString("PackName")));
req.setParam("literal.DocName", String.valueOf(rs.getString("DocName")));
req.setParam("literal.DocType", String.valueOf(rs.getString("DocType")));
req.setParam("literal.extType", String.valueOf(rs.getString("extType")));
req.setParam("literal.FileName", String.valueOf(rs.getString("FileName")));
req.setParam("literal.FilePath", String.valueOf(rs.getString("FilePath")));
req.setParam("literal.NameDeleted", String.valueOf(rs.getString("NameDeleted")));
req.setParam("literal.DateDeleted", String.valueOf(rs.getString("DateDeleted")));
req.setParam("literal.intRev", String.valueOf(rs.getString("intRev")));
solr.request(req);
}
long endTime=System.nanoTime();
long totalTime=endTime-startTime;
System.out.println("Done...");
System.out.println(totalTime);
String urlReload="http://localhost:8983/solr";
HttpSolrClient solr_reload=new HttpSolrClient.Builder(urlReload).build();
CoreAdminRequest adminRequest=new CoreAdminRequest();
adminRequest.setAction(CoreAdminAction.RELOAD);
adminRequest.setCoreName("archiveCore");
adminRequest.process(solr_reload);
}
catch(IOException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I want to run this java class in my.jsp page using jquery. When I'm clicking the update button it gives me this error.
java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://C:\Users\FTK1187\Desktop/eArchiveMaster.mdb
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.solr.dbJava.main(dbJava.java:60)
at org.apache.jsp.upload_jsp._jspService(upload_jsp.java:124)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Is there any mistake or something?? How can I call the java class in my .jsp file?

You have to move the Driver in the JRE/lib/ext

Related

How to resolve the error java.lang.NoSuchMethodError: com.amazonaws.SDKGlobalConfiguration.isInRegionOptimizedModeEnabled()Z?

I am trying to upload a file to S3 and getting error like
Target exception: java.lang.NoSuchMethodError:
com.amazonaws.SDKGlobalConfiguration.isInRegionOptimizedModeEnabled()Z
Code is
String accessKey="accesskey";
String secretKey="mysecretkey"
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 conn = new AmazonS3Client(credentials);
In the line of AmazonS3 conn = new AmazonS3Client(credentials); I am getting the target exception.
Totally I imported these many java packages showing below. still getting the same error.
import java.io.File;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.List;
import com.amazonaws.auth.*;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.util.StringUtils;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.services.s3.*;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.AmazonS3Builder;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.ClientConfigurationFactory;
import com.amazonaws.annotation.NotThreadSafe;
import com.amazonaws.annotation.SdkTestInternalApi;
import com.amazonaws.client.AwsSyncClientParams;
import com.amazonaws.internal.SdkFunction;
import com.amazonaws.regions.AwsRegionProvider;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.AmazonS3Client;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;

Java SFTP Mule Library Issue : ClassDef Not found

I am working on a Java utility that gets files from HDFS to a remote machine. I have some issues in the SFTP library import. I have included org mule transport and the related libraries in the POM and after doing mvn install I can see that the Classes are available in the dependency Path. However when I execute the class I get the error message as follow:
Exception in thread "main" java.lang.NoClassDefFoundError: org/mule/transport/sftp/SftpClient
at xxxx.yyyyyy.sftpFileTransfer.main(sftpFileTransfer.java:17)
Caused by: java.lang.ClassNotFoundException: org.mule.transport.sftp.SftpClient
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 1 more
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.mule.transport.sftp.SftpClient;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.mule.transport.sftp.SftpClient;
public class sftpFileTransfer {
public static void main(String[] args) throws IOException {
System.out.println("This is for testing");
SftpClient sftpCli = new SftpClient("abcdef");
sftpCli.login("karthick_kb","/home/karthick/.ssh/id_rsa", null);
sftpCli.changeWorkingDirectory("/tmp/");
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
FSDataInputStream fsdisPath = null;
String filePath = null;
filePath = "/a/b/c/d/e/f/1.dat.gz";
Path inputPath = new Path(filePath);
fsdisPath = fs.open(inputPath);
BufferedInputStream bis = new BufferedInputStream(fsdisPath);
sftpCli.storeFile(inputPath.getName(), bis);
fsdisPath.close();
}
}
The maven dependencies are as follows
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.mule</groupId>
<artifactId>mule-core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-sftp</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies>
I am able to see the required SFTP Classes in the maven dependencies What could I be missing.. Any information would be great

#EJB annotation causes servlet to stop working

I have the following EJB implementing a simple ActiveMQ message enqueue. The ActiveMQ code itself works just fine. This is being deployed on a TomEE server.
SenderBean class:
package Beans;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
#LocalBean
#Stateless
public class SenderBean {
private ConnectionFactory factory = null;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private MessageProducer producer = null;
public SenderBean() {
}
public void sendMessage() {
try {
factory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_BROKER_URL);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("SAMPLEQUEUE");
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText("Hello ...This is a sample message..sending from FirstClient");
producer.send(message);
System.out.println("Sent: " + message.getText());
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
I also have the following class which tries to use the bean in a servlet. If I include the #EJB annotation, like in the following example, the servlet throws an exception upon receiving post. However, if i remove the annotation and instantiate the bean class with new SenderBean(), everything works as it should. What could be the cause of this?
SenderServlet class:
package Servlets;
import Beans.ReceiverBean;
import Beans.SenderBean;
import javax.ejb.EJB;
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 java.io.IOException;
#WebServlet(name = "SenderServlet")
public class SenderServlet extends HttpServlet {
#EJB
SenderBean senderBean;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
senderBean.sendMessage();
}
}
The exception being received in the HttpServletResponse after a 500 error:
HTTP Status 500 - Error instantiating servlet class Servlets.SenderServlet</h1><div class="line"></div><p><b>type</b> Exception report</p><p><b>message</b> <u>Error instantiating servlet class Servlets.SenderServlet</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b></p><pre>javax.servlet.ServletException: Error instantiating servlet class Servlets.SenderServlet
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause javax.naming.NameNotFoundException: Name [Servlets.SenderServlet/senderBean] is not bound in this Context. Unable to find [Servlets.SenderServlet].
org.apache.naming.NamingContext.lookup(NamingContext.java:816)
org.apache.naming.NamingContext.lookup(NamingContext.java:173)
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
The exploded artifact:
don't you have a classpath clash with activemq or hibernate? are the provided library NOT in WEB-INF/lib?

Compiliing and executing Java programs in OSX

Someone needs a public RSA key from me & gave me a java program to make a keypair. I have zero experience with Java so very simple things are very difficult for me. The program looks like this:
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class CustomRSAKeyPairGenerator{
public void generate() {
try {
KeyPairGenerator objlRSAKeyPairGen =
KeyPairGenerator.getInstance("RSA");
objlRSAKeyPairGen.initialize(2048);
KeyPair objlRSAKeyPair = objlRSAKeyPairGen.generateKeyPair();
RSAPublicKey objlPublicKey = (RSAPublicKey) objlRSAKeyPair.getPublic();
RSAPrivateKey objlPrivateKey = (RSAPrivateKey) objlRSAKeyPair.getPrivate();
StringBuffer strblPublicKey = new StringBuffer();
strblPublicKey.append(objlPublicKey.getModulus().toString(16).toUpperCase());
strblPublicKey.append('~');
strblPublicKey.append(objlPublicKey.getPublicExponent().toString(16).toUpperCase()
);
System.out.println(strblPublicKey.toString());
StringBuffer strblPrivateKey = new StringBuffer();
strblPrivateKey.append(objlPrivateKey.getModulus().toString(16).toUpperCase());
strblPrivateKey.append('~');
strblPrivateKey.append(objlPrivateKey.getPrivateExponent().toString(16).toUpperCase());
System.out.println(strblPrivateKey.toString());
}catch (NoSuchAlgorithmException noSuchAlgrtm){
System.out.println(noSuchAlgrtm.getMessage());
}
}
}
When I compile this I get a file called "CustomRSAKeyPairGenerator.class" so I then run that like this:
mylogin$java CustomRSAKeyPairGenerator
and I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: CustomRSAKeyPairGenerator/class
Caused by: java.lang.ClassNotFoundException: CustomRSAKeyPairGenerator.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Am I running this wrong or is there a problem in the java source that I need to fix? Is there a way to use this to make the RSA keypair that I need?

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException

I'm trying to connect my java application with sql server 2012, but is giving me this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to com.mysql.jdbc.Connection
Can anyone can help me please?
Thank you very much.
Code of connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CriaConexao {
public static Connection getConexao()throws SQLException{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String dbURL = "jdbc:sqlserver://BRGDB:1433;database=DB_SQL;IntegratedSecurity=true";
Connection conexao = DriverManager.getConnection(dbURL);
return conexao;
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
}
Error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to com.mysql.jdbc.Connection
at sensores.forms.jTLoginConsulta.<init>(jTLoginConsulta.java:71)
at sensores.forms.jTLoginConsulta$4.run(jTLoginConsulta.java:448)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
jTLoginConsulta imports:
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.awt.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.*;
import org.openide.util.Exceptions;
import sensores.basedados.CriaConexao;
import sensores.forms.jTMainMenu;
import com.mysql.jdbc.PreparedStatement;
import java.awt.Color;
import java.awt.Toolkit;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import java.awt.*;
import java.sql.*;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
import java.util.TimerTask;
import javax.swing.*;
import sensores.basedados.CriaConexao;
import sensores.logica.Logins;
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
import java.util.List;
import sensores.logica.Alarmes;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
Line 71 where the error occurs:
68 public jTLoginConsulta() throws SQLException {
69 initComponents();
70 setIcon();
71 conexao=(Connection) CriaConexao.getConexao();
72
73 }
Check the import for this Connection object
Connection conexao = DriverManager.getConnection(dbURL);
it should be java.sql.Connection. It seems you have imported it wrongly com.mysql.jdbc.Connection
EDIT
as per edited question:
conexao=(Connection) CriaConexao.getConexao();
CriaConexo is returning the com.microsoft.sqlserver.jdbc.SQLServerConnection and you are casting it wrongly to com.mysql.jdbc.Connection. Just correct the import to java.sql.Connection and remove the cast as well.
Hope it helps.

Categories