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:nz.co.acme.spike.rest.configuration.MongoDb.java

License:Open Source License

/**
 * Close the database connection as a part of servlet context destruction.
 *
 * Retrieves the connection from the servlet context and destroys it. Over
 * zealous containers may warn about possible memory leaks due to threads
 * that the client started not being shut down. Generally this is just the
 * container moaning that it does not manage all of its threads directly. In
 * most cases this warning is not actually valid.
 *
 * @param servletContextEvent//from ww  w.j  a  va2  s.  c o m
 */
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();
    MongoClient mongoClient = (MongoClient) servletContext.getAttribute("mongoClient");
    mongoClient.close();
    logger.info("Closed connection to MongoDB.");
}

From source file:org.apache.jackrabbit.oak.upgrade.cli.node.MongoFactory.java

License:Apache License

private static Closeable asCloseable(final MongoClient client) {
    return new Closeable() {
        @Override/*  w  ww. j  a  va2 s  .  co  m*/
        public void close() throws IOException {
            client.close();
        }
    };
}

From source file:org.apache.karaf.jaas.modules.mongo.internal.MongoClientExpirationListener.java

License:Apache License

@Override
public void expired(MongoClient client) {

    try {/*  w w w. j  a v a  2  s .c o m*/
        client.close();
    } catch (Exception e) {
    }

}

From source file:org.apache.metamodel.mongodb.mongo3.MongoDbDataCopyer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.setProperty("derby.storage.tempDirector", FileHelper.getTempDir().getAbsolutePath());
    System.setProperty("derby.stream.error.file",
            File.createTempFile("metamodel-derby", ".log").getAbsolutePath());

    File dbFile = new File("../jdbc/src/test/resources/derby_testdb.jar");
    dbFile = dbFile.getCanonicalFile();//from   ww w.ja v a2s.co m
    if (!dbFile.exists()) {
        throw new IllegalStateException("File does not exist: " + dbFile);
    }

    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    Connection connection = DriverManager
            .getConnection("jdbc:derby:jar:(" + dbFile.getAbsolutePath() + ")derby_testdb;territory=en");
    connection.setReadOnly(true);

    MongoClient client = new MongoClient();
    MongoDatabase mongoDb = client.getDatabase("orderdb_copy");

    DataContext sourceDataContext = new JdbcDataContext(connection);

    new MongoDbDataCopyer(mongoDb, "orders", sourceDataContext, "APP", "orders").copy();
    new MongoDbDataCopyer(mongoDb, "offices", sourceDataContext, "APP", "offices").copy();
    new MongoDbDataCopyer(mongoDb, "payments", sourceDataContext, "APP", "payments").copy();
    new MongoDbDataCopyer(mongoDb, "orderfact", sourceDataContext, "APP", "orderfact").copy();
    new MongoDbDataCopyer(mongoDb, "products", sourceDataContext, "APP", "products").copy();

    connection.close();
    client.close();
}

From source file:org.apache.nutch.crawl.GeneratorJob2.java

License:Apache License

public int generateBatchId(Configuration conf, String batchId) {
    MongoClient mongoClient = null;
    try {/*from   w w w  . j a va2  s  . co m*/
        mongoClient = new MongoClient(goraMongoAddress);
        DB db = mongoClient.getDB(goraMongoDb);
        String cId = conf.get(Nutch.CRAWL_ID_KEY);
        String collPrefix = "";
        if (org.apache.commons.lang3.StringUtils.isNoneEmpty(cId)) {
            collPrefix = cId + "_";
        }
        String crawlColl = collPrefix + "webpage";
        DBCollection collOps = db.getCollection(crawlColl);
        //update({"count":{$gt:20}},{$set:{"name":"c4"}},false,true)  
        BasicDBObject q = new BasicDBObject("batchId", null);

        DBObject set = new BasicDBObject("batchId", batchId);
        set.put("markers._gnmrk_", batchId);
        BasicDBObject o = new BasicDBObject("$set", set);
        WriteResult wr = collOps.update(q, o, false, true);
        long curTime = System.currentTimeMillis();
        //taotoxht add
        q = new BasicDBObject();
        q.append("fetchTime", new BasicDBObject().append(QueryOperators.GT, curTime));
        o = new BasicDBObject();
        o.append("$set", new BasicDBObject().append("fetchTime", curTime));
        collOps.update(q, o, false, true);

        return wr.getN();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;

    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }

}

From source file:org.apache.rya.indexing.export.ITBase.java

License:Apache License

@AfterClass
public static void shutdownMiniResources() throws RepositoryException {
    for (final RyaSailRepository repo : ryaRepos) {
        repo.shutDown();//from w  w w. ja  va 2s  .  c o m
    }
    for (final RepositoryConnection conn : ryaConns) {
        conn.close();
    }
    for (final MongoClient client : clients) {
        client.close();
    }
    ryaRepos.clear();
    ryaConns.clear();
    clients.clear();
}

From source file:org.apache.rya.indexing.geoExamples.RyaMongoGeoDirectExample.java

License:Apache License

private static Configuration getConf() throws IOException {

    MongoDBIndexingConfigBuilder builder = MongoIndexingConfiguration.builder().setUseMockMongo(USE_MOCK)
            .setUseInference(USE_INFER).setAuths("U");

    if (USE_MOCK) {
        mock = EmbeddedMongoFactory.newFactory();
        MongoClient c = mock.newMongoClient();
        ServerAddress address = c.getAddress();
        String url = address.getHost();
        String port = Integer.toString(address.getPort());
        c.close();
        builder.setMongoHost(url).setMongoPort(port);
    } else {// w  w w  . j  a v a 2  s . co  m
        // User name and password must be filled in:
        builder = builder.setMongoUser("fill this in").setMongoPassword("fill this in")
                .setMongoHost(MONGO_INSTANCE_URL).setMongoPort(MONGO_INSTANCE_PORT);
    }

    return builder.setMongoDBName(MONGO_DB).setMongoCollectionPrefix(MONGO_COLL_PREFIX)
            .setUseMongoFreetextIndex(true).setMongoFreeTextPredicates(RDFS.LABEL.stringValue()).build();

}

From source file:org.apache.rya.shell.RyaConnectionCommands.java

License:Apache License

@CliCommand(value = CONNECT_MONGO_CMD, help = "Connect the shell to an instance of MongoDB.")
public String connectToMongo(@CliOption(key = {
        "username" }, mandatory = false, help = "The username that will be used to connect to MongoDB when performing administrative tasks.") final String username,
        @CliOption(key = {/*  www . j a v a2 s  . c  o  m*/
                "hostname" }, mandatory = true, help = "The hostname of the MongoDB that will be connected to.") final String hostname,
        @CliOption(key = {
                "port" }, mandatory = true, help = "The port of the MongoDB that will be connected to.") final String port) {

    try {
        // If a username was provided, then prompt for a password.
        char[] password = null;
        if (username != null) {
            password = passwordPrompt.getPassword();
        }

        // Create the Mongo Connection Details that describe the Mongo DB Server we are interacting with.
        final MongoConnectionDetails connectionDetails = new MongoConnectionDetails(hostname,
                Integer.parseInt(port), Optional.ofNullable(username), Optional.ofNullable(password));

        // Connect to a MongoDB server. TODO Figure out how to provide auth info?
        final MongoClient adminClient = new MongoClient(hostname, Integer.parseInt(port));
        // Make sure the client is closed at shutdown.
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                adminClient.close();
            }
        });

        try {
            //attempt to get the connection point, essentially pinging mongo server.
            adminClient.getConnectPoint();
        } catch (final MongoException e) {
            //had to rethrow to get scope on adminClient.
            adminClient.close();
            throw e;
        }

        // Initialize the connected to Mongo shared state.
        final RyaClient ryaClient = MongoRyaClientFactory.build(connectionDetails, adminClient);
        sharedState.connectedToMongo(connectionDetails, ryaClient);

    } catch (final IOException | MongoException e) {
        throw new RuntimeException("Could not connection to MongoDB. Reason: " + e.getMessage(), e);
    }

    return "Connected. You must select a Rya instance to interact with next.";
}

From source file:org.apache.rya.test.mongo.EmbeddedMongoSingleton.java

License:Apache License

public static MongoClient getNewMongoClient() throws UnknownHostException, MongoException {
    final MongoClient client = InstanceHolder.SINGLETON.factory.newMongoClient();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override//from   w ww  .ja v a 2  s  . com
        public void run() {
            try {
                client.close();
            } catch (final Throwable t) {
                // logging frameworks will likely be shut down
                t.printStackTrace(System.err);
            }
        }
    });

    return client;
}

From source file:org.araqne.logdb.mongo.query.MongoFindCommand.java

License:Apache License

@Override
public void run() {
    MongoProfile profile = options.getProfile();

    MongoClient mongo = null;
    DBCursor cursor = null;//  w  w  w  .j av a 2 s.c  o  m
    try {
        mongo = new MongoClient(profile.getAddress(), profile.getCredentials());

        DB db = mongo.getDB(options.getDatabase());
        DBCollection col = db.getCollection(options.getCollection());
        cursor = col.find();

        while (cursor.hasNext()) {
            DBObject doc = cursor.next();

            Map<String, Object> m = convert(doc);
            pushPipe(new Row(m));
        }
    } catch (Throwable t) {
        slog.error("araqne logdb mongo: cannot run mongo.find", t);
    } finally {
        if (cursor != null)
            cursor.close();

        if (mongo != null)
            mongo.close();
    }
}