Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject append.

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

From source file:io.liveoak.mongo.MongoCollectionResource.java

License:Open Source License

@Override
public Collection<Resource> members(RequestContext ctx) throws Exception {

    LinkedList<Resource> members = new LinkedList<>();

    DBObject returnFields = new BasicDBObject();
    if (ctx.returnFields() != null && !ctx.returnFields().child(LiveOak.MEMBERS).isEmpty()) {
        ReturnFields membersReturnFields = ctx.returnFields().child(LiveOak.MEMBERS);
        if (!membersReturnFields.isAll()) {
            membersReturnFields.forEach((fieldName) -> {
                returnFields.put(fieldName, true);
            });/*from   w  w  w. j  a v a  2  s .com*/
        }
    }

    DBCursor dbCursor = dbCollection.find(queryObject, returnFields);

    ResourceParams resourceParams = ctx.resourceParams();
    if (resourceParams != null && resourceParams.contains("hint")) {
        String hint = resourceParams.value("hint");
        if (hint.startsWith("{")) {
            try {
                DBObject hintObject = (DBObject) JSON.parse(hint);
                dbCursor.hint(hintObject);
            } catch (Exception e) {
                throw new NotAcceptableException(uri().toString(),
                        "Invalid JSON format for the 'hint' parameter", e);
            }
        } else {
            dbCursor.hint(hint);
        }
    }

    if (explainQuery) {
        members.add(new MongoEmbeddedObjectResource(this, dbCursor.explain()));
    } else {
        Sorting sorting = ctx.sorting();
        if (sorting != null) {
            BasicDBObject sortingObject = new BasicDBObject();
            for (Sorting.Spec spec : sorting) {
                sortingObject.append(spec.name(), spec.ascending() ? 1 : -1);
            }
            dbCursor = dbCursor.sort(sortingObject);
        }

        Pagination pagination = ctx.pagination();
        if (pagination != null) {
            dbCursor.limit(pagination.limit());
            dbCursor.skip(pagination.offset());
        }

        try {
            dbCursor.hasNext();
        } catch (Exception e) {
            throw new ResourceProcessingException(
                    "Exception encountered trying to fetch data from the Mongo Database", e);
        }

        dbCursor.forEach((dbObject) -> {
            members.add(new MongoBaseObjectResource(this, dbObject));
        });
    }

    return members;
}

From source file:io.liveoak.mongo.MongoResource.java

License:Open Source License

protected BasicDBObject createObject(ResourceState resourceState, boolean nested) throws Exception {
    BasicDBObject basicDBObject = new BasicDBObject();

    // if the state already has an id set, use it here. Otherwise one will be autocreated on insert
    String rid = resourceState.id();
    if (rid != null) {
        if (!nested) {
            basicDBObject.append(MONGO_ID_FIELD, getMongoID(rid));
        } else {// ww w. jav a 2 s  . com
            basicDBObject.append(LiveOak.ID, getMongoID(rid));
        }
    }

    Set<String> keys = resourceState.getPropertyNames();

    for (String key : keys) {
        if (key.equalsIgnoreCase("$dbref")) {
            DBRef dbRef = getDBRef((String) resourceState.getProperty("$dbref"));
            basicDBObject.append(key, dbRef);
        } else if (nested || !key.equals(LiveOak.ID)) { // don't append the ID field again
            Object value = resourceState.getProperty(key);
            if (value instanceof ResourceState) {
                Object dbrefObject = ((ResourceState) value).getProperty("$dbref");
                if (dbrefObject != null) {
                    String uri = (String) dbrefObject;
                    value = getDBRef(uri);
                } else {
                    value = createObject((ResourceState) value, true);
                }
            } else if (value instanceof Collection) {
                value = createObjectList((Collection) value);
            }
            basicDBObject.append(key, value);
        }
    }

    return basicDBObject;
}

From source file:it.csi.smartdata.odata.datadiscovery.MongoDbStore.java

public List<Map<String, Object>> getDatasetFields(Long datasetKey) {

    List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
    DB db = mongoClient.getDB(mongoParams.get("MONGO_DB_META"));
    DBCollection coll = db.getCollection(mongoParams.get("MONGO_COLLECTION_DATASET"));

    BasicDBObject query = new BasicDBObject();
    query.append("idDataset", datasetKey);
    query.put("configData.current", 1);
    query.put("configData.subtype", new BasicDBObject("$ne", "binaryDataset"));
    DBCursor cursor = coll.find(query);//from  w  w  w .j  a  va2 s  . c  om

    while (cursor.hasNext()) {

        DBObject obj = cursor.next();

        DBObject dataset = (DBObject) obj.get("info");

        BasicDBList fieldsList = (BasicDBList) dataset.get("fields");

        for (int i = 0; i < fieldsList.size(); i++) {
            DBObject measure = (DBObject) fieldsList.get(i);

            String fieldName = (String) measure.get("fieldName");
            String fieldAlias = (String) measure.get("fieldAlias");
            String dataType = (String) measure.get("dataType");
            Integer sourceColumn = measure.get("sourceColumn") == null ? null
                    : ((Number) measure.get("sourceColumn")).intValue();
            Integer isKey = measure.get("isKey") == null ? null : ((Number) measure.get("isKey")).intValue();

            String measureUnit = (String) measure.get("measureUnit");

            Map<String, Object> cur = new HashMap<String, Object>();
            cur.put("fieldName", fieldName);
            cur.put("fieldAlias", fieldAlias);
            cur.put("dataType", dataType);
            cur.put("sourceColumn", sourceColumn);
            cur.put("isKey", isKey);
            cur.put("measureUnit", measureUnit);
            ret.add(cur);
        }
    }

    return ret;
}

From source file:it.csi.smartdata.odata.datadiscovery.MongoDbStore.java

private Map<String, Object> extractOdataPropertyFromMongo(DBCollection collapi, DBCollection collstream,
        DBObject datasetFound) {// ww  w.j a va2  s  . co  m
    Long id = datasetFound.get("idDataset") == null ? null
            : ((Number) datasetFound.get("idDataset")).longValue();
    Long datasetVersion = datasetFound.get("datasetVersion") == null ? null
            : ((Number) datasetFound.get("datasetVersion")).longValue();
    String datasetCode = (String) datasetFound.get("datasetCode");
    DBObject configData = (DBObject) datasetFound.get("configData");
    String tenant = configData.get("tenantCode").toString();
    String datasetStatus = (String) configData.get("datasetStatus");

    DBObject info = (DBObject) datasetFound.get("info");

    String license = (String) info.get("license");
    String dataDomain = (String) info.get("dataDomain");
    String codSubDomain = (String) info.get("codSubDomain");
    String description = (String) info.get("description");
    Double fps = info.get("fps") == null ? null : ((Number) info.get("fps")).doubleValue();

    String datasetName = (String) info.get("datasetName");
    String visibility = (String) info.get("visibility");
    String registrationDate = (String) info.get("registrationDate");

    String startIngestionDate = (String) info.get("startIngestionDate");
    String endIngestionDate = (String) info.get("endIngestionDate");
    String importFileType = (String) info.get("importFileType");

    String disclaimer = (String) info.get("disclaimer");
    String copyright = (String) info.get("copyright");

    String externalReference = (String) info.get("externalReference");
    // opendata
    SimpleDateFormat sdp = new SimpleDateFormat("dd/MM/yyyy");
    DBObject opendata = (DBObject) datasetFound.get("opendata");
    Boolean isOpendata = null;
    String author = null;
    String dataUpdateDate = null;
    String language = null;
    if (opendata != null) {
        isOpendata = (Boolean) opendata.get("isOpendata");
        author = (String) opendata.get("author");
        //dataUpdateDate = sdp.format(new Date((Long) opendata.get("dataUpdateDate")));
        if (null != opendata.get("dataUpdateDate"))
            dataUpdateDate = sdp.format(new Date(new Long("" + opendata.get("dataUpdateDate"))));

        language = (String) opendata.get("language");
    }

    StringBuilder fieldsBuilder = new StringBuilder();
    BasicDBList fieldsList = (BasicDBList) info.get("fields");

    String prefix = "";
    for (int i = 0; i < fieldsList.size(); i++) {
        DBObject measure = (DBObject) fieldsList.get(i);
        String mis = measure.get("measureUnit") == null ? null : measure.get("measureUnit").toString();
        if (mis != null) {
            fieldsBuilder.append(prefix);
            prefix = ",";
            fieldsBuilder.append(mis);
        }
    }
    String unitaMisura = fieldsBuilder.toString();
    StringBuilder tagsBuilder = new StringBuilder();
    BasicDBList tagsList = (BasicDBList) info.get("tags");

    String tags = null;
    prefix = "";
    if (tagsList != null) {
        for (int i = 0; i < tagsList.size(); i++) {
            DBObject tagObj = (DBObject) tagsList.get(i);
            tagsBuilder.append(prefix);
            prefix = ",";
            tagsBuilder.append(tagObj.get("tagCode").toString());
        }
        tags = tagsBuilder.toString();
    }

    String tenantsharing = null;
    /*
     * if you want to return all the tenants that a dataset is shared with
     * decomment this code ;
     */
    DBObject tenantssharingDB = (DBObject) info.get("tenantssharing");
    StringBuilder tenantsBuilder = new StringBuilder();
    if (tenantssharingDB != null) {
        BasicDBList tenantsList = (BasicDBList) tenantssharingDB.get("tenantsharing");
        prefix = "";
        if (tenantsList != null) {
            for (int i = 0; i < tenantsList.size(); i++) {
                DBObject tenantsObj = (DBObject) tenantsList.get(i);
                tenantsBuilder.append(prefix);
                prefix = ",";
                tenantsBuilder.append(tenantsObj.get("tenantCode").toString());
            }
            tenantsharing = tenantsBuilder.toString();
        }
    }

    Map<String, Object> cur = new HashMap<String, Object>();
    cur.put("idDataset", id);
    cur.put("tenantCode", tenant);
    cur.put("tenantsharing", tenantsharing);
    cur.put("dataDomain", dataDomain);
    cur.put("codSubDomain", codSubDomain);
    cur.put("license", license);
    cur.put("description", description);

    cur.put("fps", fps);

    cur.put("measureUnit", unitaMisura);
    cur.put("tags", tags);

    // BasicDBObject findapi = new BasicDBObject();
    // findapi.append("dataset.idDataset", id);
    // findapi.append("dataset.datasetVersion", datasetVersion);

    StringBuilder apibuilder = new StringBuilder();
    // DBObject config = (DBObject) parent.get("configData");
    apibuilder.append(mongoParams.get("MONGO_API_ADDRESS"));
    apibuilder.append("name=" + datasetCode);
    apibuilder.append("_odata");
    apibuilder.append("&version=1.0&provider=admin");

    cur.put("API", apibuilder.toString());

    BasicDBObject findstream = new BasicDBObject();
    findstream.append("configData.idDataset", id);
    findstream.append("configData.datasetVersion", datasetVersion);
    DBObject streams = collstream.findOne(findstream);

    StringBuilder streambuilder = new StringBuilder();

    if (streams != null) {
        DBObject nx = streams;

        DBObject config = (DBObject) nx.get("configData");
        DBObject streamsObj = (DBObject) nx.get("streams");
        DBObject stream = (DBObject) streamsObj.get("stream");

        streambuilder.append(mongoParams.get("MONGO_API_ADDRESS"));
        streambuilder.append("name=" + config.get("tenantCode"));
        streambuilder.append(".");
        streambuilder.append(stream.get("virtualEntityCode"));
        streambuilder.append("_");
        streambuilder.append(nx.get("streamCode"));
        streambuilder.append("_stream");
        streambuilder.append("&version=1.0&provider=admin");
    }

    String download = mongoParams.get("MONGO_DOWNLOAD_ADDRESS") + "/" + tenant + "/" + datasetCode + "/csv";

    cur.put("STREAM", streambuilder.toString());

    cur.put("download", download);

    cur.put("datasetName", datasetName);
    cur.put("visibility", visibility);
    cur.put("registrationDate", registrationDate);
    cur.put("startIngestionDate", startIngestionDate);
    cur.put("endIngestionDate", endIngestionDate);
    cur.put("importFileType", importFileType);
    cur.put("datasetStatus", datasetStatus);

    cur.put("datasetVersion", (datasetVersion == null) ? null : datasetVersion.toString());
    cur.put("datasetCode", datasetCode);
    cur.put("disclaimer", disclaimer);
    cur.put("copyright", copyright);

    cur.put("externalReference", externalReference);
    // opendata
    cur.put("isOpendata", isOpendata);
    cur.put("author", author);
    cur.put("dataUpdateDate", dataUpdateDate);
    cur.put("language", language);

    return cur;
}

From source file:it.wami.map.mongodeploy.OsmSaxHandler.java

License:Apache License

/**
 * //from  w w  w  . j a  v a 2  s. c om
 * @param atts the Attributes
 */
private void processMember(Attributes atts) {
    BasicDBObject[] members = (BasicDBObject[]) entry.get(Relation.MEMBERS);

    if (members == null) {
        members = new BasicDBObject[1];
    } else {
        BasicDBObject[] tmp = new BasicDBObject[members.length + 1];
        System.arraycopy(members, 0, tmp, 0, members.length);
        members = tmp;
    }

    BasicDBObject member = new BasicDBObject();

    for (int i = 0; i < atts.getLength(); i++) {
        String key = atts.getQName(i);
        String value = atts.getValue(i);
        member.append(key, value);
    }

    members[members.length - 1] = member;
    entry.append(Relation.MEMBERS, members);
}

From source file:it.wami.map.mongodeploy.OsmSaxHandler.java

License:Apache License

/**
 *
 * need refactoring/* w  w w  .  j  a va  2s .  com*/
 * @param atts
 */
private void processTag(Attributes atts) {

    BasicDBObject obj;
    String key = atts.getValue(Node.Tag.K);
    String value = atts.getValue(Node.Tag.V);

    if (StringUtils.contains(key, "capacity:")) { //key.contains("capacity:")){
        String[] tmp = StringUtils.split(key, ":");//key.split(":");
        BasicDBObject o = new BasicDBObject(tmp[1], value);
        obj = new BasicDBObject("capacity", o);
        //entry.append(key, obj);
        if (entry.containsField("tags")) {
            BasicDBObject tags = (BasicDBObject) entry.get("tags");
            if (tags.containsField("capacity") && tags.get("capacity") instanceof BasicDBObject) {

                ((BasicDBObject) tags.get("capacity")).append(tmp[1], value);

            } else {
                tags.append("capacity", o);
            }
        } else {
            entry.append(Node.TAGS, obj);
        }
    } else {
        key = StringUtils.replace(key, ".", "[dot]");
        //key = key.replace(".", "[dot]");
        obj = new BasicDBObject(key, value);
        if (entry.containsField(Node.TAGS)) {
            ((BasicDBObject) entry.get(Node.TAGS)).append(key, value);
        } else {
            entry.append(Node.TAGS, obj);
        }
    }

    // create the tag and save it inside the DB.
    saveTag(key, value);
}

From source file:it.wami.map.mongodeploy.OsmSaxHandler.java

License:Apache License

/**
 * Insert in the object the attributes of the XML element
 * /*from   ww w. j  a  v a 2 s  . c  om*/
 * @param entry the XML element
 * @param atts the tag attributes
 */
private void prepElement(BasicDBObject entry, Attributes atts) {

    entry.append("_id", Long.parseLong(atts.getValue("id")));

    if (atts.getValue("name") != null) {
        entry.append("type", atts.getValue("name"));
    } else {
        entry.append("type", NODE);
    }

    if (!options.isOmit_metadata()) {
        appendMetadata(atts);
    }
}

From source file:it.wami.map.mongodeploy.OsmToMongoDB.java

License:Apache License

/**
 * Create the index in the mongoDB.//from   w  ww  . j  a va  2s  .  c o m
 * @param nodes the collection
 */
private static void createNodesIndex(DBCollection nodes) {
    BasicDBObject compound = new BasicDBObject();
    compound.append("loc", "2dsphere");
    BasicDBObject text = getTextIndex();
    DBObject sparse = new BasicDBObject("sparse", true);
    BasicDBObject amenity = getAmenityIndex();
    nodes.createIndex(text, sparse);
    nodes.createIndex(compound);
    nodes.createIndex(amenity, sparse);

}

From source file:it.wami.map.mongodeploy.OsmToMongoDB.java

License:Apache License

/**
 * Create the index in the mongoDB./*  w w w .  j  a  v a  2 s .  c  o  m*/
 * @param ways the collection
 */
private static void createWaysIndex(DBCollection ways) {
    BasicDBObject compound = new BasicDBObject();
    compound.append("loc", "2dsphere");
    BasicDBObject text = getTextIndex();
    DBObject sparse = new BasicDBObject("sparse", true);
    BasicDBObject amenity = getAmenityIndex();
    ways.createIndex(amenity, sparse);
    ways.createIndex(text, sparse);
    ways.createIndex(compound);
}