Example usage for com.mongodb MongoClient close

List of usage examples for com.mongodb MongoClient close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes all resources associated with this instance, in particular any open network connections.

Usage

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Retrieve all database names found in MongoDB as visible by the
 * authenticated user./*from   w  w  w  .  j  a  v a  2s.  co m*/
 * 
 * @param meta
 *          Input meta with connection information
 * @param varSpace
 *          Variable space to substitute variables with
 * @return A list of database names found in MongoDB
 * @throws KettleException
 */
public static List<String> getDatabaseNames(final MongoDbInputMeta meta, final VariableSpace varSpace)
        throws KettleException {
    try {
        AuthContext context = MongoUtils.createAuthContext(meta, varSpace);
        return context.doAs(new PrivilegedExceptionAction<List<String>>() {

            @Override
            public List<String> run() throws Exception {
                MongoClient conn = null;
                try {
                    conn = MongoDbInputData.initConnection(meta, varSpace, null);
                    return conn.getDatabaseNames();
                } finally {
                    if (conn != null) {
                        conn.close();
                    }
                }
            }
        });
    } catch (PrivilegedActionException ex) {
        if (ex.getCause() instanceof KettleException) {
            throw (KettleException) ex.getCause();
        } else {
            throw new KettleException("Unable to retrieve database names from MongoDB", ex.getCause());
        }
    }
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Get the set of collections for a MongoDB database.
 * /*  w  w w.ja v a  2  s. c  o  m*/
 * @param meta
 *          Input meta with connection information
 * @param varSpace
 *          Variable space to substitute variables with
 * @param dB
 *          Name of database
 * @param username
 *          Username to request collections on behalf of
 * @param realPass
 *          Password of user
 * @return Set of collections in the database requested.
 * @throws KettleException
 *           If an error occurs.
 */
public static Set<String> getCollectionsNames(final MongoDbInputMeta meta, final TransMeta varSpace,
        final String dB, final String username, final String realPass) throws KettleException {
    try {
        AuthContext context = MongoUtils.createAuthContext(meta, varSpace);
        return context.doAs(new PrivilegedExceptionAction<Set<String>>() {
            @Override
            public Set<String> run() throws Exception {
                MongoClient conn = null;
                try {
                    conn = MongoDbInputData.initConnection(meta, varSpace, null);
                    DB theDB = conn.getDB(dB);

                    if (!Const.isEmpty(username) || !Const.isEmpty(realPass)) {
                        CommandResult comResult = theDB.authenticateCommand(username, realPass.toCharArray());
                        if (!comResult.ok()) {
                            throw new Exception(
                                    BaseMessages.getString(PKG, "MongoDbInput.ErrorAuthenticating.Exception", //$NON-NLS-1$
                                            comResult.getErrorMessage()));
                        }
                    }

                    return theDB.getCollectionNames();
                } finally {
                    if (conn != null) {
                        conn.close();
                    }
                }
            }
        });
    } catch (PrivilegedActionException ex) {
        if (ex.getCause() instanceof KettleException) {
            throw (KettleException) ex.getCause();
        } else {
            throw new KettleException(
                    "Unable to retrieve collection names for database " + dB + " from MongoDB", ex.getCause());
        }
    }
}

From source file:org.radarcns.listener.MongoFactory.java

License:Apache License

@Override
public void dispose(MongoClient client) {
    if (client != null) {
        client.close();
    }
}

From source file:org.restheart.Bootstrapper.java

License:Open Source License

/**
 * stopServer//from   ww  w . java2 s.com
 *
 * @param silent
 * @param removePid
 */
private static void stopServer(boolean silent, boolean removePid) {
    if (!silent) {
        LOGGER.info("Stopping RESTHeart...");
    }

    if (shutdownHandler != null) {
        if (!silent) {
            LOGGER.info("Waiting for pending request to complete (up to 1 minute)...");
        }
        try {
            shutdownHandler.shutdown();
            shutdownHandler.awaitShutdown(60 * 1000); // up to 1 minute
        } catch (InterruptedException ie) {
            LOGGER.error("Error while waiting for pending request to complete", ie);
        }
    }

    if (MongoDBClientSingleton.isInitialized()) {
        MongoClient client = MongoDBClientSingleton.getInstance().getClient();

        if (!silent) {
            LOGGER.info("Closing MongoDB client connections...");
        }

        try {
            client.close();
        } catch (Throwable t) {
            LOGGER.warn("Error closing the MongoDB client connection", t);
        }
    }

    Path pidFilePath = FileUtils.getPidFilePath(FileUtils.getFileAbsoultePathHash(CONF_FILE_PATH));

    if (removePid && pidFilePath != null) {
        if (!silent) {
            LOGGER.info("Removing the pid file {}", pidFilePath.toString());
        }
        try {
            Files.deleteIfExists(pidFilePath);
        } catch (IOException ex) {
            LOGGER.error("Can't delete pid file {}", pidFilePath.toString(), ex);
        }
    }

    if (!silent) {
        LOGGER.info("Cleaning up temporary directories...");
    }
    TMP_EXTRACTED_FILES.keySet().forEach(k -> {
        try {
            ResourcesExtractor.deleteTempDir(k, TMP_EXTRACTED_FILES.get(k));
        } catch (URISyntaxException | IOException ex) {
            LOGGER.error("Error cleaning up temporary directory {}", TMP_EXTRACTED_FILES.get(k).toString(), ex);
        }
    });

    undertowServer.stop();

    if (!silent) {
        LOGGER.info(ansi().fg(GREEN).bold().a("RESTHeart stopped").reset().toString());
    }

    LoggingInitializer.stopLogging();
}

From source file:org.search.system.dao.ImageDao.java

License:Open Source License

public void insertImage(Image image) {
    MongoInstance mongoInstance = databaseManager.getInstance();
    MongoClient mongo = new MongoClient(mongoInstance.getHost(), mongoInstance.getPort());
    try {/* ww w. j av  a2s  .  c om*/
        MongoDatabase pages = mongo.getDatabase(DATABASE_NAME);
        Document document = new Document();
        document.put("title", image.getTitle());
        document.put("description", image.getDescription());
        document.put("link", image.getLink());
        document.put("tags", image.getTags());
        document.put("imageHash", image.getImageHash());
        for (String tag : image.getTags()) {
            MongoCollection<Document> collection = pages.getCollection(tag.toLowerCase());
            collection.insertOne(document);
        }
        for (String tag : image.getTitle().split(" ")) {
            MongoCollection<Document> collection = pages.getCollection(tag.toLowerCase());
            collection.insertOne(document);
        }
        MongoCollection<Document> collection = pages.getCollection("imagesHash");
        collection.insertOne(document);
        mongo.close();
    } catch (Exception ex) {
        mongo.close();
        LogUtil.log(ex.toString());
    }
}

From source file:org.search.system.dao.PageDao.java

License:Open Source License

public void insertPage(Page page) {
    MongoInstance mongoInstance = databaseManager.getInstance();
    MongoClient mongo = new MongoClient(mongoInstance.getHost(), mongoInstance.getPort());
    try {/*from w  w w  . jav a  2 s.c o m*/
        MongoDatabase pages = mongo.getDatabase(DATABASE_NAME);
        Document document = new Document();
        document.put("title", page.getTitle());
        document.put("description", page.getDescription());
        document.put("rang", 0);
        document.put("link", page.getLink());
        document.put("tags", page.getTags());
        for (String tag : page.getTags()) {
            MongoCollection<Document> collection = pages.getCollection(tag.toLowerCase());
            collection.insertOne(document);
        }
        for (String tag : page.getTitle().split(" ")) {
            MongoCollection<Document> collection = pages.getCollection(tag.toLowerCase());
            collection.insertOne(document);
        }
        mongo.close();
    } catch (Exception ex) {
        mongo.close();
        LogUtil.log(ex.toString());
    }
}

From source file:org.search.system.dao.WordDao.java

License:Open Source License

public void insertPage(Word word) {
    MongoInstance mongoInstance = databaseManager.getInstance();
    MongoClient mongo = new MongoClient(mongoInstance.getHost(), mongoInstance.getPort());
    try {//from www .j a  v  a2  s.  c om
        MongoDatabase synonyms = mongo.getDatabase("synonyms");
        MongoCollection<Document> collection = synonyms.getCollection("synonyms");
        Document document = new Document();
        document.put("word", word.getWord());
        document.put("synonyms", word.getSynonyms());
        collection.insertOne(document);
        mongo.close();
    } catch (Exception ex) {
        mongo.close();
        LogUtil.log(ex.toString());
    }
}

From source file:org.search.system.managers.DatabaseManager.java

License:Open Source License

private List<Document> fetchFromInstance(String databaseName, String collectionName, Document query,
        MongoInstance instance) {//from   w  w  w  . ja va2s. c o m
    List<Document> result = new ArrayList<>();
    MongoClient mongo = new MongoClient(instance.getHost(), instance.getPort());
    try {
        MongoDatabase database = mongo.getDatabase(databaseName);
        MongoCollection<Document> data = database.getCollection(collectionName);
        FindIterable<Document> cursor;
        if (query == null) {
            cursor = data.find();
        } else {
            cursor = data.find(query);
        }
        if (cursor == null) {
            return result;
        }
        for (Document doc : cursor) {
            result.add(doc);
        }
        mongo.close();
    } catch (Exception ex) {
        mongo.close();
        LogUtil.log(ex.toString());
    }
    return result;
}

From source file:org.search.system.managers.DatabaseManager.java

License:Open Source License

public Document findOne(String databaseName, String collectionName, Document query) {
    Document result = null;/*from w  ww.  j a  v  a 2 s  .  c  o m*/
    for (MongoInstance instance : instances) {
        MongoClient mongo = new MongoClient(instance.getHost(), instance.getPort());
        try {
            MongoDatabase database = mongo.getDatabase(databaseName);
            MongoCollection<Document> collection = database.getCollection(collectionName);
            result = collection.find(query).first();
            mongo.close();
        } catch (Exception ex) {
            LogUtil.log(ex.toString());
            mongo.close();
        }
        if (result != null) {
            break;
        }
    }
    return result;
}

From source file:org.search.system.models.MongoInstance.java

License:Open Source License

public int getSize() {
    int size;/* w w w. jav a2 s.c om*/
    MongoClient mongo = new MongoClient(host, port);
    DB synonyms = mongo.getDB("synonyms");
    DB pages = mongo.getDB("pages");
    CommandResult result = synonyms.getStats();
    size = (int) result.get("objects");
    result = pages.getStats();
    size += (int) result.get("objects");
    mongo.close();
    return size;
}