List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:com.gmail.kunicins.olegs.gridfs_server.Server.java
License:Creative Commons License
/** * Initialize HTTP server//from w w w .j a v a 2 s . co m * * @param gridFSHost * @param gridFSPort * @param gridFSDB * @param httpPort * @param concurrentConnections */ public Server(String gridFSHost, int gridFSPort, String gridFSDB, int httpPort, int concurrentConnections) { try { // GridFS initialization MongoClient mongo = new MongoClient(gridFSHost, gridFSPort); this.gridFs = new GridFS(mongo.getDB(gridFSDB)); this.gridFsCollection = mongo.getDB(gridFSDB).getCollection("fs.chunks"); // HTTP initialization this.selector = SelectorProvider.provider().openSelector(); this.server = ServerSocketChannel.open(); this.server.configureBlocking(false); this.server.socket().bind(new InetSocketAddress(httpPort), concurrentConnections); this.server.register(this.selector, server.validOps()); System.out.println("Listening on *:" + httpPort + ", uses GridFS '" + gridFSDB + "' on " + gridFSHost + ":" + gridFSPort); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java
License:Apache License
/** * Main demo. This first initializes an Analytics service object. It then queries for the top 25 * organic search keywords and traffic sources by visits. Finally each important part of the * response is printed to the screen.//from ww w. j av a2 s.c om * * @param args command line args. */ public static void main(String[] args) { try { if (args.length == 2) { // Start and end date are supplied startDate = new SimpleDateFormat("yyyy-MM-dd").parse(args[0]); endDate = new SimpleDateFormat("yyyy-MM-dd").parse(args[1]); } System.out.println("Retrieving for dates " + startDate + " " + endDate); HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); Analytics analytics = initializeAnalytics(); MongoClient mongo = new MongoClient("localhost", 27017); DB regus_analytics_db = mongo.getDB("regus_analytics"); DBCollection regus_visited_companies = regus_analytics_db.getCollection("ga"); DBCollection regus_visit_attributes = regus_analytics_db.getCollection("visit_attrs"); DBCollection centerMapping = regus_analytics_db.getCollection("center_mapping"); GaData gaData; for (Date d = startDate; !DateUtils.isSameDay(d, DateUtils.addDays(endDate, 1)); d = DateUtils .addDays(d, 1)) { int startIndex = 0; do { System.out.println("Executing data query for visited companies for date: " + d); gaData = executeDataQueryForVisitedCompanies(analytics, TABLE_ID, startIndex, d); insertVisitedCompaniesData(gaData, regus_visited_companies, d); startIndex = gaData.getQuery().getStartIndex() + gaData.getQuery().getMaxResults(); } while (gaData.getNextLink() != null && !gaData.getNextLink().isEmpty()); startIndex = 0; do { System.out.println("Executing data query for visit attributes for date: " + d); gaData = executeDataQueryForVisitAttributes(analytics, TABLE_ID, startIndex, d); insertVisitAttributesData(gaData, regus_visit_attributes, d, centerMapping); startIndex = gaData.getQuery().getStartIndex() + gaData.getQuery().getMaxResults(); } while (gaData.getNextLink() != null && !gaData.getNextLink().isEmpty()); } } catch (GoogleJsonResponseException e) { System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.groupon.jenkins.mongo.MongoRepository.java
License:Open Source License
private DB getDB(MongoClient client) { return client.getDB(SetupConfig.get().getDbName()); }
From source file:com.heisenberg.mongo.MongoWorkflowEngine.java
License:Apache License
@Override protected void initializeStorageServices(WorkflowEngineConfiguration cfg) { MongoWorkflowEngineConfiguration configuration = (MongoWorkflowEngineConfiguration) cfg; JsonService jsonService = serviceRegistry.getService(JsonService.class); MongoClient mongoClient = new MongoClient(configuration.getServerAddresses(), configuration.getCredentials(), configuration.getOptionBuilder().build()); this.db = mongoClient.getDB(configuration.getDatabaseName()); configuration.registerService(db);//from ww w.ja va2 s. c om boolean isPretty = configuration.isPretty(); MongoWorkflowStore processDefinitions = new MongoWorkflowStore(serviceRegistry); processDefinitions.dbCollection = db.getCollection(configuration.getWorkflowsCollectionName()); processDefinitions.isPretty = isPretty; processDefinitions.fields = configuration.getProcessDefinitionFields(); processDefinitions.writeConcernInsertProcessDefinition = processDefinitions .getWriteConcern(configuration.getWriteConcernInsertProcessDefinition()); configuration.registerService(processDefinitions); MongoWorkflowInstanceStore workflowInstances = new MongoWorkflowInstanceStore(serviceRegistry); workflowInstances.dbCollection = db.getCollection(configuration.workflowInstancesCollectionName); workflowInstances.processEngine = this; workflowInstances.isPretty = isPretty; workflowInstances.fields = configuration.getProcessInstanceFields(); workflowInstances.writeConcernStoreProcessInstance = workflowInstances .getWriteConcern(configuration.getWriteConcernInsertProcessInstance()); workflowInstances.writeConcernFlushUpdates = workflowInstances .getWriteConcern(configuration.getWriteConcernFlushUpdates()); configuration.registerService(workflowInstances); // TODO // MongoTaskService mongoTaskService = new MongoTaskService(); configuration.registerService(new MemoryTaskService()); MongoJobs mongoJobs = new MongoJobs(serviceRegistry); DBCollection jobsDbCollection = db.getCollection(configuration.getJobsCollectionName()); mongoJobs.dbCollection = jobsDbCollection; mongoJobs.isPretty = configuration.isPretty(); mongoJobs.fields = configuration.getJobFields(); mongoJobs.writeConcernJobs = mongoJobs.getWriteConcern(configuration.getWriteConcernJobs()); mongoJobs.lockOwner = configuration.getId(); mongoJobs.jsonService = jsonService; configuration.registerService(mongoJobs); MongoJobService mongoJobService = new MongoJobService(serviceRegistry); mongoJobService.jobs = mongoJobs; configuration.registerService(mongoJobService); }
From source file:com.ibm.gaiandb.mongodb.MongoConnectionFactory.java
License:Open Source License
/** * Returns a handle to a Mongo DB object - which may be used to manage collections. * /*from w ww . j a v a 2s .co m*/ * @param connectionParams - object containing all the parameters needed to connect to MongoDB * @exception UnknownHostException - if we cannot connect to the mongoDB host specified * @exception AuthenticationException - if authentication with the mongoDB process fails. * */ public static DB getMongoDB(MongoConnectionParams connectionParams) throws Exception { // connect to the mongo process MongoClient mongoClient = new MongoClient(connectionParams.getHostAddress(), connectionParams.getHostPort()); if (mongoClient == null) throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_CONNECTION_ERROR); // Connect to the specific database DB mongoDb = mongoClient.getDB(connectionParams.getDatabaseName()); // TBD possibly try to reuse these. if (mongoDb == null) throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_DATABASE_CONN_ERROR); // Authenticate if the configuration parameters have been set String userName = connectionParams.getUserName(); String password = connectionParams.getPassword(); if (userName != null && password != null) { boolean authenticated = mongoDb.authenticate(userName, password.toCharArray()); if (!authenticated) { throw new AuthenticationException(MongoMessages.DSWRAPPER_MONGODB_AUTHENTICATION_ERROR); } } return mongoDb; }
From source file:com.ibm.ws.lars.testutils.RepositoryFixture.java
License:Apache License
/** * Get a database handle for the given host and dbName, retrieving it from the cache if it has * been requested previously or creating a new handle otherwise. * * @param host the server address to connect to * @param dbName the database name//from w w w . j a va 2 s.c o m * @return a handle to the database */ private static DB getDatabase(ServerAddress host, String dbName) { String key = host + "/" + dbName; if (cache == null) { cache = new HashMap<String, DB>(); } DB db = cache.get(key); if (db == null) { MongoClient client = new MongoClient(host); db = client.getDB(dbName); cache.put(key, db); } return db; }
From source file:com.ikanow.infinit.e.data_model.store.MongoDbManager.java
License:Apache License
@SuppressWarnings("deprecation") public static void main(String[] args) throws UnknownHostException { MongoClient mc = new MongoClient(args[0]); long tnow = 0; DB db = mc.getDB("test"); DBCollection test = db.getCollection("test123"); BasicDBObject outObj = new BasicDBObject(); int ITS = 1000; test.drop();/*w w w.j a v a2 s . c om*/ boolean checkPerformance = false; boolean checkFunctionality = false; boolean checkErrors = false; // 1] Performance if (checkPerformance) { // ack'd db.setWriteConcern(WriteConcern.ACKNOWLEDGED); test.drop(); tnow = new Date().getTime(); for (int i = 0; i < ITS; ++i) { outObj.remove("_id"); outObj.put("val", i); test.save(outObj); } tnow = new Date().getTime() - tnow; System.out.println("1: Ack'd: " + tnow); // un ack'd db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); test.drop(); tnow = new Date().getTime(); outObj = new BasicDBObject(); for (int i = 0; i < ITS; ++i) { outObj.remove("_id"); outObj.put("val", i); test.save(outObj); } tnow = new Date().getTime() - tnow; System.out.println("2: unAck'd: " + tnow); // un ack'd but call getLastError db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); test.drop(); tnow = new Date().getTime(); outObj = new BasicDBObject(); for (int i = 0; i < ITS; ++i) { outObj.remove("_id"); outObj.put("val", i); test.save(outObj); db.getLastError(); } tnow = new Date().getTime() - tnow; test.drop(); System.out.println("3: unAck'd but GLEd: " + tnow); // ack'd override db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); test.drop(); tnow = new Date().getTime(); outObj = new BasicDBObject(); for (int i = 0; i < ITS; ++i) { outObj.remove("_id"); outObj.put("val", i); test.save(outObj, WriteConcern.ACKNOWLEDGED); db.getLastError(); } tnow = new Date().getTime() - tnow; System.out.println("4: unAck'd but ACKd: " + tnow); // Performance Results: // 2.6) (unack'd 100ms ... ack'd 27000) // 2.4) (same) } // 2] Functionality if (checkFunctionality) { // Unack: db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); WriteResult wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val2", "x")), false, true); CommandResult cr = db.getLastError(); System.out.println("UNACK: wr: " + wr); System.out.println("UNACK: cr: " + cr); // bonus, check that we get N==0 when insert dup object WriteResult wr2 = test.insert(outObj); System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2); CommandResult cr2 = db.getLastError(); System.out.println("ACK cr2 = " + cr2); // Ack1: db.setWriteConcern(WriteConcern.ACKNOWLEDGED); wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val3", "x")), false, true); cr = db.getLastError(); System.out.println("ACK1: wr: " + wr); System.out.println("ACK1: cr: " + cr); // Ack2: db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val4", "x")), false, true, WriteConcern.ACKNOWLEDGED); cr = db.getLastError(); System.out.println("ACK2: wr: " + wr); System.out.println("ACK2: cr: " + cr); // bonus, check that we get N==0 when insert dup object wr2 = test.insert(outObj); System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2); // Functionality results: // 2.6: unack wr == N/A, otherwise both have "n", "ok" // 2.4: unack wr == N/A all other wrs + crs identical } if (checkErrors) { //set up sharding DbManager.getDB("admin").command(new BasicDBObject("enablesharding", "test")); // Ack: try { test.drop(); test.createIndex(new BasicDBObject("key", 1)); BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123"); command1.append("key", new BasicDBObject("key", 1)); DbManager.getDB("admin").command(command1); db.setWriteConcern(WriteConcern.ACKNOWLEDGED); outObj = new BasicDBObject("key", "test"); test.save(outObj); WriteResult wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2"))); System.out.println("ACK wr = " + wr); } catch (Exception e) { System.out.println("ACK err = " + e.toString()); } // UnAck: try { test.drop(); test.createIndex(new BasicDBObject("key", 1)); BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123"); command1.append("key", new BasicDBObject("key", 1)); DbManager.getDB("admin").command(command1); db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); outObj = new BasicDBObject("key", "test"); test.save(outObj); WriteResult wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")), false, false, WriteConcern.ACKNOWLEDGED); System.out.println("ACK override wr = " + wr); } catch (Exception e) { System.out.println("ACK override err = " + e.toString()); } // UnAck: try { test.drop(); test.createIndex(new BasicDBObject("key", 1)); BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123"); command1.append("key", new BasicDBObject("key", 1)); DbManager.getDB("admin").command(command1); db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); outObj = new BasicDBObject("key", "test"); test.save(outObj); WriteResult wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2"))); System.out.println("UNACK wr = " + wr); } catch (Exception e) { System.out.println("UNACK err = " + e.toString()); } // UnAck + GLE: try { test.drop(); test.createIndex(new BasicDBObject("key", 1)); BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123"); command1.append("key", new BasicDBObject("key", 1)); DbManager.getDB("admin").command(command1); db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); outObj = new BasicDBObject("key", "test"); test.save(outObj); WriteResult wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2"))); CommandResult cr = db.getLastError(); System.out.println("UNACK GLE wr = " + wr); System.out.println("UNACK GLE cr = " + cr); } catch (Exception e) { System.out.println("UNACK GLE err = " + e.toString()); } // Error handling: // 2.6: // Ack - exception // Ack override - exception // UnAck - no error given // UnAck + GLE - gle error // 2.4: // Ack - exception // Ack override - exception // UnAck - no error given // UnAck + GLE - gle error } }
From source file:com.ikanow.utility.GridFSRandomAccessFile.java
License:Open Source License
public static void main(String[] args) throws IOException { if (args.length < 4) { System.out.println("usage: GridFSRandomAccessFile mongoip db_name fs_name id"); return;/* ww w .jav a2s . c o m*/ } // Command line: MongoClient mongoClient = new MongoClient(args[0]); DB db = mongoClient.getDB(args[1]); String fsName = args[2]; ObjectId fileId = new ObjectId(args[3]); // Create zip: GridFSRandomAccessFile shareAsFile = new GridFSRandomAccessFile(db, fsName, fileId); net.sf.jazzlib.GridFSZipFile zipFile = new net.sf.jazzlib.GridFSZipFile("myfilename", shareAsFile); // Test logic: LinkedList<net.sf.jazzlib.ZipEntry> savedEntries = new LinkedList<net.sf.jazzlib.ZipEntry>(); @SuppressWarnings("unchecked") Enumeration<net.sf.jazzlib.ZipEntry> entries = zipFile.entries(); int nFilesToMatch = 0; while (entries.hasMoreElements()) { net.sf.jazzlib.ZipEntry zipInfo = entries.nextElement(); System.out.println("FILE: " + zipInfo.getName() + " , " + zipInfo.getSize()); savedEntries.add(zipInfo); nFilesToMatch++; } byte[] tmpBuffer = new byte[1024]; int nFilesMatched = 0; CRC32 crcGen = new CRC32(); for (net.sf.jazzlib.ZipEntry zipInfo : savedEntries) { InputStream inStream = zipFile.getInputStream(zipInfo); ByteArrayOutputStream out = new ByteArrayOutputStream(); int nRead = 0; while ((nRead = inStream.read(tmpBuffer)) != -1) out.write(tmpBuffer, 0, nRead); byte[] result = out.toByteArray(); if (zipInfo.getSize() != result.length) { System.out.println("FILE LEN MISMATCH: " + zipInfo.getName() + ": " + zipInfo.getSize() + " vs " + result.length); continue; } crcGen.reset(); crcGen.update(result); if (crcGen.getValue() != zipInfo.getCrc()) { System.out.println("FILE CRC MISMATCH: " + zipInfo.getName() + ": " + zipInfo.getSize() + " vs " + result.length); continue; } nFilesMatched++; out.close(); inStream.close(); } System.out.println("Successfully validated: " + nFilesMatched + " vs " + nFilesToMatch); }
From source file:com.imos.sample.MongoDBJDBC.java
public static void main(String args[]) { try {// ww w.j a v a 2 s . c om // To connect to mongodb server MongoClient mongoClient = new MongoClient("localhost", 27017); // Now connect to your databases DB db = mongoClient.getDB("test"); System.out.println("Connect to database successfully"); // boolean auth = db.authenticate(myUserName, myPassword); // System.out.println("Authentication: "+auth); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.impetus.client.mongodb.MongoDBClientFactory.java
License:Apache License
/** * Gets the connection./*from w ww .jav a 2 s . co m*/ * * @return the connection */ private DB getConnection() { PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata() .getPersistenceUnitMetadata(getPersistenceUnit()); Properties props = puMetadata.getProperties(); String contactNode = null; String defaultPort = null; String keyspace = null; String poolSize = null; if (externalProperties != null) { contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES); defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT); keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE); poolSize = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE); } if (contactNode == null) { contactNode = (String) props.get(PersistenceProperties.KUNDERA_NODES); } if (defaultPort == null) { defaultPort = (String) props.get(PersistenceProperties.KUNDERA_PORT); } if (keyspace == null) { keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE); } if (poolSize == null) { poolSize = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE); } onValidation(contactNode, defaultPort); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); MongoClient mongo = null; try { mongo = onSetMongoServerProperties(contactNode, defaultPort, poolSize, addrs); logger.info("Connected to mongodb at " + contactNode + " on port " + defaultPort); } catch (NumberFormatException e) { logger.error("Invalid format for MONGODB port, Unale to connect!" + "; Caused by:" + e.getMessage()); throw new ClientLoaderException(e); } catch (UnknownHostException e) { logger.error("Unable to connect to MONGODB at host " + contactNode + "; Caused by:" + e.getMessage()); throw new ClientLoaderException(e); } catch (MongoException e) { logger.error("Unable to connect to MONGODB; Caused by:" + e.getMessage()); throw new ClientLoaderException(e); } DB mongoDB = mongo.getDB(keyspace); try { MongoDBUtils.authenticate(props, externalProperties, mongoDB); } catch (ClientLoaderException e) { logger.error(e.getMessage()); throw e; } logger.info("Connected to mongodb at " + contactNode + " on port " + defaultPort); return mongoDB; }