Java Code Examples for com.mongodb.util.JSON#parse()

The following examples show how to use com.mongodb.util.JSON#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonTreeModelTest.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
@Test
    public void buildDBObjectFromTreeWithSubNodes() throws Exception {
        DBObject jsonObject = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithInnerNodes.json")));

//        Hack to convert _id fron string to ObjectId
        jsonObject.put("_id", new ObjectId(String.valueOf(jsonObject.get("_id"))));

        NoSqlTreeNode treeNode = (NoSqlTreeNode) JsonTreeModel.buildJsonTree(jsonObject);

//      Simulate updating from the treeNode
        NoSqlTreeNode innerDocNode = (NoSqlTreeNode) treeNode.getChildAt(4);
        NoSqlTreeNode soldOutNode = (NoSqlTreeNode) innerDocNode.getChildAt(2);
        soldOutNode.getDescriptor().setValue("false");

        DBObject dbObject = JsonTreeModel.buildDBObject(treeNode);

        assertEquals("{ \"_id\" : { \"$oid\" : \"50b8d63414f85401b9268b99\"} , \"label\" : \"toto\" , \"visible\" : false , \"image\" :  null  , \"innerdoc\" : { \"title\" : \"What?\" , \"numberOfPages\" : 52 , \"soldOut\" : false}}",
                dbObject.toString());
    }
 
Example 2
Source File: PrivateStorageRestController.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@PostMapping(path = "/{collectionName}")
@ApiOperation(value = "Create a data in collection", notes = NOTES)
@PreAuthorize("hasAuthority('ADD_PRIVATE_STORAGE')")
public Object create(
		@PathVariable("application") String applicationId,
        @PathVariable("collectionName") String collection,
        @ApiParam(name = "body", required = true)
		@RequestBody String collectionContent) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);

    ServiceResponse<PrivateStorage> response = null;
    try {
        response = privateStorageService.save(tenant, application, user.getParentUser(), collection, collectionContent);

        if (!response.isOk()) {
            throw new BadServiceResponseException( response, validationsCode);
        } else {
            return JSON.parse(response.getResult().getCollectionContent());
        }
    } catch (JsonProcessingException e) {
        throw new NotFoundResponseException(response);
    }

}
 
Example 3
Source File: ApplicationDocumentStoreRestController.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@GetMapping
@ApiOperation(
        value = "Get a application document by collection and key",
        response = RestResponse.class
)
@PreAuthorize("hasAuthority('SHOW_APPLICATION')")
public Object read(
		@PathVariable("application") String applicationId,
		@PathVariable("collection") String collection,
		@PathVariable("key") String key) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);

    ServiceResponse<ApplicationDocumentStore> deviceResponse = applicationDocumentStoreService.findUniqueByTenantApplication(tenant, application, collection, key);

    if (!deviceResponse.isOk()) {
        throw new NotFoundResponseException(deviceResponse);
    } else {
        return JSON.parse(deviceResponse.getResult().getJson());
    }

}
 
Example 4
Source File: ApplicationDocumentStoreRestController.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@PostMapping
@ApiOperation(value = "Create a application document")
@PreAuthorize("hasAuthority('ADD_APPLICATION')")
public Object create(
		@PathVariable("application") String applicationId,
        @PathVariable("collection") String collection,
        @PathVariable("key") String key,
        @ApiParam(name = "body", required = true)
		@RequestBody String jsonCustomData) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);

    ServiceResponse<ApplicationDocumentStore> deviceResponse = applicationDocumentStoreService.save(tenant, application, collection, key, jsonCustomData);

    if (!deviceResponse.isOk()) {
        throw new BadServiceResponseException( deviceResponse, validationsCode);
    } else {
        return JSON.parse(deviceResponse.getResult().getJson());
    }

}
 
Example 5
Source File: DeviceCustomDataRestController.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@PostMapping
@ApiOperation(value = "Create a device custom data")
@PreAuthorize("hasAuthority('ADD_DEVICE')")
public Object create(
		@PathVariable("application") String applicationId,
		@PathVariable("deviceGuid") String deviceGuid,
        @ApiParam(name = "body", required = true)
		@RequestBody String jsonCustomData) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);
    Device device = getDevice(tenant, application, deviceGuid);

    ServiceResponse<DeviceCustomData> deviceResponse = deviceCustomDataService.save(tenant, application, device, jsonCustomData);

    if (!deviceResponse.isOk()) {
        throw new BadServiceResponseException( deviceResponse, validationsCode);
    } else {
        return JSON.parse(deviceResponse.getResult().getJson());
    }

}
 
Example 6
Source File: DeviceConfigVO.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public DeviceConfigVO(DeviceConfig deviceConfig) {
    this.deviceModelGuid = deviceConfig.getDeviceModelGuid();
    this.deviceModel  = deviceConfig.getDeviceModel();
    this.locationGuid = deviceConfig.getLocationGuid();
    this.locationName = deviceConfig.getLocationName();
    this.json = JSON.parse(deviceConfig.getJson());
}
 
Example 7
Source File: ObjectUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Support Format String Double Float Integer Short Byte DBObject
 * 
 * Note: array is not supported
 * 
 * @param value
 * @param targetClass
 * @return
 */
public static final Object parseStringToObject(String value, String escapeValue, Class<?> targetClass) {
	logger.debug("targetClass:{}, value:{}", targetClass, value);
	try {
		if (String.class.isAssignableFrom(targetClass)) {
			return value;
		} else if (targetClass == Boolean.class) {
			return Boolean.parseBoolean(value);
		} else if (Double.class.isAssignableFrom(targetClass)) {
			return Double.parseDouble(value);
		} else if (Float.class.isAssignableFrom(targetClass)) {
			return Float.parseFloat(value);
		} else if (Integer.class.isAssignableFrom(targetClass)) {
			return Integer.parseInt(value);
		} else if (Short.class.isAssignableFrom(targetClass)) {
			return Short.parseShort(value);
		} else if (Byte.class.isAssignableFrom(targetClass)) {
			return Byte.parseByte(value);
		} else if (DBObject.class.isAssignableFrom(targetClass)) {
			return JSON.parse(escapeValue);
		} else {
			return value;
		}
	} catch (NumberFormatException e) {
		logger.warn("Failed to convert '{}' to target. Exception", e);
		return value;
	}
}
 
Example 8
Source File: ApplicationInitializer.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Load the JSON template and perform string substitution on the ${...} tokens
 * @param is
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
Map<String, Object> loadJsonFile(InputStream is, Properties sliProps) throws IOException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer);
    String template = writer.toString();
    PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}"); 
    template = helper.replacePlaceholders(template, sliProps);
    return (Map<String, Object>) JSON.parse(template);
}
 
Example 9
Source File: MongoDbGridFSIO.java    From beam with Apache License 2.0 5 votes vote down vote up
private DBCursor createCursor(GridFS gridfs) {
  if (spec.filter() != null) {
    DBObject query = (DBObject) JSON.parse(spec.filter());
    return gridfs.getFileList(query);
  }
  return gridfs.getFileList();
}
 
Example 10
Source File: DeviceCustomDataServiceImpl.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
private boolean isValidJson(String json) {

        if (StringUtils.isBlank(json)) {
            return false;
        } else {
            try {
                JSON.parse(json);
            } catch (JSONParseException e) {
                return false;
            }
        }

        return true;

    }
 
Example 11
Source File: MongodbInputDiscoverFieldsImplTest.java    From pentaho-mongodb-plugin with Apache License 2.0 5 votes vote down vote up
@Test public void testArraysInArrays() throws MongoDbException, KettleException {
  setupPerform();

  DBObject doc = (DBObject) JSON.parse(
      "{ top : [ { parentField1 :  "
          + "[ 'nested1', 'nested2']   },"
          + " {parentField2 : [ 'nested3' ] } ] }" );
  when( cursor.next() ).thenReturn( doc );
  List<MongoField> fields =
      discoverFields
          .discoverFields( new MongoProperties.Builder(), "mydb", "mycollection", "", "", false, NUM_DOCS_TO_SAMPLE,
              inputMeta );
  validateFields( fields, "parentField1[0]", "top[0:0].parentField1.0", "stringVal", "parentField1[1]",
      "top[0:0].parentField1.1", "stringVal", "parentField2[0]", "top[1:1].parentField2.0", "stringVal" );
}
 
Example 12
Source File: MongoFieldTest.java    From pentaho-mongodb-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertArrayIndicesToKettleValue() throws KettleException {
  BasicDBObject dbObj = (BasicDBObject) JSON.parse( "{ parent : { fieldName : ['valA', 'valB'] } } " );

  initField( "fieldName", "$.parent.fieldName[0]", "String" );
  assertThat( field.convertToKettleValue( dbObj ), equalTo( (Object) "valA" ) );
  initField( "fieldName", "$.parent.fieldName[1]", "String" );
  assertThat( field.convertToKettleValue( dbObj ), equalTo( (Object) "valB" ) );
}
 
Example 13
Source File: JSONParam.java    From hvdf with Apache License 2.0 5 votes vote down vote up
public JSONParam(String json){
    try {
    	dbObject = (DBObject) JSON.parse(json);
    }
    catch (Exception ex) {
        throw ServiceException.wrap(ex, FrameworkError.CANNOT_PARSE_JSON).
        	set("json", json);
    }
}
 
Example 14
Source File: MongoQueryOptions.java    From nosql4idea with Apache License 2.0 4 votes vote down vote up
public void setFilter(String query) {
    if (!StringUtils.isBlank(query)) {
        filter = (DBObject) JSON.parse(query);
    }
}
 
Example 15
Source File: PutMongo.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final ComponentLog logger = getLogger();

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String mode = context.getProperty(MODE).getValue();
    final String updateMode = context.getProperty(UPDATE_MODE).getValue();
    final WriteConcern writeConcern = getWriteConcern(context);

    try {
        final MongoCollection<Document> collection = getCollection(context, flowFile).withWriteConcern(writeConcern);
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, in -> StreamUtils.fillBuffer(in, content, true));

        // parse
        final Object doc = (mode.equals(MODE_INSERT) || (mode.equals(MODE_UPDATE) && updateMode.equals(UPDATE_WITH_DOC.getValue())))
                ? Document.parse(new String(content, charset)) : JSON.parse(new String(content, charset));

        if (MODE_INSERT.equalsIgnoreCase(mode)) {
            collection.insertOne((Document)doc);
            logger.info("inserted {} into MongoDB", new Object[] { flowFile });
        } else {
            // update
            final boolean upsert = context.getProperty(UPSERT).asBoolean();
            final String updateKey = context.getProperty(UPDATE_QUERY_KEY).evaluateAttributeExpressions(flowFile).getValue();
            final String filterQuery = context.getProperty(UPDATE_QUERY).evaluateAttributeExpressions(flowFile).getValue();
            final Document query;

            if (!StringUtils.isBlank(updateKey)) {
                query = parseUpdateKey(updateKey, (Map)doc);
                removeUpdateKeys(updateKey, (Map)doc);
            } else {
                query = Document.parse(filterQuery);
            }

            if (updateMode.equals(UPDATE_WITH_DOC.getValue())) {
                collection.replaceOne(query, (Document)doc, new UpdateOptions().upsert(upsert));
            } else {
                BasicDBObject update = (BasicDBObject)doc;
                update.remove(updateKey);
                collection.updateOne(query, update, new UpdateOptions().upsert(upsert));
            }
            logger.info("updated {} into MongoDB", new Object[] { flowFile });
        }

        session.getProvenanceReporter().send(flowFile, getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        logger.error("Failed to insert {} into MongoDB due to {}", new Object[] {flowFile, e}, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}
 
Example 16
Source File: MongodbInputDiscoverFieldsImpl.java    From pentaho-mongodb-plugin with Apache License 2.0 4 votes vote down vote up
public static List<DBObject> jsonPipelineToDBObjectList( String jsonPipeline ) throws KettleException {
  List<DBObject> pipeline = new ArrayList<DBObject>();
  StringBuilder b = new StringBuilder( jsonPipeline.trim() );

  // extract the parts of the pipeline
  int bracketCount = -1;
  List<String> parts = new ArrayList<String>();
  int i = 0;
  while ( i < b.length() ) {
    if ( b.charAt( i ) == '{' ) {
      if ( bracketCount == -1 ) {
        // trim anything off before this point
        b.delete( 0, i );
        bracketCount = 0;
        i = 0;
      }
      bracketCount++;
    }
    if ( b.charAt( i ) == '}' ) {
      bracketCount--;
    }
    if ( bracketCount == 0 ) {
      String part = b.substring( 0, i + 1 );
      parts.add( part );
      bracketCount = -1;

      if ( i == b.length() - 1 ) {
        break;
      }
      b.delete( 0, i + 1 );
      i = 0;
    }

    i++;
  }

  for ( String p : parts ) {
    if ( !Const.isEmpty( p ) ) {
      DBObject o = (DBObject) JSON.parse( p );
      pipeline.add( o );
    }
  }

  if ( pipeline.size() == 0 ) {
    throw new KettleException( BaseMessages.getString( PKG,
      "MongoNoAuthWrapper.ErrorMessage.UnableToParsePipelineOperators" ) ); //$NON-NLS-1$
  }

  return pipeline;
}
 
Example 17
Source File: MongoEditionPanelTest.java    From nosql4idea with Apache License 2.0 4 votes vote down vote up
private DBObject buildDocument(String jsonFile) throws IOException {
    DBObject mongoDocument = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream(jsonFile)));
    mongoDocument.put("_id", new ObjectId(String.valueOf(mongoDocument.get("_id"))));
    return mongoDocument;
}
 
Example 18
Source File: MongoQueryOptions.java    From nosql4idea with Apache License 2.0 4 votes vote down vote up
public void setSort(String query) {
    if (!StringUtils.isBlank(query)) {
        sort = (DBObject) JSON.parse(query);
    }
}
 
Example 19
Source File: MongoDBUtils.java    From bdt with Apache License 2.0 3 votes vote down vote up
/**
 * Insert document in a MongoDB Collection.
 *
 * @param collection
 * @param document
 */
public void insertDocIntoMongoDBCollection(String collection, String document) {

    DBObject dbObject = (DBObject) JSON.parse(document);
    this.dataBase.getCollection(collection).insert(dbObject);

}
 
Example 20
Source File: MongoDBQueryExecutor.java    From flair-engine with Apache License 2.0 2 votes vote down vote up
@Override
public void execute(Query query, Writer writer) {

    DB db;
    try (MongoClient mongo = new MongoClient(connection.getDetails().getServerIp(), connection.getDetails().getServerPort())) {

        db = mongo.getDB(connection.getDetails().getDatabaseName());

        Jongo jongo = new Jongo(db);

        String q = query.getQuery();

        String jquery = q.substring(q.indexOf("["), q.lastIndexOf("]") + 1);

        org.jongo.MongoCollection collection = jongo.getCollection(q.substring(0, q.indexOf(".")));


        Object obj1 = JSON.parse(jquery);
        Object res = new Object();

        ObjectMapper mapper = new ObjectMapper();

        if (obj1 instanceof List) {

            List<Object> queryList = (List<Object>) obj1;

            try {
                if (queryList.size() == 2) {
                    res = collection.aggregate(JSON.serialize(queryList.get(0))).and(JSON.serialize(queryList.get(1))).as(Object.class);
                } else if (queryList.size() == 1) {
                    res = collection.aggregate(JSON.serialize(queryList.get(0))).as(Object.class);
                }
                String result = mapper.writeValueAsString(res);
                writer.write(result);
            } catch (IOException e) {
                log.error("Error running collection query", e);
            }
        }

    }

}