Example usage for com.mongodb MongoClientURI MongoClientURI

List of usage examples for com.mongodb MongoClientURI MongoClientURI

Introduction

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

Prototype

public MongoClientURI(final String uri) 

Source Link

Document

Creates a MongoURI from the given string.

Usage

From source file:rapture.mongodb.MongoDBFactory.java

License:Open Source License

private Mongo getMongoFromSysConfig(String instanceName) {
    Map<String, ConnectionInfo> map = Kernel.getSys().getConnectionInfo(ContextFactory.getKernelUser(),
            ConnectionType.MONGODB.toString());
    if (!map.containsKey(instanceName)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                mongoMsgCatalog.getMessage("NoInstance", instanceName));
    }//  w  w w  .  j  a va  2s . com
    ConnectionInfo info = map.get(instanceName);
    log.info("Connection info = " + info);
    try {
        MongoClient mongo = new MongoClient(new MongoClientURI(info.getUrl()));
        mongoDBs.put(instanceName, mongo.getDB(info.getDbName()));
        mongoDatabases.put(instanceName, mongo.getDatabase(info.getDbName()));
        mongoInstances.put(instanceName, mongo);
        return mongo;
    } catch (MongoException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, new ExceptionToString(e));
    }
}

From source file:rapture.repo.integration.LocalTestSetup.java

License:Open Source License

public static void createUser() throws IOException, InterruptedException {
    String mongoHost = MultiValueConfigLoader.getConfig("MONGODB-integrationTest");
    log.info("Host is " + mongoHost);
    if (mongoHost != null) {
        MongoClientURI uri = new MongoClientURI(mongoHost);
        List<String> hosts = uri.getHosts();
        for (String host : hosts) {
            String[] cmdarray = createSetupCommand(host, uri.getDatabase(), uri.getUsername(),
                    new String(uri.getPassword()));
            Process process = Runtime.getRuntime().exec(cmdarray);
            int retVal = process.waitFor();
            log.info(String.format("retVal=%s", retVal));
            log.info("output is " + IOUtils.toString(process.getInputStream()));
            if (retVal != 0) {
                log.info("error is " + IOUtils.toString(process.getErrorStream()));
            }/*w  w  w .  ja v  a  2 s . c  om*/
        }
    } else {
        log.error("mongo host is not defined!");
    }
}

From source file:ro.pippo.session.mongodb.MongoDBFactory.java

License:Apache License

/**
 * Create a MongoDB client with params.//from  w  w  w  .  j a va2  s  .  c o m
 *
 * @param hosts list of hosts of the form
 * "mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]"
 * @return MongoDB client
 * @see https://docs.mongodb.com/manual/reference/connection-string/
 */
public static MongoClient create(String hosts) {
    MongoClientURI connectionString = new MongoClientURI(hosts);
    return new MongoClient(connectionString);
}

From source file:rocks.devonthe.stickychunk.database.MongodbDatabase.java

License:GNU General Public License

public MongodbDatabase() {
    config = StickyChunk.getInstance().getConfig().database.mongo;
    databaseName = config.databaseName;//from   ww  w  .  j  a v a2 s.  com
    host = config.host;
    port = config.port;

    MongoClientURI connectionString = new MongoClientURI(String.format("mongodb://%s:%s", host, port));
    MongoClient client = new MongoClient(connectionString);
    database = client.getDatabase(databaseName);
}

From source file:rocks.teammolise.myunimol.webapp.issues.SendAdvice.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w  w  .  ja v  a  2 s .c  om
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    MongoClient mongoClient = null;
    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        String type = request.getParameter("type");
        String other = request.getParameter("other");
        String details = request.getParameter("details");

        ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance();
        String mdburi = confMgr.getMongoDbUri();
        int pos = mdburi.lastIndexOf("/");
        String dbName = mdburi.substring(pos + 1, mdburi.length());
        MongoClientURI uri = new MongoClientURI(mdburi);
        mongoClient = new MongoClient(uri);
        MongoDatabase db = mongoClient.getDatabase(dbName);

        MongoCollection<Document> collection = db.getCollection("advices");
        Map<String, Object> userinfo = new HashMap<String, Object>();
        userinfo.put("name", userInfo.getName());
        userinfo.put("surname", userInfo.getSurname());
        userinfo.put("course", userInfo.getCourse());
        userinfo.put("department", userInfo.getDepartment());
        userinfo.put("totalCFU", userInfo.getTotalCFU());
        userinfo.put("username", userInfo.getUsername());
        userinfo.put("studentId", userInfo.getStudentId());
        userinfo.put("enrolledExams", userInfo.getEnrolledExams());
        userinfo.put("registrationDate", userInfo.getRegistrationDate());
        userinfo.put("studentClass", userInfo.getStudentClass());
        userinfo.put("coursePath", userInfo.getCoursePath());
        userinfo.put("courseLength", userInfo.getCourseLength());
        Document userInfoDoc = new Document(userinfo);
        Map<String, Object> advice = new HashMap<String, Object>();
        advice.put("type", type);
        if (other != null)
            advice.put("other", other);
        advice.put("details", details);
        advice.put("userInfo", userInfoDoc);
        collection.insertOne(new Document(advice));

        out.println("{\"result\":\"success\"}");
    } catch (Exception ex) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } finally {
        out.close();
        mongoClient.close();
    }
}

From source file:rocks.teammolise.myunimol.webapp.issues.SendProblem.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w  .j  a  v  a2 s  .  c  om
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    MongoClient mongoClient = null;
    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        String type = request.getParameter("type");
        String other = request.getParameter("other");
        String details = request.getParameter("details");

        ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance();
        String mdburi = confMgr.getMongoDbUri();
        int pos = mdburi.lastIndexOf("/");
        String dbName = mdburi.substring(pos + 1, mdburi.length());
        MongoClientURI uri = new MongoClientURI(mdburi);
        mongoClient = new MongoClient(uri);
        MongoDatabase db = mongoClient.getDatabase(dbName);

        MongoCollection<Document> collection = db.getCollection("problems");
        Map<String, Object> userinfo = new HashMap<String, Object>();
        userinfo.put("name", userInfo.getName());
        userinfo.put("surname", userInfo.getSurname());
        userinfo.put("course", userInfo.getCourse());
        userinfo.put("department", userInfo.getDepartment());
        userinfo.put("totalCFU", userInfo.getTotalCFU());
        userinfo.put("username", userInfo.getUsername());
        userinfo.put("studentId", userInfo.getStudentId());
        userinfo.put("enrolledExams", userInfo.getEnrolledExams());
        userinfo.put("registrationDate", userInfo.getRegistrationDate());
        userinfo.put("studentClass", userInfo.getStudentClass());
        userinfo.put("coursePath", userInfo.getCoursePath());
        userinfo.put("courseLength", userInfo.getCourseLength());
        Document userInfoDoc = new Document(userinfo);
        Map<String, Object> problem = new HashMap<String, Object>();
        problem.put("type", type);
        if (other != null)
            problem.put("other", other);
        problem.put("details", details);
        problem.put("userInfo", userInfoDoc);
        collection.insertOne(new Document(problem));

        out.println("{\"result\":\"success\"}");
    } catch (Exception ex) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } finally {
        out.close();
    }
}

From source file:spring.boot.nomaven.MongoCero.java

public Mensaje buscarPorLogin(String login) {
    Mensaje p = new Mensaje();
    MongoClient mongoClient = null;/*from  ww  w.  j a v a  2  s  .c  om*/

    try {
        mongoClient = new MongoClient(
                new MongoClientURI("mongodb://campitos:raton@ds035563.mongolab.com:35563/unitec"));
        DB e = mongoClient.getDB("unitec");
        DBCollection collection = e.getCollection("profesor");

        BasicDBObject query = new BasicDBObject("login", login);
        DBObject objeto = collection.findOne(query);
        String pas = (String) objeto.get("password");
        String logino = (String) objeto.get("login");
        System.out.println("Hasta aqui todo va bien:" + pas);
        if (pas != null) {
            //p.setLogin(logino);
            //p.setPassword(pas);
        } else {
            p = null;
        }
    } catch (Exception var10) {
        System.out.println("algo malo:" + var10.getMessage());
    }

    return p;
}

From source file:thermostatapplication.TemperaturePersisterTimerTask.java

public synchronized void persistDataOnMongolab() {
    //disable console logging
    //Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); 
    //mongoLogger.setLevel(Level.SEVERE);

    iStoredTemperatures = iTemperatureStore.getTemperatures();
    if (iStoredTemperatures.isEmpty()) {
        logger.info("Nothing to persist. Exiting");
        return;//from w  ww . ja va  2  s. c  o m
    }
    logger.info("Prepairing to persist [{}] Temps in the cloud", iStoredTemperatures.size());
    MongoCollection<Document> mongoCollection = null;
    MongoClient client = null;
    List<Document> documents = new ArrayList<>();

    for (TemperatureMeasure tTemp : iStoredTemperatures) { //Exception in thread "Timer-2" java.util.ConcurrentModificationException
        Document doc = new Document();
        doc.put("Location", tTemp.getLocation()); //Location
        doc.put("Group", tTemp.getGroup()); //Group
        doc.put("Date", Helper.getDateAsString(tTemp.getDate())); //Date
        doc.put("Day", Helper.getDayAsString(tTemp.getDate()));
        doc.put("Time", Helper.getTimeAsString(tTemp.getDate()));
        doc.put("Temp", Helper.getTempAsString(tTemp.getTemp())); //Temp
        documents.add(doc);
        iPersistedTemperatures.add(tTemp);
    }

    try {
        MongoClientURI uri = new MongoClientURI(ThermostatProperties.ML_URL);
        client = new MongoClient(uri);
        MongoDatabase database = (MongoDatabase) client.getDatabase(uri.getDatabase());
        mongoCollection = database.getCollection("dailytemps");
        mongoCollection.insertMany(documents);
        //eliminate stored Temps from the collection
        iTemperatureStore.removeAll(iPersistedTemperatures);
        client.close();
        logger.info("Temperatures persisted on mongolab: [{}]. Exiting.", iPersistedTemperatures.size());
        iPersistedTemperatures.clear();
    } catch (Throwable e) {
        logger.error("Failed to store Temps in the cloud. Stacktrace: [{}]. Exiting.", e);
        iPersistedTemperatures.clear();
        e.printStackTrace();
    } finally {
        if (client != null) {
            client.close();
        }
        iPersistedTemperatures.clear();
    }
}

From source file:tools.devnull.boteco.persistence.mongodb.MongoDatabaseFactory.java

License:Open Source License

/**
 * Creates a new MongoDatabase object using the given uri and database name.
 *
 * @param uri      the mongo uri/*from w  w  w. j av a2s. com*/
 * @param database the database to access
 * @return a new MongoDatabase
 */
public static MongoDatabase createDatabase(String uri, String database) {
    MongoClient client = new MongoClient(new MongoClientURI(uri));
    return client.getDatabase(database);
}

From source file:tour.Decimal128LegacyAPIQuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *//*from   www .j av a  2 s  .c  o  m*/
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    DB database = mongoClient.getDB("mydb");

    // get a handle to the "test" collection
    DBCollection collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("amount1", Decimal128.parse(".10"))
            .append("amount2", new Decimal128(42L)).append("amount3", new Decimal128(new BigDecimal(".200")));

    collection.insert(doc);

    DBObject first = collection
            .findOne(QueryBuilder.start("amount1").is(new Decimal128(new BigDecimal(".10"))).get());

    Decimal128 amount3 = (Decimal128) first.get("amount3");
    BigDecimal amount2AsBigDecimal = amount3.bigDecimalValue();

    System.out.println(amount3.toString());
    System.out.println(amount2AsBigDecimal.toString());

}