Example usage for com.mongodb.util JSON parse

List of usage examples for com.mongodb.util JSON parse

Introduction

In this page you can find the example usage for com.mongodb.util JSON parse.

Prototype

public static Object parse(final String jsonString) 

Source Link

Document

Parses a JSON string and returns a corresponding Java object.

Usage

From source file:com.streamreduce.core.dao.GenericCollectionDAO.java

License:Apache License

public BasicDBObject createCollectionEntry(DAODatasourceType datasourceType, String collectionName,
        String payloadAsJson) {/*w  ww  . java2 s .  c o m*/
    return createCollectionEntry(datasourceType, collectionName, (BasicDBObject) JSON.parse(payloadAsJson));
}

From source file:com.streamreduce.core.dao.GenericCollectionDAO.java

License:Apache License

public BasicDBObject updateCollectionEntry(DAODatasourceType datasourceType, String collectionName, ObjectId id,
        String json) throws CollectionObjectNotFoundException {
    DB db = getDatabase(datasourceType);
    DBCollection collection = db.getCollection(collectionName);
    BasicDBObject newPayloadObject = (BasicDBObject) JSON.parse(json);
    BasicDBObject oldPayloadObject = (BasicDBObject) collection.findOne(new BasicDBObject("_id", id));

    if (oldPayloadObject == null) {
        throw new CollectionObjectNotFoundException(datasourceType, collectionName, id);
    }//from ww  w . j  ava  2s  .c  o m

    newPayloadObject.put("_id", id);

    collection.save(newPayloadObject);

    return newPayloadObject;
}

From source file:com.streamreduce.core.service.EventServiceImpl.java

License:Apache License

/**
 * {@inheritDoc}//from w w  w  .j av a  2s .c o  m
 */
@Override
public <T extends ObjectWithId> Event createEvent(EventId eventId, T target,
        Map<String, Object> extraMetadata) {
    Account account = null;
    User user = null;

    try {
        user = securityService.getCurrentUser();
        account = user.getAccount();
    } catch (AuthenticationException ae) {
        // We will not persist any READ_* events when a user is not logged in
        if (eventId == EventId.READ) {
            logger.debug("Anonymous read events are not persisted (" + target + "): " + eventId);
            return null;
        }
    } catch (UnavailableSecurityManagerException e) {
        logger.warn("Unable to derive user from SecurityService.  A User will be derived from the target ("
                + target + ") if possible.  If not, no event will be persisted", e);
    } catch (Exception nfi) {
        logger.warn("Unknown exception type in EventService", nfi);
    }

    if (extraMetadata == null) {
        extraMetadata = new HashMap<>();
    }

    // TODO: Figure out a way to make these automatically-generated metadata keys constants somewhere

    // Extend the context with T information
    if (target != null) {
        // Fill out ObjectWithId information
        extraMetadata.put("targetId", target.getId());
        extraMetadata.put("targetVersion", target.getVersion());
        // Fill out type (camel casing of the object type)
        extraMetadata.put("targetType", target.getClass().getSimpleName());

        // Fill out the SobaObject information
        if (target instanceof SobaObject) {
            SobaObject tSobaObject = (SobaObject) target;

            // Attempt to gather the user/account from the target of the event when there is no user logged in.
            // We can only do this for subclasses of SobaObject because the other two objects that create events
            // (Account/User) can only provide one piece of the puzzle.
            if (user == null) {
                user = tSobaObject.getUser();
                account = tSobaObject.getAccount();
            }

            extraMetadata.put("targetVisibility", tSobaObject.getVisibility());
            extraMetadata.put("targetAlias", tSobaObject.getAlias());
            extraMetadata.put("targetHashtags", tSobaObject.getHashtags());
        }

        // Fill in specific object information
        if (target instanceof Account) {
            Account tAccount = (Account) target;
            extraMetadata.put("targetFuid", tAccount.getFuid());
            extraMetadata.put("targetName", tAccount.getName());

        } else if (target instanceof InventoryItem) {
            InventoryItem inventoryItem = (InventoryItem) target;
            Connection connection = inventoryItem.getConnection();
            ConnectionProvider tConnectionProvider = connectionProviderFactory
                    .connectionProviderFromId(connection.getProviderId());

            extraMetadata.put("targetExternalId", inventoryItem.getExternalId());
            extraMetadata.put("targetExternalType", inventoryItem.getType());

            extraMetadata.put("targetConnectionId", connection.getId());
            extraMetadata.put("targetConnectionAlias", connection.getAlias());
            extraMetadata.put("targetConnectionHashtags", connection.getHashtags());
            extraMetadata.put("targetConnectionVersion", connection.getVersion());

            extraMetadata.put("targetProviderId", tConnectionProvider.getId());
            extraMetadata.put("targetProviderDisplayName", tConnectionProvider.getDisplayName());
            extraMetadata.put("targetProviderType", tConnectionProvider.getType());

            // Fill in the extra metadata stored in the nodeMetadata
            extraMetadata.putAll(getMetadataFromInventoryItem(inventoryItem));
        } else if (target instanceof Connection) {
            Connection tConnection = (Connection) target;
            ConnectionProvider tConnectionProvider = connectionProviderFactory
                    .connectionProviderFromId(tConnection.getProviderId());

            extraMetadata.put("targetProviderId", tConnectionProvider.getId());
            extraMetadata.put("targetProviderDisplayName", tConnectionProvider.getDisplayName());
            extraMetadata.put("targetProviderType", tConnectionProvider.getType());

        } else if (target instanceof User) {
            User tUser = (User) target;

            extraMetadata.put("targetFuid", tUser.getFuid());
            extraMetadata.put("targetFullname", tUser.getFullname());
            extraMetadata.put("targetUsername", tUser.getUsername());

        } else if (target instanceof SobaMessage) {
            // This is actually already handled in MessageServiceImpl.  This was just put here to help keep track
            // of the different types of objects we're supporting in case we want to do more later.
        }

        // If there is no user/account set and the event is not an Account/User/SobaMessage event, quick return.
        // Otherwise, set the user and/or account based on circumstances unique to each EventId.
        if (user == null) {
            if (!(target instanceof Account) && !(target instanceof User) && !(target instanceof SobaMessage)) {
                logger.debug("Anonymous SobaObject events are not persisted (" + target + "): " + eventId);
                return null;
            } else {
                switch (eventId) {
                case CREATE:
                    if (target instanceof Account) {
                        account = (Account) target;
                        user = null;
                    } else if (target instanceof User) {
                        account = user.getAccount();
                        user = null; // Nullify because this is a system event
                    } else if (target instanceof SobaMessage) {
                        // If this is a logged in user, no need to try and figure out the user/account
                        if (user != null) {
                            break;
                        }

                        ObjectId originalTargetId = extraMetadata.get("messageEventTargetId") != null
                                ? (ObjectId) extraMetadata.get("messageEventTargetId")
                                : null;
                        Event previousEvent = getLastEventForTarget(originalTargetId);

                        // Try to get the user
                        ObjectId originalEventUserId = extraMetadata.get("messageEventUserId") != null
                                ? (ObjectId) extraMetadata.get("messageEventUserId")
                                : null;

                        if (originalEventUserId != null) {
                            try {
                                user = userService.getUserById(originalEventUserId);
                            } catch (UserNotFoundException unfe) {
                                if (previousEvent != null) {
                                    try {
                                        user = userService.getUserById(previousEvent.getUserId());
                                    } catch (UserNotFoundException unfe2) {
                                        // There is nothing we can do at this point.  Let's log so we can keep
                                        // track of these unrecoverable events
                                        logger.error("Unable to identify the sender of the SobaMessage "
                                                + "having an id of " + target.getId());
                                    }
                                }
                            }
                        }

                        // Try to get the account
                        ObjectId originalEventAccountId = extraMetadata.get("messageEventAccountId") != null
                                ? (ObjectId) extraMetadata.get("messageEventAccountId")
                                : null;

                        if (originalEventAccountId != null) {
                            try {
                                account = userService.getAccount(originalEventAccountId);
                            } catch (AccountNotFoundException anfe) {
                                if (previousEvent != null) {
                                    try {
                                        account = userService.getAccount(previousEvent.getAccountId());
                                    } catch (AccountNotFoundException anfe2) {
                                        // There is nothing we can do at this point.  Let's log so we can
                                        // keep track of these unrecoverable events
                                        logger.error("Unable to identify the sender of the SobaMessage "
                                                + "having an id of " + target.getId());
                                    }
                                }
                            }
                        }
                    }
                    break;

                case CREATE_USER_REQUEST:
                    account = null; // Nullify so this doesn't get associated with the admin user's account
                    break;

                case USER_PASSWORD_RESET_REQUEST:
                    user = (User) target;
                    account = user.getAccount();
                    break;

                case READ:
                case UPDATE:
                case DELETE:
                case DELETE_USER_INVITE_REQUEST:
                case CREATE_USER_INVITE_REQUEST:
                case USER_MESSAGE:
                    if (eventId == EventId.DELETE && target instanceof Account) {
                        account = (Account) target;
                    } else {
                        // Both account and user should be set so if they aren't, quick return as these must be
                        // system events
                        logger.warn("Unexpected anonymous Account/User/SobaMessage event not persisted ("
                                + target + "): " + eventId);
                        return null;
                    }
                }
            }
        }
    }

    // Extend the context with User information
    if (user != null) {
        extraMetadata.put("sourceAlias", user.getAlias());
        extraMetadata.put("sourceFuid", user.getFuid());
        extraMetadata.put("sourceFullname", user.getFullname());
        extraMetadata.put("sourceUsername", user.getUsername());
        extraMetadata.put("sourceVersion", user.getVersion());
    }

    // Extend the context with Account information
    if (account != null) {
        extraMetadata.put("accountFuid", account.getFuid());
        extraMetadata.put("accountName", account.getName());
        extraMetadata.put("accountVersion", account.getVersion());
    }

    // Convert JSONObject entries to BasicDBObject to avoid MongoDB serialization issues
    for (Map.Entry<String, Object> metadataEntry : extraMetadata.entrySet()) {
        String key = metadataEntry.getKey();
        Object rawValue = metadataEntry.getValue();

        if (rawValue instanceof JSONObject) {
            extraMetadata.put(key, JSON.parse(rawValue.toString()));
        }
    }

    return logAndSaveEvent(new Event.Builder().eventId(eventId)
            .accountId(account != null ? account.getId() : null).actorId(user != null ? user.getId() : null)
            .targetId(target != null ? target.getId() : null).context(extraMetadata).build());
}

From source file:com.tensorwrench.testng.mongo.MongoTestDriver.java

License:Apache License

/**
 * Reads JSON from the input stream to populate the database.
 * @param db//ww w  .  j av  a  2s  . c  om
 * @param in
 * @throws IOException
 */
private void importStream(DB db, InputStream in) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    String read = reader.readLine();
    while (read != null) {
        sb.append(read);
        read = reader.readLine();
    }

    BSONObject obj = (BSONObject) JSON.parse(sb.toString());
    for (String collection : obj.keySet()) {
        @SuppressWarnings("unchecked")
        List<DBObject> docs = (List<DBObject>) obj.get(collection);

        DBCollection col = db.getCollection(collection);
        for (DBObject o : docs) {
            col.save(o);
        }
    }
}

From source file:com.yahoo.ycsb.workloads.QueryMongoDbWorkload.java

License:Open Source License

public void init(Properties p) throws WorkloadException {
    System.out.println("Init MongoDb Queries");
    filters = new HashMap<String, DBObject>();

    double readproportion = Double
            .parseDouble(p.getProperty(READ_PROPORTION_PROPERTY, READ_PROPORTION_PROPERTY_DEFAULT));
    double scanproportion = Double
            .parseDouble(p.getProperty(SCAN_PROPORTION_PROPERTY, SCAN_PROPORTION_PROPERTY_DEFAULT));
    int minscanlength = Integer
            .parseInt(p.getProperty(MIN_SCAN_LENGTH_PROPERTY, MIN_SCAN_LENGTH_PROPERTY_DEFAULT));
    int maxscanlength = Integer
            .parseInt(p.getProperty(MAX_SCAN_LENGTH_PROPERTY, MAX_SCAN_LENGTH_PROPERTY_DEFAULT));
    String scanlengthdistrib = p.getProperty(SCAN_LENGTH_DISTRIBUTION_PROPERTY,
            SCAN_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT);
    debug = Boolean.parseBoolean(p.getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT));

    String[] queries = p.getProperty("queries").split(";");
    for (int i = 0; i < queries.length; i++) {
        filters.put(String.valueOf(i), (BasicDBObject) JSON.parse(queries[i]));
    }//from w  w w  .j av a  2s  .  co m

    operationchooser = new DiscreteGenerator();
    if (readproportion > 0) {
        operationchooser.addValue(readproportion, "READ");
    }

    if (scanproportion > 0) {
        operationchooser.addValue(scanproportion, "SCAN");
    }

    if (scanlengthdistrib.compareTo("uniform") == 0) {
        scanlength = new UniformIntegerGenerator(minscanlength, maxscanlength);
    } else if (scanlengthdistrib.compareTo("zipfian") == 0) {
        scanlength = new ZipfianGenerator(minscanlength, maxscanlength);
    } else {
        throw new WorkloadException("Distribution \"" + scanlengthdistrib + "\" not allowed for scan length");
    }

    printDateTime("Start: ");
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

/**
 * Helper for providing a JSON string as a value for a setting.
 * @param conf the Configuration/*w  w w.  j a  v  a2s.  c  om*/
 * @param key the key for the setting
 * @param value the JSON string value
 */
public static void setJSON(final Configuration conf, final String key, final String value) {
    try {
        final Object dbObj = JSON.parse(value);
        setDBObject(conf, key, (DBObject) dbObj);
    } catch (final Exception e) {
        LOG.error("Cannot parse JSON...", e);
        throw new IllegalArgumentException("Provided JSON String is not representable/parseable as a DBObject.",
                e);
    }
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

public static DBObject getDBObject(final Configuration conf, final String key) {
    try {/*from w  w  w . j a va  2s. c o  m*/
        final String json = conf.get(key);
        final DBObject obj = (DBObject) JSON.parse(json);
        if (obj == null) {
            return new BasicDBObject();
        } else {
            return obj;
        }
    } catch (final Exception e) {
        throw new IllegalArgumentException("Provided JSON String is not representable/parseable as a DBObject.",
                e);
    }
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

public static DBObject getInputSplitKey(final Configuration conf) {
    try {/*  w  w w .  ja va 2  s  .c om*/
        final String json = getInputSplitKeyPattern(conf);
        final DBObject obj = (DBObject) JSON.parse(json);
        if (obj == null) {
            return new BasicDBObject("_id", 1);
        } else {
            return obj;
        }
    } catch (final Exception e) {
        throw new IllegalArgumentException("Provided JSON String is not representable/parsable as a DBObject.",
                e);
    }
}

From source file:com.zuehlke.sbdfx.dataaccess.mongo.MongoCitiesDao.java

private DBObject createDbObject(final City city) {
    final Gson gson = new Gson();
    final String json = gson.toJson(city);
    final Object result = JSON.parse(json);
    return (DBObject) result;
}

From source file:data.repository.pragma.DataObjectController.java

License:Apache License

@RequestMapping(value = "/DO/upload", method = RequestMethod.POST)
@ResponseBody//from w  ww  .j av  a 2  s . c o m
public MessageResponse DOupload(@RequestParam(value = "data", required = true) MultipartFile file,
        @RequestParam(value = "metadata", required = true) String metadata) {
    try {
        // Create metadata DBObject from input
        DBObject metadataObject = (DBObject) JSON.parse(metadata);

        // Ingest multipart file into inputstream
        byte[] byteArr = file.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);
        String file_name = file.getOriginalFilename();
        String content_type = file.getContentType();
        // Connect to MongoDB and use GridFS to store metadata and data
        // Return created DO internal id in stagingDB
        String id = Staging_repository.addDO(inputStream, file_name, content_type, metadataObject);
        MessageResponse response = new MessageResponse(true, id);
        return response;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        MessageResponse response = new MessageResponse(false, null);
        return response;
    }
}