Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:com.pavel.testtask.highway.MongoInitionalizer.java

public MongoInitionalizer() {

    try (FileInputStream fis = new FileInputStream("src/main/resources/client.properties")) {
        dbProperties.load(fis);//from www  .ja va2 s .  c  om
        MongoClient mongo = new MongoClient(/*"localhost", 27017*/
                dbProperties.getProperty("db.host"), Integer.parseInt(dbProperties.getProperty("db.port")));
        db = mongo.getDB(dbProperties.getProperty("db.name"));

    } catch (UnknownHostException ex) {
        Logger.getLogger(MongoInitionalizer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MongoInitionalizer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.percona.LinkBench.MongoDBTestConfig.java

License:Apache License

static DB createConnection(String testDB) throws InstantiationException, IllegalAccessException,
        ClassNotFoundException, MongoClientException, UnknownHostException {

    StringBuilder mongoUri = new StringBuilder("mongodb://");
    if (user != null && !"".equals(user.trim()) && pass != null && !"".equals(pass.trim())) {
        mongoUri.append(user + ":" + pass + "@");
    }/*from   w w  w  .  j a  va2  s .  com*/
    if (host != null && !"".equals(host.trim()))
        mongoUri.append(host);
    if (port > 0)
        mongoUri.append(":" + port);
    mongoUri.append("/");
    if (testDB != null && !"".equals(testDB.trim()))
        mongoUri.append(testDB);

    MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoUri.toString()));

    return (mongoClient.getDB(testDB));

}

From source file:com.ratzia.pfc.webpageanalyticaltool.dbupdater.Watcher.java

public void processDatabase(LinkedList<String> pluginsCode, String currentVersion) throws UnknownHostException {
    /**** Plugins ****/
    LinkedList<SysPlugin> plugins = loadPlugins(pluginsCode);
    /*****************/

    /*SecurityManager oldSecurityManager = System.getSecurityManager();
    DBPluginSecurityManager dbPluginSecurityManager = new DBPluginSecurityManager();
    System.setSecurityManager(dbPluginSecurityManager);
    //Will open the security manager so we need to ensure it is closed afterwards
    try{*///w  w w.  j  ava 2s. c  om
    MongoClient mongoClient = new MongoClient(serverAddress);
    DB local = mongoClient.getDB(db);
    DBCollection dbCol = local.getCollection(collection);
    BasicDBObject query = new BasicDBObject();
    query.put(PLUGIN_VERSION_FIELD, new BasicDBObject("$ne", currentVersion));
    DBCursor cursor = dbCol.find(query);
    long count = 0;
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();

        //Copy contents
        BasicDBObject res = new BasicDBObject();
        for (String k : obj.keySet()) {
            res.put(k, obj.get(k));
        }

        //Plugin operations
        for (SysPlugin plugin : plugins) {
            try {
                plugin.run(res);
            } catch (Exception ex) {
                System.out.println("Error en " + plugin.getClass());
                Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        //Put plugin only fields into the original object
        for (String k : res.keySet()) {
            if ((k.substring(0, 2)).compareTo("p_") == 0) {
                obj.put(k, res.get(k));
            }
        }

        //Update version on object
        obj.put(PLUGIN_VERSION_FIELD, currentVersion);

        dbCol.save(obj);
        count++;
    }
    cursor.close();

    if (count > 0) {
        System.out.println(count + " updated");
    }

    /*}catch(Exception ex){
    Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    //close sandbox
    System.setSecurityManager(oldSecurityManager);*/

}

From source file:com.redhat.lightblue.mongo.config.metadata.MongoConfiguration.java

License:Open Source License

public DB getDB() throws UnknownHostException {
    MongoClient client = new MongoClient(servers, getMongoClientOptions());
    return client.getDB(getName());
}

From source file:com.se452group4.db.InsertDriver.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("Shop");
    DBCollection clothCollection = db.getCollection("Clothes");
    BasicDBObject cloth1 = new BasicDBObject();
    cloth1.put("clothesId", 1000);
    cloth1.put("type", "Dress");
    cloth1.put("brandName", "Zara");
    cloth1.put("price", 100);
    cloth1.put("gender", "Women");
    cloth1.put("quantity", 5);
    clothCollection.insert(cloth1);//from w ww . j a v a 2s  . c om

    DBCursor clothCursor = clothCollection.find(cloth1);
    while (clothCursor.hasNext()) {
        System.out.println(clothCursor.next());
    }
}

From source file:com.smbtec.xo.mongodb.api.MongoDbXOProvider.java

License:Apache License

@Override
public Datastore<MongoDbDatastoreSession, DocumentMetadata, String, RelationshipMetadata, String> createDatastore(
        XOUnit xoUnit) {//from w  w w . j a v a2  s. c  om
    if (xoUnit == null) {
        throw new IllegalArgumentException("XOUnit must not be null");
    }
    final URI uri = xoUnit.getUri();
    if (uri == null) {
        throw new XOException("No URI is specified for the store.");
    }

    try {
        if ("fongodb".equals(uri.getScheme())) {
            // in memory only for testing purposes
            Fongo fongo = new Fongo("test");
            return new MongoDbDatastore(fongo.getDB("xo"));
        } else {
            MongoClient client = new MongoClient(new MongoClientURI(uri.toString()));
            return new MongoDbDatastore(client.getDB("xo"));
        }
    } catch (UnknownHostException e) {
        throw new XOException("", e);
    }
}

From source file:com.spring.tutorial.controllers.DefaultController.java

@RequestMapping(value = "/dropbox-auth-finished", method = RequestMethod.GET)
public String authenticated(HttpServletResponse response, HttpServletRequest request, ModelMap map)
        throws DbxException, IOException {

    DbxAuthFinish authFinish;/*from w  w w.ja  va 2  s .  co m*/
    String returnTo = "mydrive/mydrive";
    final String APP_KEY = "mt6yctmupgrodlm";
    final String APP_SECRET = "p68kiiyvdctftuv";

    DbxAppInfo appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);

    try {
        String redirectUrl = getUrl(request, "http://localhost:8080/FOU_1/dropbox-auth-finished");

        // Select a spot in the session for DbxWebAuth to store the CSRF token.
        HttpSession session = request.getSession();
        String sessionKey = "dropbox-auth-csrf-token";
        DbxSessionStore csrfTokenStore = new DbxStandardSessionStore(session, sessionKey);

        auth = new DbxWebAuth(getRequestConfig(request), appInfo, redirectUrl, csrfTokenStore);
        authFinish = auth.finish(request.getParameterMap());

    } catch (DbxWebAuth.BadRequestException ex) {
        log("On /dropbox-auth-finish: Bad request: " + ex.getMessage());
        response.sendError(400);
        return returnTo;
    } catch (DbxWebAuth.BadStateException ex) {
        // Send them back to the start of the auth flow.
        response.sendRedirect("http://localhost:8080/FOU_1/dropbox-auth-finished" + ex.getMessage());
        return returnTo;
    } catch (DbxWebAuth.CsrfException ex) {
        log("On /dropbox-auth-finish: CSRF mismatch: " + ex.getMessage());
        return returnTo;
    } catch (DbxWebAuth.NotApprovedException ex) {

        return "redirect:my-drive/dropbox/home";
    } catch (DbxWebAuth.ProviderException ex) {
        log("On /dropbox-auth-finish: Auth failed: " + ex.getMessage());
        response.sendError(503, "Error communicating with Dropbox." + ex.getMessage());
        return returnTo;
    } catch (DbxException ex) {
        log("On /dropbox-auth-finish: Error getting token: " + ex.getMessage());
        response.sendError(503, "Error communicating with Dropbox." + ex.getMessage());
        return returnTo;
    }

    String accessToken = authFinish.accessToken;

    DbxClient client = new DbxClient(config, accessToken);

    MongoClient mongoClient = new MongoClient();
    DB db = mongoClient.getDB("fou");

    char[] pass = "mongo".toCharArray();
    boolean auth = db.authenticate("emime", pass);
    DBCollection collection = db.getCollection("users");
    if (auth == true) {
        BasicDBObject newDocument = new BasicDBObject();
        newDocument.append("$set", new BasicDBObject().append("dropbox_token", accessToken));

        BasicDBObject searchQuery = new BasicDBObject().append("id", request.getSession().getAttribute("id"));

        collection.update(searchQuery, newDocument);
    }

    map.addAttribute("title", "my-drive");
    request.getSession().setAttribute("dropbox_token", accessToken);
    response.sendRedirect("http://localhost:8080/FOU_1/my-drive/dropbox/home");
    return "mydrive/dropbox";
}

From source file:com.spring.tutorial.entitites.DropboxUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;/*from   ww  w.  j a v  a  2s. co  m*/
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        FileInputStream inputStream = new FileInputStream(file);
        try {
            String fileName = filePart.getSubmittedFileName();
            String path = request.getParameter("path");
            if (path.equals("/home")) {
                path = "";
            }
            DbxEntry.File uploadedFile = client.uploadFile(path + "/" + filePart.getSubmittedFileName(),
                    DbxWriteMode.add(), file.length(), inputStream);
            DBCollection collection = db
                    .getCollection(request.getSession().getAttribute("id") + "_dropbox_files_meta");

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();

            long fileSize = filePart.getSize();

            BasicDBObject document = new BasicDBObject();
            document.put("rev", "");
            document.put("fileSize", Long.toString(fileSize));
            document.put("lastModified", dateFormat.format(date));
            document.put("name", filePart.getSubmittedFileName());
            document.put("path", path + "/" + filePart.getSubmittedFileName());
            document.put("type", "file");
            document.put("tags", request.getParameter("tags"));
            document.put("description", request.getParameter("description"));
            document.put("found", "true");

            collection.insert(document);

        } finally {
            inputStream.close();
        }

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;//from  w w w  .j av  a 2  s.c om
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:com.sql2nosql.SQLExecuter.java

License:Open Source License

public static String execute(String SQL) throws Exception {

    Settings settings = SettingsImporter.importSettings("sql2nosql.settings.xml");

    MongoClient mongo = new MongoClient(settings.getHost(), settings.getPort().intValue());

    DB db = mongo.getDB(settings.getDbname());

    HashMap<String, LinkedHashMap<String, Object>> list = new HashMap<String, LinkedHashMap<String, Object>>();
    SQLParser parser = new SQLParser();
    StatementNode node = parser.parseStatement(SQL);

    QueryTreeVisitor fdg = new QueryTreeVisitor(list);
    node.accept(fdg);//from ww  w  .j ava  2  s  .co  m

    String string = null;
    LinkedHashMap<String, Object> tableList = list.get(TABLE);
    for (Map.Entry<String, Object> entry : tableList.entrySet()) {
        string = entry.getKey();
        Object object = entry.getValue();

    }
    DBCollection table = db.getCollection(string.toLowerCase());

    LinkedHashMap<String, Object> whereList = list.get(WHERE);
    String string1 = null;
    Object object = null;
    for (Map.Entry<String, Object> entry : whereList.entrySet()) {
        string1 = entry.getKey();
        object = entry.getValue();

    }

    BasicDBObject searchQuery = new BasicDBObject();

    searchQuery.put(string1.toLowerCase(), object.toString());

    DBCursor cursor = table.find(searchQuery);

    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    return null;
}