not getting the output from jdbc throught servlet - java

#code of servlet
public class EmployeeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username=request.getParameter("t1");
int pass=Integer.parseInt(request.getParameter("t2"));
Connection con=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:HR/hr#localhost:1521:orcl\r\n"+ "","system","system");
Statement stmt =con.createStatement();
String query="select * from employee where emp_id="+pass;
ResultSet rs=stmt.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
stmt.close();
con.close();
// Redirect the response to success page
} catch (Exception e) {
e.printStackTrace();
}
}
output::
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Stacktrace::
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1407)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1215)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:377)
at com.dynamic.employee.controller.EmployeeServlet.doGet(EmployeeServlet.java:88)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)

getConections() may have silently returned null - in that case you will have to share the code or analyze yourself. getConections() may also have thrown an exception - you will have to check stdout where you printed the error.
Anyway you need to check stdout closely as you cannot expect any result in the browser. If you want that, ensure to write something into the HttpServletResponse object - I can not see that in your current code.
Edit:
The ClassNotFoundException indicates the JDBC driver is not on your classpath. Not a code issue itself, but check how you run your code.
Could you also check why your JDBC url contains a linefeed?

Related

Passing SQL query results into ArrayList<Object>, returning list to servlet

I am trying to refactormy code, in doing so I am trying to leave the SQL querying to one class. I am trying to pass parameters from an html form to servlet, which then passes those parameters to the ApplicationDao in its method params, which (should) return the result set in the form of a user object arraylist. When I pass the email it is saying column not found, though when I do the exact same thing from within the servlet I am refactoring the results are fine. Obviously, the array list is passing length of 0 back because of the issue!
I am really confused as to what I am doing wrong and any advice would be appreciated!
LOG IN HTML FORM
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Log In: Canadian Voting Portal</title>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
<body id="logInPage">
<div class="LogInContainer1">
<img src="images/CanadaLogo.jpg" width="150px" height="70px">
<h1 id="LogInHeading">Voting Portal Website & Access</h1>
<div class="LogInContainer2">
<div class="LogContainer3">
<form method="post" action="testServlet">
<label class="logInLabel" id="emailLabel" for="email">Email:</label>
<input class="logInInput" type="text" id="userEmail" name="email">
<br>
<label class="logInLabel" id="passwordLabel" for="password">Password:</label>
<input class="logInInput" type="text" id="userPassword" name="password">
<br>
<button id="logInButton" type="submit">LOG IN</button>
</form>
<p id="createParagraph">Don't have an account? Create one <a id="createLink" href="http://localhost:8080/CapstoneProject/CreateAccountServlet">here.</a> Forgot log-in information? Start the reset process of your account <a id="resetLink" href="http://localhost:8080/CapstoneProject/ResetPasswordServlet">here.</a></p>
</div>
</div>
</div>
</body>
</html>
APPLICATION DAO
public class ApplicationDao {
public ArrayList<User> userLogIn(String email, String password){
ArrayList<User> users = new ArrayList<User>();
try{
String sql="SELECT * FROM `user` WHERE email = ? and password = ?" ;
Connection connection =DBConnection.getConnectionToDatabase();
java.sql.PreparedStatement statement;
statement = connection.prepareStatement(sql);
statement.setString(1,email);
statement.setString(2,password);
ResultSet set = statement.executeQuery();
if(set.next()){
User user = new User();
user.setEmail(set.getString(email));
user.setPassword(password);
user.setDateOfBirth("DOB");
user.setFirstName("firstName");
user.setLastName("lastName");
set.close();
statement.close();
users.add(user);
}
}
catch(SQLException exception){
exception.printStackTrace();
}
return users;
}
}
TEST SERVLET
#WebServlet("/testServlet" )
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//List<User> users = new ArrayList<User>();
public testServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String email = request.getParameter("email");
String password = request.getParameter("password");
PrintWriter writer = response.getWriter();
ApplicationDao dao = new ApplicationDao();
ArrayList<User> user = dao.userLogIn(email,password);
String DOB = user.get(0).getDateOfBirth();
writer.write(email + DOB);
}}
CONSOLE (when passing params from servlet)
MySQL JDBC Driver Registered!
Connection made to DB!
java.sql.SQLException: Column 'caytegibbons#gmail.com' not found.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.result.ResultSetImpl.findColumn(ResultSetImpl.java:584)
at com.mysql.cj.jdbc.result.ResultSetImpl.getString(ResultSetImpl.java:896)
at dao.ApplicationDao.userLogIn(ApplicationDao.java:45)
at servlets.testServlet.doPost(testServlet.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
Jul. 19, 2022 10:16:10 A.M. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [servlets.testServlet] in context with path [/CapstoneProject] threw exception
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:459)
at servlets.testServlet.doPost(testServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
CONSOLE (when hard coding params)
The error is in the line 45 of your ApplicationDao, looking at the stack trace:
at dao.ApplicationDao.userLogIn(ApplicationDao.java:45)
I assume it's this line:
user.setEmail(set.getString(email));
You pass the email variable as the column name. It should be:
user.setEmail(set.getString("email"));

Cannot handle ConstraintViolationException for Cross-Parameter Constraints/Validations

I have gone through many post related to ConstraintViolationException on StackOverflow but couldn't get any help. I am using Spring Boot v2.3.3 web application with spring-boot-starter-validation. I want to validate a password using a custom annotation for Cross-Parameter Constraints. In order to do that, I have followed this Baeldung link. Below is the implementation class which inherits ConstraintValidator:
#SupportedValidationTarget(PARAMETERS)
public class ValidPasswordValidator implements ConstraintValidator<ValidPassword, Object[]> {
private ValidateRequestTypeEnum requestType;
#Autowired
private PasswordValidatorService passwordValidatorService;
#Override
public void initialize(ValidPassword constraintAnnotation) {
this.requestType = constraintAnnotation.requestType();
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
#Override
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
SomeUser someUser = (SomeUser) value[0];
try {
passwordValidatorService.validate(someUser, this.requestType);
} catch (ConstraintViolationException e) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(e.getMessage()).addConstraintViolation();
return false; // If this is turned true then no exception is thrown
}
return true;
}
}
Now whenever I return false in the isValid() method, I get the ConstraintViolationException, even after handling it in the catch block. The behaviour remains the same even if I throw a different Exception and handle it in the catch block.
Below are my other class implementaions and stacktrace. Any help will be greatly appreciated.
ValidPassword Annotation:
#Constraint(validatedBy = ValidPasswordValidator.class)
#Target({METHOD, CONSTRUCTOR})
#Retention(RUNTIME)
#Documented
public #interface ValidPassword {
String message() default "";
ValidateRequestTypeEnum requestType();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Controller class:
#Validated
#RestController
public class SomeController {
#ValidPassword(requestType = CREATE_USER)
#GetMapping("/create-user")
public void createUser(#RequestBody SomeUser someUser) {
System.out.println("Create User Mapping");
System.out.println(someUser.toString());
}
}
SomeUser Model class:
public class SomeUser {
private int id;
private String name;
private String password;
// getters and setters abbreviated
// toString() abbreviated
}
PasswordValidatorService:
public interface PasswordValidatorService {
void validate(SomeUser someUser, ValidateRequestTypeEnum requestType) throws ConstraintViolationException;
}
PasswordLengthValidatorImpl:
#Service
public class PasswordLengthValidatorImpl implements PasswordValidatorService {
#Override
public void validate(SomeUser someUser, ValidateRequestTypeEnum requestType) throws ConstraintViolationException {
switch (requestType) {
case CREATE_USER:
System.out.println("From Create_User block");
if (someUser.getPassword().length() < 8) {
throw new ConstraintViolationException("Password length less than 8", new HashSet<>());
}
break;
default:
System.out.println("---Default switch block---");
}
}
}
Stacktrace:
javax.validation.ConstraintViolationException: createUser.<cross-parameter>: Password length less than 8
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:116) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at com.sam.springdroolspersistence.controller.SomeController$$EnhancerBySpringCGLIB$$dbaf428.createUser(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_291]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_291]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_291]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_291]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) [tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.37.jar:9.0.37]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_291]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_291]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.37.jar:9.0.37]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_291]
Now whenever I return false in the isValid() method, I get the
ConstraintViolationException, even after handling it in the catch
block. The behaviour remains the same even if I throw a different
Exception and handle it in the catch block.
You can actually try this out in an IDE debugger ( like eclipse) and follow the validation path.
The isValid method of ConstraintValidator is a contract between validation engine and your constraint validation logic. If it fails it has to return false.
The actual code that handles it is in org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree
The stack trace you are seeing is not what you have thrown and caught - rather it's internally generated in org.springframework.validation.beanvalidation.MethodValidationInterceptor

HttpClient MultipartRequest Connection Refused

I have 2 applications which need to send files to each other using HttpClient libraries:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
Here is the code to send the file:
private static void executeRequest(HttpPost httpPost, String url) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void executeMultiPartRequest(String urlString, File file) throws IOException {
HttpPost postRequest = new HttpPost(urlString);
postRequest = addHeader(postRequest, "Access Token");
try {
HttpEntity fileEntity = MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.create("application/octet-stream"), file.getName()).build();
postRequest.setEntity(fileEntity);
} catch (Exception ex) {
ex.printStackTrace();
}
executeRequest(postRequest, urlString);
}
private static HttpPost addHeader(HttpPost httpPost, String accessToken) {
httpPost.addHeader("Accept", "application/json;odata=verbose");
httpPost.setHeader("Authorization", "Bearer " + accessToken);
return httpPost;
}
#CrossOrigin
#PostMapping(path = "/send", produces = {MULTIPART_FORM_DATA_VALUE})
public void send() throws IOException {
String url = "http://127.0.0.1:2990/asanrest/1.0/receiveFile";
File file = new File("server-info.txt");
System.out.println(file.getAbsolutePath());
executeMultiPartRequest(url, file);
}
This works on my local machine, applications send the file to each other successfully. However, when I upload one of the applications to the server, then I can send the file from local machine to the server, but when sending from the server back to the local machine, I get the following error:
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:117)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:882)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at com.softgile.asan.asanservice.rest.AsanRestController.executeRequest(AsanRestController.java:350)
at com.softgile.asan.asanservice.rest.AsanRestController.executeMultiPartRequest(AsanRestController.java:373)
at com.softgile.asan.asanservice.rest.AsanRestController.send(AsanRestController.java:389)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
What is the problem here? Isn't it possible to send the file from the server back to local machine? Is there a problem with the url? I have tried to use
http://localhost:2990
http://127.0.0.1:2990
192.168.x.x. - local IP address
Nothing works. Can anyone help with this?
Between two servers, please use local ip address to connect, and not use 127.0.0.1
please use local machine ip address instead of 127.0.0.1
String url = "http://192.168.x.x:2990/asanrest/1.0/receiveFile";
For network trouble shooting, please refer this one. https://www.a2hosting.com/kb/getting-started-guide/internet-and-networking/troubleshooting-network-applications-with-curl

Overwrite Spring HttpMessageConverter

Code Repo: https://github.com/kenuiuc/springboot-demo
I have an endpoint comsuming data in application/x-www-form-urlencoded format
If I send a PUT request like this:
curl --request PUT \
--url http://localhost:18080/user \
--header 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8' \
--data name=ken%
As you can see the data name=ken% is in illegal URL format so I get 500 response and the server-side error log:
{
"timestamp": "2021-05-27T02:25:36.849+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/user"
}
java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern
at java.net.URLDecoder.decode(URLDecoder.java:187) ~[na:1.8.0_291]
at org.springframework.http.converter.FormHttpMessageConverter.read(FormHttpMessageConverter.java:356) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.FormContentFilter.parseIfNecessary(FormContentFilter.java:109) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:88) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.7.jar:5.3.7]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96) ~[spring-boot-actuator-2.5.0-20210520.224402-561.jar:2.5.0-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.7.jar:5.3.7]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.7.jar:5.3.7]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) [tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.46.jar:9.0.46]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_291]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_291]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.46.jar:9.0.46]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_291]
My goal is to let it return 400 status instead of 500 since this error is actually the client's fault not my server's fault
So I extended the org.springframework.http.converter.FormHttpMessageConverter and overrided the read() method
public class CustomizedFormHttpMsgConverter extends FormHttpMessageConverter {
#Override
public MultiValueMap<String, String> read(#Nullable Class<? extends MultiValueMap<String, ?>> clazz,
HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
MediaType contentType = inputMessage.getHeaders().getContentType();
Charset charset = (contentType != null && contentType.getCharset() != null ?
contentType.getCharset() : StandardCharsets.UTF_8);
String body = StreamUtils.copyToString(inputMessage.getBody(), charset);
String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(pairs.length);
for (String pair : pairs) {
int idx = pair.indexOf('=');
if (idx == -1) {
result.add(URLDecoder.decode(pair, charset.name()), null);
}
else {
try {
String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
result.add(name, value);
} catch (Throwable th) {
System.out.println("HI KEN I GOT HERE!");
throw new HttpMessageNotReadableException(th.getMessage());
}
}
}
return result;
}
}
Then I registered this customized converter in my configuration class:
#Configuration
public class CoreConfig {
#Bean("customizedFormHttpMsgConverter")
public FormHttpMessageConverter createMyConverter() {
return new CustomizedFormHttpMsgConverter();
}
}
Now I can see my converter is successfully registered through my debug endpoint (/myConfig):
{
"requestMappingHandlerAdapter-converters": [
"com.ken.demo.CustomizedFormHttpMsgConverter#576c5536",
"org.springframework.http.converter.ByteArrayHttpMessageConverter#45d20f3d",
"org.springframework.http.converter.StringHttpMessageConverter#55ecbafe",
"org.springframework.http.converter.StringHttpMessageConverter#3b567dad",
"org.springframework.http.converter.ResourceHttpMessageConverter#60ecdde8",
"org.springframework.http.converter.ResourceRegionHttpMessageConverter#54fac191",
"org.springframework.http.converter.xml.SourceHttpMessageConverter#10497d4",
"org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter#9b7294c",
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#5a8ba37c",
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#f32a60f",
"org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter#dc61831"
],
"configurers": [
"org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter#257cc1fc",
"org.springframework.boot.actuate.autoconfigure.metrics.web.servlet.WebMvcMetricsAutoConfiguration$MetricsWebMvcConfigurer#42e22a53"
],
"converters": [
"com.ken.demo.CustomizedFormHttpMsgConverter#576c5536",
"org.springframework.http.converter.StringHttpMessageConverter#55ecbafe",
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#5a8ba37c"
]
}
However, it looks like the CustomizedFormHttpMsgConverter is never used because the illegal request will still result in the same error:
java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern
at java.net.URLDecoder.decode(URLDecoder.java:187) ~[na:1.8.0_291]
at org.springframework.http.converter.FormHttpMessageConverter.read(FormHttpMessageConverter.java:356) ~[spring-web-5.3.7.jar:5.3.7]
Of course, my debug msg "HI KEN I GOT THERE" is never printed out
My questions are:
Why my registered CustomizedFormHttpMsgConverter never get used?
Is my approach (to extend FormHttpMessageConverter) the right way of doing things?
Again my goal is just to change the 500 response to 400 upon URL decoding failures
It looks like the FormHttpMessageConverter is called by filter chain. I have not tested yet but the suggestion is that you should write your own filter and calling your custom converter for this case.
How to define a filter and register it: https://www.baeldung.com/spring-boot-add-filter
Rather than doing so much for just a invalidArgumentException that also for a specific use-case (Param validation).
Put a single Handler for any/all invalidArgumentException thrown from controller.
Now, even if spring or your code throw this exception, you will return custom message and status as you needed.
Sample code :
#ExceptionHandler (value = {IllegalArgumentException.class})
public final ResponseEntity<ServiceErrorResponse> invalidInputs(Exception e) {
// preparing the response body as per the template
// assigns exception message thrown by the failed method or class
// to the service response and sets respective HTTP status, code
return new ResponseEntity<ServiceErrorResponse>(e.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST);
}

HTTP Status 500 – Internal Server Error While sending a mail from java mail

I am getting this error while sending out mail from my project.
Applications I was using are:
Eclipse IDE
Apache Tomcat
Here is the error
```Servlet.service() for servlet [controler.ForgotPassword] in context with path [/Banking_App] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.sun.activation.registries.LogSupport
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1365)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1188)
at javax.activation.MailcapCommandMap.<init>(MailcapCommandMap.java:179)
at javax.activation.CommandMap.getDefaultCommandMap(CommandMap.java:85)
at javax.activation.DataHandler.getCommandMap(DataHandler.java:167)
at javax.activation.DataHandler.getDataContentHandler(DataHandler.java:629)
at javax.activation.DataHandler.writeTo(DataHandler.java:329)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:340)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1575)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2271)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2231)
at javax.mail.Transport.send(Transport.java:123)
at controler.ForgotPassword.service(ForgotPassword.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
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:53)
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:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:830)
Jul 17, 2020 7:28:31 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controler.ForgotPassword] in context with path [/Banking_App] threw exception [Servlet execution threw an exception] with root cause
java.lang.NoClassDefFoundError: com/sun/activation/registries/LogSupport
at javax.activation.MailcapCommandMap.<init>(MailcapCommandMap.java:179)
at javax.activation.CommandMap.getDefaultCommandMap(CommandMap.java:85)
at javax.activation.DataHandler.getCommandMap(DataHandler.java:167)
at javax.activation.DataHandler.getDataContentHandler(DataHandler.java:629)
at javax.activation.DataHandler.writeTo(DataHandler.java:329)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:340)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1575)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2271)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2231)
at javax.mail.Transport.send(Transport.java:123)
at controler.ForgotPassword.service(ForgotPassword.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
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:53)
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:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:830)```
Here is the java class from where it will send the mail:-
"ForgotPassword.java"
```#WebServlet("/ForgotPassword")
public class ForgotPassword extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ForgotPassword() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email=request.getParameter("email");
HttpSession session1=request.getSession(true);
session1.setAttribute("email",email);
String fromEmail="abc#gmail.com";
String psw="XYZ";
String subject="DO NOT REPLY: Mail from Java Program";
String msg="Hi, Click this link to reset your password "
+ "http://localhost:3030/Banking_App/resetPassWord.jsp";
Properties prop=new Properties();
prop.put("mail.smtp.host","smtp.gmail.com");
prop.put("mail.smtp.port", 587);
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
Session session= Session.getDefaultInstance(prop
, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, psw);
}
}
);
try {
MimeMessage mesg=new MimeMessage(session);
mesg.setFrom(new InternetAddress(fromEmail));
mesg.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
mesg.setSubject(subject);
mesg.setText(msg);
Transport.send(mesg);
System.out.println("Mail Sent!!");
response.sendRedirect("/Banking_App/forgotPassWordSuccessful.jsp");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}```
I was trying to send a link through this mail for resetting the password, where I used two jar files and deploy them in project
javax.mail
javax.activation
Thank you in advance.
Try adding this dependency and see if it works:
Gradle:
implementation 'com.sun.activation:javax.activation:1.2.0'
Maven:
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
You can also read this article for more info.

Categories