Example usage for com.mongodb.util JSON serialize

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

Introduction

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

Prototype

public static String serialize(final Object object) 

Source Link

Document

Serializes an object into its JSON form.

This method delegates serialization to JSONSerializers.getLegacy

Usage

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Returns the objects in the collection that are within the specified distance (in meters) 
 * from the center point specified by the coordinates (in WGS84). The objects are sorted 
 * from nearest to farthest.//  ww  w .  j  av a2 s  . c om
 * @param collection - collection whose objects are counted
 * @param longitude - longitude in WGS84 coordinate reference system (CRS)
 * @param latitude - latitude in WGS84 coordinate reference system (CRS)
 * @param maxDistance - limits the results to those objects that fall within the specified 
 *        distance (in meters) from the center point
 * @return the objects that are within the specified distance from the center point, sorted
 *        from nearest to farthest
 */
public BasicDBList geoNear(final String collection, final double longitude, final double latitude,
        final double maxDistance) {
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final BasicDBObject query = new BasicDBObject("geoNear", collection)
            .append("near",
                    new BasicDBObject("type", "Point").append("coordinates",
                            new double[] { longitude, latitude }))
            .append("maxDistance", maxDistance).append("spherical", true).append("uniqueDocs", true)
            .append("num", Integer.MAX_VALUE);
    LOGGER.trace("geoNear query: " + JSON.serialize(query));
    final CommandResult cmdResult = db.command(query);
    checkState(cmdResult.ok(), "geoNear search failed");
    return (BasicDBList) cmdResult.get("results");
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

public List<BasicDBObject> geoWithin(final String locationField, final String collection,
        final Polygon polygon) {
    checkArgument(isNotBlank(locationField), "Uninitialized or invalid location field");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    checkArgument(polygon != null, "Uninitialized polygon");
    final List<BasicDBObject> list = newArrayList();
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    try {//from  w w  w.  j a  v  a2s.c  o  m
        final BasicDBObject query = new BasicDBObject(locationField, new BasicDBObject("$geoWithin",
                new BasicDBObject("$geometry", (DBObject) parse(JSON_MAPPER.writeValueAsString(polygon)))));
        LOGGER.trace("geoWithin query: " + JSON.serialize(query));
        final DBCursor cursor = dbcol.find(query);
        try {
            while (cursor.hasNext()) {
                list.add((BasicDBObject) cursor.next());
            }
        } finally {
            cursor.close();
        }
        return list;
    } catch (JsonProcessingException e) {
        throw new IllegalStateException("Failed to parse request parameters", e);
    }
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Wrapper method to {@link MongoDBConnector#mapReduce(String, String, String, DBObject)} that performs a search by proximity
 * to select the documents from the collection that will be used as input of the map function.
 * @param collection - collection whose objects are searched
 * @param field - geospatial field that defines the 2dsphere index for location data defined as GeoJSON points
 * @param mapFn - map function/*from w ww. j a v  a  2 s. c om*/
 * @param reduceFn - reduce function
 * @param longitude - longitude in WGS84 coordinate reference system (CRS)
 * @param latitude - latitude in WGS84 coordinate reference system (CRS)
 * @param maxDistance - limits the results to those objects that fall within the specified 
 *        distance (in meters) from the center point
 * @return a list of {@code BasicDBObject} which contains the results of this map reduce operation.
 */
public List<BasicDBObject> mapReduce(final String collection, final String field, final String mapFn,
        final String reduceFn, final double longitude, final double latitude, final double maxDistance) {
    final BasicDBObject query = new BasicDBObject(field,
            new BasicDBObject("$nearSphere",
                    new BasicDBObject("$geometry",
                            new BasicDBObject("type", "Point").append("coordinates",
                                    new double[] { longitude, latitude })).append("$maxDistance",
                                            maxDistance)));
    LOGGER.trace("geoNear query: " + JSON.serialize(query));
    return mapReduce(collection, mapFn, reduceFn, query);
}

From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.ResourceOwnerDAO.java

License:EUPL

public List<DatasetShare> listDatashares(final String namespace, final String filename, final int start,
        final int size, final @Nullable ImmutableMap<String, String> filter, final @Nullable Sorting sorting,
        final @Nullable MutableLong count) {
    final String namespace2 = trimToNull(namespace), filename2 = trimToNull(filename);
    checkArgument(isNotBlank(namespace2), "Uninitialized or invalid namespace");
    checkArgument(isNotBlank(filename2), "Uninitialized or invalid filename");
    // execute the query in the database (unsupported filter)
    final DatasetShare share = DatasetShare.builder().namespace(namespace2).filename(filename2)
            .accessType(EDIT_SHARE).build();
    final String rw = datasetSharePermission(share);
    share.setAccessType(VIEW_SHARE);//www.  j av a  2s .c om
    final String ro = datasetSharePermission(share);
    final BasicDBObject query = new BasicDBObject(PERMISSIONS_KEY,
            new BasicDBObject("$in", new String[] { rw, ro }));
    LOGGER.trace("listDatashares query: " + JSON.serialize(query));
    return transform(MONGODB_CONN.list(sortCriteria(), COLLECTION, start, size, query, null, count),
            new Function<BasicDBObject, DatasetShare>() {
                @Override
                public DatasetShare apply(final BasicDBObject obj) {
                    return parseResourceOwner(parseBasicDBObject(obj, true), namespace2, filename2,
                            new String[] { rw, ro });
                }
            });
}

From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.ResourceOwnerDAO.java

License:EUPL

public DatasetShare findDatashare(final String namespace, final String filename, final String subject) {
    final String namespace2 = trimToNull(namespace), filename2 = trimToNull(filename),
            subject2 = convertToValidResourceOwnerId(subject, true);
    checkArgument(isNotBlank(namespace2), "Uninitialized or invalid namespace");
    checkArgument(isNotBlank(filename2), "Uninitialized or invalid filename");
    checkArgument(isNotBlank(subject2), "Uninitialized or invalid subject");
    // execute the query in the database
    final DatasetShare share = DatasetShare.builder().namespace(namespace2).filename(filename2)
            .accessType(EDIT_SHARE).build();
    final String rw = datasetSharePermission(share);
    share.setAccessType(VIEW_SHARE);//w  w w .  j  a v a  2 s . co m
    final String ro = datasetSharePermission(share);
    final BasicDBObject query = new BasicDBObject(PERMISSIONS_KEY,
            new BasicDBObject("$in", new String[] { rw, ro })).append(PRIMARY_KEY, subject2);
    LOGGER.trace("findDatashare query: " + JSON.serialize(query));
    final ResourceOwner owner = parseBasicDBObjectOrNull(MONGODB_CONN.get(query, COLLECTION), true);
    return owner != null ? parseResourceOwner(owner, namespace2, filename2, new String[] { rw, ro }) : null;
}

From source file:extract.ExtractorImpl.java

License:Apache License

private String toJSON(Entity record) {
    return JSON.serialize(record.getBody());
}

From source file:ezbake.data.mongo.EzMongoHandler.java

License:Apache License

@Override
public List<String> getIndexInfo(String collectionName, EzSecurityToken security)
        throws TException, EzMongoBaseException {
    try {//  w  ww.jav a2s . c om
        HashMap<String, String> auditParamsMap = new HashMap<>();
        auditParamsMap.put("action", "getIndexInfo");
        auditParamsMap.put("collectionName", collectionName);
        auditLog(security, AuditEventType.FileObjectAccess, auditParamsMap);

        TokenUtils.validateSecurityToken(security, this.getConfigurationProperties());

        if (StringUtils.isEmpty(collectionName)) {
            throw new EzMongoBaseException("collectionName is required.");
        }

        final String finalCollectionName = getCollectionName(collectionName);

        final List<DBObject> indexList = db.getCollection(finalCollectionName).getIndexInfo();
        final List<String> results = new ArrayList<String>();

        for (final DBObject index : indexList) {
            results.add(JSON.serialize(index));
        }

        appLog.info("got index info results: {}", results);

        return results;
    } catch (final Exception e) {
        throw enrichException("getIndexInfo", e);
    }
}

From source file:ezbake.data.mongo.EzMongoHandler.java

License:Apache License

@Override
public List<String> textSearch(String collectionName, String searchText, EzSecurityToken security)
        throws TException, EzMongoBaseException {
    try {//from  w w  w .  j  a v  a  2 s.  c  o  m
        HashMap<String, String> auditParamsMap = new HashMap<>();
        auditParamsMap.put("action", "textSearch");
        auditParamsMap.put("collectionName", collectionName);
        auditParamsMap.put("searchText", searchText);
        auditLog(security, AuditEventType.FileObjectAccess, auditParamsMap);

        TokenUtils.validateSecurityToken(security, this.getConfigurationProperties());

        if (StringUtils.isEmpty(collectionName)) {
            throw new EzMongoBaseException("collectionName is required.");
        }

        final DBObject searchObj = new BasicDBObject("$search", searchText);
        final DBObject textObj = new BasicDBObject("$text", searchObj);
        final DBObject query = new BasicDBObject("$match", textObj);

        final String finalCollectionName = getCollectionName(collectionName);

        appLog.info("textSearch, finalCollectionName: {}, query: {}", finalCollectionName, query);

        final DBObject[] aggregationCommandsArray = mongoFindHelper.getFindAggregationCommandsArray(0, 0, null,
                null, security, READ_OPERATION);

        final AggregationOutput aggregationOutput = db.getCollection(finalCollectionName).aggregate(query,
                aggregationCommandsArray);

        final BasicDBList commandResults = (BasicDBList) aggregationOutput.getCommandResult().get("result");
        final List<String> results = new ArrayList<String>();

        if (commandResults != null) {
            for (final Object obj : commandResults) {
                final DBObject dbo = (DBObject) obj;

                results.add(JSON.serialize(dbo));
            }
        } else {
            final String message = "Text search command results were null - there probably is no text index.";
            appLog.error(message);
            throw new EzMongoBaseException(message);
        }

        appLog.info("in textSearch, results size: {}", results.size());

        return results;
    } catch (final Exception e) {
        throw enrichException("textSearch", e);
    }
}

From source file:ezbake.data.mongo.helper.MongoFindHelper.java

License:Apache License

/**
 * Adds results from MongoDB to a new List; if returnPlainObjectIdString is true, it converts the id from { _id: {
 * $oid: "..." } } to { _id: "..." }//from   w  ww  . ja v  a  2s . c om
 *
 * @param resultsList
 * @param returnPlainObjectIdString
 * @param useStrings Whether to return a list of Strings rather than list of DBObjects
 *
 * @return List of Strings or DBObjects
 */
public List addMongoResultsToList(List resultsList, boolean returnPlainObjectIdString, boolean useStrings) {
    final List results = new ArrayList();

    for (final Object res : resultsList) {
        if (res instanceof DBObject) {
            final DBObject result = (DBObject) res;
            if (returnPlainObjectIdString) {
                convertIdToPlainString(result);
            }
            if (useStrings) {
                final String json = JSON.serialize(result);
                results.add(json);
            } else {
                results.add(result);
            }
        } else {
            results.add(res);
        }
    }

    return results;
}

From source file:ezbake.training.DatasetServlet.java

License:Apache License

/**
 * Creates a text index on the "text" field if it doesn't exist
 *
 * @throws TException//from   w  w w  . j av a 2s.  c  o m
 */
private void createTextIndex(MongoDatasetClient client) throws TException {
    boolean hasTextIndex = false;
    String namespace = null;

    logger.info("getting index info..");

    List<String> indexList = client.getIndexInfo(COLLECTION_NAME);
    for (String index : indexList) {
        logger.info("we have an index: {}", index);

        DBObject indexObj = (DBObject) JSON.parse(index);
        String indexName = (String) indexObj.get("name");
        if (namespace == null) {
            namespace = (String) indexObj.get("ns");
        }

        if (indexName.equals(TEXT_FIELD_NAME + "_text")) {
            hasTextIndex = true;
        }
    }

    if (!hasTextIndex) {
        DBObject obj = new BasicDBObject();
        // we are putting a text index on the "text" field in the mongo
        // collection
        obj.put(TEXT_FIELD_NAME, "text");
        String jsonKeys = JSON.serialize(obj);

        logger.info("creating text index with jsonKeys: {}, COLLECTION_NAME: {}", jsonKeys, COLLECTION_NAME);

        client.createIndex(COLLECTION_NAME, jsonKeys, null);

        logger.info("DatasetServlet: created text index: {}", jsonKeys);
    } else {
        logger.info("DatasetServlet: we already have the text index.");
    }
}