Example usage for com.mongodb ServerAddress ServerAddress

List of usage examples for com.mongodb ServerAddress ServerAddress

Introduction

In this page you can find the example usage for com.mongodb ServerAddress ServerAddress.

Prototype

public ServerAddress(@Nullable final String host, final int port) 

Source Link

Document

Creates a ServerAddress

Usage

From source file:uk.ac.susx.tag.classificationframework.datastructures.CacheManager.java

License:Apache License

public CacheManager(String hostname, int port) throws UnknownHostException {
    this(new MongoClient(new ServerAddress(hostname, port)));
}

From source file:uk.gov.nationalarchives.discovery.taxonomy.common.config.mongo.MongoConfiguration.java

License:Mozilla Public License

private MongoClient getMongoClientForCategoriesDatabase() throws UnknownHostException {
    MongoClient client;//  w  w  w.  ja  v  a 2 s.c o m
    String[] splitHosts = categoriesHosts.split(",");
    String[] splitPorts = categoriesPorts.split(",");
    if (splitHosts.length > 1) {
        List<ServerAddress> listOfServerAddresses = new ArrayList<>();
        for (int i = 0; i < splitHosts.length; i++) {
            logger.info("mongo categories database: {}:{}/{}", splitHosts[i], splitPorts[i],
                    categoriesDatabase);
            listOfServerAddresses.add(new ServerAddress(splitHosts[i], Integer.valueOf(splitPorts[i])));
        }
        client = new MongoClient(listOfServerAddresses);
    } else {
        client = new MongoClient(categoriesHosts, Integer.valueOf(categoriesPorts));
    }
    return client;
}

From source file:us.daveread.education.mongo.honeypot.BasicStatistics.java

License:Open Source License

/**
 * Create the instance. This will populate the aggregate count of documents
 * (attacks) and countries.//  w w  w .j  av  a 2 s  . c om
 * @see #totalAttacks
 * @see #computeAttackCountryCount()
 */
public BasicStatistics() {
    LOG.info("Connecting to server: " + MONGO_DB_IP + ":" + MONGO_DB_PORT + " and database: "
            + HONEYPOT_DATABASE);

    /**
     * Set a short timeout for connecting so that we don't wait the default 30
     * seconds to detect a problem.
     */
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    optionsBuilder.serverSelectionTimeout(2000);

    MongoClientOptions options = optionsBuilder.build();

    /**
     * Create the MongoClient instance.
     */
    mongoClient = new MongoClient(new ServerAddress(MONGO_DB_IP, MONGO_DB_PORT), options);

    /**
     * Create the MongoDatabase instance.
     */
    mongoDatabase = mongoClient.getDatabase(HONEYPOT_DATABASE);

    /**
     * Get the MongoCollection instance which provides read and write access
     * (bed on permissions) to a specific collection in the database.
     */
    MongoCollection<Document> collection = accessCollection(HONEYPOT_COLLECTION);

    /**
     * Get the count of documents in the collection. If the collection cannot be
     * accessed an exception will the thrown.
     */
    try {
        totalAttacks = collection.count();
    } catch (Throwable throwable) {
        LOG.fatal("Unable to connect to the MongoDB instance at " + MONGO_DB_IP + ":" + MONGO_DB_PORT,
                throwable);
        throw new IllegalStateException("Unable to connect to the MongoDB instance at " + MONGO_DB_IP + ":"
                + MONGO_DB_PORT + ". Are you sure it is running?", throwable);
    }

    /**
     * If no documents were retrieved then apparently the demo collection was
     * not loaded into the database.
     */
    if (totalAttacks == 0) {
        throw new IllegalStateException("Unable to load documents from the collection " + HONEYPOT_COLLECTION
                + " in the database " + HONEYPOT_DATABASE + ". Are you sure it was loaded?");
    }

    computeAttackCountryCount();
}

From source file:webSocket.ProjectChat.java

public ProjectChat(String projectId) throws UnknownHostException {
    this.mychat = new Chat();

    mongo = new MongoClient(new ServerAddress("127.0.0.1", 27017));
    db = mongo.getDB("test");
    this.projectId = projectId;
    coleccion = db.getCollection("chat");
    DBCursor find = coleccion.find(new BasicDBObject("projectId", projectId));
    if (find.hasNext()) {
        DBObject myobje = find.next();//  w  ww. ja v  a2  s  .  co  m
        this.mychat.setId(myobje.get("_id").toString());
        this.mychat.setProjectId(myobje.get("projectId").toString());
        String chat = myobje.get("mychat").toString();
        this.mychat.setMychat(gson.fromJson(chat, mychat.getMychat().getClass()));

    } else {
        ArrayList<MessageChat> mes = new ArrayList<>();
        mes.add(new MessageChat("System", "Se ha creado el proyecto", new Date().toGMTString()));
        mychat.setId(projectId);
        mychat.setProjectId(projectId);
        mychat.setMychat(mes);
        BasicDBList shat = gson.fromJson(gson.toJson(mes), BasicDBList.class);
        BasicDBObject basicDBObject = new BasicDBObject("_id", this.mychat.getId())
                .append("projectId", this.mychat.getProjectId()).append("mychat", shat);
        coleccion.insert(basicDBObject);
    }

    mongo.close();

}

From source file:webSocket.ProjectChat.java

public void saveChat() {
    try {//from   ww w  . ja v  a 2s.co  m
        mongo = new MongoClient(new ServerAddress("127.0.0.1", 27017));
    } catch (UnknownHostException ex) {
        Logger.getLogger(ProjectChat.class.getName()).log(Level.SEVERE, null, ex);
    }
    db = mongo.getDB("test");

    coleccion = db.getCollection("chat");
    BasicDBList dblist = gson.fromJson(gson.toJson(this.mychat.getMychat()), BasicDBList.class);
    BasicDBObject myobje = new BasicDBObject("_id", this.mychat.getId())
            .append("projectId", this.mychat.getProjectId()).append("mychat", dblist);
    coleccion.save(myobje);
    //        String toByteArray = gson.toJson(mychat);
    //        byte[] newchat = toByteArray.getBytes();
    //        ps.setChat(newchat);
    //        proyectoScrumFacade.edit(ps);
    mongo.close();
}

From source file:week1.Week1Homework4.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override/*from   w w w  . j a va2 s  .  c om*/
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this. It's just to prove
                // that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(
                        new BasicDBObject("$group",
                                new BasicDBObject("_id", "$value").append("count",
                                        new BasicDBObject("$sum", 1))),
                        new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))),
                        new BasicDBObject("$sort", new BasicDBObject("_id", 1)));

                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}

From source file:xbdd.webapp.factory.ServletContextMongoClientFactory.java

License:Apache License

private MongoDBAccessor getMongoDBAccessor() throws UnknownHostException {
    final MongoClient mc;
    if (this.username != null) {
        MongoCredential credentials = MongoCredential.createMongoCRCredential(this.username, "admin",
                this.password);
        mc = new MongoClient(new ServerAddress(this.host, this.port), Arrays.asList(credentials));
    } else {// w w w .j  a  v a  2s  .co m
        mc = new MongoClient(this.host, this.port);
    }

    return new MongoDBAccessor(mc);
}

From source file:xyz.wang11.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   w  ww.  jav a 2s.  com
 * <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 = getPortNums(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);
                try {
                    addresses.add(new ServerAddress(host.trim(), portNum));
                } catch (Exception e) {
                    errorHandler.error("MongoDB appender hostname property contains unknown host", e,
                            ErrorCode.ADDRESS_PARSE_FAILURE);
                }
                i++;
            }
        }
    }
    return addresses;
}