Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:com.exorath.simpleapi.impl.database.DBManager.java

License:Apache License

public void withClientConsumer(MongoClientConsumer consumer) {
    try (MongoClient client = new MongoClient(host)) {
        consumer.consume(client);
    }
}

From source file:com.facebook.presto.mongodb.MongoQueryRunner.java

License:Apache License

private MongoQueryRunner(Session session, int workers) throws Exception {
    super(session, workers);

    server = new MongoServer(new SyncMemoryBackend());
    address = server.bind();// www  .  j  a  v a  2  s .co  m
    client = new MongoClient(new ServerAddress(address));
}

From source file:com.ga.model.abstractclasses.ModelAbstract.java

@Override
public void init(String dbName, String collectionName) {
    try {/*from  w  w  w .  ja va  2 s. com*/
        //            ModelAbstract.conn = new MongoClient(new MongoClientURI("mongodb://116.193.163.66:27017/"));
        ModelAbstract.conn = new MongoClient(new MongoClientURI("mongodb://localhost:27017/"));
        if (ModelAbstract.conn != null) {
            ModelAbstract.db = ModelAbstract.conn.getDB(dbName);
            if (ModelAbstract.db != null) {
                ModelAbstract.collection = ModelAbstract.db.getCollection(collectionName);
                if (ModelAbstract.collection == null) {
                    Exception exCollection = new Exception(
                            "Collection \'" + collectionName + "\' does not exist in \'" + dbName + "\'.");
                    throw exCollection;

                }
            } else {
                Exception exDatabase = new Exception("Database \'" + dbName + "\' not found.");
                throw exDatabase;
            }
        } else {
            ex = new MongoException("Failed to connect with database server.");
            throw ex;
        }
    } catch (UnknownHostException e) {
        Logger.getLogger(ModelAbstract.class.getName()).log(Level.SEVERE, null, e);
    } catch (Exception exCollection) {
        Logger.getLogger(ModelAbstract.class.getName()).log(Level.SEVERE, null, exCollection);
    }

}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public void init() {
    if (args == null || args.length == 0) {
        throw new AssertionError("No arguments passed to the MongoDBTestDataProvider");
    }// w w  w .j  a v  a  2s . c o  m

    if (args.length < 3) {
        throw new AssertionError("The arguments, namely mongodb-host, mongodb-port, mongodb-database are "
                + " mandatory for MongoDBTestDataProvider");
    }

    Assert.assertNotNull("mongodb-host cannot be empty", args[0]);
    Assert.assertNotNull("mongodb-port cannot be empty", args[1]);
    Assert.assertNotNull("mongodb-database cannot be empty", args[2]);

    String host = args[0].trim();
    String port = args[1].trim();
    String dbName = args[2].trim();

    Assert.assertFalse("mongodb-host cannot be empty", host.isEmpty());
    Assert.assertFalse("mongodb-port cannot be empty", port.isEmpty());
    Assert.assertFalse("mongodb-database cannot be empty", dbName.isEmpty());

    String username = null, password = "";
    if (args.length > 3) {
        Assert.assertNotNull("mongodb-user cannot be empty", args[3]);
        Assert.assertFalse("mongodb-user cannot be empty", args[3].isEmpty());

        username = args[3].trim();
        if (args.length > 4 && args[4] != null)
            password = args[4].trim();
    }

    StringBuilder build = new StringBuilder();
    build.append("MongoDBTestDataSource configuration [\n");
    build.append(String.format("mongodb-host is %s\n", host));
    build.append(String.format("mongodb-port is %s\n", port));
    build.append(String.format("mongodb-database is %s\n", dbName));
    if (username != null) {
        build.append(String.format("mongodb-user is %s\n", username));
        build.append(String.format("mongodb-password is %s\n", password));
    }
    logger.info(build.toString());

    try {
        String[] hosts = host.split(",");
        String[] ports = port.split(",");

        if (hosts.length > ports.length) {
            Assert.assertEquals(String.format("Port missing for host %s", hosts[ports.length - 1]),
                    hosts.length, ports.length);
        } else {
            Assert.assertEquals(String.format("Host missing for port %s", ports[hosts.length - 1]),
                    hosts.length, ports.length);
        }

        for (String portVal : ports) {
            try {
                Integer.valueOf(portVal);
            } catch (Exception e) {
                throw new AssertionError(String.format("Port value invalid - %s", portVal));
            }
        }

        for (int i = 0; i < hosts.length; i++) {
            ServerAddress address = new ServerAddress(hosts[i], Integer.valueOf(ports[i]));
            addresses.add(address);
        }

        for (int i = 0; i < poolSize; i++) {
            MongoClient mongoClient = null;
            //Now try connecting to the Database
            try {
                mongoClient = new MongoClient(addresses);
            } catch (Exception e) {
                throw new AssertionError(String.format("Connection to MongoDB failed with the error %s",
                        ExceptionUtils.getStackTrace(e)));
            }

            DB db = null;
            try {
                db = mongoClient.getDB(dbName);
                if (username != null && password != null) {
                    Assert.assertTrue(String.format("Authentication to the Mongo database %s failed with %s/%s",
                            dbName, username, password), db.authenticate(username, password.toCharArray()));
                }
            } catch (Exception e) {
                throw new AssertionError(String.format("Error during initialization of MongoDB connection %s",
                        ExceptionUtils.getStackTrace(e)));
            }

            addToPool(mongoClient, false);
        }
    } catch (Exception e) {
        throw new AssertionError(String.format("Error during initialization of MongoDB connection %s",
                ExceptionUtils.getStackTrace(e)));
    } finally {
    }

}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

private Resource getResource() {
    Resource res = checkoutFromPool();
    MongoClient mongoClient = null;//ww w  . j av  a2s .co m
    if (res == null) {
        try {
            Thread.sleep(newResourceCheckoutTimeMs / 2);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        res = checkoutFromPool();
        if (res != null)
            return res;

        try {
            Thread.sleep(newResourceCheckoutTimeMs / 2);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        res = checkoutFromPool();
        if (res != null)
            return res;

        try {
            mongoClient = new MongoClient(addresses);
        } catch (Exception e) {
            throw new AssertionError(String.format("Connection to MongoDB failed with the error %s",
                    ExceptionUtils.getStackTrace(e)));
        }
        res = addToPool(mongoClient, true);
    }
    return res;
}

From source file:com.geeksanon.AppController.java

License:Open Source License

/**
 * Method to make a connection to the database, with the URI.
 * /*from   w w  w . ja  v a 2s.  com*/
 * @param URIString
 *            URI passed other than the localhost
 * @throws IOException
 *             when the page is not found.
 */
public AppController(String URIString) throws IOException {
    MongoClient mongoClient = new MongoClient(new MongoClientURI(URIString));
    DB database = mongoClient.getDB("askme");
    questionDAO = new QuestionDAO(database);
    userDAO = new UserDAO(database);
    sessionDAO = new SessionDAO(database);

    configuration = loadTemplateConfiguration();
    Spark.setPort(5115);
    intialiseRoutes();
}

From source file:com.gemini.common.repository.impl.GeminiMongoClientProvider.java

@Override
public MongoClient get() {
    Injector propInjector = Guice.createInjector(new GeminiPropertiesModule());
    GeminiProperties properties = propInjector.getInstance(GeminiProperties.class);
    MongoClient mongoClient = null;//from   www. j a v a 2  s.co  m

    try {
        mongoClient = new MongoClient(properties.getProperties().getProperty("DATABASE_HOST"));
    } catch (UnknownHostException ex) {
        Logger.error("Severe Error: Unknown database host", ex);
    }

    return mongoClient;
}

From source file:com.gemini.discover.networkdiscover.GeminiNetworkDiscover.java

public static void main(String[] args) throws UnknownHostException {
    //for now we will listen on 1234, i.e., 'localhost:1234/...'
    setPort(1234);/*from  w  ww .  ja va  2s  .  com*/

    //setup the mongodb access
    mongoClient = new MongoClient("localhost");

    //create table for the application, networks and servers
    ds = morphia.createDatastore(mongoClient, "Gemini");

    //close the client, it will be opened as required.
    mongoClient.close();

    //currently we will default to physical discovery
    //discSvc.setDiscType(GeminiEnvironmentType.PHYSICAL);
    //create the mapper
    Injector injector = Guice.createInjector(new GeminiMapperModule());
    GeminiMapper mapper = injector.getInstance(GeminiMapper.class);

    //check if authenticated, create the call context and user context here
    //for now it is empty!!!!
    before((request, response) -> {
        boolean authenticated = true;
        // ... check if authenticated
        if (!authenticated) {
            halt(401, "Nice try, you are not welcome here");
        }
    });

    after((request, response) -> {
        response.header("Access-Control-Allow-Origin", "*");
        //response.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        //response.header("Access-Control-Max-Age", "3600");
        //response.header("Access-Control-Allow-Headers", "x-requested-with");
    });

    get("/env/:envname/networks", "application/json", (request, response) -> {
        String envName;
        //decode the URL as it may contain escape characters, etc.
        try {
            envName = URLDecoder.decode(request.params(":envname"), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.error("Severe Error: Unsupported encoding in URL - server Name: {} Exception: {}",
                    request.params(":name"), ex);
            return "Severe Error: Unsupported encoding in URL";
        }
        try {
            //return the networks...
            List<GeminiNetwork> l = allNetworks(envName);
            if (l == null || l.isEmpty()) {
                response.status(404);
                Logger.info("Could not find any network for environment {}.", envName);
                return "No Applications found for environment " + envName;
            } else {
                response.status(200);
                //convert to DTO
                List<GeminiNetworkDTO> netDTOList = new ArrayList();
                l.stream().forEach(n -> netDTOList.add(mapper.getDTOFromNetwork(n)));
                Logger.debug("Found applications");
                return netDTOList;
            }
        } catch (UnknownHostException ex) {
            Logger.error("Severe Error: Unknown host - {}", "localhost");
            response.status(500);
            return "Severe Error: Unknown database host";
        }
    }, new JsonTransformer());

    //discover a single network within a single environment - the network object is in the request body
    post("/env/:envname/discovernetwork", "application/json", (request, response) -> {
        String envName;
        //decode the URL as it may contain escape characters, etc.
        try {
            envName = URLDecoder.decode(request.params(":envname"), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.error("Severe Error: Unsupported encoding in URL - server Name: {} Exception: {}",
                    request.params(":name"), ex);
            return "Severe Error: Unsupported encoding in URL";
        }

        //get DTO json from request body
        String reqBody = request.body();
        GeminiNetworkDTO netDTO = null;
        if (reqBody == null || reqBody.isEmpty()
                || (netDTO = new Gson().fromJson(reqBody, GeminiNetworkDTO.class)) == null) {
            Logger.error("Error: Wrong request - no body in Discover Network request");
            response.status(200);
            return "Error: Wrong request - no body in Discover Network request";
        }

        try {
            GeminiNetwork network = mapper.getNetworkFromDTO(netDTO);
            List<Host> lSrvs = discoverSingleEnvNetwork(envName, network);
            if (lSrvs == null || lSrvs.isEmpty()) {
                response.status(404);
                Logger.info(
                        "Could not find any hosts for environment {} network: start {} end {} network {} mask {} hosts {}",
                        envName, network.getStart(), network.getEnd(), network.getNetwork().getHostAddress(),
                        network.getMask(), network.getHost());
                return "No Applications found for environment " + envName;
            } else {
                response.status(200);
                //convert to DTO
                List<GeminiServerDTO> srvDTOList = new ArrayList();
                lSrvs.stream().forEach(n -> srvDTOList.add(mapper.getDTOFromHost(n)));
                Logger.debug(
                        "Found {} servers in environment {} for network: start {} end {} network {} mask {} hosts {}",
                        srvDTOList.size(), envName, network.getStart(), network.getEnd(),
                        network.getNetwork().getHostAddress(), network.getMask(), network.getHost());
                return srvDTOList;
            }
        } catch (UnknownHostException ex) {
            Logger.error("Severe Error: Unknown host - {}", "localhost");
            response.status(500);
            return "Severe Error: Unknown database host";
        }
    }, new JsonTransformer());

    //discover all the networks within an environment -- this is kinda like a refresh
    post("/env/:endvname/discovernetworks", "application/json", (request, response) -> {
        String envName;
        //decode the URL as it may contain escape characters, etc.
        try {
            envName = URLDecoder.decode(request.params(":envname"), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            Logger.error("Severe Error: Unsupported encoding in URL - server Name: {} Exception: {}",
                    request.params(":name"), ex);
            return "Severe Error: Unsupported encoding in URL";
        }

        try {
            List<Host> lSrvs = discoverAllEnvNetworks(envName);
            if (lSrvs == null || lSrvs.isEmpty()) {
                response.status(404);
                Logger.info("Could not find any hosts for environment {}", envName);
                return "No servers found for environment " + envName;
            } else {
                response.status(200);
                //convert to DTO
                List<GeminiServerDTO> srvDTOList = new ArrayList();
                lSrvs.stream().forEach(n -> srvDTOList.add(mapper.getDTOFromHost(n)));
                Logger.debug("Found {} servers in environment {}", srvDTOList.size(), envName);
                return srvDTOList;
            }
        } catch (UnknownHostException ex) {
            Logger.error("Severe Error: Unknown host - {}", "localhost");
            response.status(500);
            return "Severe Error: Unknown database host";
        }
    }, new JsonTransformer());
}

From source file:com.gemini.discover.networkdiscover.GeminiNetworkDiscover.java

private static List<GeminiNetwork> allNetworks(String envName) throws UnknownHostException {
    //setup the mongodb access
    mongoClient = new MongoClient("localhost");

    GeminiEnvironmentRepositoryMongoDBImpl netDB = new GeminiEnvironmentRepositoryMongoDBImpl(mongoClient,
            morphia, "Gemini");
    List<GeminiNetwork> networks = netDB.getEnvNetworks(envName);

    //close the db client
    mongoClient.close();//from  w  w  w  .j a v  a  2 s .co m

    return networks;
}

From source file:com.gemini.discover.networkdiscover.GeminiNetworkDiscover.java

private static List<Host> discoverSingleEnvNetwork(String envName, GeminiNetwork network)
        throws UnknownHostException {
    //setup the mongodb access
    mongoClient = new MongoClient("localhost");

    //get the environment object
    GeminiEnvironmentRepositoryMongoDBImpl netDB = new GeminiEnvironmentRepositoryMongoDBImpl(mongoClient,
            morphia, "Gemini");
    GeminiEnvironment env = netDB.getEnvByName(envName);
    if (env == null) {
        Logger.error("Error: Discover Single Network - environment with name {} not found", envName);
        return null;
    }//from  w  ww  . j  a v  a 2  s .c  o m

    //discover network
    discSvc.setDiscType(env.getType());
    return discSvc.discoverSingleNetwork(network);
}