java.lang.IllegalStateException: consumer key/secret pair already set - java

I'm using Spring framework to login with twitter into my website, I'm actually learning from this tutorial.
So i followed this question and changed my source accordingly below:
#RequestMapping("/welcome")
#Controller
public class HelloController {
private final String CONSUMER_KEY = "xxxx";
private final String CONSUMER_SECRET = "xxxx";
ConfigurationBuilder confBuilder = new ConfigurationBuilder()
.setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRET);
Configuration configuration = confBuilder.build();
TwitterFactory factory = new TwitterFactory(configuration);
Twitter twitter = factory.getInstance();
#Autowired
private MyAccessToken accestoken;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(HttpServletResponse response,HttpServletRequest request) {
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
RequestToken requestToken;
try {
String callbackURL = "http://127.0.0.1:8080/cwitter/callback";
System.out.println("callback url is " + callbackURL);
requestToken = twitter.getOAuthRequestToken(callbackURL);
String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();
accestoken.setTokensecret(tokenSecret);
accestoken.setToken(token);
String authUrl = requestToken.getAuthorizationURL();
request.setAttribute("authUrl", authUrl);
} catch (TwitterException e) {
e.printStackTrace();
}
return "login";
}
#RequestMapping(value = "/{username}/test1",method=RequestMethod.GET)
public String test1(#PathVariable String username,#RequestParam("userdetails") String userDetails,ModelMap model){
System.out.println("test1 " + username + "\t" + userDetails);
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
#RequestMapping(value = "/callback",method=RequestMethod.GET)
public String test1(HttpServletRequest request, ModelMap model){
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
System.out.println(twitter);
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
String verifier = request.getParameter("oauth_verifier");
Enumeration attrList = request.getSession().getAttributeNames();
while(attrList.hasMoreElements()){
System.out.println(request.getSession().getAttribute((String)attrList.nextElement()));
}
try {
System.out.println(twitter.getOAuthAccessToken(requestToken, verifier));
request.getSession().removeAttribute("requestToken");
// twitter.setOAuthAccessToken(accessToken);
User user = twitter.verifyCredentials();
model.addAttribute("message", user.getName());
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "hello";
}
}
So, I simply tried to run all my project but it says the following logs:
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/cwitter] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: consumer key/secret pair already set.] with root cause
java.lang.IllegalStateException: consumer key/secret pair already set.
at twitter4j.TwitterBaseImpl.setOAuthConsumer(TwitterBaseImpl.java:281)
at com.common.controller.HelloController.printWelcome(HelloController.java:51)
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:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:221)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:107)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:90)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1012)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:642)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1555)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please let know, What's wrong here?
Any kind of help would be appreciated!!

Related

Why would connecting to a MySQL database from Java get denied access?

I am trying to connect to MySQL from Java and I get the following error.
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:951)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1717)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2395)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2428)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2213)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.javawebtutor.jsf.LoginBean.dbData(LoginBean.java:63)
at com.javawebtutor.jsf.LoginBean.checkValidUser(LoginBean.java:80)
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.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at org.apache.jasper.el.JspMethodExpression.invoke(JspMethodExpression.java:70)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2522)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2511)
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)
Exception Occured in the process :java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)"
Thank you for all help, I am very new to this. I am positive the password and username are correct so I am unsure where to go from here. Here is my code for connecting to the database:
package com.javawebtutor.jsf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="loginBean")
#SessionScoped
public class LoginBean {
private String userName;
private String password;
private String dbuserName;
private String dbpassword;
Connection connection;
Statement statement;
ResultSet resultSet;
String SQL;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDbuserName() {
return dbuserName;
}
public void setDbuserName(String dbuserName) {
this.dbuserName = dbuserName;
}
public String getDbpassword() {
return dbpassword;
}
public void setDbpassword(String dbpassword) {
this.dbpassword = dbpassword;
}
public void dbData(String userName)
{
Connection con = null;
String conUrl = "jdbc:mysql://localhost:3306/test; user=root; password=pass;";
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(conUrl);
//connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",user = "root","pass");
statement = connection.createStatement();
SQL = "Select * from USER_DETAIL where username like ('" + userName +"')";
resultSet = statement.executeQuery(SQL);
resultSet.next();
dbuserName = resultSet.getString(1).toString();
dbpassword = resultSet.getString(2).toString();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception Occured in the process :" + ex);
}
}
public String checkValidUser()
{
dbData(userName);
if(userName.equalsIgnoreCase(dbuserName))
{
if(password.equals(dbpassword))
return "success";
else
{
return "failure";
}
}
else
{
return "failure";
}
}
}
In MySQL server administration, users are specified with both allowable hostnames and passwords. If the root user was not set up to include localhsot as a client, it will deny logins on the local machine. See this question and its accepted answer for some details.
Can you try like this
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","pass");
As getConnection function requires 3 arguments : url+dbname , username , password.
Your password is wrong it seems.
You can try with empty password given below.
String conUrl = "jdbc:mysql://localhost:3306/test; user=root; password=;";

Hibernate DAO get method does not work if called via REST, does otherwise

I wonder if anyone can explain why the following code in a DAO in a Spring and Hibernate web application:
#Override
public Book get(Integer bookId) {
logger.info(BookDAOImpl.class.getName() + ".get() method called.");
Session session = sessionFactory.openSession();
try {
System.out.println("Book : " + bookId);
Book book = (Book) session.get(Book.class, bookId);
return book;
}
finally {
session.close();
}
}
Will work perfectly well inside its parent web application but when called via REST through a controller and service class:
// Gets a Book via REST.
#RequestMapping(value="/book/{bookId}", method=RequestMethod.GET)
public #ResponseBody Object getBook(#PathVariable("bookId") String bookId) {
logger.info(RestController.class.getName() + ".getBook() method called.");
if (bookIdValid(bookId)) {
Book book = bookService.get(Integer.parseInt(bookId));
System.out.println("ABook " + book.toString());
return book;
}
else {
Messages messages = new Messages();
messages.addMessage(messageSource.getMessage("bookId.required", null, null));
return messages;
}
}
The line Book book = (Book) session.get(Book.class, bookId); returns null.
Line 53 of BookDAOImpl is line return bookId == book.getBookId().intValue(); in the method below:
#Override
public boolean check(Integer bookId) {
logger.info(BookDAOImpl.class.getName() + ".check() method called.");
try {
Book book = this.get(bookId);
return bookId == book.getBookId().intValue();
}
catch(IndexOutOfBoundsException e) {
return false;
}
}
The stacktrace is:
Book : 78
INFO|12 07 2015|22 07 16|http-apr-8080-exec-123|library.controller.PersonController| - library.controller.ExceptionController.exception() method called.
null
library.dao.BookDAOImpl.check(BookDAOImpl.java:53)
library.service.BookServiceImpl.check(BookServiceImpl.java:32)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:201)
com.sun.proxy.$Proxy571.check(Unknown Source)
library.controller.RestController.bookIdValid(RestController.java:127)
library.controller.RestController.getBook(RestController.java:102)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2451)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2440)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:744)
library.interceptor.ClientInterceptor.afterCompletion() method completed: GET: /Library/rest/book/78?null at 12 07 2015 # 22 07 ended with HTTP code: 500.
It looks like session.get(Book.class, bookId) is returning null - your database likely does not contain book 78. Do you have a create book endpoint you can use to insert into the database prior to hitting the get endpoint?

Deserialization of the Java object in using Apache HttpClient Api is not working

I am new to the Spring MVC. I am using the Spring release 4.1.6 and deployed my two web applications A and B on tomcat 7 for the development environment. But in the actual production environment the application A will be deployed on weblogic and application B will be deployed on websphere. Below is the scenario occuring on the development environment.
From the Application A , I am submitting the jsp page and invoked the below method of the controller. From this method I am creating the HttpPost request and sending the RequestDetails domain object to the another controller's method using ApacheHttpClient api.This is the code from the sender's side or from Application A's controller.
#RequestMapping(value="/httprequestJinesh.cvr",method = RequestMethod.POST)
public #ResponseBody String createMediaRequest(#RequestBody RequestDetails requestDetails ,HttpServletRequest request, HttpServletResponse response ) throws Exception{
System.out.println("****************** createMediaRequest Method of the controller gets invoked 123 *****************");
if(requestDetails!=null){
System.out.println("******************* Requestdetails Is Been Object is been received ***************" + requestDetails.getRequestId());
}
//Sending the HttpPostRequest
StringBuilder url = new StringBuilder();
String serverUrl = "http://localhost:8080/raws/createMediaRequest.raws"; //get it from app_properpties table
url.append(serverUrl);
System.out.println("************** Started creating the Httpost request ********************");
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httppostRequest = new HttpPost(serverUrl);
httppostRequest.setEntity(new SerializableEntity(requestDetails,false));
System.out.println("************** Finished creating the Http Post request ********************");
System.out.println("*********** Before sending the Httppost Request ******************");
HttpResponse httpResponse = httpClient.execute(httppostRequest);
System.out.println("*********** After sending teh Httppost Request ******************");
return "SUCCESS";
}
On the receiver application's controller I am trying to deserialize the domain object received in the POST request. Both of the Application A and B have the RequestDetails class available in the workspace but in both of the case the package hierachy for the domain object is different.Say for example in Application A RequestDetails object is available in com.test and in application B it is available in the com.test123. Below is the code on the receiver application's controller.
RequestMapping(value = "/createMediaRequest.raws", method = RequestMethod.POST)
public Object createMediaRequest(HttpServletRequest request, HttpServletResponse response){
System.out.println("***************** MediaWorkflowController Received Media Request *******************");
try{
ObjectInputStream in = new ObjectInputStream(request.getInputStream());
RequestDetails requestDetails=(RequestDetails)in.readObject();
if(requestDetails!=null){
System.out.println("requestdetails object is not null *******************" + requestDetails.getRequestId());
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
Below is the code for the RequestDetails.java on Application A
package com.test;
public class RequestDetails implements java.io.Serializable{
String requestId;
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
}
Below is the code for the RequestDetails.java on Application B
package com.test123;
public class RequestDetails implements java.io.Serializable{
String requestId;
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
}
I am getting the below exception when the code for the receiver application's controller get executed.
****************** createMediaRequest Method of the controller gets invoked 123 *****************
******************* Requestdetails Is Been Object is been received ***************12345
************** Started creating the Httpost request ********************
************** Finished creating the Http Post request ********************
*********** Before sending the Httppost Request ******************
***************** MediaWorkflowController Received Media Request *******************
java.lang.ClassNotFoundException: com.test.RequestDetails
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:274)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:625)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1612)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at com.cira.raws.mediawf.api.services.controller.MediaWFController.createMediaRequest(MediaWFController.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
*********** After sending teh Httppost Request ******************
As per my understanding the issue has occured while deserializing the object. If I am keeping the same package hierachy on both of the sides for the RequestDetails class the code is working fine.Is it compulsory to have the same package hierarchy for the RequestDetails domain object? If no how to resolve the issue I am facing?
To deserialise the object you need to have the same class in both instances. This includes the package name of the class.
As you have said the packages are different then the failure you are seeing is easy to understand.

Tomcat java.lang.NoClassDefFoundError: Could not initialize class

The full error: java.lang.NoClassDefFoundError: Could not initialize class lt.maze.dao.DAO
The class DAO is used from my LoginServlet. It is compiled and deployed, I checked WEB-INF/classes. DAO.class exists.
Why is isn't it loaded? Am I suppose to add them to my classpath manually? (I have the manifest file to load my properties file).
LoginServlet.java:
#WebServlet(name = "LoginServlet", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
#Override
public void init() throws ServletException
{
System.out.println("System. out. Its online.");
getServletContext().log("LoginServlet initialised");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().log("Http request. Request URI: " + request.getRequestURI());
System.out.println("Http request. Request URI: " + request.getRequestURI());
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username == null || password == null) {
response.sendError(401);
} else {
UserDAO userDAO = DAO.getUserDAO();
User user = userDAO.find(username, password);
if(user == null) {
response.sendError(401, "Invalid username or password");
} else {
String sessionToken = SessionTokens.getSessionToken();
response.addCookie(new Cookie("session-token", sessionToken));
getServletContext().log("Valid connection. token:"+sessionToken);
}
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().log("Request received via GET.");
System.out.println("Requeswt received via GET");
}
}
Full stacktrace:
18-May-2015 14:49:35.133 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [LoginServlet] in context with path [/ChatApp] threw exception [Servlet execution threw an exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class lt.maze.dao.DAO
at lt.maze.LoginServlet.doPost(LoginServlet.java:38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
If an exception is propagating out of the constructor of the class or a static initializer, then you also get java.lang.NoClassDefFoundError: Could not initialize class ... .

Why code insert data before validation in Spring

I have code here:
#Controller
#RequestMapping(value="/guestbook")
public class GuestBookController {
#Autowired
GuestBookServiceIF guestBookServiceIF;
#ModelAttribute("messagesModel")
public List<UserMessage> getMessagesModel() {
return guestBookServiceIF.fetchAllService();
}
#RequestMapping(method = RequestMethod.GET)
public String renderGuestBook(Model model) {
GuestBookBackObject guestBookBackObject = new GuestBookBackObject();
model.addAttribute("guestBookBackObject", guestBookBackObject);
return "book";
}
#RequestMapping(method=RequestMethod.POST)
public String saveGuestBookMessage(#ModelAttribute(value="guestBookBackObject") GuestBookBackObject guestBookBackObject,
BindingResult buindingResult) {
guestBookBackObject.setIsNameExist(guestBookServiceIF.isUserInDBService(guestBookBackObject.getUser().getUserName()));
GuestBookValidation validator = new GuestBookValidation();
validator.validate(guestBookBackObject, buindingResult);
if(buindingResult.hasErrors()) {
return "book";
} else {
guestBookBackObject.getUserMessage().setTheUser(guestBookBackObject.getUser());
guestBookServiceIF.saveMessageService(guestBookBackObject.getUserMessage());
return "redirect:/guestbook";
}
}
in saveGuestBookMessage() there is should be some validation before execute the rest of the code. The point of my validation is that it check is there same user name in Database if yes user name is exist in database then on jsp page should render some error messages like: "Choose different name" for example for this purpose is isUserInDBService() method.
Here is my validator code:
#Component
public class GuestBookValidation implements Validator{
#SuppressWarnings("rawtypes")
#Override
public boolean supports(Class clazz) {
return GuestBookBackObject.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object obj, Errors error) {
GuestBookBackObject guestBookBackObject = (GuestBookBackObject)obj;
if(guestBookBackObject.equals(obj)) {
ValidationUtils.rejectIfEmpty(error, "user.userName", "", "\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0432\u0432\u0435\u0441\u0442\u0438 \u0438\u043C\u044F");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "userMessage.theMessage", "", "\u042D\u0442\u043E \u043F\u043E\u043B\u0435 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C");
if(guestBookBackObject.getIsNameExist()== null) {
ValidationUtils.rejectIfEmpty(error, "user.userName", "", "Please choose different user name");
}
} else {
try {
throw new Exception("Object of referance variable obj not equal referance variable guestBookBackObject");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Basically it should work fine, but it gives error:
Hibernate: insert into USER_DESC (USER_NAME) values (?)
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1062, SQLState: 23000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry 'we' for key 'UK_ok6uvp3eyniad0xua3xdt5icw'
Oct 01, 2013 9:27:04 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'we' for key 'UK_ok6uvp3eyniad0xua3xdt5icw'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2460)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2377)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2361)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2975)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3487)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:214)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:194)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:735)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:727)
at org.hibernate.engine.spi.CascadingAction$5.cascade(CascadingAction.java:258)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:388)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:331)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:209)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:166)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:424)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:263)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at demidov.pkg.persistence.GuestBookDAOImpl.saveMessage(GuestBookDAOImpl.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy8.saveMessage(Unknown Source)
at demidov.pkg.service.GuestBookServiceImpl.saveMessageService(GuestBookServiceImpl.java:27)
at demidov.pkg.web.GuestBookController.saveGuestBookMessage(GuestBookController.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Which tells that value exist in database and this value should be unique. Ok! But why the Validator let insert value first with out check them???
My back object (GuestBookBackObject):
#Component
public class GuestBookBackObject {
private UserMessage userMessage;
public UserMessage getUserMessage() {
return userMessage;
}
public void setUserMessage(UserMessage userMessage) {
this.userMessage = userMessage;
}
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
private User isNameExist;
public User getIsNameExist() {
return isNameExist;
}
public void setIsNameExist(User isNameExist) {
this.isNameExist = isNameExist;
}
}
thank you.
Lacking more information like implementation of GuestBookBackObject. But based on what you have given
Simply the Exception you have got is thrown because you never check in database whether the values you going to insert exists or not in a column which is said to be unique.
You should implement this inside your validator or anywhere before you save. For example
boolean exists = guestBookServiceIF.isMessageExists(guestBookBackObject);
The only way to database to find out you are violating the a constraint is while executing that statement.
To store the validation message you are calling the wrong method.
if(guestBookBackObject.getIsNameExist()== null) {
ValidationUtils.rejectIfEmpty(error, "user.userName", "", "Please choose different user name");
}
If the property is set, but the username isn't empty nothing is going to get set. You should simply call the reject method on the Errors object.
if(guestBookBackObject.getIsNameExist()== null) {
errrors.reject("username.not.unique", "Please choose different user name");
}
Next to that you should do the check inside your Validator and not your controller. That way you can let Spring do all the heavy lifting for you.

Categories

Resources