List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
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;/*ww w .ja va 2s .c o m*/ part = new Part(obj.getString("Quantity"), obj.getString("_id"), obj.getInt("quant")); arr.add(part); } return (arr); }
From source file:com.tml.pathummoto.Dao.PartDao.java
public void addstock(int t, String p) { 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"); BasicDBObject updateQuery = new BasicDBObject(); updateQuery.append("$set", new BasicDBObject().append("quant", t)); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.append("_id", p); coll.update(searchQuery, updateQuery); ////from w w w .j a v a 2s .c o m /*BasicDBObject updateQuery = new BasicDBObject(); updateQuery.append("$set", new BasicDBObject().append("clients", "888")); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.append("type", "vps"); collection.update(searchQuery, updateQuery);*/ }
From source file:com.tml.pathummoto.Dao.UserDao.java
public void signup(User user) { try {/*ww w .j av a2s . c o m*/ // 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 mycol selected successfully"); BasicDBObject doc = new BasicDBObject("title", user.getName()).append("password", user.getPassword()); coll.insert(doc); System.out.println("Document inserted successfully"); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
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 w w w.j av a 2s . 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.ultratechnica.mongodb.Main.java
License:Apache License
public static void main(String[] args) { log.info("=============================================================================================\n" + " _ _ _ \n" + " |\\/| _ ._ _ _ | \\ |_) |_) _ ._ _ |_ \n" + " | | (_) | | (_| (_) |_/ |_) |_) (/_ | | (_ | | \n" + " _| \n" + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n" + "Licensed to Apache " + "=============================================================================================\n"); Options options = getOptions();//from w ww.ja v a 2s . com CommandLine commandLine = parseArgs(args, options); MongoClient client = null; if (commandLine.hasOption("host") && commandLine.hasOption("port")) { String host = commandLine.getOptionValue("host"); String port = commandLine.getOptionValue("port"); try { client = new MongoClient(host, Integer.parseInt(port)); } catch (UnknownHostException e) { log.error("Unable to connect to host [{}] on port [{}]", host, port); } } else if (options.hasOption("host")) { String host = commandLine.getOptionValue("host"); try { client = new MongoClient(host); } catch (UnknownHostException e) { log.error("Unable to connect to host [{}] on default port ()", host); } } else { try { client = new MongoClient(); } catch (UnknownHostException e) { log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT); } } if (client == null) { System.out.println("Exiting, due to previous connection errors"); System.exit(1); } ServerAddress clientAddress = client.getAddress(); log.info("Connected to MongoDB [{}]", clientAddress); MongoClientOptions mongoClientOptions = client.getMongoClientOptions(); log.info("=============================================================================================\n" + "Using Mongo Client options:\n" + "\tConnections per host: " + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: " + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: " + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: " + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: " + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n" + "\tMax threads allowed to block for conneciton multipler: " + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: " + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: " + mongoClientOptions.getReadPreference() + "\n" + "=============================================================================================\n"); String items = commandLine.getOptionValue("n"); int numberOfItems = 0; try { numberOfItems = Integer.parseInt(items); } catch (NumberFormatException e) { log.error("The parameter provided for -n was not an integer [{}]", items); System.exit(1); } DB local = client.getDB("local"); DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME); log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems, DEFAULT_COLLECTION_NAME); long startTime = System.currentTimeMillis(); for (int i = 0; i < numberOfItems; i++) { BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date()) .add("field1", "123456").add("field2", "2345678") .add("field3", "123123231313131232131231231231123132123123123").add("field4", true); WriteResult result = collection.insert(builder.get()); if (!result.getLastError().ok()) { log.error("An error occurred [{}]", result.getLastError()); } } long endTime = System.currentTimeMillis(); log.info("Finished benchmarking."); long timeTakenMillis = endTime - startTime; float timeTaken = (float) timeTakenMillis / 1000; log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n" + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n" + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n"); log.info("Removing test data..."); collection.remove(new BasicDBObject()); log.info("Cleared collection [test]"); }
From source file:com.vaushell.gfmongodb.MongoDbUserRealm.java
License:Open Source License
@Override protected void init(final Properties parameters) throws BadRealmException, NoSuchRealmException { super.init(parameters); // Among the other custom properties, there is a property jaas-context (which is explained later in this post). // This property should be set using the call setProperty method implemented in the parent class. /// From: https://blogs.oracle.com/nithya/entry/groups_in_custom_realms checkAndSetProperty(JAAS_CONTEXT_PARAM, parameters); for (final Map.Entry<String, String> entry : OPTIONAL_PROPERTIES.entrySet()) { setOptionalProperty(entry.getKey(), parameters, entry.getValue()); }//ww w .j ava 2s .c o m try { final MongoClient client = new MongoClient(); final DB db = client.getDB(getProperty(PARAM_DB)); usersCollection = db.getCollection(getProperty(PARAM_COLLECTION)); } catch (final UnknownHostException ex) { throw new BadRealmException(ex); } }
From source file:com.vidico.jsp.dao.UserDAO.java
public UserDAO(MongoClient mongo) { this.col = mongo.getDB("vidico").getCollection("users"); }
From source file:com.wincere.lamda.storm.bolt.CreateTable.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args//from w w w . j a v a 2 s . c o m * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public void update(BasicDBObject doc, OutputCollector collector, Tuple input) throws UnknownHostException { // connect to the local database server MongoCredential credential = MongoCredential.createMongoCRCredential("superuser", "admin", "12345678".toCharArray()); try { MongoClient mongoClient = new MongoClient(new ServerAddress("172.16.1.171", 27017), Arrays.asList(credential)); // MongoClient mongoClient = new MongoClient("172.16.1.171",27017); /* // Authenticate - optional MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password); MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential)); */ // get handle to "mydb" DB db = mongoClient.getDB("UCAPBatchTest"); // get a collection object to work with DBCollection coll = db.getCollection("Queries1"); // DBCollection status = db.getCollection("statustest1"); //DBCollection coll1 = db.getCollection("queryaudittest1"); // drop all the data in it //coll.drop(); //status.drop(); //coll1.drop(); /* status.insert(new BasicDBObject().append("queryStatus", "Open").append("QueryStatusID","1")); status.insert(new BasicDBObject().append("queryStatus", "Answered").append("QueryStatusID","2")); status.insert(new BasicDBObject().append("queryStatus", "Closed").append("QueryStatusID","3")); status.insert(new BasicDBObject().append("queryStatus", "Cancelled").append("QueryStatusID","4")); */ // make a document and insert it int count = 0; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"); try { //.equals("Open")?"1":(splitValue[5].equals("Answered")?"2":"3") BasicDBObject searchQuery = new BasicDBObject().append("queryRepeatKey", (String) doc.get("queryRepeatKey")); BasicDBObject newDocument = new BasicDBObject(); DBCursor cursor = coll.find(searchQuery); //DBObject result = cursor.next(); if (cursor.hasNext()) { DBObject result = cursor.next(); String queryValue = (String) result.get("queryValue"); String queryStatusID = (String) result.get("queryStatusID"); String queryResponse = (String) result.get("queryResponse"); String queryResolvedTimeStamp = (String) result.get("queryResolvedTimeStamp"); String queryAnsweredTimeStamp = (String) result.get("queryAnsweredTimeStamp"); String queryCreatedTimeStamp = (String) result.get("queryCreatedTimeStamp"); if (doc.get("queryValue").equals("\\N")) { doc.append("queryValue", queryValue); } if (doc.get("queryStatusID").equals("\\N")) { doc.append("queryStatusID", queryStatusID); } if (doc.get("queryResponse").equals("\\N")) { doc.append("queryResponse", queryResponse); } if (doc.get("queryResolvedTimeStamp").equals("\\N")) { doc.append("queryResolvedTimeStamp", queryResolvedTimeStamp); } if (doc.get("queryAnsweredTimeStamp").equals("\\N")) { doc.append("queryAnsweredTimeStamp", queryAnsweredTimeStamp); } doc.append("queryCreatedTimeStamp", queryCreatedTimeStamp); } if (doc.get("queryStatusID").equals("Open")) doc.append("queryCreatedTimeStamp", doc.get("queryCreatedTimeStamp")); //System.out.println(count); newDocument.append("$set", doc); try { coll.update(searchQuery, newDocument, true, true); } catch (MongoException me) { collector.fail(input); } // collector.ack(input); //coll.insert(doc); } catch (Exception e) { System.err.println("CSV file cannot be read : " + e); } //System.out.println(count); // lets get all the documents in the collection and print them out /*DBCursor cursor = coll1.find(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); }*/ /* // now use a query to get 1 document out BasicDBObject query = new BasicDBObject("i", 71); cursor = coll.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); }*/ // release resources //db.dropDatabase(); mongoClient.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.zjy.mongo.splitter.StandaloneMongoSplitter.java
License:Apache License
@Override public List<InputSplit> calculateSplits() throws SplitFailedException { final DBObject splitKey = MongoConfigUtil.getInputSplitKey(getConfiguration()); final DBObject splitKeyMax = MongoConfigUtil.getMaxSplitKey(getConfiguration()); final DBObject splitKeyMin = MongoConfigUtil.getMinSplitKey(getConfiguration()); final int splitSize = MongoConfigUtil.getSplitSize(getConfiguration()); final MongoClientURI inputURI; DBCollection inputCollection = null; final ArrayList<InputSplit> returnVal; try {//from w w w .j a va2s . c o m inputURI = MongoConfigUtil.getInputURI(getConfiguration()); MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration()); if (authURI != null) { inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI); } else { inputCollection = MongoConfigUtil.getCollection(inputURI); } returnVal = new ArrayList<InputSplit>(); final String ns = inputCollection.getFullName(); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Running splitVector on namespace: %s.%s; hosts: %s", inputURI.getDatabase(), inputURI.getCollection(), inputURI.getHosts())); } final DBObject cmd = BasicDBObjectBuilder.start("splitVector", ns).add("keyPattern", splitKey) .add("min", splitKeyMin).add("max", splitKeyMax) // force:True is misbehaving it seems .add("force", false).add("maxChunkSize", splitSize).get(); CommandResult data; boolean ok = true; try { data = inputCollection.getDB().getSisterDB(inputURI.getDatabase()).command(cmd, ReadPreference.primary()); } catch (final MongoException e) { // 2.0 servers throw exceptions rather than info in a CommandResult data = null; LOG.info(e.getMessage(), e); if (e.getMessage().contains("unrecognized command: splitVector")) { ok = false; } else { throw e; } } if (data != null) { if (data.containsField("$err")) { throw new SplitFailedException("Error calculating splits: " + data); } else if (!data.get("ok").equals(1.0)) { ok = false; } } if (!ok) { final CommandResult stats = inputCollection.getStats(); if (stats.containsField("primary")) { final DBCursor shards = inputCollection.getDB().getSisterDB("config").getCollection("shards") .find(new BasicDBObject("_id", stats.getString("primary"))); try { if (shards.hasNext()) { final DBObject shard = shards.next(); final String host = ((String) shard.get("host")).replace(shard.get("_id") + "/", ""); final MongoClientURI shardHost; if (authURI != null) { shardHost = new MongoClientURIBuilder(authURI).host(host).build(); } else { shardHost = new MongoClientURIBuilder(inputURI).host(host).build(); } MongoClient shardClient = null; try { shardClient = new MongoClient(shardHost); data = shardClient.getDB(shardHost.getDatabase()).command(cmd, ReadPreference.primary()); } catch (final Exception e) { LOG.error(e.getMessage(), e); } finally { if (shardClient != null) { shardClient.close(); } } } } finally { shards.close(); } } if (data != null && !data.get("ok").equals(1.0)) { throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg")); } } // Comes in a format where "min" and "max" are implicit // and each entry is just a boundary key; not ranged final BasicDBList splitData = (BasicDBList) data.get("splitKeys"); if (splitData.size() == 0) { LOG.warn( "WARNING: No Input Splits were calculated by the split code. Proceeding with a *single* split. Data may be too" + " small, try lowering 'mongo.input.split_size' if this is undesirable."); } BasicDBObject lastKey = null; // Lower boundary of the first min split // If splitKeyMin was given, use it as first boundary. if (!splitKeyMin.toMap().isEmpty()) { lastKey = new BasicDBObject(splitKeyMin.toMap()); } for (final Object aSplitData : splitData) { final BasicDBObject currentKey = (BasicDBObject) aSplitData; returnVal.add(createSplitFromBounds(lastKey, currentKey)); lastKey = currentKey; } BasicDBObject maxKey = null; // If splitKeyMax was given, use it as last boundary. if (!splitKeyMax.toMap().isEmpty()) { maxKey = new BasicDBObject(splitKeyMax.toMap()); } // Last max split final MongoInputSplit lastSplit = createSplitFromBounds(lastKey, maxKey); returnVal.add(lastSplit); } finally { if (inputCollection != null) { MongoConfigUtil.close(inputCollection.getDB().getMongo()); } } return returnVal; }
From source file:Controller.MongoDatabase.java
public MongoDatabase() throws UnknownHostException { MongoClient mongoClient = new MongoClient(); DB database = mongoClient.getDB("webimage"); collection = database.getCollection("users"); }