List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress(@Nullable final String host, final int port)
From source file:org.kantega.respiro.mongodb.driver.DefaultMongoDBBuilder.java
License:Apache License
@Override public Build mongodatabase(String addressList) { String[] addresses = addressList.split(","); List<ServerAddress> srvAddresses = new ArrayList<>(); for (String a : addresses) { String address[] = a.split(":"); if (address.length < 2) throw new RuntimeException( String.format("Server address cannot be split into host and port '%s', a")); srvAddresses.add(new ServerAddress(address[0], Integer.valueOf(address[1]))); }/*from w ww. ja va2s . co m*/ return mongodatabase(srvAddresses); }
From source file:org.log4mongo.MongoDbAppender.java
License:Apache License
/** * Returns a List of ServerAddress objects for each host specified in the hostname property. * Returns an empty list if configuration is detected to be invalid, e.g.: * <ul>//from ww w. j av a2 s. co m * <li>Port property doesn't contain either one port or one port per host</li> * <li>After parsing port property to integers, there isn't either one port or one port per host * </li> * </ul> * * @param hostname * Blank space delimited hostnames * @param port * Blank space delimited ports. Must specify one port for all hosts or a port per * host. * * @return List of ServerAddresses to connect to */ private List<ServerAddress> getServerAddresses(String hostname, String port) { List<ServerAddress> addresses = new ArrayList<ServerAddress>(); String[] hosts = hostname.split(" "); String[] ports = port.split(" "); if (ports.length != 1 && ports.length != hosts.length) { errorHandler.error("MongoDB appender port property must contain one port or a port per host", null, ErrorCode.ADDRESS_PARSE_FAILURE); } else { List<Integer> portNums = getPortNumbers(ports); // Validate number of ports again after parsing if (portNums.size() != 1 && portNums.size() != hosts.length) { errorHandler.error("MongoDB appender port property must contain one port or a valid port per host", null, ErrorCode.ADDRESS_PARSE_FAILURE); } else { boolean onePort = (portNums.size() == 1); int i = 0; for (String host : hosts) { int portNum = (onePort) ? portNums.get(0) : portNums.get(i); addresses.add(new ServerAddress(host.trim(), portNum)); i++; } } } return addresses; }
From source file:org.mephi.griffin.actorcloud.storage.StorageActor.java
License:Apache License
@Override public void preStart() { logger.entering("StorageActor", "preStart"); String errors = ""; Config config = getContext().system().settings().config(); try {//from w w w .j a v a 2 s. c o m String host; int port; String login = null; String pass = null; try { host = config.getString("actorcloud.storage.host"); } catch (Missing ex) { host = "localhost"; } try { port = config.getInt("actorcloud.storage.port"); } catch (Missing ex) { port = 27017; } try { login = config.getString("actorcloud.storage.login"); pass = config.getString("actorcloud.storage.pass"); } catch (Missing ex) { if (login != null) throw ex; login = ""; pass = ""; } try { dbName = config.getString("actorcloud.storage.db"); } catch (Missing ex) { dbName = "actorcloud"; } if (!login.equals("")) client = new MongoClient(new ServerAddress(host, port), Arrays .asList(MongoCredential.createPlainCredential(login, "actorcloud", pass.toCharArray()))); else client = new MongoClient(new ServerAddress(host, port)); logger.logp(Level.FINER, "StorageActor", "preStart", "Connected to " + host + ":" + port); if (client != null) { db = client.getDB(dbName); DBCursor cursor = db.getCollection("clients").find(); boolean adminFound = false; if (cursor.count() != 0) { while (cursor.hasNext()) { DBObject doc = cursor.next(); if (doc.get("name") != null && doc.get("name").equals("admin")) { adminFound = true; break; } } } if (!adminFound) { MessageDigest md = MessageDigest.getInstance("SHA-512"); BasicDBObject doc = new BasicDBObject(); byte[] hash = md.digest(("admin").getBytes()); doc.append("name", "admin"); doc.append("hash", hash); doc.append("maxSessions", 1); doc.append("maxChilds", 0); doc.append("messageHandlers", new ArrayList<>()); doc.append("childHandlers", new ArrayList<>()); db.getCollection("clients").insert(doc); } InitSuccess msg = new InitSuccess(InitSuccess.STORAGE, null, null, 0); logger.logp(Level.FINER, "StorageActor", "preStart", "InitSuccess -> Manager: " + msg); nodeManager.tell(msg, getSelf()); logger.logp(Level.INFO, "StorageActor", "preStart", "Storage started"); } else { InitFail msg = new InitFail(InitFail.STORAGE, null, null, 0, errors); logger.logp(Level.FINER, "StorageActor", "preStart", "InitFail -> Manager: " + msg); nodeManager.tell(msg, getSelf()); logger.logp(Level.WARNING, "StorageActor", "preStart", "Failed to connect to DB:\n" + errors); getContext().stop(getSelf()); } } catch (MongoException | UnknownHostException | NoSuchAlgorithmException e) { logger.throwing("StorageActor", "preStart", e); errors += e.getMessage() + "\n"; InitFail msg = new InitFail(InitFail.STORAGE, null, null, 0, errors); logger.logp(Level.FINER, "StorageActor", "preStart", "InitFail -> Manager: " + msg); nodeManager.tell(msg, getSelf()); logger.logp(Level.WARNING, "StorageActor", "preStart", "Failed to connect to DB:\n" + errors); getContext().stop(getSelf()); } logger.exiting("StorageActor", "preStart"); }
From source file:org.modeshape.jcr.value.binary.MongodbBinaryStore.java
License:Apache License
/** * Converts list of addresses specified in text format to mongodb specific address. * /* w w w .j a v a2s . com*/ * @param addresses list of addresses in text format * @return list of mongodb addresses * @throws UnknownHostException when at least one host is unknown * @throws IllegalArgumentException if address has bad format */ private List<ServerAddress> replicaSet(Set<String> addresses) throws UnknownHostException { List<ServerAddress> list = new ArrayList<ServerAddress>(); for (String address : addresses) { // address has format <host:port> String[] tokens = address.split(":"); // checking tokens number after split if (tokens.length != 2) { throw new IllegalArgumentException("Wrong address format: " + address); } String host = tokens[0]; // convert port number int port; try { port = Integer.parseInt(tokens[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Wrong address format: " + address); } list.add(new ServerAddress(host, port)); } return list; }
From source file:org.mongodb.demos.replication.RetryDemo.java
License:Apache License
public static void main(String args[]) throws Exception { //TODO : See https://gist.github.com/tgrall/954aa021ba420639d614 MongoClient client = new MongoClient( Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018))); DB db = client.getDB("jug"); DBCollection coll = db.getCollection("bar"); System.out.println("BEFORE"); boolean loop = true; while (loop) { int backoff = 0, counter = 0; DBObject obj = null;// w w w. j a v a 2 s .co m do { try { obj = BasicDBObjectBuilder.start().add("name", "mydoc").add("counter", counter++).get(); //System.out.print("\t inserting..."); coll.insert(obj, new WriteConcern(2, 3000, true, false)); backoff = 0; // System.out.println(" OK : Document inserted..."); } catch (Exception e) { System.out.println(e.toString()); if (backoff == 3) { throw new Exception("Tried 3 times... still failed"); } backoff++; System.out.println("Waiting for " + backoff + "s"); Thread.sleep(1500 * backoff); } } while (backoff != 0); } System.out.println("AFTER"); }
From source file:org.mongolink.ConfigProperties.java
License:Open Source License
public Settings addSettings(Settings settings) { ArrayList<MongoCredential> credentials = Lists.newArrayList(); if (!Strings.isNullOrEmpty(getDBUser())) { MongoCredential credential = MongoCredential.createCredential(getDBUser(), "test", getDBPassword().toCharArray()); credentials.add(credential);//from w w w.jav a 2 s. com } MongoClient mongoClient = new MongoClient(new ServerAddress(getDBHost(), getDBPort()), credentials); return settings.withClient(mongoClient).withDbName("test"); }
From source file:org.mongolink.example.web.configuration.MongoConfiguration.java
License:Open Source License
private MongoConfiguration() { ContextBuilder builder = new ContextBuilder("org.mongolink.example.persistence.mapping"); try {/* w w w . j a v a 2 s.c o m*/ Settings settings = Settings.defaultInstance().withDefaultUpdateStrategy(UpdateStrategies.DIFF) .withDbName("wordarena").withAddresses(Lists.newArrayList(new ServerAddress("host", 7689))) .withAuthentication("user", "passwd"); manager = MongoSessionManager.create(builder, settings); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.mongolink.Settings.java
License:Open Source License
private static ServerAddress serverAddress(String host, int port) { try {/* ww w. j av a2 s. c om*/ return new ServerAddress(host, port); } catch (UnknownHostException e) { throw new MongoLinkError(e); } }
From source file:org.mule.modules.morphia.MorphiaConnector.java
License:Open Source License
/** * Construct a new instance of Morphia/* w w w .j av a 2s. c o m*/ */ @PostConstruct public void init() throws ClassNotFoundException { this.mongoCache = CacheBuilder.newBuilder().maximumSize(10).build(new CacheLoader<MongoCacheKey, Mongo>() { public Mongo load(MongoCacheKey cacheKey) { return new Mongo(cacheKey.getSeeds(), cacheKey.getOptions()); } }); this.datastoreCache = CacheBuilder.newBuilder().maximumSize(50) .build(new CacheLoader<MorphiaCacheKey, Datastore>() { private Morphia morphia; @Override public Datastore load(MorphiaCacheKey morphiaCacheKey) throws Exception { initMorphia(); List<ServerAddress> seeds = getSeeds(morphiaCacheKey.getHost(), morphiaCacheKey.getPort()); MongoCacheKey mongoCacheKey = new MongoCacheKey(seeds, getMongoOptions()); Mongo mongo = mongoCache.get(mongoCacheKey); Datastore datastore = this.morphia.createDatastore(mongo, morphiaCacheKey.getDatabase(), morphiaCacheKey.getUsername(), morphiaCacheKey.getPassword().toCharArray()); datastore.ensureIndexes(ensureIndexesOnBackground); datastore.ensureCaps(); return datastore; } private void initMorphia() throws ClassNotFoundException { if (morphia == null) { morphia = new Morphia(); if (classes != null) { for (String className : classes) { this.morphia.map(Class.forName(className)); } } if (packages != null) { for (String packageName : packages) { this.morphia.mapPackage(packageName, ignoreInvalidClasses); } } } } private List<ServerAddress> getSeeds(String host, int port) throws UnknownHostException { List<ServerAddress> seeds = new ArrayList<ServerAddress>(); if (host.indexOf(',') != -1) { StringTokenizer tokenizer = new StringTokenizer(host, ","); while (tokenizer.hasMoreTokens()) { seeds.add(new ServerAddress(tokenizer.nextToken(), port)); } } else { seeds.add(new ServerAddress(host, port)); } return seeds; } private MongoOptions getMongoOptions() { MongoOptions options = new MongoOptions(); if (connectionsPerHost != null) options.connectionsPerHost = connectionsPerHost; if (threadsAllowedToBlockForConnectionMultiplier != null) options.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; if (maxWaitTime != null) options.maxWaitTime = maxWaitTime; if (connectTimeout != null) options.connectTimeout = connectTimeout; if (socketTimeout != null) options.socketTimeout = socketTimeout; if (autoConnectRetry != null) options.autoConnectRetry = autoConnectRetry; if (slaveOk != null) options.slaveOk = slaveOk; if (safe != null) options.safe = safe; if (w != null) options.w = w; if (wtimeout != null) options.wtimeout = wtimeout; if (fsync != null) options.fsync = fsync; return options; } }); }
From source file:org.opencb.cellbase.mongodb.serializer.CellBaseMongoDBSerializer.java
License:Apache License
public void init() throws UnknownHostException { ServerAddress serverAddres = new ServerAddress(host, port); if (this.user != null) { mongoClient = new MongoClient(serverAddres, Arrays.asList(MongoCredential.createMongoCRCredential(user, database, password))); } else {/* w w w . ja v a 2 s. c o m*/ mongoClient = new MongoClient(serverAddres); } db = mongoClient.getDB(database); // TODO: mongo clients options, like write concern jsonObjectMapper = new ObjectMapper(); jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); }