Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents, final InsertOptions insertOptions) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:models.datasource.SingletonDataSource.java

public static User insertIntoUsersCollection(User user) {
    // Get the collection (connection to our mongo database)
    DBCollection collection = connectDB("mongo.usersCollection");

    // Create the query
    BasicDBObject query = new BasicDBObject().append(Constants.USER_NAME, user.name)
            .append(Constants.USER_SURNAMES, user.surnames).append(Constants.USER_EMAIL, user.email)
            .append(Constants.USER_PASSWORD, Utils.encryptWithSHA1(user.password))
            .append(Constants.USER_EMAIL_VERIFICATION_KEY, user.emailVerificationKey)
            .append(Constants.USER_CONNECTION_TIMESTAMP, user.connectionTimestamp)
            .append(Constants.USER_RESTORE_PASSWORD_TOKEN, user.restorePasswordToken)
            .append(Constants.USER_RESTORE_PASSWORD_TIMESTAMP, user.restorePasswordTimestamp)
            .append(Constants.USER_REGISTRATION_DATE, user.registrationDate)
            .append(Constants.USER_BIRTH_DATE, user.birthDate)
            .append(Constants.USER_RESIDENCE_CITY, user.residenceCity)
            .append(Constants.USER_RESIDENCE_ADDRESS, user.residenceAddress)
            .append(Constants.USER_RESIDENCE_NUMBER, user.residenceNumber)
            .append(Constants.USER_RESIDENCE_ZIP_CODE, user.residenceZipCode)
            .append(Constants.USER_PHONE_NUMBER, user.phoneNumber)
            .append(Constants.USER_STUDY_TITLE, user.studyTitle)
            .append(Constants.USER_STUDY_LOCATION, user.studyLocation)
            .append(Constants.USER_EDUCATION_LEVEL, user.educationLevel)
            .append(Constants.USER_DRIVING_LICENSE, user.drivingLicense)
            .append(Constants.USER_CERTIFICATE_OF_DISABILITY, user.certificateOfDisability)
            .append(Constants.USER_COURSES, JSON.parse(user.coursesToJson()))
            .append(Constants.USER_LANGUAGES, JSON.parse(user.languagesToJson()))
            .append(Constants.USER_SOFTWARE, JSON.parse(user.softwareToJson()))
            .append(Constants.USER_ORIENTATION_STEPS,
                    JSON.parse(user.completedOrientationSteps.orientationStepsToJson()))
            .append(Constants.USER_CURRENT_SITUATION, JSON.parse(user.currentSituation.toJsonString()))
            .append(Constants.USER_SKILLS_LIST, JSON.parse(user.skillsToJson()))
            .append(Constants.USER_INTERESTS_LIST, user.interests)
            .append(Constants.USER_PERSONAL_CHARACTERISTICS_LIST, user.personalCharacteristics)
            .append(Constants.USER_PROFESSIONAL_VALUES_LIST, JSON.parse(user.professionalValuesToJson()))
            .append(Constants.USER_PHOTO, JSON.parse(user.photo.toJsonString()))
            .append(Constants.USER_NEXT_INTERVIEWS_LIST, JSON.parse(user.interviewScheduleListToJson()));
    collection.insert(WriteConcern.SAFE, query);

    // Close connection
    mongoClient.close();/*from   ww  w .jav a  2  s.c o  m*/

    // Returns the new user
    return user;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
/**/*  www  .  j  a va 2 s . c  o  m*/
 * Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified
 * record key.
 *
 * @param entitySet The name of the table
 * @param entityPK The record key of the record to insert.
 * @param values A HashMap of field/value pairs to insert in the record
 * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
 */
public int insertEntity(String entitySet, String entityPK, HashMap<String, ByteIterator> values,
        boolean insertImage) {
    com.mongodb.DB db = null;
    WriteResult res = null;
    try {
        // get the appropriate database
        db = mongo.getDB(database);
        // ensure order
        db.requestStart();
        // appropriate table - collection
        DBCollection collection = db.getCollection(entitySet);
        // create the row-object-document
        // need to insert key as integer else the sorting based on id for
        // topk s wont happen properly

        DBObject r = new BasicDBObject().append("_id", Integer.parseInt(entityPK));
        for (String k : values.keySet()) {
            if (!(k.toString().equalsIgnoreCase("pic") || k.toString().equalsIgnoreCase("tpic")))
                r.put(k, values.get(k).toString());
        }

        if (entitySet.equalsIgnoreCase("users")) {
            // ArrayList x = new ArrayList();
            r.put("ConfFriends", new ArrayList<Integer>());
            r.put("PendFriends", new ArrayList<Integer>());
            r.put("wallResources", new ArrayList<Integer>());
        }

        if (entitySet.equalsIgnoreCase("users") && insertImage) {
            // insert picture separately
            // create one gridFS for the datastore
            byte[] profileImage = ((ObjectByteIterator) values.get("pic")).toArray();
            r.put("pic", profileImage);
            // create the thumbnail image
            /*
             * File file = new File("mypic.jpg"); byte fileContent[] = null;
             * try{ //create FileInputStream object FileInputStream fin =
             * new FileInputStream(file); fileContent = new
             * byte[(int)file.length()]; fin.read(fileContent);
             * }catch(Exception e){ e.printStackTrace(); } byte[] thumbImage
             * = fileContent;
             */

            byte[] thumbImage = ((ObjectByteIterator) values.get("tpic")).toArray();
            r.put("tpic", thumbImage);

        }

        res = collection.insert(r, writeConcern);

        if (entitySet.equalsIgnoreCase("resources")) {
            // add the rid to the walluserids profile
            collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", Integer.parseInt((String) r.get("walluserid")));
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            BasicDBObject updateCommand = new BasicDBObject();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                int[] resIds = new int[resourceIds.length + 1];
                for (int i = 0; i < resourceIds.length; i++) { // to limit
                    // it
                    resIds[i] = Integer.parseInt(resourceIds[i].trim());
                }
                resIds[resourceIds.length] = Integer.parseInt(r.get("_id").toString());
                Arrays.sort(resIds);
                updateCommand.put("$set", new BasicDBObject("wallResources", resIds));
            } else
                updateCommand.put("$push", new BasicDBObject("wallResources", r.get("_id")));
            res = collection.update(q, updateCommand, false, false, writeConcern);
        }

        /*
         * // test to see if inserted - search query BasicDBObject
         * searchQuery = new BasicDBObject(); searchQuery.put("_id",
         * Integer.parseInt(key)); // query it DBCursor cursor =
         * collection.find(searchQuery); // loop over the cursor and display
         * the retrieved result while (cursor.hasNext()) {
         * System.out.println(cursor.next()); } return 0;
         */
    } catch (Exception e) {
        System.out.println(e.toString());
        return -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return res.getError() == null ? 0 : -1;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int postCommentOnResource(int commentCreatorID, int profileOwnerID, int resourceID,
        HashMap<String, ByteIterator> commentValues) {
    int retVal = 0;
    if (profileOwnerID < 0 || commentCreatorID < 0 || resourceID < 0)
        return -1;
    // create a new document
    com.mongodb.DB db = null;//  w  ww. j a  va  2  s .c  o m
    try {
        // get the appropriate database
        db = mongo.getDB(database);
        db.requestStart();
        if (!manipulationArray) { // consider a separate manipoulations
            // table
            DBCollection collection = db.getCollection("manipulation");
            // create the row-object-document
            // need to insert key as integer else the sorting based on id
            // for topk s wont happen properly
            HashMap<String, ByteIterator> values = new HashMap<String, ByteIterator>();
            values.put("mid", commentValues.get("mid"));
            values.put("creatorid", new ObjectByteIterator(Integer.toString(profileOwnerID).getBytes()));
            values.put("rid", new ObjectByteIterator(Integer.toString(resourceID).getBytes()));
            values.put("modifierid", new ObjectByteIterator(Integer.toString(commentCreatorID).getBytes()));
            values.put("timestamp", commentValues.get("timestamp"));
            values.put("type", commentValues.get("type"));
            values.put("content", commentValues.get("content"));

            DBObject r = new BasicDBObject();
            for (String k : values.keySet()) {
                r.put(k, values.get(k).toString());
            }

            WriteResult res = collection.insert(r, writeConcern);
            return res.getError() == null ? 0 : -1;
        } else {
            // second approach - store manipulations as elements in an array
            // for resource
            HashMap<String, String> sVals = new HashMap<String, String>();
            sVals.put("mid", commentValues.get("mid").toString());
            sVals.put("creatorid", Integer.toString(profileOwnerID));
            sVals.put("rid", Integer.toString(resourceID));
            sVals.put("modifierid", Integer.toString(commentCreatorID));
            sVals.put("timestamp", commentValues.get("timestamp").toString());
            sVals.put("type", commentValues.get("type").toString());
            sVals.put("content", commentValues.get("content").toString());
            DBCollection collection = db.getCollection("resources");
            DBObject q = new BasicDBObject().append("_id", resourceID);

            BasicDBObject updateCommand = new BasicDBObject();
            updateCommand.put("$push", new BasicDBObject("Manipulations", sVals));
            WriteResult res = collection.update(q, updateCommand, false, false, writeConcern);
            db.requestDone();
            return res.getError() == null ? 0 : -1;
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongodb1.Mongodb1.java

/**
 * @param args the command line arguments
 *//*w  ww . j  a  va  2  s  .  co  m*/
public static void main(String[] args) {

    try { //Connect

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("labbd2016");
        System.out.println("Connect to database successfully");

        DBCollection table = db.getCollection("alunos");
        System.out.println("Collection retrieved successfully");

        List<String> dbs = mongo.getDatabaseNames();
        System.out.println(dbs);

        Set<String> collections = db.getCollectionNames();
        System.out.println(collections);
        //Insert
        BasicDBObject document = new BasicDBObject();
        document.put("nome", "Adao");
        document.put("idade", 30);
        table.insert(WriteConcern.SAFE, document);
        for (DBObject doc : table.find()) {
            System.out.println(doc);
        }
        //Find
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("idade", new BasicDBObject("$gt", 1));
        DBCursor cursor = table.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:mongodbutils.MongodbConnection.java

public boolean insertJSON(String dbName, String collectionName, String json) {
    try {//w w  w . j  a  v  a  2  s. co  m
        //System.out.println("mongo start insert");

        if (mongoClient == null) {
            //System.out.println("client is null");
        }

        db = mongoClient.getDB(dbName);

        //System.out.println("mongo get collection");
        DBCollection coll = db.getCollection(collectionName);

        //System.out.println("parse json");
        DBObject dbObject = (DBObject) JSON.parse(json);

        //System.out.println("insert data");
        //coll.insert(dbObject,WriteConcern.JOURNALED);
        coll.insert(dbObject, WriteConcern.NORMAL);

        return true;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

}

From source file:org.apache.metamodel.mongodb.mongo2.MongoDbInsertionBuilder.java

License:Apache License

@Override
public void execute() throws MetaModelException {
    final Column[] columns = getColumns();
    final Object[] values = getValues();

    final BasicDBObject doc = new BasicDBObject();

    for (int i = 0; i < values.length; i++) {
        Object value = values[i];
        if (value != null) {
            doc.put(columns[i].getName(), value);
        }//from   w w w.  j av  a 2 s. com
    }

    final MongoDbUpdateCallback updateCallback = getUpdateCallback();
    final DBCollection collection = updateCallback.getCollection(getTable().getName());

    final WriteConcern writeConcern = updateCallback.getWriteConcernAdvisor().adviceInsert(collection, doc);

    final WriteResult writeResult = collection.insert(doc, writeConcern);
    logger.info("Insert returned result: {}", writeResult);
}

From source file:org.datanucleus.store.mongodb.MongoDBPersistenceHandler.java

License:Open Source License

@Override
public void insertObjects(ObjectProvider... ops) {
    // This is called by the flush() process, so groups inserts.
    List<ObjectProvider> insertOps = new ArrayList<ObjectProvider>();
    for (int i = 0; i < ops.length; i++) {
        insertOps.add(ops[i]);/*from  w w  w .  ja  v a2  s.  c o m*/
    }

    if (ops.length == 1) {
        insertObject(ops[0]);
        return;
    }

    // Process "identity" cases first in case they are referenced
    for (int i = 0; i < ops.length; i++) {
        AbstractClassMetaData cmd = ops[i].getClassMetaData();
        if (cmd.pkIsDatastoreAttributed(storeMgr)) {
            insertObject(ops[i]);
        }
    }

    // Separate the objects to be persisted into groups, for the "table" in question
    Map<String, Set<ObjectProvider>> opsByTable = new HashMap();
    for (int i = 0; i < ops.length; i++) {
        AbstractClassMetaData cmd = ops[i].getClassMetaData();
        if (!cmd.pkIsDatastoreAttributed(storeMgr)) {
            String tableName = storeMgr.getNamingFactory().getTableName(cmd);
            Set<ObjectProvider> opsForTable = opsByTable.get(tableName);
            if (opsForTable == null) {
                opsForTable = new HashSet<ObjectProvider>();
                opsByTable.put(tableName, opsForTable);
            }
            opsForTable.add(ops[i]);
        }
    }

    for (String tableName : opsByTable.keySet()) {
        Set<ObjectProvider> opsForTable = opsByTable.get(tableName);
        ExecutionContext ec = ops[0].getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnection(ec);
        try {
            DB db = (DB) mconn.getConnection();
            long startTime = System.currentTimeMillis();

            DBCollection collection = db.getCollection(tableName);
            DBObject[] dbObjects = new DBObject[opsForTable.size()];
            int i = 0;
            for (ObjectProvider op : opsForTable) {
                assertReadOnlyForUpdateOfObject(op);
                AbstractClassMetaData cmd = op.getClassMetaData();
                if (!storeMgr.managesClass(cmd.getFullClassName())) {
                    // Make sure schema exists (using this connection)
                    ((MongoDBStoreManager) storeMgr).addClasses(new String[] { cmd.getFullClassName() },
                            op.getExecutionContext().getClassLoaderResolver(), db);
                }

                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.Start",
                            op.getObjectAsPrintable(), op.getInternalObjectId()));
                }

                dbObjects[i] = getDBObjectForObjectProviderToInsert(op, true);

                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST
                            .debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersisted",
                                    op.getObjectAsPrintable(), op.getInternalObjectId()));
                }

                i++;
            }

            if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) {
                NucleusLogger.DATASTORE_NATIVE
                        .debug("Persisting objects as " + StringUtils.objectArrayToString(dbObjects));
            }
            collection.insert(dbObjects, new WriteConcern(1));
            if (ec.getStatistics() != null) {
                ec.getStatistics().incrementNumWrites();
                for (int j = 0; j < dbObjects.length; j++) {
                    ec.getStatistics().incrementInsertCount();
                }
            }

            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.ExecutionTime",
                        (System.currentTimeMillis() - startTime)));
            }
        } catch (MongoException me) {
            NucleusLogger.PERSISTENCE.error("Exception inserting objects", me);
            throw new NucleusDataStoreException("Exception inserting objects", me);
        } finally {
            mconn.release();
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBPersistenceHandler.java

License:Open Source License

public void insertObject(ObjectProvider op) {
    assertReadOnlyForUpdateOfObject(op);

    ExecutionContext ec = op.getExecutionContext();
    ManagedConnection mconn = storeMgr.getConnection(ec);
    try {//from  www  .  j av a  2s  .c om
        DB db = (DB) mconn.getConnection();

        AbstractClassMetaData cmd = op.getClassMetaData();
        if (!storeMgr.managesClass(cmd.getFullClassName())) {
            // Make sure schema exists, using this connection
            ((MongoDBStoreManager) storeMgr).addClasses(new String[] { cmd.getFullClassName() },
                    ec.getClassLoaderResolver(), db);
        }

        long startTime = System.currentTimeMillis();
        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
            NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.Start",
                    op.getObjectAsPrintable(), op.getInternalObjectId()));
        }

        DBCollection collection = db.getCollection(storeMgr.getNamingFactory().getTableName(cmd));
        DBObject dbObject = getDBObjectForObjectProviderToInsert(op, !cmd.pkIsDatastoreAttributed(storeMgr));

        NucleusLogger.DATASTORE_NATIVE.debug("Persisting object " + op + " as " + dbObject);
        collection.insert(dbObject, new WriteConcern(1));
        if (ec.getStatistics() != null) {
            ec.getStatistics().incrementNumWrites();
        }

        if (cmd.pkIsDatastoreAttributed(storeMgr)) {
            // Set the identity of the object based on the datastore-generated IDENTITY strategy value
            if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                // Set identity from MongoDB "_id" field
                ObjectId idKey = (ObjectId) dbObject.get("_id");
                op.setPostStoreNewObjectId(idKey.toString());
                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg(
                            "MongoDB.Insert.ObjectPersistedWithIdentity", op.getObjectAsPrintable(), idKey));
                }
            } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                int[] pkFieldNumbers = cmd.getPKMemberPositions();
                for (int i = 0; i < pkFieldNumbers.length; i++) {
                    AbstractMemberMetaData mmd = cmd
                            .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]);
                    if (storeMgr.isStrategyDatastoreAttributed(cmd, pkFieldNumbers[i])) {
                        if (mmd.getType() != String.class) {
                            // Field type must be String since MongoDB "_id" is a hex String.
                            throw new NucleusUserException(
                                    "Any field using IDENTITY value generation with MongoDB should be of type String");
                        }
                        ObjectId idKey = (ObjectId) dbObject.get("_id");
                        op.replaceField(mmd.getAbsoluteFieldNumber(), idKey.toString());
                        op.setPostStoreNewObjectId(idKey); // TODO This is incorrect if part of a composite PK
                        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                            NucleusLogger.DATASTORE_PERSIST
                                    .debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersistedWithIdentity",
                                            op.getObjectAsPrintable(), idKey));
                        }
                    }
                }
            }

            // Update any relation fields
            StoreFieldManager fieldManager = new StoreFieldManager(op, dbObject, true);
            int[] fieldNumbers = cmd.getRelationMemberPositions(ec.getClassLoaderResolver(),
                    ec.getMetaDataManager());
            if (fieldNumbers != null && fieldNumbers.length > 0) {
                op.provideFields(fieldNumbers, fieldManager);
                NucleusLogger.DATASTORE_NATIVE.debug("Saving object " + op + " as " + dbObject);
                collection.save(dbObject);
                if (ec.getStatistics() != null) {
                    ec.getStatistics().incrementNumWrites();
                }
            }
        } else {
            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersisted",
                        op.getObjectAsPrintable(), op.getInternalObjectId()));
            }
        }

        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
            NucleusLogger.DATASTORE_PERSIST.debug(
                    LOCALISER_MONGODB.msg("MongoDB.ExecutionTime", (System.currentTimeMillis() - startTime)));
        }
        if (ec.getStatistics() != null) {
            ec.getStatistics().incrementInsertCount();
        }
    } catch (MongoException me) {
        NucleusLogger.PERSISTENCE.error("Exception inserting object " + op, me);
        throw new NucleusDataStoreException("Exception inserting object for " + op, me);
    } finally {
        mconn.release();
    }
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@POST
@Path("/databases/{dbName}/collections/{collName}/documents")
@Override/*from w  w  w . ja  va 2s.  c  o m*/
public Response createDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        org.exoplatform.mongo.entity.request.Document document, @Context HttpHeaders headers,
        @Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                String documentJson = document.getJson();
                if (!StringUtils.isNullOrEmpty(documentJson)) {
                    DBObject mongoDocument = (DBObject) JSON.parse(document.getJson());
                    try {
                        dbCollection.insert(mongoDocument, WriteConcern.SAFE);
                        ObjectId documentId = ((ObjectId) mongoDocument.get("_id"));
                        if (documentId != null && !StringUtils.isNullOrEmpty(documentId.toString())) {
                            URI statusSubResource = uriInfo
                                    .getBaseUriBuilder().path(MongoRestServiceImpl.class).path("/databases/"
                                            + dbName + "/collections/" + collName + "/documents/" + documentId)
                                    .build();
                            response = Response.created(statusSubResource).build();
                        } else {
                            response = Response.status(ServerError.RUNTIME_ERROR.code())
                                    .entity(ServerError.RUNTIME_ERROR.message()).build();
                        }
                    } catch (DuplicateKey duplicateObject) {
                        response = Response.status(ClientError.BAD_REQUEST.code())
                                .entity("Document already exists and could not be created").build();
                    }
                } else {
                    response = Response.status(ClientError.BAD_REQUEST.code())
                            .entity("Document JSON is required").build();
                }
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "createDocument");
    }
    return response;
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@PUT
@Path("/databases/{dbName}/collections/{collName}/documents/{docId}")
@Override/*from   w  w  w  .  j a v  a  2 s  . c om*/
public Response updateDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @PathParam("docId") String docId, org.exoplatform.mongo.entity.request.Document document,
        @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                String documentJson = document.getJson();
                if (!StringUtils.isNullOrEmpty(documentJson)) {
                    DBObject incomingDocument = (DBObject) JSON.parse(documentJson);
                    DBObject query = new BasicDBObject();
                    query.put("_id", new ObjectId(docId));
                    DBObject persistedDocument = dbCollection.findOne(query);
                    URI statusSubResource = null;
                    try {
                        if (persistedDocument == null) {
                            dbCollection.insert(incomingDocument, WriteConcern.SAFE);
                            statusSubResource = uriInfo.getBaseUriBuilder().path(MongoRestServiceImpl.class)
                                    .path("/databases/" + dbName + "/collections/" + collName + "/documents/"
                                            + ((DBObject) incomingDocument.get("_id")))
                                    .build();
                            response = Response.created(statusSubResource).build();
                        } else {
                            dbCollection.save(incomingDocument);
                            statusSubResource = uriInfo
                                    .getBaseUriBuilder().path(MongoRestServiceImpl.class).path("/databases/"
                                            + dbName + "/collections/" + collName + "/documents/" + docId)
                                    .build();
                            response = Response.ok(statusSubResource).build();
                        }
                    } catch (DuplicateKey duplicateObject) {
                        response = Response.status(ClientError.BAD_REQUEST.code())
                                .entity("Document already exists and could not be created").build();
                    }
                } else {
                    response = Response.status(ClientError.BAD_REQUEST.code())
                            .entity("Document JSON is required").build();
                }
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "updateDocument");
    }
    return response;
}