List of usage examples for com.mongodb BasicDBObject get
public Object get(final String key)
From source file:org.pentaho.di.trans.steps.mongodboutput.MongoDbOutputData.java
License:Open Source License
/** * Get an object that encapsulates the fields and modifier operations to use for a modifier update. * <p/>//from w w w.j a v a2s .c o m * NOTE: that with modifier upserts the query conditions get created if the record does not exist (i.e. insert). This * is different than straight non- modifier upsert where the query conditions just locate a matching record (if any) * and then a complete object replacement is done. So for standard upsert it is necessary to duplicate the query * condition paths in order for these fields to be in the object that is inserted/updated. * <p/> * This also means that certain modifier upserts are not possible in the case of insert. E.g. here we are wanting to * test if the field "f1" in record "rec1" in the first element of array "two" is set to "george". If so, then we want * to push a new record to the end of the array; otherwise create a new document with the array containing just the * new record: * <p/> * <p/> * <pre> * db.collection.update({ "one.two.0.rec1.f1" : "george"}, * { "$push" : { "one.two" : { "rec1" : { "f1" : "bob" , "f2" : "fred"}}}}, * true) * </pre> * <p/> * This does not work and results in a "Cannot apply $push/$pushAll modifier to non-array" error if there is no match * (i.e. insert condition). This is because the query conditions get created as well as the modifier opps and, * furthermore, they get created first. Since mongo doesn't know whether ".0." indicates an array index or a field * name it defaults to creating a field with name "0". This means that "one.two" gets created as a record (not an * array) before the $push operation is executed. Hence the error. * * @param fieldDefs the list of document field definitions * @param inputMeta the input row format * @param row the current incoming row * @param vars environment variables * @param topLevelStructure the top level structure of the document * @return a DBObject encapsulating the update to make * @throws KettleException if a problem occurs */ protected DBObject getModifierUpdateObject(List<MongoDbOutputMeta.MongoField> fieldDefs, RowMetaInterface inputMeta, Object[] row, VariableSpace vars, MongoTopLevel topLevelStructure) throws KettleException, MongoDbException { boolean haveUpdateFields = false; boolean hasNonNullUpdateValues = false; // main update object, keyed by $ operator BasicDBObject updateObject = new BasicDBObject(); m_setComplexArrays.clear(); m_primitiveLeafModifiers.clear(); m_pushComplexStructures.clear(); // do we need to determine whether this will be an insert or an update? boolean checkForMatch = false; for (MongoDbOutputMeta.MongoField field : fieldDefs) { if (!field.m_updateMatchField && (field.m_modifierOperationApplyPolicy.equals("Insert") || field.m_modifierOperationApplyPolicy //$NON-NLS-1$ .equals("Update"))) { //$NON-NLS-1$ checkForMatch = true; break; } } boolean isUpdate = false; if (checkForMatch) { DBObject query = getQueryObject(fieldDefs, inputMeta, row, vars, topLevelStructure); MongoCursorWrapper cursor = getCollection().find(query).limit(1); if (cursor.hasNext()) { isUpdate = true; } } for (MongoDbOutputMeta.MongoField field : fieldDefs) { // skip query match fields if (field.m_updateMatchField) { continue; } String modifierUpdateOpp = vars.environmentSubstitute(field.m_modifierUpdateOperation); if (!Const.isEmpty(modifierUpdateOpp) && !modifierUpdateOpp.equals("N/A")) { //$NON-NLS-1$ if (checkForMatch) { if (isUpdate && field.m_modifierOperationApplyPolicy.equals("Insert")) { //$NON-NLS-1$ continue; // don't apply this opp } if (!isUpdate && field.m_modifierOperationApplyPolicy.equals("Update")) { //$NON-NLS-1$ continue; // don't apply this opp } } haveUpdateFields = true; String incomingFieldName = vars.environmentSubstitute(field.m_incomingFieldName); int index = inputMeta.indexOfValue(incomingFieldName); ValueMetaInterface vm = inputMeta.getValueMeta(index); if (!vm.isNull(row[index]) || field.insertNull) { hasNonNullUpdateValues = true; // modifier update objects have fields using "dot" notation to reach // into embedded documents String mongoPath = (field.m_mongoDocPath != null) ? field.m_mongoDocPath : ""; //$NON-NLS-1$ String path = vars.environmentSubstitute(mongoPath); if (path.endsWith("]") && modifierUpdateOpp.equals("$push") //$NON-NLS-1$ //$NON-NLS-2$ && !field.m_useIncomingFieldNameAsMongoFieldName) { // strip off the brackets as push appends to the end of the named // array path = path.substring(0, path.indexOf('[')); } boolean hasPath = !Const.isEmpty(path); path += ((field.m_useIncomingFieldNameAsMongoFieldName) ? (hasPath ? "." //$NON-NLS-1$ + incomingFieldName : incomingFieldName) : ""); //$NON-NLS-1$ // check for array creation if (modifierUpdateOpp.equals("$set") && path.indexOf('[') > 0) { //$NON-NLS-1$ String arrayPath = path.substring(0, path.indexOf('[')); String arraySpec = path.substring(path.indexOf('['), path.length()); MongoDbOutputMeta.MongoField a = new MongoDbOutputMeta.MongoField(); a.m_incomingFieldName = field.m_incomingFieldName; a.m_mongoDocPath = arraySpec; // incoming field name has already been appended (if necessary) a.m_useIncomingFieldNameAsMongoFieldName = false; a.m_JSON = field.m_JSON; a.init(vars); List<MongoDbOutputMeta.MongoField> fds = m_setComplexArrays.get(arrayPath); if (fds == null) { fds = new ArrayList<MongoDbOutputMeta.MongoField>(); m_setComplexArrays.put(arrayPath, fds); } fds.add(a); } else if (modifierUpdateOpp.equals("$push") && path.indexOf('[') > 0) { //$NON-NLS-1$ // we ignore any index that might have been specified as $push // always appends to the end of the array. String arrayPath = path.substring(0, path.indexOf('[')); String structureToPush = path.substring(path.indexOf(']') + 1, path.length()); // check to see if we're pushing a record at this point in the path // or another array... if (structureToPush.charAt(0) == '.') { // skip the dot structureToPush = structureToPush.substring(1, structureToPush.length()); } MongoDbOutputMeta.MongoField a = new MongoDbOutputMeta.MongoField(); a.m_incomingFieldName = field.m_incomingFieldName; a.m_mongoDocPath = structureToPush; // incoming field name has already been appended (if necessary) a.m_useIncomingFieldNameAsMongoFieldName = false; a.m_JSON = field.m_JSON; a.init(vars); List<MongoDbOutputMeta.MongoField> fds = m_pushComplexStructures.get(arrayPath); if (fds == null) { fds = new ArrayList<MongoDbOutputMeta.MongoField>(); m_pushComplexStructures.put(arrayPath, fds); } fds.add(a); } else { Object[] params = new Object[4]; params[0] = modifierUpdateOpp; params[1] = index; params[2] = field.m_JSON; params[3] = field.insertNull; m_primitiveLeafModifiers.put(path, params); } } } } // do the array $sets for (String path : m_setComplexArrays.keySet()) { List<MongoDbOutputMeta.MongoField> fds = m_setComplexArrays.get(path); DBObject valueToSet = kettleRowToMongo(fds, inputMeta, row, vars, MongoTopLevel.ARRAY, false); DBObject fieldsToUpdateWithValues; if (updateObject.get("$set") != null) { //$NON-NLS-1$ // if we have some field(s) already associated with this type of // modifier // operation then just add to them fieldsToUpdateWithValues = (DBObject) updateObject.get("$set"); //$NON-NLS-1$ } else { // otherwise create a new DBObject for this modifier operation fieldsToUpdateWithValues = new BasicDBObject(); } fieldsToUpdateWithValues.put(path, valueToSet); updateObject.put("$set", fieldsToUpdateWithValues); //$NON-NLS-1$ } // now do the $push complex for (String path : m_pushComplexStructures.keySet()) { List<MongoDbOutputMeta.MongoField> fds = m_pushComplexStructures.get(path); // check our top-level structure MongoTopLevel topLevel = MongoTopLevel.RECORD; if (fds.get(0).m_mongoDocPath.charAt(0) == '[') { topLevel = MongoTopLevel.RECORD; } DBObject valueToSet = kettleRowToMongo(fds, inputMeta, row, vars, topLevel, false); DBObject fieldsToUpdateWithValues = null; if (updateObject.get("$push") != null) { //$NON-NLS-1$ // if we have some field(s) already associated with this type of // modifier // operation then just add to them fieldsToUpdateWithValues = (DBObject) updateObject.get("$push"); //$NON-NLS-1$ } else { // otherwise create a new DBObject for this modifier operation fieldsToUpdateWithValues = new BasicDBObject(); } fieldsToUpdateWithValues.put(path, valueToSet); updateObject.put("$push", fieldsToUpdateWithValues); //$NON-NLS-1$ } // do the modifiers that involve primitive field values for (Map.Entry<String, Object[]> entry : m_primitiveLeafModifiers.entrySet()) { String path = entry.getKey(); Object[] params = entry.getValue(); String modifierUpdateOpp = params[0].toString(); int index = (Integer) params[1]; boolean isJSON = (Boolean) params[2]; boolean allowNull = (Boolean) params[3]; ValueMetaInterface vm = inputMeta.getValueMeta(index); DBObject fieldsToUpdateWithValues = null; if (updateObject.get(modifierUpdateOpp) != null) { // if we have some field(s) already associated with this type of // modifier // operation then just add to them fieldsToUpdateWithValues = (DBObject) updateObject.get(modifierUpdateOpp); } else { // otherwise create a new DBObject for this modifier operation fieldsToUpdateWithValues = new BasicDBObject(); } setMongoValueFromKettleValue(fieldsToUpdateWithValues, path, vm, row[index], isJSON, allowNull); updateObject.put(modifierUpdateOpp, fieldsToUpdateWithValues); } if (!haveUpdateFields) { throw new KettleException(BaseMessages.getString(PKG, "MongoDbOutput.Messages.Error.NoFieldsToUpdateSpecifiedForModifierOpp")); //$NON-NLS-1$ } if (!hasNonNullUpdateValues) { return null; } return updateObject; }
From source file:org.pentaho.mongo.wrapper.field.MongoArrayExpansion.java
License:Open Source License
public Object[][] convertToKettleValue(BasicDBObject mongoObject, VariableSpace space) throws KettleException { if (mongoObject == null) { return nullResult(); }/*from w w w . j a va 2 s . co m*/ if (m_tempParts.size() == 0) { throw new KettleException(BaseMessages.getString(PKG, "MongoDbInput.ErrorMessage.MalformedPathRecord")); //$NON-NLS-1$ } String part = m_tempParts.remove(0); if (part.charAt(0) == '[') { // we're not expecting an array at this point - this document does not // contain our field(s) return nullResult(); } if (part.indexOf('[') > 0) { String arrayPart = part.substring(part.indexOf('[')); part = part.substring(0, part.indexOf('[')); // put the array section back into location zero m_tempParts.add(0, arrayPart); } // part is a named field of this record Object fieldValue = mongoObject.get(part); if (fieldValue == null) { return nullResult(); } if (fieldValue instanceof BasicDBObject) { return convertToKettleValue(((BasicDBObject) fieldValue), space); } if (fieldValue instanceof BasicDBList) { return convertToKettleValue(((BasicDBList) fieldValue), space); } // must mean we have a primitive here, but we're expecting to process more // path so this doesn't match us - return null return nullResult(); }
From source file:org.pentaho.mongo.wrapper.field.MongodbInputDiscoverFieldsImpl.java
License:Open Source License
private static void processRecord(BasicDBObject rec, String path, String name, Map<String, MongoField> lookup) { for (String key : rec.keySet()) { Object fieldValue = rec.get(key); if (fieldValue instanceof BasicDBObject) { processRecord((BasicDBObject) fieldValue, path + "." + key, name + "." + //$NON-NLS-1$ //$NON-NLS-2$ key, lookup);/*from ww w. j a v a2 s. c o m*/ } else if (fieldValue instanceof BasicDBList) { processList((BasicDBList) fieldValue, path + "." + key, name + "." + //$NON-NLS-1$ //$NON-NLS-2$ key, lookup); } else { // some sort of primitive String finalPath = path + "." + key; //$NON-NLS-1$ String finalName = name + "." + key; //$NON-NLS-1$ if (!lookup.containsKey(finalPath)) { MongoField newField = new MongoField(); int kettleType = mongoToKettleType(fieldValue); // Following suit of mongoToKettleType by interpreting null as String type newField.m_mongoType = String.class; if (fieldValue != null) { newField.m_mongoType = fieldValue.getClass(); } newField.m_fieldName = finalName; newField.m_fieldPath = finalPath; newField.m_kettleType = ValueMeta.getTypeDesc(kettleType); newField.m_percentageOfSample = 1; lookup.put(finalPath, newField); } else { // update max indexes in array parts of name MongoField m = lookup.get(finalPath); Class<?> fieldClass = String.class; if (fieldValue != null) { fieldClass = fieldValue.getClass(); } if (!m.m_mongoType.isAssignableFrom(fieldClass)) { m.m_disparateTypes = true; } m.m_percentageOfSample++; updateMaxArrayIndexes(m, finalName); } } } }
From source file:org.restheart.hal.metadata.AbstractAggregationOperation.java
License:Open Source License
/** * @param obj/* w w w . j a v a 2 s .c om*/ * @param aVars RequestContext.getAggregationVars() * @return the json object where the variables ({"_$var": "var") are * replaced with the values defined in the avars URL query parameter * @throws org.restheart.hal.metadata.InvalidMetadataException * @throws org.restheart.hal.metadata.QueryVariableNotBoundException */ protected Object bindAggregationVariables(Object obj, DBObject aVars) throws InvalidMetadataException, QueryVariableNotBoundException { if (obj == null) { return null; } if (obj instanceof BasicDBObject) { BasicDBObject _obj = (BasicDBObject) obj; if (_obj.size() == 1 && _obj.get("$var") != null) { Object varName = _obj.get("$var"); if (!(varName instanceof String)) { throw new InvalidMetadataException("wrong variable name " + varName.toString()); } if (aVars == null || aVars.get((String) varName) == null) { throw new QueryVariableNotBoundException("variable " + varName + " not bound"); } return aVars.get((String) varName); } else { BasicDBObject ret = new BasicDBObject(); for (String key : ((BasicDBObject) obj).keySet()) { ret.put(key, bindAggregationVariables(((BasicDBObject) obj).get(key), aVars)); } return ret; } } else if (obj instanceof BasicDBList) { BasicDBList ret = new BasicDBList(); for (Object el : ((BasicDBList) obj).toArray()) { ret.add(bindAggregationVariables((BasicDBObject) el, aVars)); } return ret; } else { return obj; } }
From source file:org.restheart.hal.metadata.singletons.ContentSizeChecker.java
License:Open Source License
@Override public boolean check(HttpServerExchange exchange, RequestContext context, DBObject args) { if (args instanceof BasicDBObject) { BasicDBObject condition = (BasicDBObject) args; Integer maxSize = null;/*from www . j a v a 2 s. c o m*/ Object _maxSize = condition.get("max"); if (_maxSize != null && _maxSize instanceof Integer) { maxSize = (Integer) _maxSize; } else { context.addWarning("checker wrong definition: 'max' property missing."); return true; } Integer minSize = null; Object _minSize = condition.get("min"); if (_minSize != null && _minSize instanceof Integer) { minSize = (Integer) _minSize; } return (minSize == null ? checkSize(exchange, -1, maxSize) : checkSize(exchange, minSize, maxSize)); } else { context.addWarning( "checker wrong definition: args property must be a json object with 'min' and 'max' properties."); return true; } }
From source file:org.restheart.hal.metadata.singletons.JsonPathConditionsChecker.java
License:Open Source License
protected boolean applyConditions(BasicDBList conditions, DBObject json, final RequestContext context) { return conditions.stream().allMatch((Object _condition) -> { if (_condition instanceof BasicDBObject) { BasicDBObject condition = (BasicDBObject) _condition; String path = null;/*from w ww . ja va 2s .c om*/ Object _path = condition.get("path"); if (_path != null && _path instanceof String) { path = (String) _path; } String type = null; Object _type = condition.get("type"); if (_type != null && _type instanceof String) { type = (String) _type; } Set<Integer> counts = new HashSet<>(); Object _count = condition.get("count"); if (_count != null) { if (_count instanceof Integer) { counts.add((Integer) _count); } else if (_count instanceof BasicDBList) { BasicDBList countsArray = (BasicDBList) _count; countsArray.forEach((Object countElement) -> { if (countElement instanceof Integer) { counts.add((Integer) countElement); } }); } } Set<String> mandatoryFields; Object _mandatoryFields = condition.get("mandatoryFields"); if (_mandatoryFields != null) { mandatoryFields = new HashSet<>(); if (_mandatoryFields instanceof BasicDBList) { BasicDBList mandatoryFieldsArray = (BasicDBList) _mandatoryFields; mandatoryFieldsArray.forEach((Object element) -> { if (element instanceof String) { mandatoryFields.add((String) element); } }); } } else { mandatoryFields = null; } Set<String> optionalFields; Object _optionalFields = condition.get("optionalFields"); if (_optionalFields != null) { optionalFields = new HashSet<>(); if (_optionalFields instanceof BasicDBList) { BasicDBList optionalFieldsArray = (BasicDBList) _optionalFields; optionalFieldsArray.forEach((Object element) -> { if (element instanceof String) { optionalFields.add((String) element); } }); } } else { optionalFields = null; } String regex = null; Object _regex = condition.get("regex"); if (_regex != null && _regex instanceof String) { regex = (String) _regex; } Boolean optional = false; Object _optional = condition.get("optional"); if (_optional != null && _optional instanceof Boolean) { optional = (Boolean) _optional; } Boolean nullable = false; Object _nullable = condition.get("nullable"); if (_nullable != null && _nullable instanceof Boolean) { nullable = (Boolean) _nullable; } if (counts.isEmpty() && type == null && regex == null) { context.addWarning( "condition does not have any of 'count', 'type' and 'regex' properties, specify at least one: " + _condition); return true; } if (path == null) { context.addWarning( "condition in the args list does not have the 'path' property: " + _condition); return true; } if (type != null && !counts.isEmpty() && regex != null) { return checkCount(json, path, counts, context) && checkType(json, path, type, mandatoryFields, optionalFields, optional, nullable, context) && checkRegex(json, path, regex, optional, nullable, context); } else if (type != null && !counts.isEmpty()) { return checkCount(json, path, counts, context) && checkType(json, path, type, mandatoryFields, optionalFields, optional, nullable, context); } else if (type != null && regex != null) { return checkType(json, path, type, mandatoryFields, optionalFields, optional, nullable, context) && checkRegex(json, path, regex, optional, nullable, context); } else if (!counts.isEmpty() && regex != null) { return checkCount(json, path, counts, context) && checkRegex(json, path, regex, optional, nullable, context); } else if (type != null) { return checkType(json, path, type, mandatoryFields, optionalFields, optional, nullable, context); } else if (!counts.isEmpty()) { return checkCount(json, path, counts, context); } else if (regex != null) { return checkRegex(json, path, regex, optional, nullable, context); } return true; } else { context.addWarning("property in the args list is not an object: " + _condition); return true; } }); }
From source file:org.restheart.hal.metadata.singletons.SimpleContentChecker.java
License:Open Source License
@Override public boolean check(HttpServerExchange exchange, RequestContext context, DBObject args) { if (args instanceof BasicDBList) { BasicDBList conditions = getApplicableConditions((BasicDBList) args, context.getMethod(), context.getContent());/* ww w . j a v a 2s. c o m*/ return conditions.stream().allMatch(_condition -> { if (_condition instanceof BasicDBObject) { BasicDBObject condition = (BasicDBObject) _condition; String path = null; Object _path = condition.get("path"); if (_path != null && _path instanceof String) { path = (String) _path; } String type = null; Object _type = condition.get("type"); if (_type != null && _type instanceof String) { type = (String) _type; } Set<Integer> counts = new HashSet<>(); Object _count = condition.get("count"); if (_count != null) { if (_count instanceof Integer) { counts.add((Integer) _count); } else if (_count instanceof BasicDBList) { BasicDBList countsArray = (BasicDBList) _count; countsArray.forEach(countElement -> { if (countElement instanceof Integer) { counts.add((Integer) countElement); } }); } } Set<String> mandatoryFields; Object _mandatoryFields = condition.get("mandatoryFields"); if (_mandatoryFields != null) { mandatoryFields = new HashSet<>(); if (_mandatoryFields instanceof BasicDBList) { BasicDBList mandatoryFieldsArray = (BasicDBList) _mandatoryFields; mandatoryFieldsArray.forEach(element -> { if (element instanceof String) { mandatoryFields.add((String) element); } }); } } else { mandatoryFields = null; } Set<String> optionalFields; Object _optionalFields = condition.get("optionalFields"); if (_optionalFields != null) { optionalFields = new HashSet<>(); if (_optionalFields instanceof BasicDBList) { BasicDBList optionalFieldsArray = (BasicDBList) _optionalFields; optionalFieldsArray.forEach(element -> { if (element instanceof String) { optionalFields.add((String) element); } }); } } else { optionalFields = null; } String regex = null; Object _regex = condition.get("regex"); if (_regex != null && _regex instanceof String) { regex = (String) _regex; } Boolean optional = false; Object _optional = condition.get("optional"); if (_optional != null && _optional instanceof Boolean) { optional = (Boolean) _optional; } Boolean nullable = false; Object _nullable = condition.get("nullable"); if (_nullable != null && _nullable instanceof Boolean) { nullable = (Boolean) _nullable; } if (counts.isEmpty() && type == null && regex == null) { context.addWarning( "condition does not have any of 'count', 'type' and 'regex' properties, specify at least one: " + _condition); return true; } if (path == null) { context.addWarning( "condition in the args list does not have the 'path' property: " + _condition); return true; } if (type != null && !counts.isEmpty() && regex != null) { return checkCount(context.getContent(), path, counts, context) && checkType(context.getContent(), path, type, mandatoryFields, optionalFields, optional, nullable, context) && checkRegex(context.getContent(), path, regex, optional, nullable, context); } else if (type != null && !counts.isEmpty()) { return checkCount(context.getContent(), path, counts, context) && checkType(context.getContent(), path, type, mandatoryFields, optionalFields, optional, nullable, context); } else if (type != null && regex != null) { return checkType(context.getContent(), path, type, mandatoryFields, optionalFields, optional, nullable, context) && checkRegex(context.getContent(), path, regex, optional, nullable, context); } else if (!counts.isEmpty() && regex != null) { return checkCount(context.getContent(), path, counts, context) && checkRegex(context.getContent(), path, regex, optional, nullable, context); } else if (type != null) { return checkType(context.getContent(), path, type, mandatoryFields, optionalFields, optional, nullable, context); } else if (!counts.isEmpty()) { return checkCount(context.getContent(), path, counts, context); } else if (regex != null) { return checkRegex(context.getContent(), path, regex, optional, nullable, context); } return true; } else { context.addWarning("property in the args list is not an object: " + _condition); return true; } }); } else { context.addWarning( "checker wrong definition: args property must be an arrary of string property names."); return true; } }
From source file:org.restheart.hal.metadata.singletons.SimpleContentChecker.java
License:Open Source License
private BasicDBList getApplicableConditions(BasicDBList conditions, RequestContext.METHOD method, DBObject content) {/*from w ww .jav a 2s . c o m*/ if (method == RequestContext.METHOD.POST || method == RequestContext.METHOD.PUT) { return filterNullableAndOptionalNullConditions(conditions, content); } else if (method == RequestContext.METHOD.PATCH) { List filtered = conditions.stream().filter(condition -> { if (!(condition instanceof BasicDBObject)) { return false; } BasicDBObject _condition = (BasicDBObject) condition; String path = null; Object _path = _condition.get("path"); if (_path != null && _path instanceof String) { path = (String) _path; } if (path == null) { return false; } Object _count = _condition.get("count"); if (_count != null) { if (path.equals("$") || path.equals("$.*")) { return false; } else { try { List<Optional<Object>> matches = JsonUtils.getPropsFromPath(content, path); if (matches == null || matches.isEmpty()) { return false; } return !(matches.size() == 1 && matches.get(0) == null); } catch (IllegalArgumentException ex) { return false; } } } else { try { List<Optional<Object>> matches = JsonUtils.getPropsFromPath(content, path); if (matches == null || matches.isEmpty()) { return false; } return !(matches.size() == 1 && matches.get(0) == null); } catch (IllegalArgumentException ex) { return false; } } }).collect(Collectors.toList()); BasicDBList ret = new BasicDBList(); filtered.stream().forEach((fc) -> { ret.add(fc); }); return filterNullableAndOptionalNullConditions(ret, content); } else { return new BasicDBList(); } }
From source file:org.restheart.handlers.aggregation.AggregationTransformer.java
License:Open Source License
@Override public void tranform(HttpServerExchange exchange, RequestContext context, final DBObject contentToTransform, DBObject args) {//from w ww. j av a 2s . c om if (contentToTransform == null) { // nothing to do return; } if (context.getType() == RequestContext.TYPE.COLLECTION) { BasicDBList aggrs = getAggregationMetadata(contentToTransform); if (aggrs == null) { // nothing to do return; } if (context.getMethod() == RequestContext.METHOD.PUT || context.getMethod() == RequestContext.METHOD.PATCH) { contentToTransform.put(AbstractAggregationOperation.AGGREGATIONS_ELEMENT_NAME, (DBObject) JsonUtils.escapeKeys(aggrs, true)); } else if (context.getMethod() == RequestContext.METHOD.GET) { contentToTransform.put(AbstractAggregationOperation.AGGREGATIONS_ELEMENT_NAME, (DBObject) JsonUtils.unescapeKeys(aggrs)); } } else if ((context.getType() == RequestContext.TYPE.DB) && context.getMethod() == RequestContext.METHOD.GET) { // apply transformation on embedded schemas BasicDBObject _embedded = (BasicDBObject) contentToTransform.get("_embedded"); if (_embedded == null) { // nothing to do return; } BasicDBList colls = (BasicDBList) _embedded.get("rh:coll"); if (colls == null) { // nothing to do return; } colls.stream().filter(coll -> { return coll instanceof BasicDBObject; }).forEach(_coll -> { BasicDBObject coll = (BasicDBObject) _coll; BasicDBList aggrs = getAggregationMetadata(coll); if (aggrs == null) { // nothing to do return; } coll.put(AbstractAggregationOperation.AGGREGATIONS_ELEMENT_NAME, (DBObject) JsonUtils.unescapeKeys(aggrs)); }); } }
From source file:org.restheart.handlers.bulk.BulkPostCollectionHandler.java
License:Open Source License
private boolean checkId(HttpServerExchange exchange, RequestContext context, BasicDBObject document) { if (document.get("_id") != null && document.get("_id") instanceof String && RequestContext.isReservedResourceDocument(context.getType(), (String) document.get("_id"))) { ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_FORBIDDEN, "id is reserved: " + document.get("_id")); return false; }/*from w w w .j av a 2 s . c om*/ if (document.containsField("_id")) { if (!(context.getDocIdType() == DOC_ID_TYPE.OID || context.getDocIdType() == DOC_ID_TYPE.STRING_OID)) { ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE, "_id in content body is mandatory for documents with id type " + context.getDocIdType().name()); return false; } } return true; }