List of usage examples for com.mongodb MongoClient MongoClient
public MongoClient(final MongoClientURI uri)
From source file:com.hipstogram.rest.HistogramMongoDBResource.java
License:Apache License
/** * Create a new instance of this class/*from w w w .ja va 2 s .c o m*/ */ public HistogramMongoDBResource() { // MongoDB MongoDBSection mongoDBSection = HipstogramContext.getInstance().getConfiguration().getMongoSection(); try { mongo = new MongoClient(new ServerAddress(mongoDBSection.host)); } catch (UnknownHostException e) { e.printStackTrace(); } // Morphia Morphia morphia = new Morphia(); morphia.map(TrackCount.class); ds = morphia.createDatastore(mongo, "test"); // Gson gson = new Gson(); }
From source file:com.hurence.logisland.service.mongodb.AbstractMongoDBControllerService.java
License:Apache License
protected final void createClient(ControllerServiceInitializationContext context) throws IOException { if (mongoClient != null) { closeClient();/*from w w w.jav a 2s .c o m*/ } getLogger().info("Creating MongoClient"); // Set up the client for secure (SSL/TLS communications) if configured to do so /*final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class); final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();*/ final SSLContext sslContext = null; /* if (sslService != null) { final SSLContextService.ClientAuth clientAuth; if (StringUtils.isBlank(rawClientAuth)) { clientAuth = SSLContextService.ClientAuth.REQUIRED; } else { try { clientAuth = SSLContextService.ClientAuth.valueOf(rawClientAuth); } catch (final IllegalArgumentException iae) { throw new ProviderCreationException(String.format("Unrecognized client auth '%s'. Possible values are [%s]", rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", "))); } } sslContext = sslService.createSSLContext(clientAuth); } else { sslContext = null; }*/ try { if (sslContext == null) { mongoClient = new MongoClient(new MongoClientURI(getURI(context))); } else { mongoClient = new MongoClient(new MongoClientURI(getURI(context), getClientOptions(sslContext))); } } catch (Exception e) { getLogger().error("Failed to schedule {} due to {}", new Object[] { this.getClass().getName(), e }, e); throw e; } }
From source file:com.hydadmin.utilities.SpringMongoConfig.java
public @Bean MongoDbFactory mongoDbFactory() throws Exception { // MongoClient mongo = new MongoClient("localhost"); // SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongo, "hmp"); MongoClient mongo = new MongoClient("198.15.127.150"); SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongo, "hmp"); // MongoClient mongo = new MongoClient("128.199.64.31"); // SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongo, "truckguru"); return simpleMongoDbFactory; }
From source file:com.ibm.haac.hx.engine.tool.mongodb.MongoDBAccess.java
License:Open Source License
public MongoDBAccess() throws Exception { try {//from ww w. jav a2 s . com if (mongoUri != null && !mongoUri.trim().equals("")) { System.out.println("Use mongo connection uri"); mongoUri = mongoUri.trim(); // http://stackoverflow.com/questions/15052074/connecting-a-mongodb-created-in-mongolab-through-a-java-application MongoClientURI uri = new MongoClientURI(mongoUri); this.mongoClient = new MongoClient(uri); int index = mongoUri.lastIndexOf("/"); dbName = mongoUri.substring(index + 1); } else { System.out.println("Use mongo database connection properties"); MongoCredential credential = MongoCredential.createMongoCRCredential(userName, dbName, pwd.toCharArray()); // connect to the server this.mongoClient = new MongoClient(new ServerAddress(serverIP, serverPort), Arrays.asList(credential)); } // attach to the database this.db = this.mongoClient.getDB(dbName); morphia = new Morphia(); if (morphiaDatastore == null) morphiaDatastore = morphia.createDatastore(this.mongoClient, dbName); ensureEntities(); this.mongoConnected = true; } catch (MongoException e) { throw new Exception("MongoDB exception: " + e.getMessage()); } catch (UnknownHostException e) { throw new Exception("MongoDB UnknownHostException exception: " + e.getMessage()); } }
From source file:com.ibm.research.mongotx.daytrader.Load.java
License:Open Source License
public static void main(String[] args) throws Exception { //MongoClient client = new MongoClient(new MongoClientURI("mongodb://admin:admin@ds043714.mongolab.com:43714/?authSource=trade&authMechanism=SCRAM-SHA-1")); MongoClient client = new MongoClient("localhost"); TxDatabase txDB = new LatestReadCommittedTxDB(client, client.getDatabase("trade")); dropCollections(txDB);// w ww .j a v a2 s . com populate(txDB); client.close(); }
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/* w w w . j a v a2s . c om*/ * @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.aleph2.shared.crud.mongodb.services.MongoDbCrudServiceFactory.java
License:Apache License
@Inject public MongoDbCrudServiceFactory(MongoDbConfigurationBean config) throws UnknownHostException { String mongo_config = Optional.ofNullable(config.mongodb_connection()).orElse("localhost:27017"); // Create a list of server addresses and connect String[] servers = mongo_config.split("\\s*,\\s*"); List<ServerAddress> server_list = Arrays.asList(servers).stream().map(a -> { try {/*from ww w . j a v a 2 s .c om*/ String[] server_and_port = a.split("\\s*:\\s*"); if (1 == server_and_port.length) { return new ServerAddress(a); } else { return new ServerAddress(server_and_port[0], Integer.decode(server_and_port[1])); } } catch (Exception e) { return (ServerAddress) null; } }).filter(sa -> null != sa).collect(Collectors.toList()); _mongo_client = new MongoClient(server_list); }
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();//from w w w .j av 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;//from w w w . jav a 2s. c om } // 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.images3.data.impl.MongoDBAccessProvider.java
License:Apache License
private void initMongoClient() { String url = config.getProperty("mongodb.url"); int port = Integer.valueOf(config.getProperty("mongodb.port")); String username = config.getProperty("mongodb.username"); String password = config.getProperty("mongodb.password"); try {/* ww w . j av a 2 s . co m*/ if (username.trim().length() == 0) { this.mongoClient = new MongoClient(new ServerAddress(url, port)); } else { MongoCredential credential = MongoCredential.createMongoCRCredential(username, DBNAME, password.toCharArray()); this.mongoClient = new MongoClient(new ServerAddress(url, port), Arrays.asList(credential)); } } catch (UnknownHostException e) { throw new RuntimeException(e); } }