List of usage examples for com.mongodb MongoClientOptions builder
public static Builder builder()
From source file:org.wso2.carbon.dataservices.core.description.config.MongoConfig.java
License:Open Source License
private MongoClientOptions extractMongoOptions(Map<String, String> properties) { MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); String connectionsPerHost = properties.get(DBConstants.MongoDB.CONNECTIONS_PER_HOST); if (!DBUtils.isEmptyString(connectionsPerHost)) { builder.connectionsPerHost(Integer.parseInt(connectionsPerHost)); }// w w w.j a va 2 s . com String maxWaitTime = properties.get(DBConstants.MongoDB.MAX_WAIT_TIME); if (!DBUtils.isEmptyString(maxWaitTime)) { builder.maxWaitTime(Integer.parseInt(maxWaitTime)); } String connectTimeout = properties.get(DBConstants.MongoDB.CONNECT_TIMEOUT); if (!DBUtils.isEmptyString(connectTimeout)) { builder.connectTimeout(Integer.parseInt(connectTimeout)); } String socketTimeout = properties.get(DBConstants.MongoDB.SOCKET_TIMEOUT); if (!DBUtils.isEmptyString(socketTimeout)) { builder.socketTimeout(Integer.parseInt(socketTimeout)); } String threadsAllowedToBlockForConnectionMultiplier = properties .get(DBConstants.MongoDB.THREADS_ALLOWED_TO_BLOCK_CONN_MULTIPLIER); if (!DBUtils.isEmptyString(threadsAllowedToBlockForConnectionMultiplier)) { builder.threadsAllowedToBlockForConnectionMultiplier( Integer.parseInt(threadsAllowedToBlockForConnectionMultiplier)); } return builder.build(); }
From source file:org.wso2.carbon.datasource.reader.mongo.MongoDataSourceReaderUtil.java
License:Open Source License
public static MongoClient loadConfiguration(String xmlConfiguration) throws DataSourceException { ByteArrayInputStream baos = null; try {//w w w . j a va2 s . c om xmlConfiguration = CarbonUtils.replaceSystemVariablesInXml(xmlConfiguration); JAXBContext ctx = JAXBContext.newInstance(MongoDataSourceConfiguration.class); baos = new ByteArrayInputStream(xmlConfiguration.getBytes()); MongoDataSourceConfiguration fileConfig = (MongoDataSourceConfiguration) ctx.createUnmarshaller() .unmarshal(baos); MongoClient result = null; MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (fileConfig.getUrl() != null) { if (fileConfig.getSslInvalidHostNameAllowed() != null) { builder.sslInvalidHostNameAllowed(fileConfig.getSslInvalidHostNameAllowed()); } MongoClientURI uri = new MongoClientURI(fileConfig.getUrl(), builder); result = new MongoClient(uri); } else { List<ServerAddress> addressList = new ArrayList<ServerAddress>(); if (fileConfig.getReplicaSetConfig() != null) { ServerAddress address1 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost1(), Integer.parseInt(fileConfig.getReplicaSetConfig().getPort1())); addressList.add(address1); if (fileConfig.getReplicaSetConfig().getHost2() != null && fileConfig.getReplicaSetConfig().getPort2() != null) { ServerAddress address2 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost2(), Integer.parseInt(fileConfig.getReplicaSetConfig().getPort2())); addressList.add(address2); } if (fileConfig.getReplicaSetConfig().getHost3() != null && fileConfig.getReplicaSetConfig().getPort3() != null) { ServerAddress address3 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost3(), Integer.parseInt(fileConfig.getReplicaSetConfig().getPort3())); addressList.add(address3); } } else { ServerAddress address = new ServerAddress(fileConfig.getHost(), Integer.parseInt(fileConfig.getPort())); addressList.add(address); } MongoCredential credential = null; if (fileConfig.getWithSSL() != null) { builder.sslEnabled(fileConfig.getWithSSL()); } if (fileConfig.getSslInvalidHostNameAllowed() != null) { builder.sslInvalidHostNameAllowed(fileConfig.getSslInvalidHostNameAllowed()); } if (fileConfig.getAuthenticationMethodEnum() != null && fileConfig.getUsername() != null) { credential = createCredentials(fileConfig); } if (credential != null) { result = new MongoClient(addressList, Arrays.asList(new MongoCredential[] { credential }), builder.build()); } else { result = new MongoClient(addressList, builder.build()); } } return result; } catch (Exception e) { throw new DataSourceException("Error loading Mongo Datasource configuration: " + e.getMessage(), e); } finally { if (baos != null) { try { baos.close(); } catch (IOException ignore) { // ignore } } } }
From source file:org.wso2.extension.siddhi.store.mongodb.MongoDBEventTable.java
License:Open Source License
/** * Method for initializing mongoClientURI and database name. * * @param storeAnnotation the source annotation which contains the needed parameters. * @param configReader {@link ConfigReader} ConfigurationReader. * @throws MongoTableException when store annotation does not contain mongodb.uri or contains an illegal * argument for mongodb.uri *//*w w w .j ava2 s.c o m*/ private void initializeConnectionParameters(Annotation storeAnnotation, ConfigReader configReader) { String mongoClientURI = storeAnnotation.getElement(MongoTableConstants.ANNOTATION_ELEMENT_URI); if (mongoClientURI != null) { MongoClientOptions.Builder mongoClientOptionsBuilder = MongoTableUtils .extractMongoClientOptionsBuilder(storeAnnotation, configReader); try { this.mongoClientURI = new MongoClientURI(mongoClientURI, mongoClientOptionsBuilder); this.databaseName = this.mongoClientURI.getDatabase(); } catch (IllegalArgumentException e) { throw new SiddhiAppCreationException("Annotation '" + storeAnnotation.getName() + "' contains " + "illegal value for 'mongodb.uri' as '" + mongoClientURI + "'. Please check your query and " + "try again.", e); } } else { throw new SiddhiAppCreationException("Annotation '" + storeAnnotation.getName() + "' must contain the element 'mongodb.uri'. Please check your query and try again."); } }
From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java
License:Open Source License
/** * Utility method which can be used to create MongoClientOptionsBuilder from values defined in the * deployment yaml file.// www. j ava 2 s .c o m * * @param storeAnnotation the source annotation which contains the needed parameters. * @param configReader {@link ConfigReader} Configuration Reader * @return MongoClientOptions.Builder */ public static MongoClientOptions.Builder extractMongoClientOptionsBuilder(Annotation storeAnnotation, ConfigReader configReader) { MongoClientOptions.Builder mongoClientOptionsBuilder = MongoClientOptions.builder(); try { mongoClientOptionsBuilder.connectionsPerHost( Integer.parseInt(configReader.readConfig(MongoTableConstants.CONNECTIONS_PER_HOST, "100"))); mongoClientOptionsBuilder.connectTimeout( Integer.parseInt(configReader.readConfig(MongoTableConstants.CONNECT_TIMEOUT, "10000"))); mongoClientOptionsBuilder.heartbeatConnectTimeout(Integer .parseInt(configReader.readConfig(MongoTableConstants.HEARTBEAT_CONNECT_TIMEOUT, "20000"))); mongoClientOptionsBuilder.heartbeatSocketTimeout(Integer .parseInt(configReader.readConfig(MongoTableConstants.HEARTBEAT_SOCKET_TIMEOUT, "20000"))); mongoClientOptionsBuilder.heartbeatFrequency( Integer.parseInt(configReader.readConfig(MongoTableConstants.HEARTBEAT_FREQUENCY, "10000"))); mongoClientOptionsBuilder.localThreshold( Integer.parseInt(configReader.readConfig(MongoTableConstants.LOCAL_THRESHOLD, "15"))); mongoClientOptionsBuilder.maxWaitTime( Integer.parseInt(configReader.readConfig(MongoTableConstants.MAX_WAIT_TIME, "120000"))); mongoClientOptionsBuilder.minConnectionsPerHost( Integer.parseInt(configReader.readConfig(MongoTableConstants.MIN_CONNECTIONS_PER_HOST, "0"))); mongoClientOptionsBuilder.minHeartbeatFrequency( Integer.parseInt(configReader.readConfig(MongoTableConstants.MIN_HEARTBEAT_FREQUENCY, "500"))); mongoClientOptionsBuilder.serverSelectionTimeout(Integer .parseInt(configReader.readConfig(MongoTableConstants.SERVER_SELECTION_TIMEOUT, "30000"))); mongoClientOptionsBuilder.socketTimeout( Integer.parseInt(configReader.readConfig(MongoTableConstants.SOCKET_TIMEOUT, "0"))); mongoClientOptionsBuilder.threadsAllowedToBlockForConnectionMultiplier( Integer.parseInt(configReader.readConfig(MongoTableConstants.THREADS_ALLOWED_TO_BLOCK, "5"))); mongoClientOptionsBuilder.socketKeepAlive( Boolean.parseBoolean(configReader.readConfig(MongoTableConstants.SOCKET_KEEP_ALIVE, "false"))); mongoClientOptionsBuilder.sslEnabled( Boolean.parseBoolean(configReader.readConfig(MongoTableConstants.SSL_ENABLED, "false"))); mongoClientOptionsBuilder.cursorFinalizerEnabled(Boolean .parseBoolean(configReader.readConfig(MongoTableConstants.CURSOR_FINALIZER_ENABLED, "true"))); mongoClientOptionsBuilder.readPreference(ReadPreference .valueOf(configReader.readConfig(MongoTableConstants.READ_PREFERENCE, "primary"))); mongoClientOptionsBuilder.writeConcern(WriteConcern .valueOf(configReader.readConfig(MongoTableConstants.WRITE_CONCERN, "acknowledged"))); String readConcern = configReader.readConfig(MongoTableConstants.READ_CONCERN, "DEFAULT"); if (!readConcern.matches("DEFAULT")) { mongoClientOptionsBuilder.readConcern(new ReadConcern(ReadConcernLevel.fromString(readConcern))); } int maxConnectionIdleTime = Integer .parseInt(configReader.readConfig(MongoTableConstants.MAX_CONNECTION_IDLE_TIME, "0")); if (maxConnectionIdleTime != 0) { mongoClientOptionsBuilder.maxConnectionIdleTime(maxConnectionIdleTime); } int maxConnectionLifeTime = Integer .parseInt(configReader.readConfig(MongoTableConstants.MAX_CONNECTION_LIFE_TIME, "0")); if (maxConnectionIdleTime != 0) { mongoClientOptionsBuilder.maxConnectionLifeTime(maxConnectionLifeTime); } String requiredReplicaSetName = configReader.readConfig(MongoTableConstants.REQUIRED_REPLICA_SET_NAME, ""); if (!requiredReplicaSetName.equals("")) { mongoClientOptionsBuilder.requiredReplicaSetName(requiredReplicaSetName); } String applicationName = configReader.readConfig(MongoTableConstants.APPLICATION_NAME, ""); if (!applicationName.equals("")) { mongoClientOptionsBuilder.applicationName(applicationName); } String secureConnectionEnabled = storeAnnotation .getElement(MongoTableConstants.ANNOTATION_ELEMENT_SECURE_CONNECTION); secureConnectionEnabled = secureConnectionEnabled == null ? "false" : secureConnectionEnabled; if (secureConnectionEnabled.equalsIgnoreCase("true")) { mongoClientOptionsBuilder.sslEnabled(true); String trustStore = storeAnnotation.getElement(MongoTableConstants.ANNOTATION_ELEMENT_TRUSTSTORE); trustStore = trustStore == null ? configReader.readConfig("trustStore", DEFAULT_TRUST_STORE_FILE) : trustStore; trustStore = resolveCarbonHome(trustStore); String trustStorePassword = storeAnnotation .getElement(MongoTableConstants.ANNOTATION_ELEMENT_TRUSTSTOREPASS); trustStorePassword = trustStorePassword == null ? configReader.readConfig("trustStorePassword", DEFAULT_TRUST_STORE_PASSWORD) : trustStorePassword; String keyStore = storeAnnotation.getElement(MongoTableConstants.ANNOTATION_ELEMENT_KEYSTORE); keyStore = keyStore == null ? configReader.readConfig("keyStore", DEFAULT_KEY_STORE_FILE) : keyStore; keyStore = resolveCarbonHome(keyStore); String keyStorePassword = storeAnnotation .getElement(MongoTableConstants.ANNOTATION_ELEMENT_STOREPASS); keyStorePassword = keyStorePassword == null ? configReader.readConfig("keyStorePassword", DEFAULT_KEY_STORE_PASSWORD) : keyStorePassword; mongoClientOptionsBuilder.socketFactory(MongoTableUtils.extractSocketFactory(trustStore, trustStorePassword, keyStore, keyStorePassword)); } return mongoClientOptionsBuilder; } catch (IllegalArgumentException e) { throw new MongoTableException("Values Read from config readers have illegal values : ", e); } }
From source file:org.z.core.es.plugins.memorystore.MongodbUtils.java
License:Apache License
@SuppressWarnings("deprecation") private static MongoClientOptions getClientOptions() { MongoClientOptions mongoClientOptions = null; try {//from ww w . j av a 2 s.c o m Builder builder = null; builder = MongoClientOptions.builder(); builder.autoConnectRetry(true); builder.connectionsPerHost(100); builder.threadsAllowedToBlockForConnectionMultiplier(50); builder.maxWaitTime(10000); builder.connectTimeout(3000); mongoClientOptions = builder.build(); } catch (Exception e) { e.printStackTrace(); } return mongoClientOptions; }
From source file:parlare.application.server.model.Database.java
private void doConnectionMongo() { try {/* ww w. jav a 2 s. c o m*/ System.out.println("MONGO server: " + server); System.out.println("MONGO user: " + user); System.out.println("MONGO source: " + source); System.out.println(); MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())), new MongoClientOptions.Builder().build()); DB testDB = mongoClient.getDB("html5apps"); System.out.println("Count: " + testDB.getCollection("html5apps").count()); System.out.println("Insert result: " + testDB.getCollection("html5apps").insert(new BasicDBObject())); } catch (UnknownHostException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:parlare.application.server.model.Database.java
private String doClientMongo() { String print = ""; System.out.println("User:" + user + " Source:" + source + " Password:" + password); try {//from w w w.j a v a 2 s . c o m // connect to the local database server MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())), new MongoClientOptions.Builder().build()); // get handle to "mydb" DB db = mongoClient.getDB("html5apps"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get a list of the collections in this database and print them out Set<String> collectionNames = db.getCollectionNames(); for (String s : collectionNames) { System.out.println(s); } // get a collection object to work with DBCollection testCollection = db.getCollection("testCollection"); // drop all the data in it testCollection.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); testCollection.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = testCollection.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { testCollection.insert(new BasicDBObject().append("i", i)); } System.out.println("total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount()); // lets get all the documents in the collection and print them out DBCursor cursor = testCollection.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 = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a range query to get a larger subset query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println("Cursor: " + cursor.next()); } } finally { cursor.close(); } // range query with multiple constraints query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // create an index on the "i" field testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = testCollection.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); // release resources mongoClient.close(); } catch (UnknownHostException ex) { Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); } return print; }
From source file:piecework.config.MongoConfiguration.java
License:Educational Community License
@Bean @Primary/*from ww w . j ava 2 s .co m*/ public Mongo mongo() throws Exception { if (environment.acceptsProfiles("embedded-mongo")) { mongoInstance = embeddedMongo(); mongoInstance.startEmbeddedMongo(); mongoInstance.importData(); return new MongoClient(Collections.singletonList(new ServerAddress("127.0.0.1", 37017))); } MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder(); if (environment.getProperty("mongo.use.ssl", Boolean.class, Boolean.FALSE)) optionsBuilder.socketFactory(SSLSocketFactory.getDefault()); return new MongoClient(getServerAddresses(), optionsBuilder.build()); }
From source file:simple.crawler.impl.PrototypeScheduler.java
License:Open Source License
public static void main(String[] args) throws Exception { CrawlerConfiguration config = new CrawlerConfiguration("http://congdongjava.com/forum/", "HTML/BODY[1]/DIV[@id='headerMover']/DIV[@id='content']/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[3]/H1[1]", "HTML/BODY[1]/DIV[@id='headerMover']/DIV[@id='content']/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[3]/H1[1]", "^forums/[a-zA-Z0-9-%]+\\.[0-9]+/(page-[0-9]+)?", "^threads/[a-zA-Z0-9-%]+\\.[0-9]+/(page-[0-9]+)?", true);/*from w ww . j a v a 2 s .co m*/ CrawlerImpl crawler = new CrawlerImpl(config, 10, new ServerAddress("localhost"), new MongoClientOptions.Builder().build()); crawler.schedule(1, 60 * 60, TimeUnit.SECONDS); crawler.start(); }
From source file:simple.crawler.mongo.CrawlingDB.java
License:Open Source License
public CrawlingDB(String dbName) throws UnknownHostException { this.dbName = dbName; ServerAddress address = new ServerAddress("localhost"); MongoClientOptions options = new MongoClientOptions.Builder().build(); this.client = new MongoClient(address, options); }