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(final InetSocketAddress inetSocketAddress) 

Source Link

Document

Creates a ServerAddress

Usage

From source file:MongoCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];//from  w  ww .  j av a2 s  .c om
    String user = args[1];
    String password = args[2];
    String databaseName = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createMongoCRCredential(user, "test", password.toCharArray())),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));

}

From source file:NegotiatedAuthenticationProtocolExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    String server = args[0];/*from w  w w.j ava  2  s. c  o m*/
    String user = args[1];
    String pwd = args[2];
    String db = args[3];

    MongoCredential credentials = new MongoCredential(user, pwd.toCharArray(),
            MongoAuthenticationProtocol.NEGOTIATE, db);

    MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credentials),
            new MongoClientOptions.Builder().build());

    DB testDB = mongoClient.getDB(db);
    testDB.getCollection("test").insert(new BasicDBObject());
    System.out.println("Count: " + testDB.getCollection("test").count());
}

From source file:GSSAPICredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    // Set this property to avoid the default behavior where the program prompts on the command line for username/password
    //        Security.setProperty("auth.login.defaultCallbackHandler", "DefaultSecurityCallbackHandler");

    String server = args[0];//w  w  w.j  a  v a 2  s. c o m
    String user = args[1];
    String databaseName = args[2];

    System.out.println("javax.security.auth.useSubjectCredsOnly: "
            + System.getProperty("javax.security.auth.useSubjectCredsOnly"));
    System.out.println("java.security.krb5.realm: " + System.getProperty("java.security.krb5.realm"));
    System.out.println("java.security.krb5.kdc: " + System.getProperty("java.security.krb5.kdc"));
    System.out.println(
            "auth.login.defaultCallbackHandler: " + Security.getProperty("auth.login.defaultCallbackHandler"));
    System.out.println("login.configuration.provider: " + Security.getProperty("login.configuration.provider"));
    System.out.println(
            "java.security.auth.login.config: " + Security.getProperty("java.security.auth.login.config"));
    System.out.println("login.config.url.1: " + Security.getProperty("login.config.url.1"));
    System.out.println("login.config.url.2: " + Security.getProperty("login.config.url.2"));
    System.out.println("login.config.url.3: " + Security.getProperty("login.config.url.3"));

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createGSSAPICredential(user)),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
    System.out.println("Count: " + testDB.getCollection("test").count());
}

From source file:CramMd5CredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    String server = args[0];//ww  w. j a  va2 s. c om
    String user = args[1];
    String pwd = args[2];
    String db = args[3];
    MongoClient mongo = new MongoClient(
            new MongoClientAuthority(new ServerAddress(server),
                    new MongoClientCredentials(user, pwd.toCharArray(),
                            MongoClientCredentials.CRAM_MD5_MECHANISM, db)),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongo.getDB(db);
    System.out.println("Find     one: " + testDB.getCollection("test").findOne());
    System.out.println("Count: " + testDB.getCollection("test").count());
    WriteResult writeResult = testDB.getCollection("test").insert(new BasicDBObject());
    System.out.println("Write result: " + writeResult);

    System.out.println();

    System.out.println("Count: " + testDB.getCollection("test").count());

}

From source file:RestrictedService.java

License:Open Source License

public void init() throws ServletException {
    if (!gateInited) {
        try {/*from  www . j  a va 2 s  .c om*/
            // GATE home is setted, so it can be used by SAGA.
            ServletContext ctx = getServletContext();
            File gateHome = new File(ctx.getRealPath("/WEB-INF"));
            Gate.setGateHome(gateHome);
            // GATE user configuration file is setted. 
            Gate.setUserConfigFile(new File(gateHome, "user-gate.xml"));
            //GATE is initialized as non visible.
            Gate.init();
            // We load the plugins that are going to be used by the SAGA modules.
            // Load ANNIE.
            Gate.getCreoleRegister().registerDirectories(ctx.getResource("/WEB-INF/plugins/ANNIE"));
            // Load processingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/processingResources"));
            // Load webProcessingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/webProcessingResources"));
            // Now we create the sentiment analysis modules that are going to be provided by the service.
            // English financial module.
            ArrayList<URL> dictionaries = new ArrayList<URL>();
            dictionaries.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def"));
            modules.put("enFinancial",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries));
            // English financial + emoticon module.
            ArrayList<URL> dictionaries2 = new ArrayList<URL>();
            dictionaries2.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def"));
            dictionaries2.add((new RestrictedService()).getClass()
                    .getResource("/resources/gazetteer/emoticon/lists.def"));
            modules.put("enFinancialEmoticon",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries2));
            // Mongo login
            String user = "";
            String password = "";
            MongoCredential credential = MongoCredential.createMongoCRCredential(user, "RestrictedDictionaries",
                    password.toCharArray());
            MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"),
                    Arrays.asList(credential));
            db = mongoClient.getDB("RestrictedDictionaries");

            gateInited = true;

        } catch (Exception ex) {
            throw new ServletException("Exception initialising GATE", ex);
        }
    }
}

From source file:PlainCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/*  ww  w  .  ja  v a  2s . c  o m*/
    String user = args[1];
    String password = args[2];
    String source = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("source: " + source);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createPlainCredential(user, source, password.toCharArray())),
            new MongoClientOptions.Builder().build());
    DB testDB = mongoClient.getDB("test");

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
}

From source file:anuncius.singleton.MongoHandler.java

public final MongoClient connectToDatabase() {
    if (secureMode) {
        //If MongoDB in secure mode, authentication is required.
        //... missing procedure
        System.out.println("Connecting to Mongo DB instance on " + MONGO_HOST + " at " + MONGO_PORT
                + " using user " + USERNAME);
        MongoCredential credential = MongoCredential.createCredential(USERNAME, database,
                PASSWORD.toCharArray());
        mongo = new MongoClient(new ServerAddress(MONGO_HOST), Arrays.asList(credential));
    } else {/*w  ww . j a  va  2  s .c  o  m*/
        // Since 2.10.0, uses MongoClient
        System.out.println("Connecting to Mongo DB instance on " + MONGO_HOST + " at " + MONGO_PORT);
        mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
    }
    return mongo;
}

From source file:at.oneminutedistraction.mongodbrealm.DefaultMongoClientFactory.java

@Override
public com.mongodb.MongoClient create() throws Exception {

    //Server list
    String servers = props.getProperty(PROP_SERVER, "localhost");
    List<ServerAddress> serverList = new LinkedList<>();
    for (String s : servers.trim().replaceAll(" +", " ").split(" ")) {
        String[] hostPort = s.split(":");
        ServerAddress serverAddress = null;
        try {/*w w  w  .  j  a  va2  s.  com*/
            switch (hostPort.length) {
            case 1:
                serverAddress = new ServerAddress(hostPort[0]);
                break;
            case 2:
                serverAddress = new ServerAddress(hostPort[0], Integer.parseInt(hostPort[1]));
                break;
            default:
                continue;

            }
        } catch (UnknownHostException ex) {
            logger.log(Level.WARNING, "Ignoring unknown host: {0}", hostPort[0]);
            continue;
        } catch (NumberFormatException ex) {
            logger.log(Level.WARNING, "Ignoring port number error: {0}", s);
            continue;
        }
        serverList.add(serverAddress);
    }

    if (serverList.size() > 0) {
        logger.log(Level.INFO, "MongoDB replicas: {0}", serverList);
        return (new com.mongodb.MongoClient(serverList));
    } else {
        logger.log(Level.INFO, "MongoDB instance at localhost");
        try {
            return (new com.mongodb.MongoClient("localhost"));
        } catch (UnknownHostException ex) {
            //Seriously?
        }
    }
    return (null);
}

From source file:biopolis.headless.BiopolisPersistencyLayer.java

public BiopolisPersistencyLayer(BiopolisProperties props) throws BiopolisGeneralException, SQLException {
    org.neo4j.jdbc.Driver driver = new org.neo4j.jdbc.Driver();
    this.connNeo4j = driver.connect("jdbc:neo4j://" + props.neo4j_endpoint, new Properties());
    try {//from   www .java  2s.c  om
        System.out.println(props.mongo_host);
        MongoClientOptions mco = new MongoClientOptions.Builder().connectionsPerHost(10)
                .threadsAllowedToBlockForConnectionMultiplier(10).build();
        mongo = new MongoClient(new ServerAddress("localhost"), mco); //addresses is a pre-populated List 
    } catch (MongoException e) {
        e.printStackTrace();
        throw new BiopolisGeneralException("Mongo exception problem");
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new BiopolisGeneralException("Mongo connection problem");
    }
    DB dbo = mongo.getDB(BiopolisPersistencyLayer.dbName);
    if (dbo.collectionExists(BiopolisPersistencyLayer.collectionNamePlaces)) {
        this.dbcolPlaces = dbo.getCollection(BiopolisPersistencyLayer.collectionNamePlaces);

    } else {
        this.dbcolPlaces = dbo.createCollection(BiopolisPersistencyLayer.collectionNamePlaces, null);
        this.dbcolPlaces.createIndex(new BasicDBObject("loc", "2dsphere"));
    }

    if (dbo.collectionExists(collectionNameSearches)) {
        this.dbcolSearches = dbo.getCollection(collectionNameSearches);

    } else {
        this.dbcolSearches = dbo.createCollection(collectionNameSearches, null);
        this.dbcolSearches.createIndex(new BasicDBObject("biopolisttl", 1),
                new BasicDBObject("expireAfterSeconds", props.expire_search));
    }
    this.segSZ = props.segment_size;
}

From source file:com.blogging.BloggingEnvironment.java

License:Apache License

/**
  * @param bootstrapString//from  www.  j  a  va 2s.c  o  m
  * @return
  */
private List<ServerAddress> parseBootstraps(String bootstrapString) {
    String[] bs = bootstrapString.split(",");
    List<ServerAddress> results = new ArrayList<ServerAddress>();

    for (String server : bs) {
        String[] hostAndPort = server.split(":");
        String host = hostAndPort[0];
        int port = DEFAULT_MONGODB_PORT;

        if (hostAndPort.length > 1) {
            port = Integer.parseInt(hostAndPort[1]);
        }

        results.add(new ServerAddress(new InetSocketAddress(host, port)));
    }

    return results;
}