Example usage for com.mongodb BasicDBObject get

List of usage examples for com.mongodb BasicDBObject get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

From source file:GeoHazardServices.Inst.java

License:Apache License

@POST
@Path("/data_insert")
@Produces(MediaType.APPLICATION_JSON)/*from   w  ww.  j a v  a2s. c  om*/
public String data_insert(@Context HttpServletRequest request, @FormParam("inst") String inst,
        @FormParam("secret") String secret, @FormParam("id") String id, @FormParam("name") String name,
        @FormParam("lon") Double lon, @FormParam("lat") Double lat, @FormParam("mag") Double mag,
        @FormParam("slip") Double slip, @FormParam("length") Double length, @FormParam("width") Double width,
        @FormParam("depth") Double depth, @FormParam("dip") Double dip, @FormParam("strike") Double strike,
        @FormParam("rake") Double rake, @FormParam("date") String dateStr,
        @FormParam("sea_area") String sea_area, @FormParam("root") String root,
        @FormParam("parent") String parent, @FormParam("comp") Integer comp, @FormParam("accel") Integer accel,
        @FormParam("gridres") Integer gridres, @FormParam("apikey") String apikey,
        @FormParam("algo") @DefaultValue("easywave") String algo) {

    /* Check for invalid parameter configurations. */
    if ((inst != null || secret != null) && apikey != null)
        return jsfailure("Don't mix 'apikey' and 'secret'.");

    if (mag != null && (slip != null || length != null || width != null))
        return jsfailure("Don't mix 'mag' with 'slip', 'length' and 'width'.");

    /* Support 'inst' and 'secret' for compatibility reasons. */
    if (inst != null && secret != null) {
        /* Obtain the 'apikey' and pretend a call to the new api. */
        DBObject query = new BasicDBObject("name", inst).append("secret", secret);
        DBObject tmp_inst = db.getCollection("institutions").findOne(query);
        if (tmp_inst == null)
            return jsdenied();
        apikey = (String) ((DBObject) tmp_inst.get("api")).get("key");
        if (apikey == null)
            return jsfailure("No 'apikey' set for this institution!");
    }

    /* Continue with the new API. */
    Object[] required = { apikey, id, name, dateStr };

    if (!checkParams(request, required))
        return jsfailure();

    DBObject db_user = auth_api(apikey, "user");
    DBObject db_inst = auth_api(apikey, "inst");

    /* check if we got a valid institution and the correct secret */
    ObjectId user_id;
    String user_name;
    User user;
    if (db_user != null) {
        user_id = (ObjectId) db_user.get("_id");
        user_name = (String) db_user.get("username");
        user = new User(db_user, getInst(db_user));
    } else if (db_inst != null) {
        user_id = (ObjectId) db_inst.get("_id");
        user_name = (String) db_inst.get("name");
        user = new Inst(db_inst);
    } else {
        return jsdenied();
    }

    System.out.println(user.name + " - " + user.inst);

    /* get Date object from date string */
    System.out.println(dateStr);
    Date date = parseIsoDate(dateStr);
    if (date == null)
        return jsfailure("Invalid date format.");

    System.out.println(id);

    /* get current timestamp */
    Date timestamp = new Date();

    /* create new sub object that stores the properties */
    BasicDBObject sub = new BasicDBObject();
    sub.put("date", date);
    sub.put("region", name);
    sub.put("latitude", lat);
    sub.put("longitude", lon);
    sub.put("magnitude", mag);
    sub.put("slip", slip);
    sub.put("length", length);
    sub.put("width", width);
    sub.put("depth", depth);
    sub.put("dip", dip);
    sub.put("strike", strike);
    sub.put("rake", rake);
    sub.put("sea_area", sea_area);

    if (accel == null)
        accel = 1;

    /* create new DB object that should be added to the eqs collection */
    BasicDBObject obj = new BasicDBObject();
    obj.put("id", id);
    obj.put("user", user_id);
    obj.put("timestamp", timestamp);
    obj.put("prop", sub);
    obj.put("root", root);
    obj.put("parent", parent);
    obj.put("accel", accel);
    //obj.put( "gridres", gridres );

    /* create a new event */
    BasicDBObject event = new BasicDBObject();
    event.put("user", user_id);
    event.put("timestamp", timestamp);
    event.put("event", "new");

    Long refineId = 0L;

    /* get earthquake collection */
    DBCollection coll = db.getCollection("eqs");
    /* search for given id */
    BasicDBObject inQuery = new BasicDBObject("id", id).append("user", user_id);
    DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("refineId", -1));

    BasicDBObject entry = null;

    /* if id is already used, make a refinement */
    if (cursor.hasNext()) {

        /* get properties of returned entry */
        entry = (BasicDBObject) cursor.next();

        /* update entry ID in database by appending deprecated field */
        BasicDBObject depr = new BasicDBObject("depr", true);
        coll.update(entry, new BasicDBObject("$set", depr));

        refineId = (Long) entry.get("refineId");

        if (refineId == null) {
            refineId = new Long(0);
        }

        refineId++;

        /* override parent and root attributes */
        root = entry.get("root") == null ? (String) entry.get("_id") : (String) entry.get("root");
        obj.put("root", root);
        obj.put("parent", entry.get("_id"));

        /* override event type */
        event.put("event", "update");
    }

    /* set refinement and compound Ids */
    final CompId compId = new CompId(user_name, id, refineId);
    obj.put("_id", compId.toString());
    obj.put("refineId", refineId);
    event.put("id", compId.toString());

    /* clean up query */
    cursor.close();

    /* insert object into 'eqs' collection */
    coll.insert(obj);

    System.out.println(obj);

    Object[] reqComp1 = { id, lon, lat, mag, depth, dip, strike, rake };
    Object[] reqComp2 = { id, lon, lat, slip, length, width, depth, dip, strike, rake };
    boolean simulate = comp != null && (checkParams(request, reqComp1) || checkParams(request, reqComp2));

    /* insert new event into 'events'-collection */
    db.getCollection("events").insert(event);

    System.out.println(simulate);

    if (simulate)
        //computeById( request, null, null, id, refineId, comp, accel, apikey );
        _computeById(user, compId.toString(), comp, accel, gridres, algo);
    else
        /* run request in a separate thread to avoid blocking */
        new Thread() {
            public void run() {
                sendPost(GlobalParameter.wsgi_url + "webguisrv/post_compute", "evtid=" + compId.toString());
            }
        }.start();

    return jssuccess(new BasicDBObject("refineId", refineId).append("evtid", compId.toString()));
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private String static_int(String id, Double lon, Double lat, Double zoom, Object uid) {

    DBCollection coll = db.getCollection("shared_links");
    BasicDBObject inQuery = new BasicDBObject("evtid", id);
    inQuery.put("lon", lon);
    inQuery.put("lat", lat);
    inQuery.put("zoom", zoom);
    inQuery.put("timestamp", new Date());
    inQuery.put("userid", uid);

    coll.insert(inQuery);/*from  www . j  a v a  2s  .c  om*/
    ObjectId objId = (ObjectId) inQuery.get("_id");

    return objId.toString();
}

From source file:gov.llnl.iscr.iris.Iris.java

License:Open Source License

/**
 * returns a <code>String</code> representation of a trigram, if it exist, within the given list of ngrams
 * @param ngrams a list of ngram objects
 * @return//from   w w  w  .j a va  2  s  . c o  m
 */
public String getTrigram(List<BasicDBObject> ngrams) {
    BasicDBObject trigram = ngrams.get(0);
    if ((Integer) trigram.get("size") == 3)
        return trigram.getString("ngram");
    else
        return "(No trigrams found)";
}

From source file:gov.llnl.iscr.iris.Iris.java

License:Open Source License

/**
 * returns a single formatted <code>String</code> representation of bigrams within the given list of ngrams
 * @param ngrams a list of ngram objects
 * @return/* w  w  w.j a v  a 2s .  c o  m*/
 */
public String getBigrams(List<BasicDBObject> ngrams) {
    StringBuffer bigrams = new StringBuffer();
    int count = 0;
    for (BasicDBObject bigram : ngrams) {
        if ((Integer) bigram.get("size") == 2) {
            if (count == 0) {
                bigrams.append(bigram.get("ngram"));
                ++count;
            } else if (count == 1) {
                bigrams.append(", " + bigram.get("ngram"));
                break;
            }
        } else
            continue;
    }

    return bigrams.toString();
}

From source file:gov.llnl.iscr.iris.Iris.java

License:Open Source License

/**
 * returns a single formatted <code>String</code> representation of unigrams within the given list of ngrams
 * @param ngrams// w ww  .j av a 2 s  .c om
 * @return
 */
public String getUnigrams(List<BasicDBObject> ngrams) {
    StringBuffer unigrams = new StringBuffer();
    int count = 0;
    for (BasicDBObject unigram : ngrams) {
        if (unigram.containsField("word")) {
            if (count == 0) {
                unigrams.append(unigram.get("word"));
                ++count;
            } else if (count < 4) {
                unigrams.append(", " + unigram.get("word"));
                ++count;
            } else
                break;
        }
    }
    return unigrams.toString();
}

From source file:gr.ntua.ivml.awareness.search.SearchServiceAccess.java

public BasicDBObject searchEuropeana(String originalTerm, String type, int startPage) throws Exception {
    String[] termsarray = originalTerm.split(" ");
    List terms = Arrays.asList(termsarray);
    URI uri = constructURI(terms, type, startPage - 1);
    httpGet = new HttpGet(uri);
    BasicDBObject response = new BasicDBObject();

    httpRes = httpClient.execute(httpGet);
    httpEntity = httpRes.getEntity();/*from   www. jav a  2 s. co m*/
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    httpEntity.writeTo(out);
    String resp = new String(out.toByteArray(), "UTF-8");
    BasicDBObject obj = (BasicDBObject) JSON.parse(resp);
    response.put("itemsCount", obj.getString("itemsCount"));
    response.put("totalResults", obj.getString("totalResults"));
    response.put("term", originalTerm);
    response.put("type", type);
    response.put("pageNumber", startPage);
    @SuppressWarnings("unchecked")
    ArrayList<Object> items = (ArrayList<Object>) obj.get("items");
    if (items != null) {
        Iterator<Object> it = items.iterator();
        ArrayList<BasicDBObject> responseItems = new ArrayList<BasicDBObject>();
        while (it.hasNext()) {
            BasicDBObject tmp = (BasicDBObject) it.next();
            BasicDBObject re = new BasicDBObject();
            String recid = tmp.getString("id");

            re.put("europeanaid", recid);
            re.put("type", tmp.getString("type"));
            re.put("source", tmp.getString("guid"));
            BasicDBList titleslist = (BasicDBList) tmp.get("title");
            if (titleslist != null)
                re.put("title", StringUtils.join(titleslist, ','));

            BasicDBList providerslist = (BasicDBList) tmp.get("dataProvider");
            if (providerslist != null)
                re.put("dataProvider", providerslist.get(0));
            providerslist = (BasicDBList) tmp.get("provider");
            if (providerslist != null)
                re.put("provider", providerslist.get(0));

            BasicDBList creatorlist = (BasicDBList) tmp.get("dcCreator");
            if (creatorlist != null)
                re.put("dcCreator", creatorlist.get(0));

            BasicDBList languagelist = (BasicDBList) tmp.get("language");
            if (languagelist != null)
                re.put("language", languagelist.get(0));

            BasicDBList thumbslist = (BasicDBList) tmp.get("edmPreview");
            if (thumbslist != null)
                re.put("url", thumbslist.get(0));

            BasicDBList rightslist = (BasicDBList) tmp.get("rights");
            if (rightslist != null)
                re.put("license", rightslist.get(0));

            responseItems.add(re);

        }
        response.put("items", responseItems);
    }
    return response;
}

From source file:gr.ntua.ivml.awareness.search.SearchServiceAccess.java

public BasicDBObject searchEuropeanaRecord(String recid) throws Exception {
    URI uri = constructURIRecord(recid);
    httpGet = new HttpGet(uri);

    httpRes = httpClient.execute(httpGet);
    httpEntity = httpRes.getEntity();//from  w w w. jav  a 2  s .com
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    httpEntity.writeTo(out);
    String resprec = new String(out.toByteArray(), "UTF-8");
    BasicDBObject objrecord = (BasicDBObject) JSON.parse(resprec);

    BasicDBObject record = (BasicDBObject) objrecord.get("object");
    BasicDBObject re = new BasicDBObject();

    ArrayList<Object> items = (ArrayList<Object>) record.get("aggregations");
    Iterator<Object> it = items.iterator();
    while (it.hasNext()) {
        BasicDBObject tmp = (BasicDBObject) it.next();
        Object edmObject = tmp.get("edmObject");
        if (edmObject != null)
            re.put("europeana_image", edmObject.toString());

    }

    return re;

}

From source file:guardar.en.base.de.datos.DocumentosDB.java

public void makefn2(DBObject bson) {
    BasicDBObject b = (BasicDBObject) bson;
    this.id_documento = (int) b.get("documento");
    this.frecuencia = (int) b.get("frecuencia");
}

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

License:Open Source License

@Override
public void createMember(RequestContext ctx, ResourceState state, Responder responder) {
    BasicDBObject basicDBObject = null;
    try {// ww w  .  j a  v a2  s  .  c  om
        basicDBObject = (BasicDBObject) createObject(state);
        Object key = basicDBObject.get(MONGO_ID_FIELD);
        if (key != null) {
            if (getDBCollection().findOne(new BasicDBObject(MONGO_ID_FIELD, key)) != null) {
                responder.resourceAlreadyExists(key.toString());
                return;
            }
        }
        WriteResult wResult = getDBCollection().insert(basicDBObject);
    } catch (Exception e) {
        logger().error("", e);
    }

    DBObject newDBObject = getDBCollection()
            .findOne(new BasicDBObject(MONGO_ID_FIELD, basicDBObject.get(MONGO_ID_FIELD)));
    responder.resourceCreated(new MongoBaseObjectResource(this, newDBObject));
}

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

License:Apache License

/**
 *
 * need refactoring//from w  w  w.  j  a  va  2 s . c om
 * @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);
}