implementing mongodb text search in jsp - mongodb

I am trying to implement mongodb text search in jsp page but I am getting an error. Below is my code and error. Please let me know if you find some thing wrong with my code.
Your help is greatly appreciated. Thanks in advance.
Code:
Mongo m=new MongoClient("localhost",27017);
DB db = m.getDB("sagar");
String searchText="samosa";
DBCollection collection=db.getCollection("review");
DBObject searchCmd = new BasicDBObject();
searchCmd.put("text",collection);
searchCmd.put("search",searchText);
DBCursor cursor = collection.find(searchCmd);
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
Error:
type Exception report
message An exception occurred processing JSP page /review.jsp at line 33
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /review.jsp at line 33
30: String id= (String) dbo.get("text");
31: out.println(id+"\n");
32: }*/
33: while(cursor.hasNext())
34: {
35: System.out.println(cursor.next());
36: }
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalArgumentException: can't serialize class com.mongodb.DBCollectionImpl
org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:299)
org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:194)
org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:136)
com.mongodb.DefaultDBEncoder.writeObject(DefaultDBEncoder.java:36)
com.mongodb.OutMessage.putObject(OutMessage.java:289)
com.mongodb.OutMessage.writeQuery(OutMessage.java:211)
com.mongodb.OutMessage.query(OutMessage.java:86)
com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:83)
com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:68)
com.mongodb.DBCursor._check(DBCursor.java:498)
com.mongodb.DBCursor._hasNext(DBCursor.java:621)
com.mongodb.DBCursor.hasNext(DBCursor.java:657)
org.apache.jsp.review_jsp._jspService(review_jsp.java:93)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

You are trying map collection object to value with key text:
searchCmd.put("text",collection)
You may need to do only searchCmd.put("search",searchText);
Like, db.reviews.find({"search":"samosa"})

Related

Caused by: java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use

I am getting the below error when trying to download file in liferay
05:03:35,867 ERROR [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'][PortletRequestDispatcherImpl:115] org.springframework.web.util.NestedServletException: View rendering failed; nested exception is java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use
org.springframework.web.util.NestedServletException: View rendering failed; nested exception is java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use
at org.springframework.web.servlet.ViewRendererServlet.processRequest(ViewRendererServlet.java:96)
at org.springframework.web.servlet.ViewRendererServlet.doGet(ViewRendererServlet.java:67)
Caused by: java.lang.IllegalStateException: Cannot obtain Writer because OutputStream is already in use
at com.liferay.portlet.MimeResponseImpl.getWriter(MimeResponseImpl.java:90)
at com.liferay.portlet.PortletServletResponse.getWriter(PortletServletResponse.java:207)
at com.netcracker.portal.framework.spring.templates.view.SoyDataView.renderMergedOutputModel(SoyDataView.java:93)
and below is the code, i tried searching online but none of them have worked
String defaultFileName = "hello.pdf";
resourceResponse.setContentType("application/octet-stream");
resourceResponse.addProperty(GenericServiceTransport.CONTENT_DISPOSITION, "attachment; filename= hello.pdf" );
resourceResponse.flushBuffer();
try {
out = resourceResponse.getPortletOutputStream();
out.write(backendFile.getContent());
out.flush();
out.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
return;
As first item I'd try to remove the flushBuffer call. You probably get the exception in the line following it, and flushing the buffer surely will use the output stream.
If that doesn't help, please add mute code, e.g. the complete method including its signature

Catching messages thrown by classes in a lower level

There are four levels in my application: (1) My application, (2) pivot4j, (3) olap4j, and (4) Mondrian
If I run this code in Scala:
try {
renderer.render(model, new HtmlRenderCallback(sw))
}
catch {
case ex: Exception => println(ex.getMessage)
}
The application prints the error thrown by pivot4j:
org.olap4j.OlapException: mondrian gave exception while parsing query
If I don't catch the error, the stack trace is (in bold the relevant messages):
play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution
exception[[PivotException: org.olap4j.OlapException: mondrian gave
exception while parsing query]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:293)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:220)
at play.api.GlobalSettings$class.onError(GlobalSettings.scala:160)
at play.api.DefaultGlobal$.onError(GlobalSettings.scala:188)
at play.api.http.GlobalSettingsHttpErrorHandler.onServerError(HttpErrorHandler.scala:100)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:100)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:99)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:346)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:345)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:36) Caused
by: org.pivot4j.PivotException: org.olap4j.OlapException: mondrian
gave exception while parsing query
at org.pivot4j.impl.PivotModelImpl.getCellSet(PivotModelImpl.java:598)
at org.pivot4j.ui.table.TableRenderer.render(TableRenderer.java:425)
at olap.process.RunOlap.doRunMdx(RunOlap.scala:91)
at olap.process.RunOlap$$anonfun$runMdx$1.apply(RunOlap.scala:53)
at olap.process.RunOlap$$anonfun$runMdx$1.apply(RunOlap.scala:51)
at login.Authentication$LoggedAction$$anonfun$invokeBlock$1.apply(LoggedAction.scala:47)
at login.Authentication$LoggedAction$$anonfun$invokeBlock$1.apply(LoggedAction.scala:42)
at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:253)
at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:36) Caused
by: org.olap4j.OlapException: mondrian gave exception while parsing
query
at mondrian.olap4j.MondrianOlap4jConnection$Helper.createException(MondrianOlap4jConnection.java:858)
at mondrian.olap4j.MondrianOlap4jStatement.parseQuery(MondrianOlap4jStatement.java:375)
at mondrian.olap4j.MondrianOlap4jStatement.executeOlapQuery(MondrianOlap4jStatement.java:346)
at org.pivot4j.impl.PivotModelImpl.executeMdx(PivotModelImpl.java:646)
at org.pivot4j.impl.PivotModelImpl.getCellSet(PivotModelImpl.java:596)
at org.pivot4j.ui.table.TableRenderer.render(TableRenderer.java:425)
at olap.process.RunOlap.doRunMdx(RunOlap.scala:91)
at olap.process.RunOlap$$anonfun$runMdx$1.apply(RunOlap.scala:53)
at olap.process.RunOlap$$anonfun$runMdx$1.apply(RunOlap.scala:51)
at login.Authentication$LoggedAction$$anonfun$invokeBlock$1.apply(LoggedAction.scala:47)
Caused by: mondrian.olap.MondrianException: Mondrian Error: MDX object '[Measures].[Unit Cost]' not found in cube 'Sales'
Mondrian is the one that is originating the error, and I need to get the message that is throwing:
MDX object '[Measures].[Unit Cost]' not found in cube 'Sales'
I tried:
try {
renderer.render(model, new HtmlRenderCallback(sw))
}
catch {
case ex: MondrianException => println(ex.getMessage)
}
But is not catching the error.
Use Apache Commons ExceptionUtils to get the root exception.

Media type separator is missing

Please help as I don't know what is wrong here. I have a very simple REST GET service but I keep running into the error below:
#GET
#Path("users/{id}")
#Produces("text/plain")
public Response getUserById(#PathParam("id") String id) {
return Response.status(200).entity("getUserById is called, id : " + id).build();
}
And the exception I'm seeing is below:
[ERROR ] SRVE0315E: An exception occurred: java.lang.Throwable: javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:5000)
at [internal classes]
Caused by: javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:401)
... 1 more
Caused by: java.lang.IllegalArgumentException: Media type separator is missing
at org.apache.cxf.jaxrs.impl.MediaTypeHeaderProvider.handleMediaTypeWithoutSubtype(MediaTypeHeaderProvider.java:196)
... 1 more
Any idea what is wrong here? TIA

E11000 duplicate key error when doing PUT for modifiable resource with Spring Data Rest

Update:
According to this question, the author of Spring data rest say, the #Version properties will become ETags in response header. And there are two options for update:
Just PUT without an If-Match header -- enforces overriding whatever is present on the server as the aggregate gets loaded, incoming data mapped onto it and it written back. You still get optimistic locking applied if another client changed the aggregate in the meantime (although an admittedly very short window). If that's the case you'll see a 409 Conflict.
I am currently using this way for PUT, and a 409 conflict is what I have got. But the exception doesn't seems to be optimistic locking. And there suppose will not have another client changed the aggreate in the meantime.
PUT with an If-Match header - Spring Data REST checks the ETag submitted against the current value of the version property of the aggregate and return a 412 Precondition Failed in case there's a mismatch at that point.
I have tried to add If-Match header(If-Match: "0" or If-Match: 0), but both of them got 500 Internal server error. The exception is as below and I have check that the resource I PUT is currently version "0" in both db and ETags in response header if I GET it.
java.lang.NullPointerException: null
at org.springframework.data.rest.webmvc.support.ETag.getVersionInformation(ETag.java:192) ~[spring-data-rest-webmvc-2.4.1.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.support.ETag.from(ETag.java:76) ~[spring-data-rest-webmvc-2.4.1.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.support.ETag.verify(ETag.java:94) ~[spring-data-rest-webmvc-2.4.1.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryEntityController.putItemResource(RepositoryEntityController.java:410) ~[spring-data-rest-webmvc-2.4.1.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969) [spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:882) [spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]
According to this question, the author of Spring data rest say, with Spring Data JPA, you need to use #javax.persistence.Version. #org.springframework.data.annotation.Version is the annotation to use for other Spring Data modules.
I have tried to changed to using #javax.persistence.Version, but the version properties will no longer become ETags in header, it will shows in "version" field in response body. In the meantime, if I put without If-Match, it will successful(200), but the version field will be droped away. If I put with If-Match: 0, it will got 412 Precondition Failed. No matter what, I am not using spring-data-jpa, I am using spring-boot-starter-data-rest and spring-boot-starter-data-mongodb. So that, I think that is right way for my #Version will be org.springframework.data.annotation.Version in Spring Data Common.
We have a REST API webapp by Spring Data Rest framework with MongoDB. And there has a #document class DeliveryOrder
#Document(collection = "delivery_orders")
public class DeliveryOrder extends PersistableDocument {
private static final long serialVersionUID = 1L;
#LastModifiedBy
protected String lastModifiedBy;
#LastModifiedDate
#DateTimeFormat(iso = ISO.DATE_TIME)
protected Instant lastModifiedDate;
#Version
protected Long version;
protected Map<String, Object> dyna;
...
}
And the PersistableDocument as below
public abstract class PersistableDocument {
private static final long serialVersionUID = 1L;
#Id
protected String id;
#CreatedBy
protected String createdBy;
#CreatedDate
#DateTimeFormat(iso = ISO.DATE_TIME)
#Indexed(direction = IndexDirection.ASCENDING, unique = false)
protected Instant createdDate;
...
}
If I PUT the resource which already existed (URI: https://${HOST}/${APPLICATION_NAMEAME}/${Object_Id}) will got 409 conflict and the exception as below. But If I have removed the #Version field, it will works as PUT method. It seems not because the _id field is duplicated. Might be some optimistic locking issue?
Any help is appreciated
2016-05-04 17:38:34.413 ERROR 8668 --- [nio-1010-exec-2]
o.s.d.r.w.RepositoryRestExceptionHandler : Write failed with error code 11000 and error message 'E11000 duplicate key error collection: 56cbfbd323f5496dcc02c579.delivery_orders index: _id_ dup key: { : ObjectId('56d6b81623f54966b07b0587') }'; nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: 56cbfbd323f5496dcc02c579.delivery_orders index: _id_ dup key: { : ObjectId('56d6b81623f54966b07b0587') }'
org.springframework.dao.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: 56cbfbd323f5496dcc02c579.delivery_orders index: _id_ dup key: { : ObjectId('56d6b81623f54966b07b0587') }'; nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: 56cbfbd323f5496dcc02c579.delivery_orders index: _id_ dup key: { : ObjectId('56d6b81623f54966b07b0587') }'
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:71) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2060) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:464) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.insertDBObject(MongoTemplate.java:985) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:798) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.doSaveVersioned(MongoTemplate.java:941) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:925) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.save(SimpleMongoRepository.java:78) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.11.1.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468) ~[spring-data-commons-1.11.1.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440) ~[spring-data-commons-1.11.1.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.11.1.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at com.sun.proxy.$Proxy122.save(Unknown Source) ~[na:na]
at org.springframework.data.repository.support.CrudRepositoryInvoker.invokeSave(CrudRepositoryInvoker.java:100) ~[spring-data-commons-1.11.1.RELEASE.jar:na]
at org.springframework.data.rest.core.support.UnwrappingRepositoryInvokerFactory$UnwrappingRepositoryInvoker.invokeSave(UnwrappingRepositoryInvokerFactory.java:225) ~[spring-data-rest-core-2.4.1.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryEntityController.saveAndReturn(RepositoryEntityController.java:491) ~[spring-data-rest-webmvc-2.4.1.RELEASE.jar:na]
at org.springframework.data.rest.webmvc.RepositoryEntityController.putItemResource(RepositoryEntityController.java:413) ~[spring-data-rest-webmvc-2.4.1.RELEASE.jar:na]
Caused by: com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: 56cbfbd323f5496dcc02c579.delivery_orders index: _id_ dup key: { : ObjectId('56d6b81623f54966b07b0587') }'
at com.mongodb.operation.BaseWriteOperation.convertBulkWriteException(BaseWriteOperation.java:236) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.BaseWriteOperation.access$300(BaseWriteOperation.java:60) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:146) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:133) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:230) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:133) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:60) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.Mongo.execute(Mongo.java:782) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.Mongo$2.execute(Mongo.java:765) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.DBCollection.insert(DBCollection.java:328) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.DBCollection.insert(DBCollection.java:319) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.DBCollection.insert(DBCollection.java:289) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.DBCollection.insert(DBCollection.java:255) ~[mongo-java-driver-3.2.0.jar:na]
at com.mongodb.DBCollection.insert(DBCollection.java:192) ~[mongo-java-driver-3.2.0.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate$9.doInCollection(MongoTemplate.java:990) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:462) ~[spring-data-mongodb-1.8.1.RELEASE.jar:na]
... 117 common frames omitted
I have found the root cause finally. That is because I didn't give the version field in my PUT body, and Spring-data-rest may be considered to do some insert operation for the document, hence, there will have E11000 duplicate key error exception being thrown.
But, the main issue is that I shall not have an implementation for the setter of the version field as below:
public void setVersion(Long version)
{
this.version = version;
}
The version parameter will be null if there has no version field in the body of your PUT request. Just remove this setter or annotate with #JsonIgnore can solve this problem. Spring-data-rest will take care the rest.
An alternative answer that doesn't directly address the OP issue, but others maybe running into.
If you are overriding SDR in a #RepositoryRestController PUT method, it's unlikely that your front end is sending a version property, just as it's unlikely that SPD is sending down a version property.
I'm not sure what the right solution is, but we settled on extracting the etag from the header and putting it on the model before submitting a PUT request to our custom controller.
if (obj && header.etag && _.isInteger(header.etag)) {
obj.version = parseInt(header.etag, 10);
}
For existings rows, i have added manually my collection with a version Number
db.getCollection('myCollection').updateMany({}, {$set:{version: NumberLong(0)}})
On my Document i have just
#Version
private Long version;

Drools: Compiling rules (or loading compiled rules) fails with obscure exceptions in JamVM

I'm developing a framework that, as one of its features, enables robots to use a rule based system. We began with Jess as the RBS, and now wanted to implement drools (using Drools 5.2.0 final), which works on our development machines running on OpenJDK 6.
Our robot controller runs ARM Linux and JamVM, previously 1.4.3, but I recently compiled 1.5.4 because it was missing classes needed by drools. After failures, I installed JamVM in a virtual machine using the same configurations as when I compiled it for the controller, and there it failed with the same exceptions.
A little research showed that there are bug reports for Drools + JamVM, but this also means that it generally does work.
When Running the framework with precompiled rules with the following code...
kBase = KnowledgeBaseFactory.newKnowledgeBase();
ObjectInputStream in;
Collection<KnowledgePackage> kpkgs;
try {
in = new ObjectInputStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(
packageFile));
kpkgs = (Collection<KnowledgePackage>) in.readObject();
in.close();
} catch(IOException e) {
throw new DisboticsException("Couldn't read drools knowledge package file!", e);
} catch(ClassNotFoundException e) {
throw new DisboticsException("Drools knowledge package file didn't contain expected instance.", e);
}
kBase.addKnowledgePackages(kpkgs);
kSession = kBase.newStatefulKnowledgeSession();
...I got this exception:
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:152)
at org.drools.rule.JavaDialectRuntimeData.write(JavaDialectRuntimeData.java:383)
at org.drools.rule.JavaDialectRuntimeData.merge(JavaDialectRuntimeData.java:266)
at org.drools.rule.JavaDialectRuntimeData.clone(JavaDialectRuntimeData.java:251)
at org.drools.rule.DialectRuntimeRegistry.merge(DialectRuntimeRegistry.java:110)
at org.drools.common.AbstractRuleBase.addPackages(AbstractRuleBase.java:496)
at org.drools.reteoo.ReteooRuleBase.addPackages(ReteooRuleBase.java:427)
at org.drools.impl.KnowledgeBaseImpl.addKnowledgePackages(KnowledgeBaseImpl.java:149)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:76)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
Exception in thread "main" org.drools.RuntimeDroolsException: java.lang.UnsupportedOperationException
at org.drools.rule.JavaDialectRuntimeData.write(JavaDialectRuntimeData.java:386)
at org.drools.rule.JavaDialectRuntimeData.merge(JavaDialectRuntimeData.java:266)
at org.drools.rule.JavaDialectRuntimeData.clone(JavaDialectRuntimeData.java:251)
at org.drools.rule.DialectRuntimeRegistry.merge(DialectRuntimeRegistry.java:110)
at org.drools.common.AbstractRuleBase.addPackages(AbstractRuleBase.java:496)
at org.drools.reteoo.ReteooRuleBase.addPackages(ReteooRuleBase.java:427)
at org.drools.impl.KnowledgeBaseImpl.addKnowledgePackages(KnowledgeBaseImpl.java:149)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:76)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:152)
at org.drools.rule.JavaDialectRuntimeData.write(JavaDialectRuntimeData.java:383)
...9 more
...which works in OpenJDK. weirdly, it turns out that the list in question in JavaDialectRuntimeData is obtained via Collections.emptyList() and is never changed again (or so eclipse suggests...).
When running with bare .drl files using this code:
Properties props = new Properties();
props.put("drools.dialect.java.compiler", "JANINO");
KnowledgeBuilderConfiguration kbConfig = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(props,
(ClassLoader[]) null);
KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kbConfig);
kBuilder.add(ResourceFactory.newClassPathResource("disbotics/core/rules/drools/function.drl",
DroolsRulesPlugin.class), ResourceType.DRL);
kBuilder.add(ResourceFactory.newClassPathResource(rulesFile, DroolsRulesPlugin.class), ResourceType.DRL);
if(kBuilder.hasErrors()) {
String errorMessage = "";
for(KnowledgeBuilderError error:kBuilder.getErrors())
errorMessage = errorMessage + error.getMessage() + "\n";
throw new DisboticsException(errorMessage);
}
kBase = KnowledgeBaseFactory.newKnowledgeBase();
kBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
kSession = kBase.newStatefulKnowledgeSession();
... I get these (unexpected) exceptions from the rules compiler:
Exception in thread "main" disbotics.core.common.DisboticsException: Line 2:8 unexpected exception at input '"mvel"'. Exception: java.lang.UnsupportedOperationException. Stack trace:
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:152)
at org.drools.lang.descr.PackageDescr.addAttribute(PackageDescr.java:138)
at org.drools.lang.api.impl.PackageDescrBuilderImpl.attribute(PackageDescrBuilderImpl.java:93)
at org.drools.lang.ParserHelper.start(ParserHelper.java:684)
at org.drools.lang.DRLParser.stringAttribute(DRLParser.java:1289)
at org.drools.lang.DRLParser.attribute(DRLParser.java:1062)
at org.drools.lang.DRLParser.statement(DRLParser.java:276)
at org.drools.lang.DRLParser.compilationUnit(DRLParser.java:155)
at org.drools.compiler.DrlParser.compile(DrlParser.java:225)
at org.drools.compiler.DrlParser.parse(DrlParser.java:136)
at org.drools.compiler.DrlParser.parse(DrlParser.java:141)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(PackageBuilder.java:352)
at org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:538)
at org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:28)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:55)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
[ERR 107] Line 2:8 mismatched input '"mvel"' expecting one of the following tokens: '[package, import, global, declare, function, rule, query]'.
Line 4:0 unexpected exception at input 'global'. Exception: java.util.EmptyStackException. Stack trace:
java.util.EmptyStackException
at java.util.Stack.pop(Stack.java:109)
at org.drools.lang.ParserHelper.popParaphrases(ParserHelper.java:421)
at org.drools.lang.ParserHelper.end(ParserHelper.java:732)
at org.drools.lang.DRLParser.globalStatement(DRLParser.java:401)
at org.drools.lang.DRLParser.statement(DRLParser.java:261)
at org.drools.lang.DRLParser.compilationUnit(DRLParser.java:155)
at org.drools.compiler.DrlParser.compile(DrlParser.java:225)
at org.drools.compiler.DrlParser.parse(DrlParser.java:136)
at org.drools.compiler.DrlParser.parse(DrlParser.java:141)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(PackageBuilder.java:352)
at org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:538)
at org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:28)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:55)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
Parser returned a null Package
Line 2:8 unexpected exception at input '"java"'. Exception: java.lang.UnsupportedOperationException. Stack trace:
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:152)
at org.drools.lang.descr.PackageDescr.addAttribute(PackageDescr.java:138)
at org.drools.lang.api.impl.PackageDescrBuilderImpl.attribute(PackageDescrBuilderImpl.java:93)
at org.drools.lang.ParserHelper.start(ParserHelper.java:684)
at org.drools.lang.DRLParser.stringAttribute(DRLParser.java:1289)
at org.drools.lang.DRLParser.attribute(DRLParser.java:1062)
at org.drools.lang.DRLParser.statement(DRLParser.java:276)
at org.drools.lang.DRLParser.compilationUnit(DRLParser.java:155)
at org.drools.compiler.DrlParser.compile(DrlParser.java:225)
at org.drools.compiler.DrlParser.parse(DrlParser.java:136)
at org.drools.compiler.DrlParser.parse(DrlParser.java:141)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(PackageBuilder.java:352)
at org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:538)
at org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:28)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:57)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
[ERR 107] Line 2:8 mismatched input '"java"' expecting one of the following tokens: '[package, import, global, declare, function, rule, query]'.
Line 4:0 unexpected exception at input 'import'. Exception: java.util.EmptyStackException. Stack trace:
java.util.EmptyStackException
at java.util.Stack.pop(Stack.java:109)
at org.drools.lang.ParserHelper.popParaphrases(ParserHelper.java:421)
at org.drools.lang.ParserHelper.end(ParserHelper.java:732)
at org.drools.lang.DRLParser.importStatement(DRLParser.java:349)
at org.drools.lang.DRLParser.statement(DRLParser.java:258)
at org.drools.lang.DRLParser.compilationUnit(DRLParser.java:155)
at org.drools.compiler.DrlParser.compile(DrlParser.java:225)
at org.drools.compiler.DrlParser.parse(DrlParser.java:136)
at org.drools.compiler.DrlParser.parse(DrlParser.java:141)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(PackageBuilder.java:352)
at org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:538)
at org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:28)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:57)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
Line 6:0 unexpected exception at input 'rule'. Exception: java.util.EmptyStackException. Stack trace:
java.util.EmptyStackException
at java.util.Stack.pop(Stack.java:109)
at org.drools.lang.ParserHelper.popParaphrases(ParserHelper.java:421)
at org.drools.lang.ParserHelper.end(ParserHelper.java:732)
at org.drools.lang.DRLParser.rule(DRLParser.java:886)
at org.drools.lang.DRLParser.statement(DRLParser.java:267)
at org.drools.lang.DRLParser.compilationUnit(DRLParser.java:155)
at org.drools.compiler.DrlParser.compile(DrlParser.java:225)
at org.drools.compiler.DrlParser.parse(DrlParser.java:136)
at org.drools.compiler.DrlParser.parse(DrlParser.java:141)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(PackageBuilder.java:352)
at org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:538)
at org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:28)
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:57)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
Parser returned a null Package
at disbotics.core.config.DroolsRulesPlugin.initialize(DroolsRulesPlugin.java:63)
at disbotics.core.common.DisboticsCore.startFramework(DisboticsCore.java:109)
at disbotics.core.common.DisboticsCore.main(DisboticsCore.java:56)
again, compiling the rules worked just fine in OpenJDK. We're using Janino, and it is properly referenced on the classpath (the classpath used at runtime is created by the Maven build, so contains all jars referenced by drools/janino/ anything else)
Does anyone know what's going on here and/or how to get Drools working with JamVM?
Are you compiling the knowledge packages using OpenJDK 1.6? and then trying to load it with 1.5.4? You should try compiling the original packages using 1.5.4 and see if you have the same errors.
For the stack trace, it looks like you are trying to add something to an unmodifiable list right?
Basically you are getting the exception here: kBase.addKnowledgePackages(kpkgs);
Right?