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) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java

License:Apache License

private static void insertVisitAttributesData(GaData gaData, DBCollection collection, Date d,
        DBCollection centerMapping) throws JSONException {
    if (gaData.getTotalResults() > 0) {
        System.out.println("Data Table:" + collection);

        String[] columns = (VISIT_ATTRIBUTES_METRICS + "," + VISIT_ATTRIBUTES_DIMENSIONS).split(",");
        HashMap<String, Integer> columnLookUp = new HashMap<String, Integer>();
        List<ColumnHeaders> columnHeaders = gaData.getColumnHeaders();
        for (String column : columns) {
            for (int i = 0; i < columnHeaders.size(); i++) {
                if (columnHeaders.get(i).getName().equals(column)) {
                    columnLookUp.put(column, i);
                    break;
                }/* ww  w  .  j  a  v  a  2  s. c  o  m*/
            }
        }

        if (!gaData.getContainsSampledData()) {
            for (List<String> rowValues : gaData.getRows()) {
                String demandBaseId = rowValues.get(columnLookUp.get("ga:dimension11"));
                String clientId = rowValues.get(columnLookUp.get("ga:dimension2"));
                String pagePath = rowValues.get(columnLookUp.get("ga:pagePath"));
                String source = rowValues.get(columnLookUp.get("ga:source"));
                String medium = rowValues.get(columnLookUp.get("ga:medium"));
                //                    String visits = rowValues.get(columnLookUp.get("ga:visits"));
                //                    String users = rowValues.get(columnLookUp.get("ga:users"));
                //                    String pageViews = rowValues.get(columnLookUp.get("ga:pageviews"));
                //                    String sessionDuration = rowValues.get(columnLookUp.get("ga:sessionDuration"));

                HashMap<Object, Object> map = new HashMap<Object, Object>();
                map.put("demandbase_sid", demandBaseId);
                map.put("clientId", clientId);
                String[] split = pagePath.split("\\?"); // remove all characters after the URL parameters
                String[] withoutMobileUrl = split[0].split("regus.com");
                String strippedPagePath = withoutMobileUrl[withoutMobileUrl.length - 1];

                String product = "", centerLookUp = "", centerId = "";
                String[] locations = strippedPagePath.split("locations/");
                if (locations.length > 1) {
                    int index = locations[1].indexOf("/");
                    product = locations[1].substring(0, index);
                    centerLookUp = locations[1].substring(index + 1);

                    HashMap<Object, Object> centerLookUpMap = new HashMap<Object, Object>();
                    centerLookUpMap.put("CentreURLName", centerLookUp);
                    BasicDBObject objectToRemove = new BasicDBObject(centerLookUpMap);
                    DBCursor cursor = centerMapping.find(objectToRemove);
                    if (cursor.hasNext()) {
                        centerId = cursor.next().get("CentreID").toString();
                    }

                }
                map.put("pagePath", strippedPagePath);
                map.put("source", source);
                map.put("medium", medium);
                map.put("product", product);
                map.put("centerId", centerId);
                //                    map.put("visits", visits);
                //                    map.put("users", users);
                //                    map.put("pageViews", pageViews);
                //                    map.put("sessionDuration", sessionDuration);
                map.put("date", new SimpleDateFormat("yyyy/MM/dd").format(d));
                BasicDBObject objectToInsert = new BasicDBObject(map);
                collection.insert(objectToInsert);
            }
        } else {
            System.out.println(" Excluding analytics data since it has sample data");
        }
    } else {
        System.out.println("No data");
    }
}

From source file:com.groupon.jenkins.mongo.MongoDataLoadRule.java

License:Open Source License

@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override// w  w w  . j  av a 2 s  .  c  om
        public void evaluate() throws Throwable {
            if (Jenkins.getInstance() == null || SetupConfig.get().getInjector() == null
                    || SetupConfig.get().getInjector().getInstance(Datastore.class) == null) {
                throw new IllegalStateException("Requires configured Jenkins and Mongo configurations");
            }

            DB db = SetupConfig.get().getInjector().getInstance(Datastore.class).getDB();

            //Load mongo data
            File homedir = Jenkins.getInstance().getRootDir();

            for (File fileOfData : homedir.listFiles()) {
                if (!fileOfData.getName().endsWith(".json"))
                    continue;

                String collectionName = fileOfData.getName().replaceAll("\\.json$", "");
                DBCollection collection = db.createCollection(collectionName, new BasicDBObject());

                String data = FileUtils.readFileToString(fileOfData);
                Object bsonObject = JSON.parse(data);
                if (bsonObject instanceof BasicDBList) {
                    BasicDBList basicDBList = (BasicDBList) bsonObject;
                    collection.insert(basicDBList.toArray(new DBObject[0]));
                } else {
                    collection.insert((DBObject) bsonObject);
                }

            }

            for (OrganizationContainer container : Jenkins.getInstance()
                    .getAllItems(OrganizationContainer.class)) {
                container.reloadItems();
            }

            base.evaluate();

            // Clean up mongo data
            for (String collectioName : db.getCollectionNames()) {
                db.getCollection(collectioName).drop();
            }
        }
    };
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * insert document/*from  www . j  a va 2 s .c o m*/
 * 
 * @param userDB
 * @param colName
 * @param jsonStr
 * @throws Exception
 */
public static void insertDocument(UserDBDAO userDB, String colName, String jsonStr) throws Exception {
    DBObject dbObject = (DBObject) JSON.parse(jsonStr);
    DBCollection collection = findCollection(userDB, colName);

    WriteResult wr = collection.insert(dbObject);
    //      ?    ??   ?(????????????????????????????????)
    //      if(logger.isDebugEnabled()) {
    //         logger.debug( "[writer document]" + wr.toString() );
    //         logger.debug( wr.getError() );      
    //         logger.debug("[n]" + wr.getN() );
    //      }
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * insert document/*  w  w w. j  av  a2s  . c om*/
 * 
 * @param userDB
 * @param colName
 * @param dbObject
 * @throws Exception
 */
public static void insertDocument(UserDBDAO userDB, String colName, List<DBObject> dbObject) throws Exception {
    if (dbObject.size() == 0)
        return;

    DBCollection collection = findCollection(userDB, colName);
    WriteResult wr = collection.insert(dbObject);
    if (logger.isDebugEnabled()) {
        try {
            logger.debug("[writer document]" + wr != null ? wr.toString() : "");
            logger.debug("[wr error]" + wr != null ? wr.getError() : "");
            logger.debug("[n]" + wr != null ? wr.getN() : "");
        } catch (Exception e) {
            logger.error("insert document", e);
        }
    }
}

From source file:com.hangum.tadpole.mongodb.core.test.ConvertJsonToDBObject.java

License:Open Source License

public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBCollection myColl = db.getCollection("objectInsert");

    //      // w w  w  .j a  va 2 s. c o m
    //      DBObject dbObject = new BasicDBObject();
    //      dbObject.put("aa", 1);
    //      dbObject.put("bb", "33");

    DBObject dbObject = (DBObject) JSON.parse("{'rental_id':1,  'inventory_id':367}");
    myColl.insert(dbObject);

    DBCursor cursorDoc = myColl.find();
    while (cursorDoc.hasNext()) {
        System.out.println(cursorDoc.next());
    }

    System.out.println("Done");

}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestReferenceCollection.java

License:Open Source License

/**
 * @param args/*  w  ww .  j a v a2 s .  c o m*/
 */
public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBObject colInformation = (DBObject) JSON.parse("{capped:true, size:100000}");
    DBCollection ref1Coll = db.getCollection(REF_1);
    if (ref1Coll != null)
        ref1Coll.drop();
    ref1Coll = db.createCollection(REF_1, colInformation);

    DBObject dbObjRef1 = (DBObject) JSON.parse("{ 'name' : 'cho'}");//"{'names': {'First': 'Gonza', 'Last': 'Vieira'}}");
    WriteResult wr = ref1Coll.insert(dbObjRef1);

    DBObject retDBObj = ref1Coll.findOne();
    createRef1Collection(db, retDBObj.get("_id"));

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestReferenceCollection.java

License:Open Source License

public static void createRef1Collection(DB db, Object objId) {
    DBObject colInformation = (DBObject) JSON.parse("{capped:true, size:100000}");
    DBCollection ref2Coll = db.getCollection(REF_2);
    if (ref2Coll != null)
        ref2Coll.drop();/*from   w ww . j a v a 2s  .  c  o  m*/
    ref2Coll = db.createCollection(REF_2, colInformation);

    BasicDBObject insertObj = new BasicDBObject();
    insertObj.put(REF_1 + "_id", objId);

    DBObject addField = new BasicDBObject();
    addField.put("name", "Reference id");

    insertObj.putAll(addField);

    //      DBObject dbObjRef2 = (DBObject) JSON.parse("{'ref1_id': 50f9437cf023f820730a3b42,  {'names': {'First': 'Gonza', 'Last': 'Vieira'}}}");
    ref2Coll.insert(insertObj);
}

From source file:com.hangum.tadpole.mongodb.core.test.UpdateEx.java

License:Open Source License

public static void insert(DBCollection coll, String hosting, String type, int clients) {
    BasicDBObject doc = new BasicDBObject();
    doc.put("hosting", hosting);
    doc.put("type", type);
    doc.put("clients", clients);
    coll.insert(doc);
}

From source file:com.ibm.bluemix.smartveggie.dao.SubOutletVendorAllocationDaoImpl.java

@Override
public BasicDBObject allocatedSubOutlet(SubOutletVendorAllocationDTO subOutletVendorAllocationDTO) {

    System.out.println("Allocating Outlet to vendor...");
    DB db = MongodbConnection.getMongoDB();
    DBCollection col = db.getCollection(ICollectionName.COLLECTION_ALLOC_SUBOUTLETS);
    // create a document
    BasicDBObject json = new BasicDBObject();
    json.append("smartCityCode", subOutletVendorAllocationDTO.getSmartCityCode());
    json.append("smartOutletCode", subOutletVendorAllocationDTO.getSmartOutletCode());
    json.append("suboutletCode", subOutletVendorAllocationDTO.getSuboutletCode());
    json.append("vendorLicenseNo", subOutletVendorAllocationDTO.getVendorLicenseNo());
    json.append("vendorUsername", subOutletVendorAllocationDTO.getVendorUsername());
    json.append("suboutletAllocatedFrom", subOutletVendorAllocationDTO.getSuboutletAllocatedFrom());
    json.append("suboutletAllocatedTo", subOutletVendorAllocationDTO.getSuboutletAllocatedTo());

    // insert the document
    col.insert(json);
    System.out.println("After allocating outlet..");
    return json;/*from  w w  w  . j a va 2  s. co m*/
}

From source file:com.ibm.bluemix.smartveggie.dao.UserDaoImpl.java

@Override
public BasicDBObject createUser(UserDTO userDTO) {

    System.out.println("Creating User...");
    DB db = MongodbConnection.getMongoDB();
    DBCollection col = db.getCollection(ICollectionName.COLLECTION_USERS);
    // create a document
    BasicDBObject json = new BasicDBObject();
    json.append("firstName", userDTO.getFirstName());
    json.append("lastName", userDTO.getLastName());
    json.append("addressLine1", userDTO.getAddressLine1());
    json.append("addressLine2", userDTO.getAddressLine2());
    json.append("sex", userDTO.getSex());
    json.append("age", userDTO.getAge());
    json.append("city", userDTO.getCity());
    json.append("pin", userDTO.getPinCode());
    json.append("userType", userDTO.getUserTypeCode());
    json.append("userName", userDTO.getUserName());
    json.append("password", userDTO.getPassword());

    if (userDTO.getUserTypeCode() != null && userDTO.getUserTypeCode().equals("vendor")) {

        json.append("licenseNo", userDTO.getLicenseNo());

        //Process the date field
        SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
        String validFrom = userDTO.getValidFrom();
        String validTo = userDTO.getValidTo();

        try {/*from   w ww .  j a v  a 2  s  .c  o m*/

            Date validFromDate = formatter.parse(validFrom);
            Date validToDate = formatter.parse(validTo);
            System.out.println(validFromDate);
            json.append("validFrom", validFromDate);
            json.append("validTo", validToDate);
            //System.out.println(formatter.format(validFromDate));

        } catch (Exception e) {
            e.printStackTrace();
        }
        // insert the document
    } else if (userDTO.getUserTypeCode() != null && userDTO.getUserTypeCode().equalsIgnoreCase("regulator")) {
        json.append("regulatingCityCode", userDTO.getRegulatingCityCode());
        json.append("regulatingCityName", userDTO.getRegulatingCityName());
    }
    col.insert(json);
    System.out.println("after insert");
    return json;
}