List of usage examples for com.mongodb BasicDBObject get
public Object get(final String key)
From source file:com.mulesoft.quartz.mongo.MongoDBJobStore.java
License:Open Source License
protected ObjectId storeJobInMongo(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException { JobKey key = newJob.getKey();// w w w . j a v a2 s. c o m BasicDBObject job = keyAsDBObject(key); if (replaceExisting) { DBObject result = jobCollection.findOne(job); if (result != null) { result = job; } } job.put(JOB_KEY_NAME, key.getName()); job.put(JOB_KEY_GROUP, key.getGroup()); job.put(JOB_DESCRIPTION, newJob.getDescription()); job.put(JOB_CLASS, newJob.getJobClass().getName()); job.putAll(newJob.getJobDataMap()); try { jobCollection.insert(job); return (ObjectId) job.get("_id"); } catch (DuplicateKey e) { throw new ObjectAlreadyExistsException(e.getMessage()); } }
From source file:com.mysema.query.mongodb.MongodbSerializer.java
License:Apache License
@Override public Object visit(Operation<?> expr, Void context) { Operator<?> op = expr.getOperator(); if (op == Ops.EQ) { return asDBObject(asDBKey(expr, 0), asDBValue(expr, 1)); } else if (op == Ops.STRING_IS_EMPTY) { return asDBObject(asDBKey(expr, 0), ""); } else if (op == Ops.AND) { BasicDBObject left = (BasicDBObject) handle(expr.getArg(0)); left.putAll((BSONObject) handle(expr.getArg(1))); return left; } else if (op == Ops.NOT) { //Handle the not's child BasicDBObject arg = (BasicDBObject) handle(expr.getArg(0)); //Only support the first key, let's see if there //is cases where this will get broken String key = arg.keySet().iterator().next(); Operator<?> subOp = ((Operation<?>) expr.getArg(0)).getOperator(); if (subOp != Ops.EQ && subOp != Ops.STRING_IS_EMPTY) { return asDBObject(key, asDBObject("$not", arg.get(key))); } else {//from w w w . j ava2 s. c o m return asDBObject(key, asDBObject("$ne", arg.get(key))); } } else if (op == Ops.OR) { BasicDBList list = new BasicDBList(); list.add(handle(expr.getArg(0))); list.add(handle(expr.getArg(1))); return asDBObject("$or", list); } else if (op == Ops.NE) { return asDBObject(asDBKey(expr, 0), asDBObject("$ne", asDBValue(expr, 1))); } else if (op == Ops.STARTS_WITH) { return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1))); } else if (op == Ops.STARTS_WITH_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1), Pattern.CASE_INSENSITIVE)); } else if (op == Ops.ENDS_WITH) { return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$")); } else if (op == Ops.ENDS_WITH_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE)); } else if (op == Ops.EQ_IGNORE_CASE) { return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE)); } else if (op == Ops.STRING_CONTAINS) { return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*")); } else if (op == Ops.STRING_CONTAINS_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*", Pattern.CASE_INSENSITIVE)); } else if (op == Ops.MATCHES) { return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString())); } else if (op == Ops.MATCHES_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE)); } else if (op == Ops.LIKE) { String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString(); return asDBObject(asDBKey(expr, 0), Pattern.compile(regex)); } else if (op == Ops.BETWEEN) { BasicDBObject value = new BasicDBObject("$gte", asDBValue(expr, 1)); value.append("$lte", asDBValue(expr, 2)); return asDBObject(asDBKey(expr, 0), value); } else if (op == Ops.IN) { int constIndex = 0; int exprIndex = 1; if (expr.getArg(1) instanceof Constant<?>) { constIndex = 1; exprIndex = 0; } if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) { Collection<?> values = (Collection<?>) ((Constant<?>) expr.getArg(constIndex)).getConstant(); return asDBObject(asDBKey(expr, exprIndex), asDBObject("$in", values.toArray())); } else { return asDBObject(asDBKey(expr, exprIndex), asDBValue(expr, constIndex)); } } else if (op == Ops.LT) { return asDBObject(asDBKey(expr, 0), asDBObject("$lt", asDBValue(expr, 1))); } else if (op == Ops.GT) { return asDBObject(asDBKey(expr, 0), asDBObject("$gt", asDBValue(expr, 1))); } else if (op == Ops.LOE) { return asDBObject(asDBKey(expr, 0), asDBObject("$lte", asDBValue(expr, 1))); } else if (op == Ops.GOE) { return asDBObject(asDBKey(expr, 0), asDBObject("$gte", asDBValue(expr, 1))); } else if (op == Ops.IS_NULL) { return asDBObject(asDBKey(expr, 0), asDBObject("$exists", false)); } else if (op == Ops.IS_NOT_NULL) { return asDBObject(asDBKey(expr, 0), asDBObject("$exists", true)); } else if (op == MongodbOps.NEAR) { return asDBObject(asDBKey(expr, 0), asDBObject("$near", asDBValue(expr, 1))); } else if (op == MongodbOps.ELEM_MATCH) { return asDBObject(asDBKey(expr, 0), asDBObject("$elemMatch", asDBValue(expr, 1))); } throw new UnsupportedOperationException("Illegal operation " + expr); }
From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java
License:Open Source License
protected ObjectId storeJobInMongo(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException { JobKey key = newJob.getKey();/*from w w w . j a v a 2 s . c o m*/ BasicDBObject keyDbo = keyToDBObject(key); BasicDBObject job = keyToDBObject(key); job.put(KEY_NAME, key.getName()); job.put(KEY_GROUP, key.getGroup()); job.put(JOB_DESCRIPTION, newJob.getDescription()); job.put(JOB_CLASS, newJob.getJobClass().getName()); job.put(JOB_DURABILITY, newJob.isDurable()); job.putAll(newJob.getJobDataMap()); DBObject object = jobCollection.findOne(keyDbo); ObjectId objectId = null; if (object != null && replaceExisting) { jobCollection.update(keyDbo, job); } else if (object == null) { try { jobCollection.insert(job); objectId = (ObjectId) job.get("_id"); } catch (DuplicateKey e) { // Fine, find it and get its id. object = jobCollection.findOne(keyDbo); objectId = (ObjectId) object.get("_id"); } } else { objectId = (ObjectId) object.get("_id"); } return objectId; }
From source file:com.petpet.c3po.dao.mongo.MongoFilterSerializer.java
License:Apache License
public DBObject serializeNew(Filter filter) { DBObject result = new BasicDBObject(); if (filter != null) { if (filter.getRaw() != null) { Object o = com.mongodb.util.JSON.parse(filter.getRaw()); return (DBObject) o; }/*w ww.ja v a 2s.c om*/ if (filter.getConditions() != null && filter.getConditions().size() > 0) return serialize(filter); List<PropertyFilterCondition> propertyFilterConditions = filter.getPropertyFilterConditions(); List<BasicDBObject> and = new ArrayList<BasicDBObject>(); for (PropertyFilterCondition propertyFilterCondition : propertyFilterConditions) { BasicDBObject metadata = new BasicDBObject(); BasicDBObject elemMatch = new BasicDBObject(); BasicDBObject elemMatchComponents = new BasicDBObject(); String propertyName = propertyFilterCondition.getProperty(); elemMatchComponents.put("property", propertyName); //process separate property values if (propertyFilterCondition.getValues().size() > 0) { List<Object> list = new ArrayList<Object>(); for (String value : propertyFilterCondition.getValues()) { list.add(normalizeValue(value, propertyName)); } BasicDBObject all = new BasicDBObject("$all", list); if (filter.isStrict()) all.put("$size", list.size()); elemMatchComponents.put("sourcedValues.value", all); } //process separate property value sources if (propertyFilterCondition.getSources().size() > 0) { List<Object> list = new ArrayList<Object>(); for (String source : propertyFilterCondition.getSources()) { Source s = null; if (source.contains(":")) { String[] split = source.split(":"); s = Configurator.getDefaultConfigurator().getPersistence().getCache() .getSource(split[0], split[1]); } else s = Configurator.getDefaultConfigurator().getPersistence().getCache().getSource(source); list.add(s.getId()); } BasicDBObject all = new BasicDBObject("$all", list); if (filter.isStrict()) all.put("$size", list.size()); elemMatchComponents.put("sourcedValues.source", all); } //process property sourced values if (propertyFilterCondition.getSourcedValues().size() > 0) { List<Object> list = new ArrayList<Object>(); List<String> sourceIDs = new ArrayList<String>(); for (Map.Entry<String, String> stringStringEntry : propertyFilterCondition.getSourcedValues() .entrySet()) { if (stringStringEntry.getValue().equals("UNKNOWN")) { BasicDBObject elemMatchSourcedValue = produceElemMatch(stringStringEntry, propertyName); BasicDBObject tmp_elemMatch = (BasicDBObject) elemMatchSourcedValue.get("$elemMatch"); sourceIDs.add(tmp_elemMatch.getString("source")); } else { BasicDBObject elemMatchSourcedValue = produceElemMatch(stringStringEntry, propertyName); list.add(elemMatchSourcedValue); } if (sourceIDs.size() > 0) { BasicDBObject nin = new BasicDBObject("$nin", sourceIDs); elemMatchComponents.put("sourcedValues.source", nin); } } BasicDBObject all = new BasicDBObject("$all", list); if (filter.isStrict()) all.put("$size", list.size()); if (list.size() > 0) elemMatchComponents.put("sourcedValues", all); } //process separate property statuses if (propertyFilterCondition.getStatuses().size() > 0) { List<Object> list = new ArrayList<Object>(); for (String status : propertyFilterCondition.getStatuses()) { list.add(status); } BasicDBObject all = new BasicDBObject("$in", list); elemMatchComponents.put("status", all); } elemMatch.put("$elemMatch", elemMatchComponents); metadata.put("metadata", elemMatch); and.add(metadata); } if (and.size() > 0) result.put("$and", and); /*if (filter.getConditions()!=null && filter.getConditions().size()>0) return serialize(filter); List<PropertyFilterCondition> propertyFilterConditions = filter.getPropertyFilterConditions(); List<BasicDBObject> and = new ArrayList<BasicDBObject>(); for (PropertyFilterCondition propertyFilterCondition : propertyFilterConditions) { String propertyName = propertyFilterCondition.getProperty(); and.addAll(getSourcedValueList(propertyFilterCondition.getSourcedValues(), propertyName)); and.addAll(getPropertyList(propertyName)) ; and.addAll(getStatusList(propertyFilterCondition.getStatuses(), "$or")); and.addAll(getSourceList(propertyFilterCondition.getSources(), "$and")); and.addAll(getValueList(propertyFilterCondition.getValues(), "$and", propertyName)); } if (and.size() > 0) result.put("$and", and);*/ } return result; }
From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java
License:Apache License
public Map<String, Long> parseMapReduce(DBObject object, String property) { Map<String, Long> histogram = new HashMap<String, Long>(); if (object == null) { return histogram; }/* w ww.j ava 2 s .c om*/ List<BasicDBObject> results = (List<BasicDBObject>) object; for (final BasicDBObject dbo : results) { String p = ((BasicDBObject) dbo.get("_id")).getString("property"); String val = ((BasicDBObject) dbo.get("_id")).getString("value"); try { long count = dbo.getLong("value"); String type = getCache().getProperty(p).getType(); if (type.equals(PropertyType.DATE.toString())) { try { Double v = Double.parseDouble(val); int i = v.intValue(); histogram.put(String.valueOf(i), count); } catch (NumberFormatException nfe) { histogram.put(val, count); } } else histogram.put(val, count); } catch (Exception e) { BasicDBObject v = (BasicDBObject) dbo.get("value"); long sum, min, max, avg, std, var, count; try { count = v.getLong("count"); } catch (Exception ex) { count = 0; } try { sum = v.getLong("sum"); } catch (Exception ex) { sum = 0; } try { min = v.getLong("min"); } catch (Exception ex) { min = 0; } try { max = v.getLong("max"); } catch (Exception ex) { max = 0; } try { avg = v.getLong("avg"); } catch (Exception ex) { avg = 0; } try { std = v.getLong("stddev"); } catch (Exception ex) { std = 0; } try { var = v.getLong("variance"); } catch (Exception ex) { var = 0; } histogram.put("sum", sum); histogram.put("min", min); histogram.put("max", max); histogram.put("avg", avg); histogram.put("std", std); histogram.put("var", var); histogram.put("count", count); } } return histogram; }
From source file:com.ratzia.pfc.webpageanalyticaltool.dbupdater.Watcher.java
public void processDatabase(LinkedList<String> pluginsCode, String currentVersion) throws UnknownHostException { /**** Plugins ****/ LinkedList<SysPlugin> plugins = loadPlugins(pluginsCode); /*****************/ /*SecurityManager oldSecurityManager = System.getSecurityManager(); DBPluginSecurityManager dbPluginSecurityManager = new DBPluginSecurityManager(); System.setSecurityManager(dbPluginSecurityManager); //Will open the security manager so we need to ensure it is closed afterwards try{*//* w ww.j a v a 2 s. c om*/ MongoClient mongoClient = new MongoClient(serverAddress); DB local = mongoClient.getDB(db); DBCollection dbCol = local.getCollection(collection); BasicDBObject query = new BasicDBObject(); query.put(PLUGIN_VERSION_FIELD, new BasicDBObject("$ne", currentVersion)); DBCursor cursor = dbCol.find(query); long count = 0; while (cursor.hasNext()) { DBObject obj = cursor.next(); //Copy contents BasicDBObject res = new BasicDBObject(); for (String k : obj.keySet()) { res.put(k, obj.get(k)); } //Plugin operations for (SysPlugin plugin : plugins) { try { plugin.run(res); } catch (Exception ex) { System.out.println("Error en " + plugin.getClass()); Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex); } } //Put plugin only fields into the original object for (String k : res.keySet()) { if ((k.substring(0, 2)).compareTo("p_") == 0) { obj.put(k, res.get(k)); } } //Update version on object obj.put(PLUGIN_VERSION_FIELD, currentVersion); dbCol.save(obj); count++; } cursor.close(); if (count > 0) { System.out.println(count + " updated"); } /*}catch(Exception ex){ Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex); } //close sandbox System.setSecurityManager(oldSecurityManager);*/ }
From source file:com.redhat.lightblue.crud.mongo.Translator.java
License:Open Source License
private void translateSet(FieldTreeNode root, SetExpression expr, BasicDBObject dest) throws CannotTranslateException { String op;/*from w w w . j a v a2s.c o m*/ switch (expr.getOp()) { case _set: op = "$set"; break; case _add: op = "$inc"; break; default: throw new CannotTranslateException(expr); } BasicDBObject obj = (BasicDBObject) dest.get(op); if (obj == null) { obj = new BasicDBObject(); dest.put(op, obj); } for (FieldAndRValue frv : expr.getFields()) { Path field = frv.getField(); if (hasArray(root, field)) { throw new CannotTranslateException(expr); } RValueExpression rvalue = frv.getRValue(); if (rvalue.getType() == RValueExpression.RValueType._value) { Value value = rvalue.getValue(); FieldTreeNode ftn = root.resolve(field); if (ftn == null) { throw new CannotTranslateException(expr); } if (!(ftn instanceof SimpleField)) { throw new CannotTranslateException(expr); } Object valueObject = ftn.getType().cast(value.getValue()); if (field.equals(ID_PATH)) { valueObject = new ObjectId(valueObject.toString()); } obj.put(translatePath(field), valueObject); } else { throw new CannotTranslateException(expr); } } }
From source file:com.redhat.lightblue.crud.mongo.Translator.java
License:Open Source License
private void translateUnset(FieldTreeNode root, UnsetExpression expr, BasicDBObject dest) throws CannotTranslateException { BasicDBObject obj = (BasicDBObject) dest.get("$unset"); if (obj == null) { obj = new BasicDBObject(); dest.put("$unset", obj); }/*ww w . ja va 2 s . c om*/ for (Path field : expr.getFields()) { if (hasArray(root, field)) { throw new CannotTranslateException(expr); } obj.put(translatePath(field), ""); } }
From source file:com.redhat.lightblue.mongo.crud.ExpressionTranslator.java
License:Open Source License
private void translateSet(FieldTreeNode root, SetExpression expr, BasicDBObject dest) throws CannotTranslateException { String op;//from w ww. j a v a2s. com switch (expr.getOp()) { case _set: op = "$set"; break; case _add: op = "$inc"; break; default: throw new CannotTranslateException(expr); } BasicDBObject obj = (BasicDBObject) dest.get(op); if (obj == null) { obj = new BasicDBObject(); dest.put(op, obj); } for (FieldAndRValue frv : expr.getFields()) { Path field = frv.getField(); if (hasArray(root, field)) { throw new CannotTranslateException(expr); } RValueExpression rvalue = frv.getRValue(); if (rvalue.getType() == RValueExpression.RValueType._value) { Value value = rvalue.getValue(); FieldTreeNode ftn = root.resolve(field); if (ftn == null) { throw new CannotTranslateException(expr); } if (!(ftn instanceof SimpleField)) { throw new CannotTranslateException(expr); } Object valueObject = ftn.getType().cast(value.getValue()); if (field.equals(ID_PATH)) { valueObject = DocTranslator.createIdFrom(valueObject); } obj.put(translatePath(field), DocTranslator.filterBigNumbers(valueObject)); } else { throw new CannotTranslateException(expr); } } }
From source file:com.redhat.mongotx.TransactionLogger.java
License:Open Source License
/** * Inserts a record into the transaction collection, and returns * the new transaction id//from w w w .ja v a 2 s .c o m */ public String startTransaction() { Date date = new Date(); BasicDBObject txDoc = new BasicDBObject().append(STATE, TxState.active.toString()).append(STARTED, date) .append(LAST_TOUCHED, date); txCollection.insert(txDoc, WriteConcern.SAFE); return txDoc.get(ID).toString(); }