Is there a way to "pivot" a ImmutableMap<String, ImmutableSet<String>>? - guava

I have a ImmutableMap<String, ImmutableSet<String>>. Is there an easy way to "pivot" this kid or do I have to code it myself? I am trying to figure out the best way to view...
{
type1=[FieldA, FieldB, FieldC],
type2=[FieldB, FieldC, FieldD],
type3=[FieldC, FieldD, FieldE]
}
...as...
{
FieldA=[type1],
FieldB=[type1, type2],
FieldC=[type1, type2, type3],
FieldD=[type1, type2],
FieldE=[type3]
}
Does MultiMap solve this problem?

It looks like MultiMap is the way to go. The ImmutableMultiMap#inverse() method is what I was looking for:
ImmutableMultimap.Builder<String, String> builder = new ImmutableMultimap.Builder<String, String>();
builder.putAll( "type1", Arrays.asList( "FieldA", "FieldB", "FieldC") );
builder.putAll( "type2", Arrays.asList( "FieldB", "FieldC", "FieldD") );
builder.putAll( "type3", Arrays.asList( "FieldC", "FieldD", "FieldE") );
ImmutableMultimap<String, String> typesToFields = builder.build();
ImmutableMultimap<String, String> fieldsToTypes = typesToFields.inverse();
System.out.println( "typesToFields: " + typesToFields );
System.out.println( "fieldsToTypes: " + fieldsToTypes );
...produces...
typesToFields: {type1=[FieldA, FieldB, FieldC], type2=[FieldB, FieldC, FieldD], type3=[FieldC, FieldD, FieldE]}
fieldsToTypes: {FieldA=[type1], FieldB=[type1, type2], FieldC=[type1, type2, type3], FieldD=[type2, type3], FieldE=[type3]}

Related

Spring data r2dbc and group by

I am using the DatabaseClient to perform my sql queries and I don't see how I can do a group by:
databaseClient.select()
.from( myClass.class )
.matching( where( "row_1" ).is( "value_1" ) )
//group by row_2 ...
.orderBy( Sort.Order.desc( "row_3" ) )
.page( pageable )
.fetch()
.all();
A workaround solution using sql directly.
public Flux<Map<Object, Object>> countByStatus() {
return this.databaseClient
.sql("SELECT count(*) as cnt, status FROM posts group by status")
.map((row, rowMetadata) -> {
Long cnt = row.get("cnt", Long.class);
Post.Status s = row.get("status", Post.Status.class);
return Map.<Object, Object>of("cnt", cnt, "status", s);
})
.all();
}
Check the complete codes.

REST API: pass parameters to preparedQuery in Vertx pgclient

This is the response from my API:
"The number of parameters to execute should be consistent with the expected number of parameters = [2] but the actual number is [0]."
I use pgClient, Vert.x 3.9.3 and consume various REST API's without problems, but....in this query (probably it's wrong)
private static final String SELECT_CBA = "select art.leyenda, $1::numeric(10,3) as cantidad, uni.abreviatura, \r"
+ "round(((art.precio_costo * (art.utilidad_fraccionado/100)) + art.precio_costo) * $2::numeric(10,3),2) as totpagar \r"
+ "FROM public.articulos art join public.unidades uni on uni.idunidad = art.idunidad \r"
+ "WHERE (substring(art.codigobarra,1,2) = \'$3\' and substring(art.codigobarra,3,6) = \'$4\')";
Some explanation
$1 and $2 are the same parameters; $2 and $3 must be quoted parameters.
This is my rest verticle:
poolClient = PgPool.pool(vertx, options, poolOptions);
bizArticulo = new BizArticulo(poolClient);
Router router = Router.router(vertx);
router.route("/api/articulos*").handler(BodyHandler.create());
router.get("/api/articulos").handler(bizArticulo::getAll);
router.get("/api/articulos/:cantcomp1/:cantcomp2/:tipoprod/:prodpadre").handler(bizArticulo::getOneReadingBarcode);
Where :cantcomp1 -> $1, :cantcomp2 -> $2, :tipoprod -> $3 and $4 -> :prodpadre
and finally, this my "business"
public void getOneReadingBarcode(RoutingContext routingContext) {
HttpServerResponse response = routingContext.response();
pgClient
.preparedQuery(SELECT_CBA)
.execute(ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result();
List<Articulo> articulos = new ArrayList<>();
rows.forEach(row -> {
articulos.add(fromBarCode(row));
});
response.putHeader("content-type", "application/json; charset=utf-8")
.setStatusCode(200)
.end(Json.encodePrettily(articulos));
} else {
System.out.println("Failure: " + ar.cause().getMessage());
response.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(ar.cause().getMessage()));
}
});
}
In Postman, I wrote:
192.168.0.15:8092/api/articulos/0.750/0.750/20/021162; where I assume the parameters match, but it returns the error mentioned above.
¿What's wrong? Any help would be appreciated
Ernesto
Ok, I answer to myself...
First: little fix to my query (SELECT_CB), I put the parameters $1, $2... in parentheses..
private static final String SELECT_CBA = "select art.leyenda, ($1::numeric(10,3)) as cantidad, uni.abreviatura, \r"
+ "round(((art.precio_costo * (art.utilidad_fraccionado/100)) + art.precio_costo) * ($2::numeric(10,3)),2) as totpagar \r"
+ "FROM public.articulos art join public.unidades uni on uni.idunidad = art.idunidad \r"
+ "WHERE (substring(art.codigobarra,1,2) = ($3) and substring(art.codigobarra,3,6) = ($4))";
Second: got the params from context (see router.context in previous question)
Double cantComprada1 = Double.parseDouble(routingContext.request().getParam("cantcomp1"));
Double cantComprada2 = Double.parseDouble(routingContext.request().getParam("cantcomp2"));
String tipoProducto = routingContext.request().getParam("tipoprod");
String productoPadre = routingContext.request().getParam("prodpadre");
and Third: put the params as arguments
pgClient
.preparedQuery(SELECT_CBA)
.execute(Tuple.of(cantComprada1, cantComprada2, tipoProducto, productoPadre), ar -> {
......
......
}
All work's fine

Typescript not inserting into Mongo Collection

I am using Ionic2 with Meteor/MongoDb.
I have a collection, that I am trying to insert a message object into. However, the code seems to freeze where it tries to do the insert. However, if I try insert the message object from a different place (i.e. invoke setLocalMessage(message: Message)), it does so successfully. This makes me think, the problem is not with the collection or message objects, but rather the way I am calling the function that does the insert.
private localMessageCollection: Mongo.Collection<Message> = new Mongo.Collection<Message>(null);
and
private loadMessages(): void {
let promise: Promise<string> = this.utilityService.getLoggedInPerson();
if (promise) {
promise.then((data) => {
this.personModelLoggedIn = JSON.parse(data);
if (this.personModelLoggedIn) {
this.senderId = 'P' + this.personModelLoggedIn.id;
this.title = this.activeChat.title;
this.picture = this.activeChat.picture;
this.subscribe('messages', this.activeChat._id, this.senderId, () => {
this.autorun(() => {
let promiseLocalMessages: Promise<Mongo.Collection<Message>> = this.findLocalMessages();
promiseLocalMessages.then((messageData: Mongo.Collection<Message>) => {
messageData.find().forEach((message: Message) => {
this.setLocalMessage(message);
});
});
let promiseMessages: Promise<Mongo.Collection<Message>> = this.findMessages();
promiseMessages.then((messageData: Mongo.Collection<Message>) => {
messageData.find().forEach((message: Message) => {
this.setLocalMessage(message);
});
});
});
});
} else {
this.nav.push(LoginPage, {
fromMessages: true
});
}
});
} else {
this.nav.push(LoginPage, {
fromMessages: true
});
}
}
and
private setLocalMessage(message: Message): void {
console.log('setLocalNessage: ' + message._id);
console.log(this.localMessageCollection);
this.localMessageCollection.insert(message);
console.log('setLocalNessage done: ' + message);
}
output
setLocalNessage: eC7hDZ4Z6ZwTnjP4h
Mongo.Collection {_makeNewID: function, _transform: null, _connection: null, _collection: LocalCollection, _name: null…}
but then it freezes.
If anyone can assist I would appreciate it.
UPDATE
It is freezing in the Meteor api on this line:
}Meteor.default_connection=Meteor.connection;Meteor.connect=DDP.connect}).call(this);if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package["ddp-client"]={},{DDP:DDP,LivedataTest:LivedataTest})})();(function(){var Meteor=Package.meteor.Meteor;var global=Package.meteor.global;var meteorEnv=Package.meteor.meteorEnv;var DDP=Package["ddp-client"].DDP;if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package.ddp={},{DDP:DDP})})();(function(){var Meteor=Package.meteor.Meteor;var global=Package.meteor.global;var meteorEnv=Package.meteor.meteorEnv;var _=Package.underscore._;var LocalCollection=Package.minimongo.LocalCollection;var Minimongo=Package.minimongo.Minimongo;var check=Package.check.check;var Match=Package.check.Match;var EJSON=Package.ejson.EJSON;var DDP=Package["ddp-client"].DDP;var meteorInstall=Package.modules.meteorInstall;var Buffer=Package.modules.Buffer;var process=Package.modules.process;var Symbol=Package["ecmascript-runtime"].Symbol;var Map=Package["ecmascript-runtime"].Map;var Set=Package["ecmascript-runtime"].Set;var meteorBabelHelpers=Package["babel-runtime"].meteorBabelHelpers;var Promise=Package.promise.Promise;var AllowDeny;var require=meteorInstall({node_modules:{meteor:{"allow-deny":{"allow-deny.js":function(){AllowDeny={CollectionPrototype:{}};var CollectionPrototype=AllowDeny.CollectionPrototype;CollectionPrototype.allow=function(options){addValidator(this,"allow",options)};CollectionPrototype.deny=function(options){addValidator(this,"deny",options)};CollectionPrototype._defineMutationMethods=function(options){var self=this;options=options||{};self._restricted=false;self._insecure=undefined;self._validators={insert:{allow:[],deny:[]},update:{allow:[],deny:[]},remove:{allow:[],deny:[]},upsert:{allow:[],deny:[]},fetch:[],fetchAllFields:false};if(!self._name)return;self._prefix="/"+self._name+"/";if(self._connection&&(self._connection===Meteor.server||Meteor.isClient)){(function(){var m={};_.each(["insert","update","remove"],function(method){var methodName=self._prefix+method;if(options.useExisting){var handlerPropName=Meteor.isClient?"_methodHandlers":"method_handlers";if(self._connection[handlerPropName]&&typeof self._connection[handlerPropName][methodName]==="function")return}m[methodName]=function(){check(arguments,[Match.Any]);var args=_.toArray(arguments);try{var generatedId=null;if(method==="insert"&&!_.has(args[0],"_id")){generatedId=self._makeNewID()}if(this.isSimulation){if(generatedId!==null)args[0]._id=generatedId;return self._collection[method].apply(self._collection,args)}if(method!=="insert")throwIfSelectorIsNotId(args[0],method);if(self._restricted){if(self._validators[method].allow.length===0){throw new Meteor.Error(403,"Access denied. No allow validators set on restricted "+"collection for method '"+method+"'.")}var validatedMethodName="_validated"+method.charAt(0).toUpperCase()+method.slice(1);args.unshift(this.userId);method==="insert"&&args.push(generatedId);return self[validatedMethodName].apply(self,args)}else if(self._isInsecure()){if(generatedId!==null)args[0]._id=generatedId;return self._collection[method].apply(self._collection,args)}else{throw new Meteor.Error(403,"Access denied")}}catch(e){if(e.name==="MongoError"||e.name==="MinimongoError"){throw new Meteor.Error(409,e.toString())}else{throw e}}}});self._connection.methods(m)})()}};CollectionPrototype._updateFetch=function(fields){var self=this;if(!self._validators.fetchAllFields){if(fields){self._validators.fetch=_.union(self._validators.fetch,fields)}else{self._validators.fetchAllFields=true;self._validators.fetch=null}}};CollectionPrototype._isInsecure=function(){var self=this;if(self._insecure===undefined)return!!Package.insecure;return self._insecure};CollectionPrototype._validatedInsert=function(userId,doc,generatedId){var self=this;if(_.any(self._validators.insert.deny,function(validator){return validator(userId,docToValidate(validator,doc,generatedId))})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.insert.allow,function(validator){return!validator(userId,docToValidate(validator,doc,generatedId))})){throw new Meteor.Error(403,"Access denied")}if(generatedId!==null)doc._id=generatedId;self._collection.insert.call(self._collection,doc)};CollectionPrototype._validatedUpdate=function(userId,selector,mutator,options){var self=this;check(mutator,Object);options=_.clone(options)||{};if(!LocalCollection._selectorIsIdPerhapsAsObject(selector))throw new Error("validated update should be of a single ID");if(options.upsert)throw new Meteor.Error(403,"Access denied. Upserts not "+"allowed in a restricted collection.");var noReplaceError="Access denied. In a restricted collection you can only"+" update documents, not replace them. Use a Mongo update operator, such "+"as '$set'.";var fields=[];if(_.isEmpty(mutator)){throw new Meteor.Error(403,noReplaceError)}_.each(mutator,function(params,op){if(op.charAt(0)!=="$"){throw new Meteor.Error(403,noReplaceError)}else if(!_.has(ALLOWED_UPDATE_OPERATIONS,op)){throw new Meteor.Error(403,"Access denied. Operator "+op+" not allowed in a restricted collection.")}else{_.each(_.keys(params),function(field){if(field.indexOf(".")!==-1)field=field.substring(0,field.indexOf("."));if(!_.contains(fields,field))fields.push(field)})}});var findOptions={transform:null};if(!self._validators.fetchAllFields){findOptions.fields={};_.each(self._validators.fetch,function(fieldName){findOptions.fields[fieldName]=1})}var doc=self._collection.findOne(selector,findOptions);if(!doc)return 0;if(_.any(self._validators.update.deny,function(validator){var factoriedDoc=transformDoc(validator,doc);return validator(userId,factoriedDoc,fields,mutator)})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.update.allow,function(validator){var factoriedDoc=transformDoc(validator,doc);return!validator(userId,factoriedDoc,fields,mutator)})){throw new Meteor.Error(403,"Access denied")}options._forbidReplace=true;return self._collection.update.call(self._collection,selector,mutator,options)};var ALLOWED_UPDATE_OPERATIONS={$inc:1,$set:1,$unset:1,$addToSet:1,$pop:1,$pullAll:1,$pull:1,$pushAll:1,$push:1,$bit:1};CollectionPrototype._validatedRemove=function(userId,selector){var self=this;var findOptions={transform:null};if(!self._validators.fetchAllFields){findOptions.fields={};_.each(self._validators.fetch,function(fieldName){findOptions.fields[fieldName]=1})}var doc=self._collection.findOne(selector,findOptions);if(!doc)return 0;if(_.any(self._validators.remove.deny,function(validator){return validator(userId,transformDoc(validator,doc))})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.remove.allow,function(validator){return!validator(userId,transformDoc(validator,doc))})){throw new Meteor.Error(403,"Access denied")}return self._collection.remove.call(self._collection,selector)};CollectionPrototype._callMutatorMethod=function(){function _callMutatorMethod(name,args,callback){if(Meteor.isClient&&!callback&&!alreadyInSimulation()){callback=function(){function callback(err){if(err)Meteor._debug(name+" failed: "+(err.reason||err.stack))}return callback}()}var firstArgIsSelector=name==="update"||name==="remove";if(firstArgIsSelector&&!alreadyInSimulation()){throwIfSelectorIsNotId(args[0],name)}var mutatorMethodName=this._prefix+name;return this._connection.apply(mutatorMethodName,args,{returnStubValue:true},callback)}return _callMutatorMethod}();function transformDoc(validator,doc){if(validator.transform)return validator.transform(doc);return doc}function docToValidate(validator,doc,generatedId){var ret=doc;if(validator.transform){ret=EJSON.clone(doc);if(generatedId!==null){ret._id=generatedId}ret=validator.transform(ret)}return ret}function addValidator(collection,allowOrDeny,options){var VALID_KEYS=["insert","update","remove","fetch","transform"];_.each(_.keys(options),function(key){if(!_.contains(VALID_KEYS,key))throw new Error(allowOrDeny+": Invalid key: "+key)});collection._restricted=true;_.each(["insert","update","remove"],function(name){if(options.hasOwnProperty(name)){if(!(options[name]instanceof Function)){throw new Error(allowOrDeny+": Value for `"+name+"` must be a function")}if(options.transform===undefined){options[name].transform=collection._transform}else{options[name].transform=LocalCollection.wrapTransform(options.transform)}collection._validators[name][allowOrDeny].push(options[name])}});if(options.update||options.remove||options.fetch){if(options.fetch&&!(options.fetch instanceof Array)){throw new Error(allowOrDeny+": Value for `fetch` must be an array")}collection._updateFetch(options.fetch)}}function throwIfSelectorIsNotId(selector,methodName){if(!LocalCollection._selectorIsIdPerhapsAsObject(selector)){throw new Meteor.Error(403,"Not permitted. Untrusted code may only "+methodName+" documents by ID.")}}function alreadyInSimulation(){var enclosing=DDP._CurrentInvocation.get();return enclosing&&enclosing.isSimulation}}}}}},{extensions:[".js",".json"]});require("./node_modules/meteor/allow-deny/allow-deny.js");if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package["allow-deny"]={},{AllowDeny:AllowDeny})})();(function(){var Meteor=Package.meteor.Meteor;var global=Package.meteor.global;var meteorEnv=Package.meteor.meteorEnv;var AllowDeny=Package["allow-deny"].AllowDeny;var Random=Package.random.Random;var EJSON=Package.ejson.EJSON;var _=Package.underscore._;var LocalCollection=Package.minimongo.LocalCollection;var Minimongo=Package.minimongo.Minimongo;var DDP=Package["ddp-client"].DDP;var Tracker=Package.tracker.Tracker;var Deps=Package.tracker.Deps;var DiffSequence=Package["diff-sequence"].DiffSequence;var MongoID=Package["mongo-id"].MongoID;var check=Package.check.check;var Match=Package.check.Match;var meteorInstall=Package.modules.meteorInstall;var Buffer=Package.modules.Buffer;var process=Package.modules.process;var Symbol=Package["ecmascript-runtime"].Symbol;var Map=Package["ecmascript-runtime"].Map;var Set=Package["ecmascript-runtime"].Set;var meteorBabelHelpers=Package["babel-runtime"].meteorBabelHelpers;var Promise=Package.promise.Promise;var LocalCollectionDriver,Mongo;var require=meteorInstall({node_modules:{meteor:{mongo:{"local_collection_driver.js":function(){LocalCollectionDriver=function LocalCollectionDriver(){var self=this;self.noConnCollections={}};var ensureCollection=function ensureCollection(name,collections){if(!(name in collections))collections[name]=new LocalCollection(name);return collections[name]};_.extend(LocalCollectionDriver.prototype,{open:function(){function open(name,conn){var self=this;if(!name)return new LocalCollection;if(!conn){return ensureCollection(name,self.noConnCollections)}if(!conn._mongo_livedata_collections)conn._mongo_livedata_collections={};return ensureCollection(name,conn._mongo_livedata_collections)}return open}()});LocalCollectionDriver=new LocalCollectionDriver},"collection.js":function(require,exports,module){Mongo={};Mongo.Collection=function(name,options){var self=this;if(!(self instanceof Mongo.Collection))throw new Error('use "new" to construct a Mongo.Collection');if(!name&&name!==null){Meteor._debug("Warning: creating anonymous collection. It will not be "+"saved or synchronized over the network. (Pass null for "+"the collection name to turn off this warning.)");name=null}if(name!==null&&typeof name!=="string"){throw new Error("First argument to new Mongo.Collection must be a string or null")}if(options&&options.methods){options={connection:options}}if(options&&options.manager&&!options.connection){options.connection=options.manager}options=_.extend({connection:undefined,idGeneration:"STRING",transform:null,_driver:undefined,_preventAutopublish:false},options);switch(options.idGeneration){case"MONGO":self._makeNewID=function(){var src=name?DDP.randomStream("/collection/"+name):Random.insecure;return new Mongo.ObjectID(src.hexString(24))};break;case"STRING":default:self._makeNewID=function(){var src=name?DDP.randomStream("/collection/"+name):Random.insecure;return src.id()};break}self._transform=LocalCollection.wrapTransform(options.transform);if(!name||options.connection===null)self._connection=null;else if(options.connection)self._connection=options.connection;else if(Meteor.isClient)self._connection=Meteor.connection;else self._connection=Meteor.server;if(!options._driver){if(name&&self._connection===Meteor.server&&typeof MongoInternals!=="undefined"&&MongoInternals.defaultRemoteCollectionDriver){options._driver=MongoInternals.defaultRemoteCollectionDriver()}else{options._driver=LocalCollectionDriver}}self._collection=options._driver.open(name,self._connection);self._name=name;self._driver=options._driver;if(self._connection&&self._connection.registerStore){var ok=self._connection.registerStore(name,{beginUpdate:function(){function beginUpdate(batchSize,reset){if(batchSize>1||reset)self._collection.pauseObservers();if(reset)self._collection.remove({})}return beginUpdate}(),update:function(){function update(msg){var mongoId=MongoID.idParse(msg.id);var doc=self._collection.findOne(mongoId);if(msg.msg==="replace"){var replace=msg.replace;if(!replace){if(doc)self._collection.remove(mongoId)}else if(!doc){self._collection.insert(replace)}else{self._collection.update(mongoId,replace)}return}else if(msg.msg==="added"){if(doc){throw new Error("Expected not to find a document already present for an add")}self._collection.insert(_.extend({_id:mongoId},msg.fields))}else if(msg.msg==="removed"){if(!doc)throw new Error("Expected to find a document already present for removed");self._collection.remove(mongoId)}else if(msg.msg==="changed"){if(!doc)throw new Error("Expected to find a document to change");if(!_.isEmpty(msg.fields)){var modifier={};_.each(msg.fields,function(value,key){if(value===undefined){if(!modifier.$unset)modifier.$unset={};modifier.$unset[key]=1}else{if(!modifier.$set)modifier.$set={};modifier.$set[key]=value}});self._collection.update(mongoId,modifier)}}else{throw new Error("I don't know how to deal with this message")}}return update}(),endUpdate:function(){function endUpdate(){self._collection.resumeObservers()}return endUpdate}(),saveOriginals:function(){function saveOriginals(){self._collection.saveOriginals()}return saveOriginals}(),retrieveOriginals:function(){function retrieveOriginals(){return self._collection.retrieveOriginals()}return retrieveOriginals}(),getDoc:function(){function getDoc(id){return self.findOne(id)}return getDoc}(),_getCollection:function(){function _getCollection(){return self}return _getCollection}()});if(!ok){var message='There is already a collection named "'+name+'"';if(options._suppressSameNameError===true){console.warn?console.warn(message):console.log(message)}else{throw new Error(message)}}}if(options.defineMutationMethods!==false){try{self._defineMutationMethods({useExisting:options._suppressSameNameError===true})}catch(error){if(error.message==="A method named '/"+name+"/insert' is already defined")throw new Error('There is already a collection named "'+name+'"');throw error}}if(Package.autopublish&&!options._preventAutopublish&&self._connection&&self._connection.publish){self._connection.publish(null,function(){return self.find()},{is_auto:true})}};_.extend(Mongo.Collection.prototype,{_getFindSelector:function(){function _getFindSelector(args){if(args.length==0)return{};else return args[0]}return _getFindSelector}(),_getFindOptions:function(){function _getFindOptions(args){var self=this;if(args.length<2){return{transform:self._transform}}else{check(args[1],Match.Optional(Match.ObjectIncluding({fields:Match.Optional(Match.OneOf(Object,undefined)),sort:Match.Optional(Match.OneOf(Object,Array,Function,undefined)),limit:Match.Optional(Match.OneOf(Number,undefined)),skip:Match.Optional(Match.OneOf(Number,undefined))})));return _.extend({transform:self._transform},args[1])}}return _getFindOptions}(),find:function(){function find(){var self=this;var argArray=_.toArray(arguments);return self._collection.find(self._getFindSelector(argArray),self._getFindOptions(argArray))}return find}(),findOne:function(){function findOne(){var self=this;var argArray=_.toArray(arguments);return self._collection.findOne(self._getFindSelector(argArray),self._getFindOptions(argArray))}return findOne}()});Mongo.Collection._publishCursor=function(cursor,sub,collection){var observeHandle=cursor.observeChanges({added:function(){function added(id,fields){sub.added(collection,id,fields)}return added}(),changed:function(){function changed(id,fields){sub.changed(collection,id,fields)}return changed}(),removed:function(){function removed(id){sub.removed(collection,id)}return removed}()});sub.onStop(function(){observeHandle.stop()});return observeHandle};Mongo.Collection._rewriteSelector=function(selector){if(LocalCollection._selectorIsId(selector))selector={_id:selector};if(_.isArray(selector)){throw new Error("Mongo selector can't be an array.")}if(!selector||"_id"in selector&&!selector._id)return{_id:Random.id()};var ret={};_.each(selector,function(value,key){if(value instanceof RegExp){ret[key]=convertRegexpToMongoSelector(value)}else if(value&&value.$regex instanceof RegExp){ret[key]=convertRegexpToMongoSelector(value.$regex);if(value.$options!==undefined)ret[key].$options=value.$options}else if(_.contains(["$or","$and","$nor"],key)){ret[key]=_.map(value,function(v){return Mongo.Collection._rewriteSelector(v)})}else{ret[key]=value}});return ret};function convertRegexpToMongoSelector(regexp){check(regexp,RegExp);var selector={$regex:regexp.source};var regexOptions="";if(regexp.ignoreCase)regexOptions+="i";if(regexp.multiline)regexOptions+="m";if(regexOptions)selector.$options=regexOptions;return selector}Mongo.Collection.prototype.insert=function(){function insert(doc,callback){if(!doc){throw new Error("insert requires an argument")}doc=_.extend({},doc);if("_id"in doc){if(!doc._id||!(typeof doc._id==="string"||doc._id instanceof Mongo.ObjectID)){throw new Error("Meteor requires document _id fields to be non-empty strings or ObjectIDs")}}else{var generateId=true;if(this._isRemoteCollection()){var enclosing=DDP._CurrentInvocation.get();if(!enclosing){generateId=false}}if(generateId){doc._id=this._makeNewID()}}var chooseReturnValueFromCollectionResult=function(){function chooseReturnValueFromCollectionResult(result){if(doc._id){return doc._id}doc._id=result;return result}return chooseReturnValueFromCollectionResult}();var wrappedCallback=wrapCallback(callback,chooseReturnValueFromCollectionResult);if(this._isRemoteCollection()){var result=this._callMutatorMethod("insert",[doc],wrappedCallback);return chooseReturnValueFromCollectionResult(result)}try{var _result=this._collection.insert(doc,wrappedCallback);return chooseReturnValueFromCollectionResult(_result)}catch(e){if(callback){callback(e);return null}throw e}}return insert}();Mongo.Collection.prototype.update=function(){function update(selector,modifier){for(var _len=arguments.length,optionsAndCallback=Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){optionsAndCallback[_key-2]=arguments[_key]}var callback=popCallbackFromArgs(optionsAndCallback);selector=Mongo.Collection._rewriteSelector(selector);var options=_.clone(optionsAndCallback[0])||{};if(options&&options.upsert){if(options.insertedId){if(!(typeof options.insertedId==="string"||options.insertedId instanceof Mongo.ObjectID))throw new Error("insertedId must be string or ObjectID")}else if(!selector._id){options.insertedId=this._makeNewID()}}var wrappedCallback=wrapCallback(callback);if(this._isRemoteCollection()){var args=[selector,modifier,options];return this._callMutatorMethod("update",args,wrappedCallback)}try{return this._collection.update(selector,modifier,options,wrappedCallback)}catch(e){if(callback){callback(e);return null}throw e}}return update}();Mongo.Collection.prototype.remove=function(){function remove(selector,callback){selector=Mongo.Collection._rewriteSelector(selector);var wrappedCallback=wrapCallback(callback);if(this._isRemoteCollection()){return this._callMutatorMethod("remove",[selector],wrappedCallback)}try{return this._collection.remove(selector,wrappedCallback)}catch(e){if(callback){callback(e);return null}throw e}}return remove}();Mongo.Collection.prototype._isRemoteCollection=function(){function _isRemoteCollection(){return this._connection&&this._connection!==Meteor.server}return _isRemoteCollection}();function wrapCallback(callback,convertResult){if(!callback){return}convertResult=convertResult||_.identity;return function(error,result){callback(error,!error&&convertResult(result))}}Mongo.Collection.prototype.upsert=function(){function upsert(selector,modifier,options,callback){if(!callback&&typeof options==="function"){callback=options;options={}}var updateOptions=_.extend({},options,{_returnObject:true,upsert:true});return this.update(selector,modifier,updateOptions,callback)}return upsert}();Mongo.Collection.prototype._ensureIndex=function(index,options){var self=this;if(!self._collection._ensureIndex)throw new Error("Can only call _ensureIndex on server collections");self._collection._ensureIndex(index,options)};Mongo.Collection.prototype._dropIndex=function(index){var self=this;if(!self._collection._dropIndex)throw new Error("Can only call _dropIndex on server collections");self._collection._dropIndex(index)};Mongo.Collection.prototype._dropCollection=function(){var self=this;if(!self._collection.dropCollection)throw new Error("Can only call _dropCollection on server collections");self._collection.dropCollection()};Mongo.Collection.prototype._createCappedCollection=function(byteSize,maxDocuments){var self=this;if(!self._collection._createCappedCollection)throw new Error("Can only call _createCappedCollection on server collections");self._collection._createCappedCollection(byteSize,maxDocuments)};Mongo.Collection.prototype.rawCollection=function(){var self=this;if(!self._collection.rawCollection){throw new Error("Can only call rawCollection on server collections")}return self._collection.rawCollection()};Mongo.Collection.prototype.rawDatabase=function(){var self=this;if(!(self._driver.mongo&&self._driver.mongo.db)){throw new Error("Can only call rawDatabase on server collections")}return self._driver.mongo.db};Mongo.ObjectID=MongoID.ObjectID;Mongo.Cursor=LocalCollection.Cursor;Mongo.Collection.Cursor=Mongo.Cursor;Mongo.Collection.ObjectID=Mongo.ObjectID;Meteor.Collection=Mongo.Collection;_.extend(Meteor.Collection.prototype,AllowDeny.CollectionPrototype);function popCallbackFromArgs(args){if(args.length&&(args[args.length-1]===undefined||args[args.length-1]instanceof Function)){return args.pop()}}}}}}},{extensions:[".js",".json"]});require("./node_modules/meteor/mongo/local_collection_driver.js");require("./node_modules/meteor/mongo/collection.js");if(typeof Package==="undefined")Package={};(function(pkg,symbols){for(var s in symbols)s in pkg||(pkg[s]=symbols[s])})(Package.mongo={},{Mongo:Mongo})})();Meteor=Package.meteor.Meteor;global=Package.meteor.global;meteorEnv=Package.meteor.meteorEnv;_=Package.underscore._;DDP=Package["ddp-client"].DDP;Mongo=Package.mongo.Mongo;Tracker=Package.tracker.Tracker;Deps=Package.tracker.Deps;

Drools 6 loading and executing rule from String

I am trying to load a rule from a String in Drools 6 like this:
// the rule
def drl = '''
dialect "mvel"
rule "Person is over 18"
when
$person : Person(age > 18)
then
System.out.println("Person is "+$person.name);
end
'''
// setup for rule
KieServices kieServices = KieServices.Factory.get()
KieFileSystem kfs = kieServices.newKieFileSystem()
kfs.write( "src/main/resources/simple.drl",
kieServices.getResources().newReaderResource( new StringReader(drl) ) )
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll()
// check there have been no errors for rule setup
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
println( results.getMessages() )
throw new IllegalStateException( "### errors ###" )
}
KieContainer kieContainer =
kieServices.newKieContainer( kieBuilder.getKieModule().getReleaseId() )
KieSession kieSession = kieContainer.newKieSession()
// insert facts and fire rules
kieSession.insert(new Person("Jon Doe", 21))
kieSession.insert(new Person("Jon Darcy", 1))
kieSession.fireAllRules()
kieSession.dispose()
#Immutable
class Person {
String name
int age
}
What I wanted to happen is getting the person name printed out. By attaching eventlistener and logger I can see that the facts are added and asserted. By having an error in the drl I can be sure the rule is seen and compiled. But the rule never fires.
I am pretty sure there is jsut a stupid little mistake somewhere in the code. Can somebody help me?
Getting a KieBase from the KieContainer and creating the KieSession from that is what works for me:
KieContainer kieContainer =
kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
KieSession kieSession = kieBase.newKieSession();
But your code is working, too - at least after doing it all in Java, and making sure that Person and the DRL file are in the same package.
String drl = "package drlstring;\n" +
"dialect 'mvel'\n" +
"rule Person_is_over_18\n" +
"when\n" +
"$person : Person(age > 18)\n" +
"then\n" +
"System.out.println(\"Person is \"+$person.getName());\n" +
"end";
// setup for rule
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.write( "src/main/resources/simple.drl",
kieServices.getResources().newReaderResource( new StringReader(drl) ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
// check there have been no errors for rule setup
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
kieServices.newKieContainer( kieBuilder.getKieModule().getReleaseId() );
KieSession kieSession = kieContainer.newKieSession();
// insert facts and fire rules
kieSession.insert(new Person("Jon Doe", 21));
kieSession.insert(new Person("Jon Darcy", 1));
kieSession.fireAllRules();
kieSession.dispose();
If you want to continue with your Scala setup, narrow the possible causes for the failure to fire down by adding a rule with an empty condition:
rule hello
when then
System.out.println( "Hello!" );
end
I think it is the Scala definition of class Person that isn't recognized by the Drools engine.

Logging mongodb query in java

I am using mongo-java-driver-2.9.1 for interacting with mongodb, I want to log the query that are fired on to the mongodb server. e.g. In java for inserting the document this is the code that I write
DBCollection coll = db.getCollection("mycollection");
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
.append("type", "database")
.append("count", 1);
coll.insert(doc);
for this, equivalent code in "mongo" client for inserting document in mongodb is
db.mycollection.insert({
"name" : "MongoDB",
"type" : "database",
"count" : 1
})
I want to log this second code, is there any way to do it?
I think the MongoDB Java driver has not logging support so you have to write your logging Message by your own. Here an Example:
DBCollection coll = db.getCollection("mycollection");
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
.append("type", "database")
.append("count", 1);
WriteResult insert = coll.insert(doc);
String msg = "";
if(insert.getError() == null){
msg = "insert into: " + collection.toString() +" ; Object " + q.toString());
//log the message
} else {
msg = "ERROR by insert into: " + collection.toString() +" ; Object " + q.toString());
msg = msg + " Error message: " + insert.getError();
}
//log the message