Example usage for com.mongodb DBObject put

List of usage examples for com.mongodb DBObject put

Introduction

In this page you can find the example usage for com.mongodb DBObject put.

Prototype

Object put(String key, Object v);

Source Link

Document

Sets a name/value pair in this object.

Usage

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * PUT a json file to the database//from   w ww .j a  va  2 s .c  om
 * @param collName the name of the collection
 * @param docID the docid of the resource 
 * @param json the json to put there
 * @return the server response
 */
@Override
public String putToDb(String collName, String docID, String json) throws AeseException {
    try {
        docIDCheck(collName, docID);
        DBObject doc = (DBObject) JSON.parse(json);
        doc.put(JSONKeys.DOCID, docID);
        connect();
        DBCollection coll = getCollectionFromName(collName);
        DBObject query = new BasicDBObject(JSONKeys.DOCID, docID);
        WriteResult result = coll.update(query, doc, true, false);
        //return removeFromDb( path );
        return result.toString();
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:cfel.service.PortalImportTask.java

License:Open Source License

private void importActivity(JSONObject activity, String portal_image_url) {
    // System.out.println(activity.toString());
    try {/*from ww  w .j  av  a2 s  .c o m*/
        JSONObject member = activity.getJSONObject("member");
        if (member.containsKey("id")) {
            String title = activity.getString("body").replace(activity.getString("image_large_url"), "").trim();
            DBObject photo = new BasicDBObject();
            photo.put("portal_image_url", portal_image_url);
            if (mPhotoCollection.count(photo) > 0) {
                System.err.println(portal_image_url + " already exists");
                return;
            } else {
                System.out.println("Inserting " + portal_image_url);
            }
            String imageSourceUrl = Config.PORTAL_URL.startsWith("http:")
                    ? portal_image_url.replace("https://", "http://")
                    : portal_image_url;
            BufferedImage[] images = ImageUtil.convertImage(new URL(imageSourceUrl));
            if (images == null) {
                System.err.println(portal_image_url + " corrupted");
                return;
            }
            saveThumbnailImages(photo, images, "/" + getFileId(portal_image_url) + ".png");
            photo.put("uploader_user_id", member.getString("id"));
            photo.put("title", title);
            Object exifObj = getExifData(portal_image_url);
            Date date = null;
            if (exifObj instanceof JSONObject) {
                JSONObject exif = (JSONObject) exifObj;
                if (exif.containsKey("date")) {
                    try {
                        date = FORMAT_DATE_ISO.parse(exif.getString("date"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (exif.containsKey("location")) {
                    photo.put("exif_location", exif.getJSONArray("location"));
                }
            }
            if (date == null && activity.containsKey("created_at")) {
                try {
                    date = FORMAT_DATE.parse(activity.getString("created_at"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (date != null) {
                photo.put("exif_date", date);

            }
            mPhotoCollection.insert(photo);
            // System.out.println(photo);
            // System.out.println();
        }
    } catch (JSONException | MalformedURLException e) {
        e.printStackTrace();
    }
}

From source file:cfel.service.PortalImportTask.java

License:Open Source License

private void saveThumbnailImages(DBObject photo, BufferedImage[] images, String suffix) {
    for (int i = 0; i < IMAGE_TYPES.length; i++) {
        String fileName = IMAGE_TYPES[i] + suffix;
        OutputStream os = mDS.getFileOutputStream(fileName, "image/png");
        try {/*from   w  w w.j  a v  a2 s .c o  m*/
            if (os != null) {
                ImageIO.write(images[i], "png", os);
                photo.put(IMAGE_TYPES[i] + "_image_url", FILE_URL + fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            images[i].flush();
        }
    }
}

From source file:cfel.servlet.ImportCsvServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from  ww  w.ja v  a  2 s.  c o m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DBCollection collection = mDS.getCollection("photo");
    if (collection == null) {
        response.sendError(404, "No photo collection");
        return;
    }
    InputStream is = null;
    try {
        is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine(); // Ignore header
        while ((line = br.readLine()) != null) {
            String[] values = getStrings(line);
            if (values.length == 2) {
                String portal_image_url = values[0];
                String class_id = values[1];
                System.out.println("url=" + portal_image_url + ", season=" + class_id);
                DBObject query = new BasicDBObject("portal_image_url", portal_image_url);
                DBObject photo = collection.findOne(query);
                if (photo == null) {
                    continue;
                }
                Object guessObj = photo.get("guess");
                if (guessObj instanceof List<?>) {
                    System.out.println(guessObj);
                    List<?> guess = (List<?>) guessObj;
                    Object lastGuess = guess.get(guess.size() - 1);
                    if (lastGuess instanceof DBObject
                            && class_id.equals(((DBObject) lastGuess).get("class_id"))) {
                        continue;
                    }
                }
                DBObject newGuess = new BasicDBObject();
                newGuess.put("updated", new Date());
                newGuess.put("class_id", class_id);
                DBObject update = new BasicDBObject("$push", new BasicDBObject("guess", newGuess));
                collection.update(photo, update, true, false);
            } else {
                System.err.println("Unknown data: " + line);
            }
        }

    } finally {
        if (is != null) {
            is.close();
        }
    }
    response.setStatus(200);
}

From source file:ch.agent.crnickl.mongodb.MongoDB.java

License:Apache License

private DBCollection createCollection(DB db, String name, String... keys) throws T2DBException {
    DBCollection coll = db.getCollection(name);
    if (keys.length > 0) {
        DBObject index = new BasicDBObject();
        DBObject options = new BasicDBObject();
        for (String key : keys) {
            index.put(key, 1);
        }//from w  w w.j  av  a  2  s .  c  om
        options.put("unique", 1);
        coll.ensureIndex(index, options);
    }
    return coll;
}

From source file:ch.agent.crnickl.mongodb.MongoDB.java

License:Apache License

private void createIndex(DBCollection coll, String... keys) throws T2DBException {
    if (keys.length > 0) {
        DBObject index = new BasicDBObject();
        for (String key : keys)
            index.put(key, 1);
        coll.ensureIndex(index);//  w  w w .jav a2 s.c  o m
    }
}

From source file:ch.agent.crnickl.mongodb.WriteMethodsForSchema.java

License:Apache License

/**
 * Find a chronicle referencing one of the schemas. 
 * This looks like a "reading" method but is used in the context of schema updating.
 * /*from  ww w.  j a  v a 2s  .  c  o  m*/
 * @param schema a schema
 * @return a surrogate or null
 * @throws T2DBException
 */
public Surrogate findChronicle(Schema schema) throws T2DBException {
    Surrogate result = null;
    try {
        Database db = schema.getDatabase();
        DBObject query = new BasicDBObject();
        query.put(MongoDatabase.FLD_CHRON_SCHEMA, getId(schema));
        DBObject obj = getMongoDB(db).getChronicles().findOne(query);
        if (obj != null)
            result = makeSurrogate(db, DBObjectType.CHRONICLE, getObjectId((BasicDBObject) obj));
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E30117);
    }
    return result;
}

From source file:ch.bfh.uniboard.persistence.mongodb.PersistenceService.java

License:GNU General Public License

@Override
public ResultContainer get(Query query) {
    try {/*from  w  ww .java2  s .  c  o m*/
        //Check Database connection
        if (!this.connectionManager.isConnected()) {
            Attributes gamma = new Attributes();
            gamma.add(Attributes.ERROR, new StringValue("Internal Server Error. Service not available"));
            logger.log(Level.WARNING, "Database error: unable to connect to database");
            return new ResultContainer(new ArrayList<Post>(), gamma);
        }

        //TODO Remove this block and its tests
        //check basic wellformedness of query
        if (query == null || query.getConstraints() == null || query.getConstraints().isEmpty()
                || query.getConstraints().contains(null)) {
            Attributes gamma = new Attributes();
            gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Incomplete query"));
            logger.log(Level.WARNING, "Syntax error: Incomplete query");
            return new ResultContainer(new ArrayList<Post>(), gamma);
        }

        List<DBObject> constraintsList = new ArrayList<>();

        //iterates over the constraints and constructs the corresponding query string
        for (Constraint c : query.getConstraints()) {

            //constructs the key
            String keyString = "";
            if (c.getIdentifier() instanceof MessageIdentifier) {
                //TODO constraint that wants to compare the raw byte[]
                keyString += "searchable-message";
            } else if (c.getIdentifier() instanceof AlphaIdentifier) {
                keyString += "alpha";
            } else if (c.getIdentifier() instanceof BetaIdentifier) {
                keyString += "beta";
            } else {
                Attributes gamma = new Attributes();
                gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown identifier"));
                logger.log(Level.WARNING, "Syntax error: Unknown identifier");
                return new ResultContainer(new ArrayList<Post>(), gamma);
            }

            //constructs the hierarchy of the keys
            for (String key : c.getIdentifier().getParts()) {
                keyString += "." + key;
            }

            //constructs the researched value string by checking the type of constraints and getting the searched values
            DBObject actualConstraint = new BasicDBObject();
            if (c instanceof Equal) {
                Equal op = (Equal) c;
                actualConstraint.put(keyString, op.getValue().getValue());
            } else if (c instanceof NotEqual) {
                NotEqual op = (NotEqual) c;
                actualConstraint.put(keyString, new BasicDBObject("$ne", op.getValue().getValue()));
            } else if (c instanceof In) {
                In op = (In) c;
                List<Object> values = new ArrayList<>();
                Class valueClass = op.getSet().get(0).getClass();
                for (Value v : op.getSet()) {
                    if (!(v.getClass().equals(valueClass))) {
                        Attributes gamma = new Attributes();
                        gamma.add(Attributes.REJECTED,
                                new StringValue("Syntax error: not same value type for IN constraint"));
                        logger.log(Level.WARNING, "Syntax error: not same value type for IN constraint");
                        return new ResultContainer(new ArrayList<Post>(), gamma);
                    }
                    values.add(v.getValue());
                }
                actualConstraint.put(keyString, new BasicDBObject("$in", values));
            } else if (c instanceof Between) {
                Between op = (Between) c;
                if (!(op.getStart().getClass().equals(op.getEnd().getClass()))) {
                    Attributes gamma = new Attributes();
                    gamma.add(Attributes.REJECTED,
                            new StringValue("Syntax error: not same value type for BETWEEN constraint"));
                    logger.log(Level.WARNING, "Syntax error: not same value type for BETWEEN constraint");
                    return new ResultContainer(new ArrayList<Post>(), gamma);
                }
                actualConstraint.put(keyString, new BasicDBObject("$gt", op.getStart().getValue()).append("$lt",
                        op.getEnd().getValue()));
            } else if (c instanceof Greater) {
                Greater op = (Greater) c;
                actualConstraint.put(keyString, new BasicDBObject("$gt", op.getValue().getValue()));
            } else if (c instanceof GreaterEqual) {
                GreaterEqual op = (GreaterEqual) c;
                actualConstraint.put(keyString, new BasicDBObject("$gte", op.getValue().getValue()));
            } else if (c instanceof Less) {
                Less op = (Less) c;
                actualConstraint.put(keyString, new BasicDBObject("$lt", op.getValue().getValue()));
            } else if (c instanceof LessEqual) {
                LessEqual op = (LessEqual) c;
                actualConstraint.put(keyString, new BasicDBObject("$lte", op.getValue().getValue()));
            } else {
                Attributes gamma = new Attributes();
                gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown type of constraint"));
                logger.log(Level.WARNING, "Syntax error: Unknown type of constraint");
                return new ResultContainer(new ArrayList<Post>(), gamma);
            }
            constraintsList.add(actualConstraint);
        }

        //combine the different constrainst in an AND query
        DBObject completeQuery = new BasicDBObject();
        completeQuery.put("$and", constraintsList);

        DBCursor cursor;

        if (query.getOrder().size() > 0) {

            //Create orderBy
            BasicDBObject orderBy = new BasicDBObject();

            for (Order order : query.getOrder()) {
                String identifier;
                if (order.getIdentifier() instanceof MessageIdentifier) {
                    identifier = "message";
                } else if (order.getIdentifier() instanceof AlphaIdentifier) {
                    identifier = "alpha";
                } else if (order.getIdentifier() instanceof BetaIdentifier) {
                    identifier = "beta";
                } else {
                    Attributes gamma = new Attributes();
                    gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown identifier"));
                    logger.log(Level.WARNING, "Syntax error: Unknown identifier");
                    return new ResultContainer(new ArrayList<Post>(), gamma);
                }
                for (String key : order.getIdentifier().getParts()) {
                    identifier += "." + key;
                }
                int ascDesc;
                if (order.isAscDesc()) {
                    ascDesc = 1;
                } else {
                    ascDesc = -1;
                }
                orderBy.append(identifier, ascDesc);
            }
            cursor = this.connectionManager.getCollection().find(completeQuery).sort(orderBy)
                    .limit(query.getLimit());
        } else {
            //apply query on database
            cursor = this.connectionManager.getCollection().find(completeQuery).limit(query.getLimit());
        }

        //creates the result container with the db result
        List<Post> list = new ArrayList<>();
        while (cursor.hasNext()) {
            DBObject object = cursor.next();
            //convert to PersistedPost
            list.add(PersistedPost.fromDBObject(object));
        }
        return new ResultContainer(list, new Attributes());
    } catch (Exception e) {
        Attributes gamma = new Attributes();
        gamma.add(Attributes.ERROR, new StringValue("General error: " + e.getMessage()));
        logger.log(Level.WARNING, "General Get error", e);
        return new ResultContainer(new ArrayList<Post>(), gamma);
    }
}

From source file:ch.windmobile.server.social.mongodb.ChatServiceImpl.java

License:Open Source License

@Override
public Message postMessage(String chatRoomId, String pseudo, String text, String emailHash) {
    String collectionName = computeCollectionName(chatRoomId);
    DBCollection col = getOrCreateCappedCollection(collectionName);

    DBObject chatItem = new BasicDBObject();
    Double id = (Double) db.eval(counter, chatRoomId);
    chatItem.put("_id", id.longValue());
    chatItem.put(MongoDBConstants.CHAT_PROP_TEXT, text);
    chatItem.put(MongoDBConstants.CHAT_PROP_USER, pseudo);
    DateTime date = new DateTime().toDateTimeISO();
    chatItem.put(MongoDBConstants.CHAT_PROP_TIME, date.toString());
    chatItem.put(MongoDBConstants.CHAT_PROP_EMAIL_HASH, emailHash);
    col.insert(chatItem);//from ww w  . ja  v  a 2 s. co  m

    Message message = new Message();
    message.setId(id.toString());
    message.setDate(date);
    message.setPseudo(pseudo);
    message.setText(text);
    message.setEmailHash(emailHash);

    return message;
}

From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java

License:Open Source License

@Override
public List<Favorite> getFavorites(String email) throws UserNotFound {
    if (email == null) {
        throw new IllegalArgumentException("Email cannot be null");
    }// w  w w  .  j a  va 2  s .  com
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by email
    DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email));
    if (userDb == null) {
        throw new UserNotFound("Unable to find user with email '" + email + "'");
    }

    DBObject favoritesDb = (DBObject) userDb.get(MongoDBConstants.USER_PROP_FAVORITES);
    if (favoritesDb == null) {
        favoritesDb = new BasicDBObject();

        userDb.put(MongoDBConstants.USER_PROP_FAVORITES, favoritesDb);
        col.save(userDb);
    }

    List<Favorite> returnValue = new ArrayList<Favorite>(favoritesDb.keySet().size());
    for (String stationId : favoritesDb.keySet()) {
        Favorite favorite = new Favorite();
        favorite.setStationId(stationId);
        DBObject favoriteItemsDb = (DBObject) favoritesDb.get(stationId);
        favorite.setLastMessageId(
                (Long) favoriteItemsDb.get(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID));
        returnValue.add(favorite);
    }
    return returnValue;
}