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.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java

public List<DBObject> listAndSort(DBObject query, BasicDBObject sorter) throws CompatibilityDataException {
    List<DBObject> objects = new ArrayList<DBObject>();

    DBCursor cursor = null;//from  w ww .  j  a  va 2  s  .c o  m
    MongoClient client = null;
    try {
        client = getService().createClient();
        cursor = client.getDB(database).getCollection(collection).find(query).sort(sorter);
        while (cursor.hasNext()) {
            objects.add(cursor.next());
        }
    } catch (Exception ex) {
        throw new CompatibilityDataException(
                String.format("(Unknown Host) Failed to fetch object with query %s", query), ex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
        if (client != null) {
            client.close();
        }
    }
    return objects;
}

From source file:org.lambdamatic.mongodb.internal.connection.MongoClientProducer.java

License:Open Source License

/**
 * Method called when the client is to be disposed.
 * /*from   w  w w . jav  a  2 s.  c o m*/
 * @param mongoClient the {@link MongoClient} to dispose
 */
@SuppressWarnings("static-method")
public void disposeClient(@Disposes MongoClient mongoClient) {
    mongoClient.close();
}

From source file:org.mandar.analysis.recsys2014.recsysMain.java

License:Open Source License

public void run() {
    // We first need to configure the data access.
    LenskitConfiguration dataConfig = this.configureDAO(DBSettings.TRAINING_COLLECTION);
    // Now we create the LensKit configuration...
    LenskitConfiguration config = new LenskitConfiguration();
    if (algo.equals("svd")) {
        config = this.configureSVDRecommender(numFeatures, numIterations, regularizationParam,
                stoppingCondition, threshold);
    } else if (algo.equals("ii")) {
        config = this.configureIIRecommender(numNeighbours, similarityModel);
    } else if (algo.equals("uu")) {
        config = this.configureUURecommender(numNeighbours);
    } else if (algo.equals("so")) {
        config = this.configureSORecommender(damping);
    } else if (algo.equals("tfidf")) {
        config = this.configureTFIDFRecommender();
    }/*w  ww  .j a  v  a 2 s.c  om*/

    // There are more parameters, roles, and components that can be set. See the
    // JavaDoc for each recommender algorithm for more information.
    // Now that we have a factory, build a recommender from the configuration
    // and data source. This will compute the similarity matrix and return a recommender
    // that uses it.
    LenskitRecommender rec = null;
    try {
        LenskitRecommenderEngine engine = LenskitRecommenderEngine.newBuilder().addConfiguration(config)
                .addConfiguration(dataConfig).build();
        rec = engine.createRecommender(dataConfig);

    } catch (RecommenderBuildException e) {
        e.printStackTrace();
        System.exit(1);
    }
    // we want to recommend items
    if ("training".equals(this.goal)) {
        ItemRecommender irec = rec.getItemRecommender();
        assert irec != null; // not null because we configured one
        // for users
        try {
            MongoClient mongoClient = new MongoClient(DBSettings.DBHOST);
            DB db = mongoClient.getDB(DBSettings.DATABASE);
            DBCollection collection = db.getCollection(DBSettings.MOVIES_COLLECTION);
            for (long user : users) {
                // get 10 recommendation for the user
                List<ScoredId> recs = irec.recommend(user, 10);
                System.out.format("Recommendations for %d:\n", user);
                for (ScoredId item : recs) {
                    DBObject obj = collection.findOne(new BasicDBObject(DBSettings.FIELDS.movie, item.getId()));
                    String recTitle = obj.get("title").toString();
                    String recDirector = obj.get("director").toString();
                    String recRel = obj.get("release_date").toString();
                    String recStars = obj.get("stars").toString();

                    System.out.format("\tID:%d, %s, %s Directed By: %s Starring: %s\n", item.getId(), recTitle,
                            recRel, recDirector, recStars);
                }
            }
            mongoClient.close();
        } catch (UnknownHostException u) {
            u.printStackTrace();
        }
    } else if ("eval".equals(this.goal)) {
        //ItemScorer iscorer = rec.getItemScorer();
        RatingPredictor rat = rec.getRatingPredictor();
        File outFile = new File("data/participant_solution_" + algo + ".dat");
        String line = "";
        //String cvsSplitBy = ",";
        long eng = 0;
        int count = 0;
        try {
            long lines = Utils.countLines("data/test_solution.dat");
            //outFile.delete();
            BufferedWriter brout = new BufferedWriter((new FileWriter(outFile, false)));
            //BufferedReader br = new BufferedReader(new FileReader(csvData));
            long progress = 0;
            //br.readLine();
            System.out.println(
                    "Reading from Test Set and writing result " + "data/participant_solution_" + algo + ".dat");

            MongoClient mongoClient = new MongoClient(DBSettings.DBHOST);
            DB db = mongoClient.getDB(DBSettings.DATABASE);
            DBCollection collection = db.getCollection(DBSettings.TEST_COLLECTION_EMPTY);
            DBCursor cur = collection.find();

            ArrayList<DBObject> arr = new ArrayList<DBObject>(cur.size());

            System.out.println("Making ObjectArrayList out of test collection result");
            while (cur.hasNext()) {
                DBObject buff = cur.next();
                eng = (long) Math.abs(rat.predict(Long.parseLong(buff.get("uID").toString()),
                        Long.parseLong(buff.get("movieID").toString())));
                buff.put("engagement", eng);
                arr.add(buff);
                count++;
            }

            cur.close();
            //Now sort this by uID (desc), engagement (desc) and tweetID (desc)
            System.out.println("Sorting ObjectArrayList");
            Collections.sort(arr, new MongoComparator());
            for (int i = 0; i < arr.size(); i++) {
                brout.write(arr.get(i).get("uID") + "," + arr.get(i).get("tweetID") + ","
                        + arr.get(i).get("engagement"));
                brout.newLine();
                progress++;
                if ((progress * 100 / lines) % 10 >= 0 && (progress * 100 / lines) % 10 <= 1) {
                    System.out.println("File write Progress: " + (progress * 100 / lines) + " %");
                }
            }
            brout.close();

            ProcessBuilder pbr = new ProcessBuilder("java", "-jar",
                    "rscevaluator-0.1-jar-with-dependencies.jar", "data/test_solution.dat",
                    "data/participant_solution_" + algo + ".dat");
            Process p = pbr.start();

            BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
            double resultbuff = 0.0d;
            while ((line = is.readLine()) != null) {
                if (line.contains("nDCG@10:")) {
                    resultbuff = Double.parseDouble(line.substring(9));
                }
                System.out.println(line);
            }
            System.out.println("Writing evaluation results to MongoDB");
            this.writeAlgoTestResults(resultbuff, db);
            mongoClient.close();
            p.waitFor();

        } catch (FileNotFoundException f) {
            f.printStackTrace();
        } catch (IOException f) {
            f.printStackTrace();
        } catch (InterruptedException i) {
            i.printStackTrace();
        } catch (NullPointerException n) {
            n.printStackTrace();
        }
    }
}

From source file:org.netbeans.modules.mongodb.MongoConnection.java

License:Open Source License

public MongoClient connect() {
    synchronized (connectionLock) {
        if (client == null) {
            BaseProgressUtils.showProgressDialogAndRun(new Runnable() {

                @Override/* w ww.j  av  a  2  s  .  c o  m*/
                public void run() {
                    final ConnectionInfo connection = getLookup().lookup(ConnectionInfo.class);
                    try {
                        client = new MongoClient(connection.getMongoURI());
                        fireConnectionStateChanged(ConnectionState.CONNECTED);
                    } catch (MongoException ex) {
                        DialogNotification
                                .error("error connectiong to mongo database: " + ex.getLocalizedMessage());
                        MongoClient client = MongoConnection.this.client;
                        MongoConnection.this.client = null;
                        if (client != null) {
                            client.close();
                        }
                    }
                }
            }, Bundle.waitWhileConnecting());
        }
    }
    return client;
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBChecker.java

License:Apache License

@Override
public void check(ConfigurationGenerator cg) throws ConfigurationException {
    MongoClient ret = null;
    String serverName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_SERVER);
    String dbName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_NAME);

    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            .serverSelectionTimeout((int) TimeUnit.SECONDS.toMillis(1)).description("Nuxeo DB Check");
    if (serverName.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        ret = new MongoClient(new MongoClientURI(serverName, optionsBuilder));
    } else {// w w  w  .  j  av  a 2  s.co m
        ret = new MongoClient(new ServerAddress(serverName), optionsBuilder.build());
    }
    try {
        Document ping = new Document("ping", "1");
        ret.getDatabase(dbName).runCommand(ping);
    } catch (MongoTimeoutException e) {
        throw new ConfigurationException(
                String.format("Unable to connect to MongoDB at %s, please check your connection", serverName));
    } finally {
        ret.close();
    }
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBRepositoryTestCase.java

License:Open Source License

protected void clearMongoDb() throws UnknownHostException {
    MongoClient mongoClient = MongoDBRepository.newMongoClient(descriptor);
    try {/*w  ww.  j a  va  2s .  c o m*/
        DBCollection coll = MongoDBRepository.getCollection(descriptor, mongoClient);
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
        coll = MongoDBRepository.getCountersCollection(descriptor, mongoClient);
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    } finally {
        mongoClient.close();
    }
}

From source file:org.nuxeo.ecm.core.test.StorageConfiguration.java

License:Apache License

protected void clearMongoDB(MongoDBRepositoryDescriptor descriptor) throws UnknownHostException {
    MongoClient mongoClient = MongoDBRepository.newMongoClient(descriptor);
    try {//from w  w  w.j  av  a 2 s.  co  m
        DBCollection coll = MongoDBRepository.getCollection(descriptor, mongoClient);
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
        coll = MongoDBRepository.getCountersCollection(descriptor, mongoClient);
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    } finally {
        mongoClient.close();
    }
}

From source file:org.pentaho.di.trans.steps.mongodboutput.MongoDbOutputDialog.java

License:Open Source License

private void showIndexInfo() {
    String hostname = transMeta.environmentSubstitute(m_hostnameField.getText());
    String dbName = transMeta.environmentSubstitute(m_dbNameField.getText());
    String collection = transMeta.environmentSubstitute(m_collectionField.getText());

    if (!Const.isEmpty(hostname)) {
        MongoClient conn = null;
        try {/*from  w ww.  j  a  v a 2  s  .  c  o  m*/
            MongoDbOutputMeta meta = new MongoDbOutputMeta();
            getInfo(meta);
            MongoClientWrapper wrapper = MongoWrapperUtil.createMongoClientWrapper(meta, transMeta, log);
            StringBuffer result = new StringBuffer();
            for (String index : wrapper.getIndexInfo(dbName, collection)) {
                result.append(index).append("\n\n"); //$NON-NLS-1$
            }

            ShowMessageDialog smd = new ShowMessageDialog(shell, SWT.ICON_INFORMATION | SWT.OK,
                    BaseMessages.getString(PKG, "MongoDbOutputDialog.IndexInfo", collection), result.toString(),
                    true); //$NON-NLS-1$
            smd.open();
        } catch (Exception e) {
            logError(getString("MongoDbOutputDialog.ErrorMessage.GeneralError.Message") //$NON-NLS-1$
                    + ":\n\n" + e.getMessage(), e); //$NON-NLS-1$
            new ErrorDialog(shell, getString("MongoDbOutputDialog.ErrorMessage.IndexPreview.Title"),
                    //$NON-NLS-1$
                    getString("MongoDbOutputDialog.ErrorMessage.GeneralError.Message") //$NON-NLS-1$
                            + ":\n\n" + e.getMessage(), //$NON-NLS-1$
                    e);
        } finally {
            if (conn != null) {
                conn.close();
                conn = null;
            }
        }
    }
}

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

License:Open Source License

/**
 * Return a list of custom "lastErrorModes" (if any) defined in the replica
 * set configuration object on the server. These can be used as the "w"
 * setting for the write concern in addition to the standard "w" values of
 * <number> or "majority".//from  w  w  w  .  j a va2s  .  c o  m
 * 
 * @param hostsPorts the hosts to use
 * @param singlePort the default port to use if no ports are given in the
 *          hostsPorts spec
 * @param username the username for authentication
 * @param password the password for authentication
 * @param vars the environment variables to use
 * @param log for logging
 * @return a list of the names of any custom "lastErrorModes"
 * @throws KettleException if a problem occurs
 */
public static List<String> getLastErrorModes(String hostsPorts, String singlePort, MongoCredential cred,
        VariableSpace vars, LogChannelInterface log) throws KettleException {

    List<String> customLastErrorModes = new ArrayList<String>();

    MongoClient mongo = null;
    try {
        if (cred != null && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) {
            // need to make a new credential that specifies the local database
            cred = MongoCredential.createMongoCRCredential(cred.getUserName(), LOCAL_DB, cred.getPassword());
        }
        mongo = initConnection(hostsPorts, singlePort, cred, false, null, null, null, null, null, false, null,
                vars, log);

        DB local = mongo.getDB(LOCAL_DB);
        if (local != null) {

            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();

                extractLastErrorModes(config, customLastErrorModes);
            }
        }
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }

    return customLastErrorModes;
}

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

License:Open Source License

protected static BasicDBList getRepSetMemberRecords(String hostsPorts, String singlePort, MongoCredential cred,
        VariableSpace vars, LogChannelInterface log) throws KettleException {

    MongoClient mongo = null;
    BasicDBList setMembers = null;/*from  w  w w  . j av  a2  s. c  om*/
    try {
        if (cred != null && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) {
            // need to make a new credential that specifies the local database
            cred = MongoCredential.createMongoCRCredential(cred.getUserName(), LOCAL_DB, cred.getPassword());
        }
        mongo = initConnection(hostsPorts, singlePort, cred, false, null, null, null, null, null, false, null,
                vars, log);

        DB local = mongo.getDB(LOCAL_DB);
        if (local != null) {

            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();

                if (config != null) {
                    Object members = config.get(REPL_SET_MEMBERS);

                    if (members instanceof BasicDBList) {
                        if (((BasicDBList) members).size() == 0) {
                            // log that there are no replica set members defined
                            if (log != null) {
                                log.logBasic(BaseMessages.getString(PKG,
                                        "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                            }
                        } else {
                            setMembers = (BasicDBList) members;
                        }

                    } else {
                        // log that there are no replica set members defined
                        if (log != null) {
                            log.logBasic(BaseMessages.getString(PKG,
                                    "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                        }
                    }
                } else {
                    // log that there are no replica set members defined
                    if (log != null) {
                        log.logBasic(BaseMessages.getString(PKG,
                                "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                    }
                }
            } else {
                // log that the replica set collection is not available
                if (log != null) {
                    log.logBasic(BaseMessages.getString(PKG,
                            "MongoUtils.Message.Warning.ReplicaSetCollectionUnavailable")); //$NON-NLS-1$
                }
            }
        } else {
            // log that the local database is not available!!
            if (log != null) {
                log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.LocalDBNotAvailable")); //$NON-NLS-1$
            }
        }
    } catch (Exception ex) {
        throw new KettleException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }

    return setMembers;
}