MongoDB Get all records Java API - java

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
}
}

Related

Socket Timeout Exception in tomcat?

Getting socket timeout exception frequently in my web application. Let me explain what's the issue is while reading data at very first time application works fine and according to my idea after some time it goes to ideal state. While executing it again(after some time), getting socket timeout error as mentioned below. Please help me in finding solution, Thank you.
Dec 12, 2017 9:17:31 AM
com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not
be mapped to a response, re-throwing to the HTTP container
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:535)
at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:504)
at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:566)
at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:137)
at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:341)
at org.apache.coyote.Request.doRead(Request.java:431)
at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:290)
at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:449)
at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:315)
at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:200)
at org.codehaus.jackson.impl.StreamBasedParserBase.loadMore(StreamBasedParserBase.java:107)
at org.codehaus.jackson.impl.Utf8StreamParser._skipWS(Utf8StreamParser.java:1689)
at org.codehaus.jackson.impl.Utf8StreamParser.nextToken(Utf8StreamParser.java:310)
at org.codehaus.jackson.map.deser.ArrayDeserializers$ByteDeser.deserialize(ArrayDeserializers.java:260)
at org.codehaus.jackson.map.deser.ArrayDeserializers$ByteDeser.deserialize(ArrayDeserializers.java:229)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:230)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:334)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:495)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:351)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2112)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1004)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:410)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:474)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:183)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
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.filters.CorsFilter.handleNonCORS(CorsFilter.java:438)
at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:179)
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:957)
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(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)
// Variables to build a client to call the Web Resource.
Client c = Client.create();
// Declaring WebResource to connect to the web application
WebResource r =
c.resource(UriBuilder.fromUri(ReallyMakeConstants.URL_SERVER)
.build());
MultivaluedMap<String, String> retrieveBidRequests = new
MultivaluedMapImpl();
// Binding the values
retrieveBidRequests.add("vendorId", vendorId);
retrieveBidRequests.add("makeType", makeType);
retrieveBidRequests.add("selectedStatus", selectedBidStatus);
String veRequestsList = r.path("bidResource")
.path("retrieveVendorBidRequests2")
.queryParams(retrieveBidRequests)
.accept(MediaType.APPLICATION_JSON).get(String.class);
String bidRequestsList = request
.getAttribute("veRequestsList ").toString();
JSONParser bidRequestJsonParser = new JSONParser();
JSONArray bidRequestJsonArray;
BidRequest bidRequest = null;
Model model = null;
Object obj = bidRequestJsonParser.parse(bidRequestsList);
bidRequestJsonArray = (JSONArray) obj;

org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next

String id = request.getParameter("id");
try {
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://172.10.10.3:5432/stepup380qty","stepup380qty","stepup380qty");
String query = "select binarydata from ad_image where ad_image_id =" + id;
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery(query);
rs.next();
String img = rs.getString("binarydata");
byte[] img2 = new byte[img.length()];
InputStream imgstream = rs.getBinaryStream("binarydata");
int index = imgstream.read(img2, 0, img.length());
stm.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(img2,0,img2.length);
response.getOutputStream().flush();
imgstream.close();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
This is my code and i am getting this error
org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.checkResultSet(AbstractJdbc2ResultSet.java:2881)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:1956)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:2568)
at ireportImage.IreportIMAGE.doGet(IreportIMAGE.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
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: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(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)

java.lang.ClassNotFoundException: org.apache.spark.launcher.LauncherProtocol$Message

I at the time of running spark job in my project:
public static List<String> getAllSavedModelFoldersJob(String saveModelsFolderFilePath) {
JavaSparkContext ctx = null;
List<String> list = new ArrayList<String>();
try {
ctx = new JavaSparkContext(
new SparkConf().setAppName("Save Models into File").setMaster("local"));
list = getAllSavedModelFolders(ctx, saveModelsFolderFilePath).collect();
} catch (Exception e) {
e.printStackTrace();
return list;
} finally { // ctx.stop(); } return list; }
}
But getting below error,
java.lang.ClassNotFoundException: org.apache.spark.launcher.LauncherProtocol$Message
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at org.apache.spark.scheduler.local.LocalBackend.(LocalBackend.scala:107)
at org.apache.spark.SparkContext$.org$apache$spark$SparkContext$$createTaskScheduler(SparkContext.scala:2603)
at org.apache.spark.SparkContext.(SparkContext.scala:522)
at org.apache.spark.api.java.JavaSparkContext.(JavaSparkContext.scala:59)
at com.nuevora.core.spark.SaveModelsJob.getAllSavedModelFoldersJob(SaveModelsJob.java:257)
at com.nuevora.controllers.FormsValidatorServlet.service(FormsValidatorServlet.java:546)
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:504)
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:1074)
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(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)
I am using spark version is spark-1.6,hadoop2.6 and java1.8.

I am trying following query and getting unexpected token : in exception

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.

No Database selected SQLException using Datasource

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

Categories

Resources