public boolean insert(Product product){
boolean result = true;
Transaction tx = null;
int quantity=0;
try {
tx = session.getTransaction();
tx.begin();
Query query=session.createQuery("update Stock s set s.quantity=s.quantity+100");
query.executeUpdate();
session.saveOrUpdate(product);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
result=false;
} finally {
session.close();
}
return result;
}
select ,save and delete query are working successfully but This exception I am getting only in while update the record....
I want to save the record in Product Table and as well as update Stock Table
BELOW IS MY EXCEPTION
org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:8: unexpected token: in
Sep 12, 2015 10:34:41 AM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:8: unexpected token: in
line 1:8: unexpected token: in
at org.hibernate.hql.internal.antlr.HqlBaseParser.updateStatement(HqlBaseParser.java:239)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:169)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:295)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:131)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:93)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836)
at in.edu.pondiuni.service.ProductService.insert(ProductService.java:23)
at in.edu.pondiuni.controller.ProductServlet.processRequest(ProductServlet.java:53)
at in.edu.pondiuni.controller.ProductServlet.doGet(ProductServlet.java:91)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
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:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
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:744)
If sure of the executed query, I would try using another package name, in is a reserved keyword and that might be the issue, that would correspond to position 8:
UPDATE in.edu.pondiuni.xxx.Stock
^
8
To do so, a search and replace in your codebase of in.edu.pondiuni should do the job, you can replace it with edu.pondiuni for example.
Related
I have a controller which handles a long polling mechanism by using Springs DeferredResult. At times when I call the controller method multiple times I get the below exception :
java.lang.IllegalStateException: getOutputStream() has already been called for this response
So there is a call views/getLongPollingGraphData which passes some ids and returns with a json response for one or none id. When I load the page multiple times which makes this URL call some times I get the above exception.
The issue that I face is I am using the onCompletion callback on DeferredResult to remove the DeferredResult from a map when it either times out or the response is set on it. But in the case of this exception the onCompletion is not called and it stays on the map. I have read different So posts about this exception but I could not relate to any one of them.
Below is the entire stack trace of the exception and parts of my controller method.
Nov 07, 2016 9:52:06 AM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:648)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:104)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:186)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
at org.apache.jsp.WEB_002dINF.jsp.ClientAbortException_jsp._jspService(ClientAbortException_jsp.java:136)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:659)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:625)
at org.apache.catalina.core.AsyncContextImpl$1.run(AsyncContextImpl.java:239)
at org.apache.catalina.core.AsyncContextImpl.doInternalDispatch(AsyncContextImpl.java:382)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:215)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
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.asyncDispatch(CoyoteAdapter.java:299)
at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1652)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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)
Nov 07, 2016 9:52:06 AM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet main-dispatcher threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:648)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:104)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:186)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
at org.apache.jsp.WEB_002dINF.jsp.ClientAbortException_jsp._jspService(ClientAbortException_jsp.java:136)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:659)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:625)
at org.apache.catalina.core.AsyncContextImpl$1.run(AsyncContextImpl.java:239)
at org.apache.catalina.core.AsyncContextImpl.doInternalDispatch(AsyncContextImpl.java:382)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:215)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
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.asyncDispatch(CoyoteAdapter.java:299)
at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1652)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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)
Nov 07, 2016 9:52:06 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [main-dispatcher] in context with path [/test-web] threw exception [java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:648)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:104)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:186)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
at org.apache.jsp.WEB_002dINF.jsp.ClientAbortException_jsp._jspService(ClientAbortException_jsp.java:136)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:659)
at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:625)
at org.apache.catalina.core.AsyncContextImpl$1.run(AsyncContextImpl.java:239)
at org.apache.catalina.core.AsyncContextImpl.doInternalDispatch(AsyncContextImpl.java:382)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:215)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
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.asyncDispatch(CoyoteAdapter.java:299)
at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1652)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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)
Controller method:
#RequestMapping(value = "views/getLongPollingGraphData", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public DeferredResult<WebServiceResponse> getLongGraphData(
HttpServletRequest request,
#RequestParam(value = "ids") String ids)
throws Exception
{
//perform operations
//set time out this DeferredResult, after 5 seconds
final DeferredResult<WebServiceResponse> deferredResult = new DeferredResult<WebServiceResponse>(5000L, awrDefault);
//listOfViews is a list containing ids
mMapOfDeferredResultAndViews.put(deferredResult, listOfViews);
//more operations
deferredResult.onCompletion(new Runnable() {
#Override
public void run()
{
mMapOfDeferredResultAndViews.remove(deferredResult);
}
});
return deferredResult;
}
Edit:
I think that a org.apache.catalina.connector.ClientAbortException is thrown at some point when the page is continuously refreshed. I use org.springframework.web.servlet.handler.SimpleMappingExceptionResolver to handle it in a jsp page. Below is the code:
main-dispatcher-servlet.xml
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">Exception</prop>
<prop key="org.apache.catalina.connector.ClientAbortException">ClientAbortException</prop>
</props>
</property>
</bean>
ClientAbortException.jsp
<%#page import="org.slf4j.LoggerFactory"%>
<%#page import="org.slf4j.Logger"%>
<%#page import="com.test.model.messages.Messages"%>
<%#page import="java.util.Enumeration"%>
<%#page import="org.codehaus.jackson.map.ObjectMapper"%>
<%#page import="com.test.model.exceptions.TestException"%>
<%#page import="com.test.web.exchange.WebServiceResponse"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
Logger LOGGER = LoggerFactory.getLogger(this.getClass());
LOGGER.debug("Exception caught in JSP: ", (Exception) request.getAttribute("exception"));
boolean bReturnJson = false;
Enumeration<?> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
if (headerName.equals("accept")) {
if (request.getHeader(headerName).equals(
"application/json; charset=utf-8")) {
bReturnJson = true;
}
break;
}
}
if (bReturnJson) {
WebServiceResponse awsr = new WebServiceResponse();
TestException exception = new TestException(
Messages.ERROR.toString(),
(Exception) request.getAttribute("exception"));
awsr.setException(exception);
ObjectMapper mapper = new ObjectMapper();
out.write(mapper.writeValueAsString(awsr));
} else {
((Exception) request.getAttribute("exception")).printStackTrace();
%>
HTML error!
<%
}
%>
The problem is obvious:
http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getInputStream--
Throws:
IllegalStateException - if the getReader() method has already been called for this request
To find out, which Filter (or something similar) calls the getReader() method before your JSP servlet does, set a break point to IllegalStateException. Call your JSP. In your debugger's call stack, find out the specific implementation class of the interface ServletRequest (this is container specific). Set a break point to getReader(), then call your JSP again and you got the root cause.
If you really have to call getReader() or getInputStream() multiple times, a HttpServletRequestWrapper might help you, see e.g.:
How to read InputStream multiple times
https://gist.github.com/calo81/2071634
Without your whole project code no-one will be able to find out the cause for this Exception.
I am running a query to get all the records for a particular collection from mongoDB, the code is -
#WebMethod(operationName = "getAllWorkItem", action = "urn:GetWorkItem")
#WebResult(name = "workItems")
public List<WorkItem> getAllWorkItem() {
List<WorkItem> workItemList = new ArrayList<WorkItem>();
WorkItem workItem;
AttachmentTransactions atr = new AttachmentTransactions();
AuditInfoTransactions autr = new AuditInfoTransactions();
// documentWItem.put("id", workItemId);
FindIterable<Document> item = transaction.getWorkItemCollection().find();
for (Document document : item) {
workItem = new WorkItem();
#SuppressWarnings("unchecked")
ArrayList<String> attchObjArr = (ArrayList<String>) document.get("attachmentId");
workItem.setAttachment(atr.getAttachmentById("", attchObjArr.get(0)));
#SuppressWarnings("unchecked")
ArrayList<String> auditObjArr = (ArrayList<String>) document.get("auditInfoId");
workItem.setAuditInfo(autr.getAuditInfoById("", auditObjArr.get(0)));
workItem.setEtc(document.getDate("etc"));
workItem.setExecutionUrl(document.getString("executionUrl"));
workItem.setId(document.get("_id").toString());
workItem.setName(document.getString("name"));
workItem.setPriority(document.getString("priority"));
workItem.setProcessName(document.getString("processName"));
workItem.setStatus(document.getString("status"));
workItem.setType(document.getString("type"));
workItemList.add(workItem);
}
return workItemList;
}
However I am getting error, I do not understand is it a issue due to time out or the way I am executing the API? Any help or pointer would be appreciated.
Apr 18, 2016 1:31:56 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://ws.ss.inct.com/}WorkItemFacadeService# {http://ws.ss.inct.com/}getAllWorkItem has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:64)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.interceptor.OutgoingChainInterceptor.handleMessage(OutgoingChainInterceptor.java:81)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at org.apache.openejb.server.cxf.CxfWsContainer.onMessage(CxfWsContainer.java:89)
at org.apache.openejb.server.webservices.WsServlet.service(WsServlet.java:98)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:83)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
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.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
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:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
Caused by: org.apache.catalina.connector.ClientAbortException: java.net.SocketException: Broken pipe
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:407)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:356)
at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:308)
at org.apache.catalina.connector.CoyoteOutputStream.close(CoyoteOutputStream.java:108)
at org.apache.cxf.transport.http.AbstractHTTPDestination$WrappedOutputStream.close(AbstractHTTPDestination.java:734)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
at org.apache.cxf.transport.http.AbstractHTTPDestination$BackChannelConduit.close(AbstractHTTPDestination.java:677)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
... 31 more
Caused by: java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:366)
at org.apache.coyote.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:240)
at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:119)
at org.apache.coyote.http11.AbstractOutputBuffer.doWrite(AbstractOutputBuffer.java:192)
at org.apache.coyote.Response.doWrite(Response.java:499)
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:402)
... 39 more
Another Way to to connect mongo db using java
public static void main(String[] args) {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("mydb");// db name
DBCollection collection = db.getCollection("test");
BasicDBObject query = new BasicDBObject();
BasicDBObject rmfld = new BasicDBObject();
JSONArray jrr=new JSONArray();
JSONObject jobj=new JSONObject();
// query.put("name", "test");
rmfld.put("_id", 0);
try{
DBCursor openCur = collection.find(query,rmfld);
while (openCur.hasNext()) {
jrr.put(openCur.next());
}
if(openCur!=null)
{
openCur.close();
}
System.out.println(jrr);
}
catch (Exception e) {
// TODO: handle exception
}
}
I have an action that should select a row from a table using the id:
#RequestMapping("/test/{userId}")
#ResponseBody
public void testUserSettings(#DestinationVariable Integer userId){
System.out.println("test");
Session session = sessionFactory.openSession();
Query query = session.createQuery("select us.settings from UserSettings us"
+ " where us.userId = :userId");
Transaction transaction = null;
try {
transaction = session.beginTransaction();
query.setParameter("userId", userId);
query.executeUpdate();
transaction.commit();
} catch (HibernateException e) {
if (transaction != null)
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
It invokes the method because "test" is printed. The problem is in the statement. For some reason I get the following output in the console:
org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for select queries [select us.settings from com.musala.ving.entities.UserSettings us where us.userId = :userId]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.errorIfSelect(QueryTranslatorImpl.java:324)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:444)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:379)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1286)
at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:118)
at com.musala.ving.controllers.UserSettingsController.testUserSettings(UserSettingsController.java:46)
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.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
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:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
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:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:503)
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:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
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)
You are calling query.executeUpdate(); for a select query. Try using query.list(), or query.uniqueResult() instead.
query.uniqueResult() should be used if you expect a single result.
Javadoc excerpt for Query#list():
Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].
Javadoc excerpt for Query#uniqueResult():
Convenience method to return a single instance that matches the query, or null if the query returns no results.
Also, transaction.commit(); should not be necessary since this query doesn't update the database.
#RequestMapping("/test/{userId}")
#ResponseBody
public void testUserSettings(#DestinationVariable Integer userId){
System.out.println("test");
Session session = sessionFactory.openSession();
Query query = session.createQuery("select us.settings from UserSettings us"
+ " where us.userId = :userId");
Transaction transaction = null;
try {
transaction = session.beginTransaction();
query.setParameter("userId", userId);
query.list();
transaction.commit();
} catch (HibernateException e) {
if (transaction != null)
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
I am using hibernate with hql (in conjunction with spring mvc, if that matters) and fixed the issue by doing the following:
String hql = "select clientId from Cart where cartId = :val" ;
Query query = getSession().createQuery(hql);
query.setParameter("val", cartId);
//int result = query.executeUpdate(); OLD VERSION. REPLACED WITH THE LINE BELOW:
int result = query.getFirstResult();
return result;
So for me getFirstResult() solved the problem.
query.executeUpdate();
you do a update of an select query !?
How the error message says... "Not supported for select queries"
use query.execute(); or what the correct method is...
I am currently working on a small addresstable with vaadin, just to get to know vaadin a little. I have run into a problem, where I want to sort the entries of my table manually. The problem is, that I get a NullPointerException when i try to do this:
item.getItemProperty(Columns.NAME).getValue()
I have tried a few things here. I checked item and item isn't null, neither is item.getItemProperty(Columns.NAME) null. So when I try to make an if I still get a NullPointerException
if(item.getItemProperty(Columns.NAME).getValue() == null){}
The value is null and I understand that, but I want to give this value to an other item and I have no idea how to.
SEVERE: Servlet.service() for servlet [com.example.addresstable.AddresstableUI$Servlet] in context with path [/Addresstable] threw exception [com.vaadin.server.ServiceException: java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.vaadin.data.util.IndexedContainer$IndexedContainerProperty.getValue(IndexedContainer.java:898)
at com.example.addresstable.AddressTable.addAddressToTable(AddressTable.java:114)
at com.example.addresstable.AddresstableUI.init(AddresstableUI.java:26)
at com.vaadin.ui.UI.doInit(UI.java:639)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:222)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1402)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:305)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
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:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
IndexedContainer's Items are IndexedContainerItem.
When call it's getItemProperty the result is never null:
#Override
public Property getItemProperty(Object id) {
return new IndexedContainerProperty(itemId, id);
}
But when you call Property's getValue it may be null if there is no itemId or propertyId:
#Override
public T getValue() {
return (T) items.get(itemId).get(propertyId);
}
Probably it is a Vaadin bug: link
EDIT
If you want to check the container contains the item, you can do this:
public class MyIndexedContainer extends IndexedContainer {
#Override
public Item getUnfilteredItem(Object itemId) { // make it public
return super.getUnfilteredItem(itemId);
}
}
then
Table table = new Table();
MyIndexedContainer mic = new MyIndexedContainer();
table.setContainerDataSource(mic);
//...
// check that the container contains the item
if (mic.getUnfilteredItem(item) != null) {
//...
}
I have created a webapp using servlets. I am establishing a connection to a MySQL database using a DataSource object and get the following stacktrace when I load the webpage:
java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2832)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2781)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1569)
at uk.co.morleys.TestimonialService.countTestimonials(TestimonialService.java:106)
at uk.co.morleys.TestimonialService.getPaginationDetails(TestimonialService.java:122)
at uk.co.morleys.HomeController.doGet(HomeController.java:77)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
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:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
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:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This is the TestimonialService.java file:
public class TestimonialService {
ResultSet rs;
DataSource ds;
public TestimonialService(){
rs = null;
ds = DataSourceFactory.getMySQLDataSource();
}
public int countTestimonials() throws SQLException{
int count = 0;
try(Connection con = ds.getConnection()){
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM morleys_testimonial WHERE isActive=1");
while(rs.next()){
count = rs.getInt(1);
}
}catch(SQLException e){
e.printStackTrace();
}
return count;
}
}
This is the DataSourceFactory.java where I establish a connection to the database:
public class DataSourceFactory {
public static DataSource getMySQLDataSource() {
MysqlDataSource mysqlDS = null;
try {
mysqlDS = new MysqlDataSource();
mysqlDS.setURL("jdbc:mysql://hostname/");
mysqlDS.setDatabaseName("dbname");
mysqlDS.setUser("user");
mysqlDS.setPassword("password");
} catch (Exception e) {
throw new IllegalStateException(e);
}
return mysqlDS;
}
}
Question Am I not selecting the database with setDatabaseName()? If not how do I do this?
Why dont you simply try this
mysqlDS.setURL("jdbc:mysql://hostname/dbname");
instead of
mysqlDS.setDatabaseName("dbname");
Are you providing port number along with the hostname? If not try giving portnumber as well.
Additionally make sure you have Mysql JDBC Driver
You can follow any of these tutorial for creating MysqlDataSource:
http://www.journaldev.com/2509/jdbc-datasource-example-oracle-mysql-and-apache-dbcp-tutorial
or
http://www.herongyang.com/JDBC/MySQL-JDBC-Driver-DataSource.html