java.io.FileNotFoundException uploading image with apache.commons - java

I'm developing a Spring-MVC project that requires uploading images by the users of the app. I'm using apache.commons, Eclipse Mars2 and Java1.8. Everytime I test the upload, eclipse console throws this:
EDIT: it seems the problem is to find the path to the project independently of the OS. At this moment we are using:
File localFile = new File(System.getProperty("user.home")+File. separator+ "workspace"+File. separator+"ProyectoSpring"+File. separator + "WebContent" + File. separator+"usr"+File. separator+imagen.getNombreImagen());
The problem is the workspace is hardcoded and the app is being developed by more people. Any way to find the path to the project? user.dir returns the eclipe path, not the project or workspace.
Original question:
java.io.FileNotFoundException: C:\Users\UserName\workspace\ApacheTomcat7\ProyectoSpring\WebContent\usr\back.jpg (El sistema no puede encontrar la ruta especificada)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at controller.ImagenController.grabarFicheroALocal(ImagenController.java:84)
at controller.ImagenController.processAddSubmit(ImagenController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Controller methods:
#RequestMapping(value="/uploadImagen" , method=RequestMethod.GET)
public String addImagen(Model model) {
model.addAttribute("imagen", new Imagen());
return "imagen/uploadImagen";
}
#RequestMapping(value="/uploadImagen", method=RequestMethod.POST)
public String processAddSubmit(#ModelAttribute("imagen") Imagen imagen,
BindingResult bindingResult) {
//if (bindingResult.hasErrors())
// return "imagen/uploadImagen";
//
try {
String aux = imagen.getFichero().getOriginalFilename();
imagen.setImageName(System.getProperty("catalina.home")+ File. separator +"ProyectoSpring"+ File. separator +"WebContent"+ File. separator +"usr"+ File. separator + aux);
grabarFicheroALocal(imagen);
} catch (Exception e) {
e.printStackTrace();
return "user/error";
}
return "redirect:../index.jsp";
}
private void grabarFicheroALocal(Imagen imagen) throws Exception {
CommonsMultipartFile uploaded = imagen.getFichero();
File localFile = new File(imagen.getImageName());
FileOutputStream os = null;
try {
os = new FileOutputStream(localFile);
os.write(uploaded.getBytes());
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
An extract from the object:
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class Imagen {
private String imageName;
private CommonsMultipartFile fichero;
public Imagen(){
super();
}
//GETTERS AND SETTERS
public CommonsMultipartFile getFichero() {
return fichero;
}
public void setFichero(CommonsMultipartFile fichero) {
this.fichero = fichero;
}
...
Of course, the image is not uploaded. In other pc with Linux (I'm using W7-64) the code works, so I suspect it may be a permissions problem, but all folders in the path have write permissions. Any ideas? Thx.

Related

Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts

i am using jjwt-0.9.1.jar and runtime gives this exception for jersey reset API call.
When i use this code using java main() method, its works perfectly but when i call from servlet to that class, the method throws exception.
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.UUID;
public String createJWTToken() {
String id = UUID.randomUUID().toString().replace("-", "");
//The JWT signature algorithm we will be using to sign the token
// SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//Let's set the JWT Claims
JwtBuilder builder = null;
try {
builder = Jwts.builder().setId(id).setHeaderParam("typ", "JWT")
.setIssuedAt(now)
.setSubject("")
.setIssuer(API_KEY)
.signWith(SignatureAlgorithm.HS256,SECRET_KEY.getBytes("UTF-8"));
//if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.compact();//Builds the JWT and serializes it to a compact, URL-safe string
}
When call servlet to java class method i.e.createJWTToken() gives following exception in tomcat.
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:328)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:204)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:48)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.general.FilterDemo.doFilter(FilterDemo.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
at com.zoom.JWTTokenGeneration.createJWTToken(JWTTokenGeneration.java:31)
at com.zoom.Utilities.setMeeting(Utilities.java:571)
at com.general.InsertController.doPost(InsertController.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) ... 22 more Caused by: java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546) ... 28 more
The exception is java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
Check the Jar file(jwt) is packaged in the build or not?

Java exception in openConnection method (fetching data from html)

I have a problem getting the input stream using 'getInputStream' method for few URLs (most of the URLs works fine) although the URL seems to work via web browser.
I am using the following code:
public static String getContents(String uri, String encoding) {
StringBuffer sb = new StringBuffer();
URL url;
try {
url = new URL(uri);
URLConnection con = url.openConnection();
con.setReadTimeout(90000);
System.out.println("--------2.1:");//////////////////////////////////////////////////////////////
InputStream is = con.getInputStream();
System.out.println("--------2.2:"+is);/////////////////////////////////////////////////////////
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// read lines from HTML
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("--------2.6:");//////////////////////////////////////////////////////
return null;
}
return sb.toString();
}
output:
--------2.1:http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
--------2.6:
Exception:
java.io.IOException: Server returned HTTP response code: 503 for URL: http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.irWizard.common.util.FileUtils.getContents(FileUtils.java:29)
at com.irWizard.web.controller.WizardController.getActualTotalOfRecords(WizardController.java:500)
at com.irWizard.web.controller.WizardController.validateSets(WizardController.java:419)
at com.irWizard.web.controller.WizardController.onSubmit(WizardController.java:242)
at com.irWizard.web.controller.BaseController.onSubmit(BaseController.java:127)
at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:258)
at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:652)
at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:257)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:45)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:728)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:350)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
It seems that it's code 503.
Does anyone know how it can be solved? (it works fine via browser).
Mike

strange error while working with JasperReports, Hibernate and Spring

I am getting a strange error when trying to print my report.
Handler processing failed; nested exception is java.lang.VerifyError: class org.codehaus.groovy.runtime.callsite.GroovySunClassLoader$2 overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V
Please can anyone suggest what can be the solution for this.
here is the code for printing the jasper report.
#RequestMapping("/report")
public String displayReport(Map<String,Object> map){
System.out.println("Hello");
String sourceFileName = "D://jasper"
+ "/report2.jrxml";
String jasperFileName = "D://jasper"
+ "/report2.jasper";
List<Project> projectList=projectService.getAllproject();
String printFileName = null;
JRBeanCollectionDataSource beanColDataSource =
new JRBeanCollectionDataSource(projectList);
try{
// 1. Add report parameters
HashMap<String, Object> parameters= new HashMap<String, Object>();
parameters.put("ReportTitle", "Project Details");
parameters.put("Author", "Prepared By Priyanka");
JasperCompileManager.compileReportToFile(sourceFileName);
printFileName = JasperFillManager.fillReportToFile(jasperFileName,
parameters, beanColDataSource);
if (printFileName != null) {
/**
* 1- export to PDF
*/
JasperExportManager.exportReportToPdfFile(printFileName,
"D://jasper/sample_report.pdf");
/**
* 2- export to HTML
*/
JasperExportManager.exportReportToHtmlFile(printFileName,
"D://jasper/sample_report.html");
/**
* 3- export to Excel sheet
*/
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME,
printFileName);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
"D://jasper/sample_report.xls");
exporter.exportReport();
}
} catch (JRException e) {
e.printStackTrace();
}
return "report";
}
also the stack trace is as follows:
SEVERE: Servlet.service() for servlet [spring] in context with path [/Project5] threw exception [Handler processing failed; nested exception is java.lang.VerifyError: class org.codehaus.groovy.runtime.callsite.GroovySunClassLoader$2 overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V] with root cause
java.lang.VerifyError: class org.codehaus.groovy.runtime.callsite.GroovySunClassLoader$2 overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2895)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at org.codehaus.groovy.runtime.callsite.CallSiteGenerator.isCompilable(CallSiteGenerator.java:243)
at org.codehaus.groovy.reflection.CachedMethod.createPojoMetaMethodSite(CachedMethod.java:239)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.createCachedMethodSite(PojoMetaMethodSite.java:158)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.createPojoMetaMethodSite(PojoMetaMethodSite.java:147)
at groovy.lang.MetaClassImpl.createPojoCallSite(MetaClassImpl.java:2979)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createPojoSite(CallSiteArray.java:114)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:148)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:121)
at org.codehaus.groovy.ast.builder.AstBuilderTransformation.visit(AstBuilderTransformation.groovy:61)
at org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:268)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:799)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:464)
at net.sf.jasperreports.compilers.JRGroovyCompiler.compileUnits(JRGroovyCompiler.java:109)
at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:201)
at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:354)
at net.sf.jasperreports.engine.JasperCompileManager.compileToFile(JasperCompileManager.java:270)
at net.sf.jasperreports.engine.JasperCompileManager.compileToFile(JasperCompileManager.java:229)
at net.sf.jasperreports.engine.JasperCompileManager.compileReportToFile(JasperCompileManager.java:539)
at com.mvc.project.controller.ProjectController.displayReport(ProjectController.java:224)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The language attribute in the header of your report2.jrxml file is set to groovy, not java.
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
...
language="groovy"
...>
Change this to
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
...
language="java"
...>

Why am I getting "No suitable driver found for jdbc:mysql://localhost:3306/test2"?

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test2
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.room302.util.DBConnectionUtil.getConnection(DBConnectionUtil.java:32)
at com.room302.dao.roomDAO.addexpense(roomDAO.java:26)
at com.room302.servlet.Navigator.doPost(Navigator.java:69)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
My Util file is as follows:
public class DBConnectionUtil
{
private static final String USERNAME="root";
private static final String PASSWORD="1234";
private static final String URL="jdbc:mysql://localhost:3306/test2";
private static final String DRIVER_NAME="mysql";
private static Connection conn=null;
static
{
try
{
System.out.println("searching for driver");
Class.forName(DRIVER_NAME);
}
catch(ClassNotFoundException cnfe)
{
}
}
public static Connection getConnection() throws SQLException
{
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return conn;
}
public static void closeConnection(Connection conn)
{
if(conn!=null)
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
}
I have put MySQL connector in the buildpath and also in lib folder of web-inf.
Why am I still getting this error?
You need to load the com.mysql.jdbc.Driver driver class.
private static final String DRIVER_NAME="com.mysql.jdbc.Driver";
Look at the official documentation:
The name of the class that implements java.sql.Driver in MySQL Connector/J is com.mysql.jdbc.Driver. The org.gjt.mm.mysql.Driver class name is also usable for backward compatibility with MM.MySQL, the predecessor of Connector/J. Use this class name when registering the driver, or when otherwise configuring software to use MySQL Connector/J.
This is a fairly old thread so I just though I should add that "com.mysql.jdbc.Driver" has been deprecated so you need to use "com.mysql.cj.jdbc.Driver"

How to dynamically load a class on tomcat?

I've learned how to dynamically load a ".class" file into my program, but if I run it on a tomcat id doesn't work. Here is the code:
package testPackage;
public class ModuleEngine {
public static void main(String pth, String name) {
ModuleLoader loader = new ModuleLoader(pth, ClassLoader.getSystemClassLoader());
try {
Class clazz = loader.loadClass(name);
Protocol execute = (Protocol)clazz.newInstance();
execute.run();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public class ModuleLoader extends ClassLoader {
private String pathtobin;
public ModuleLoader(String pathtobin, ClassLoader parent) {
super(parent);
this.pathtobin = pathtobin;
}
#Override
public Class findClass(String className) throws ClassNotFoundException {
try {
byte b[]= fetchClassFromFS(pathtobin + className + ".class");
return defineClass(null, b, 0, b.length);
} catch (FileNotFoundException ex) {
return super.findClass(className);
} catch (IOException ex) {
return super.findClass(className);
}
}
}
I run main method in ModuleEngine class with path to subclass of the class Protocol. This subclass is placed in different package. So when I try to define it (defineClass) it tries to load the superclass (Protocol) but fails to do that. Here is the stack trace:
java.lang.ClassNotFoundException: testPackage.Protocol
at java.lang.ClassLoader.findClass(Unknown Source)
at testPackage.ModuleLoader.findClass(ModuleLoader.java:30)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at testPackage.ModuleLoader.findClass(ModuleLoader.java:28)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at testPackage.ModuleEngine.main(ModuleEngine.java:13)
at testPackage.HtmlPage.doGet(HtmlPage.java:27)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Instead of ClassLoader.getSystemClassLoader() try using ModuleEngine.class.getClassLoader (). This will return class loader that knows about classes sitting near ModuleEngine class.

Categories