Example usage for com.mongodb BasicDBObject getString

List of usage examples for com.mongodb BasicDBObject getString

Introduction

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

Prototype

public String getString(final String key) 

Source Link

Document

Returns the value of a field as a string

Usage

From source file:com.tml.pathummoto.Dao.PartDao.java

public ArrayList searchpart4(String modelName, String PartType) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    //         // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("part");
    System.out.println("Collection user selected successfully");
    System.out.println(modelName);
    System.out.println(PartType);
    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("Model Name", modelName);
    whereQuery.put("Part Type", PartType);
    DBCursor cursor = coll.find(whereQuery);
    ArrayList<Part> arr = new ArrayList<Part>();
    while (cursor.hasNext()) {
        BasicDBObject obj = (BasicDBObject) cursor.next();
        Part part;//from w  w w .  ja  v  a 2 s .  c  om
        part = new Part(obj.getString("Quantity"), obj.getString("_id"), obj.getInt("quant"));

        arr.add(part);

    }
    return (arr);

}

From source file:com.tml.pathummoto.Dao.UserDao.java

public User login(String name) {
    User user = new User();
    // To connect to mongodb server
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("user");
    System.out.println("Collection user selected successfully");

    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("title", name);
    DBCursor cursor = coll.find(whereQuery);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }/*from  ww w .  j ava  2 s.c  o  m*/
    BasicDBObject doc = (BasicDBObject) cursor.curr();
    if (doc != null) {
        user.setName(doc.getString("title"));
        user.setPassword(doc.getString("password"));
    }

    return user;
}

From source file:com.wordnik.system.mongodb.Analyzer.java

License:Open Source License

protected void run() {
    long startTime = System.currentTimeMillis();
    //  decide what collections to process
    selectCollections();/*from www  .ja  v  a  2 s . c  om*/

    //  create any re-mappings
    Map<String, String> collectionMappings = new HashMap<String, String>();
    Map<String, String> databaseMappings = new HashMap<String, String>();
    createMappings(DATABASE_MAPPING_STRING, COLLECTION_MAPPING_STRING, databaseMappings, collectionMappings);

    try {
        File[] files = new File(INPUT_DIR).listFiles();
        if (files != null) {
            List<File> filesToProcess = new ArrayList<File>();
            for (File file : files) {
                if (file.getName().indexOf(".bson") > 0) {
                    filesToProcess.add(file);
                }
            }
            long operationsRead = 0;
            long operationsSkipped = 0;
            long lastOutput = System.currentTimeMillis();
            for (File file : filesToProcess) {
                System.out.println("analyzing file " + file.getName());
                BufferedInputStream inputStream = null;
                try {
                    if (file.getName().endsWith(".gz")) {
                        InputStream is = new GZIPInputStream(new FileInputStream(file));
                        inputStream = new BufferedInputStream(is);
                    } else {
                        inputStream = new BufferedInputStream(new FileInputStream(file));
                    }
                    BSONDecoder decoder = new DefaultDBDecoder();
                    while (true) {
                        if (inputStream.available() == 0) {
                            break;
                        }
                        BSONObject obj = decoder.readObject(inputStream);
                        if (obj == null) {
                            break;
                        }
                        BasicDBObject dbo = new BasicDBObject((BasicBSONObject) obj);

                        BSONTimestamp operationTimestamp = (BSONTimestamp) dbo.get("ts");
                        String namespace = dbo.getString("ns");

                        processRecord(dbo);
                        operationsRead++;

                        long durationSinceLastOutput = System.currentTimeMillis() - lastOutput;
                        if (durationSinceLastOutput > REPORT_INTERVAL) {
                            report(operationsRead, System.currentTimeMillis() - startTime);
                            lastOutput = System.currentTimeMillis();
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    report(0, System.currentTimeMillis() - startTime);
}

From source file:com.wordnik.system.mongodb.Analyzer.java

License:Open Source License

protected void processRecord(BasicDBObject dbo) {
    String operationType = dbo.getString("op");
    String namespace = dbo.getString("ns");

    String key = operationType + " - " + namespace;
    Long count = new Long(1);
    if (counters.containsKey(key)) {
        count = new Long(counters.get(key).longValue() + 1);
    }//from w ww  .j a v  a 2  s .c om
    counters.put(key, count);
}

From source file:com.wordnik.system.mongodb.ReplayUtil.java

License:Open Source License

protected void run() {
    long startTime = System.currentTimeMillis();
    //   decide what collections to process
    selectCollections();/* w  ww . j ava2  s. c  o  m*/

    OplogReplayWriter util = new OplogReplayWriter();

    //   create any re-mappings
    Map<String, String> collectionMappings = new HashMap<String, String>();
    Map<String, String> databaseMappings = new HashMap<String, String>();
    createMappings(DATABASE_MAPPING_STRING, COLLECTION_MAPPING_STRING, databaseMappings, collectionMappings);

    //   configure the writer
    util.setCollectionMappings(collectionMappings);
    util.setDatabaseMappings(databaseMappings);
    util.setDestinationDatabaseUsername(DEST_DATABASE_USER_NAME);
    util.setDestinationDatabasePassword(DEST_DATABASE_PASSWORD);
    util.setDestinationDatabaseHost(DEST_DATABASE_HOST);

    try {
        File[] files = new File(INPUT_DIR).listFiles();
        if (files != null) {
            List<File> filesToProcess = new ArrayList<File>();
            for (File file : files) {
                if (file.getName().indexOf(".bson") > 0) {
                    filesToProcess.add(file);
                }
            }
            long operationsRead = 0;
            long operationsSkipped = 0;
            long lastOutput = System.currentTimeMillis();
            for (File file : filesToProcess) {
                System.out.println("replaying file " + file.getName());
                BufferedInputStream inputStream = null;
                try {
                    if (file.getName().endsWith(".gz")) {
                        InputStream is = new GZIPInputStream(new FileInputStream(file));
                        inputStream = new BufferedInputStream(is);
                    } else {
                        inputStream = new BufferedInputStream(new FileInputStream(file));
                    }
                    BSONDecoder decoder = new DefaultDBDecoder();
                    while (true) {
                        if (inputStream.available() == 0) {
                            break;
                        }
                        BSONObject obj = decoder.readObject(inputStream);
                        if (obj == null) {
                            break;
                        }
                        BasicDBObject dbo = new BasicDBObject((BasicBSONObject) obj);

                        BSONTimestamp operationTimestamp = (BSONTimestamp) dbo.get("ts");
                        String namespace = dbo.getString("ns");
                        String collection = util.getUnmappedCollectionFromNamespace(namespace);

                        boolean shouldProcess = shouldProcessRecord(collection, operationTimestamp);

                        if (collection != null && shouldProcess) {
                            util.processRecord(dbo);
                            operationsRead++;
                        } else {
                            operationsSkipped++;
                        }

                        long durationSinceLastOutput = System.currentTimeMillis() - lastOutput;
                        if (durationSinceLastOutput > REPORT_INTERVAL) {
                            report(util.getInsertCount(), util.getUpdateCount(), util.getDeleteCount(),
                                    operationsRead, operationsSkipped, System.currentTimeMillis() - startTime);
                            lastOutput = System.currentTimeMillis();
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java

License:Apache License

/**
 * Contacts the config server and builds a map of each shard's name to its
 * host(s) by examining config.shards./*from w  w  w.j  ava2  s.  c o  m*/
 * @return a Map of shard name onto shard hostnames
 */
protected Map<String, String> getShardsMap() {
    DBCursor cur = null;
    HashMap<String, String> shardsMap = new HashMap<String, String>();
    DB configDB = null;
    try {
        configDB = getConfigDB();
        DBCollection shardsCollection = configDB.getCollection("shards");
        cur = shardsCollection.find();
        while (cur.hasNext()) {
            final BasicDBObject row = (BasicDBObject) cur.next();
            String host = row.getString("host");
            // for replica sets host will look like: "setname/localhost:20003,localhost:20004"
            int slashIndex = host.indexOf('/');
            if (slashIndex > 0) {
                host = host.substring(slashIndex + 1);
            }
            shardsMap.put((String) row.get("_id"), host);
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    return shardsMap;
}

From source file:controllers.FilterController.java

License:Apache License

private static void calculateNumericHistogramResults(MapReduceOutput output, List<String> keys,
        List<String> values, long width) {
    List<BasicDBObject> results = (List<BasicDBObject>) output.getCommandResult().get("results");
    for (BasicDBObject obj : results) {

        String id = obj.getString("_id");

        if (!id.equals("Unknown") && !id.equals("Conflicted")) {
            long low = (int) Double.parseDouble(id) * width;
            long high = low + width - 1;
            keys.add(low + " - " + high);
        }//  ww  w  .j av a  2 s  . c  o m
        values.add(obj.getString("value"));
    }
}

From source file:controllers.FilterController.java

License:Apache License

private static void parseHistogram(BasicDBObject dbo, List<String> keys, List<String> values) {
    String key = dbo.getString("_id");
    if (key.endsWith(".0")) {
        key = key.substring(0, key.length() - 2);
    }/*from  w  w w .ja v a 2  s.  c o  m*/
    keys.add(key);
    values.add(dbo.getString("value"));
}

From source file:cs.karibu.helloworld.stage2.ExampleShellOutputNullStorage.java

License:Apache License

@Override
public void process(String producerCode, BasicDBObject dbo) {
    System.out.println("Received payload with producer code:" + producerCode);
    if (producerCode.equals(ExampleCodes.EXAMPLE_PRODUCER_CODE)) {
        System.out.println(/*w  w  w.  ja  v a  2s.c  o m*/
                " *** The favorite game of " + dbo.getString("name") + " is " + dbo.getString("game") + " ***");
    } else {
        System.out.println("Unknown producer code - ignoring...");
    }

}

From source file:cs.rsa.ts14dist.appserver.StandardServerRequestHandler.java

License:Apache License

@Override
public JSONObject handleRequest(JSONObject request) {
    // System.out.println("ServerRequestHandler/handling request: "+ requestObject); 

    JSONObject reply;//from   ww w  .j  a  v a2 s.  c  o  m

    // Extract the user and command from the request object 
    String user = request.get(Constants.USER_KEY).toString();
    String command = request.get(Constants.COMMAND_KEY).toString();

    // Switch on the type of request from the client 
    if (command.equals(Constants.ADDLINE_REQUEST)) {
        // Get the actual line to add from the request object 
        String newLineToAdd = request.get(Constants.PARAMETER_KEY).toString();

        // Compute an answer for the given added line 
        LineType lineType = ts14facade.classify(newLineToAdd);

        // if the line type is legal, compose a reply, and update 
        // the database 
        if (lineType != LineType.INVALID_LINE) {
            // update the database with the new contents 
            if (updateContentsForUserWithNewLine(user, newLineToAdd)) {
                //success, define the return value of this method 
                reply = CommandLanguage.createValidReplyWithReturnValue(lineType.ordinal());
            } else {
                //errror
                reply = CommandLanguage
                        .createInvalidReplyWithExplantion("Update of docment failed, document to too big");
            }

        } else {
            // invalid line type - tell the client 
            reply = CommandLanguage
                    .createInvalidReplyWithExplantion("Line: #" + newLineToAdd + "# is invalid line type");
        }
    } else if (command.equals(Constants.GETREPORT_REQUEST)) {
        // get the contents of the timesag 

        try {
            BasicDBObject dbo = storage.getDocumentFor(user);

            if (dbo == null) {
                reply = CommandLanguage.createInvalidReplyWithExplantion("Document for user not found");
            } else {
                String contents = dbo.getString("contents");
                if (contents.length() > Constants.MAX_DOCUMENT_SIZE) {
                    reply = CommandLanguage
                            .createInvalidReplyWithExplantion("Document too big for report generation");
                } else {
                    // get the required type of report 
                    String reporttype = request.get(Constants.PARAMETER_KEY).toString();

                    // Run contents through the processor 
                    String report = generateReport(contents, reporttype);
                    reply = CommandLanguage.createValidReplyWithReturnValue(report);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            reply = CommandLanguage.createInvalidReplyWithExplantion("Database unavailable, try again later");
        }
    } else if (command.equals(Constants.GETCONTENTS_REQUEST)) {
        // get the contents of the timesag for the given user 

        try {
            BasicDBObject dbo = storage.getDocumentFor(user);

            if (dbo == null) {
                reply = CommandLanguage.createInvalidReplyWithExplantion("Document for user not found");
            } else {
                String contents = dbo.getString("contents");
                if (contents.length() > Constants.MAX_DOCUMENT_SIZE) {
                    reply = CommandLanguage
                            .createInvalidReplyWithExplantion("Document too big for report generation");
                } else {
                    reply = CommandLanguage.createValidReplyWithReturnValue(contents);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            reply = CommandLanguage.createInvalidReplyWithExplantion("Database unavailable, try again later");
        }

    } else {
        // huh?? Not a known command
        reply = CommandLanguage
                .createInvalidReplyWithExplantion("Unknown command received: " + command + "/obj=" + request);
    }

    return reply;

}