Example usage for com.mongodb Mongo close

List of usage examples for com.mongodb Mongo close

Introduction

In this page you can find the example usage for com.mongodb Mongo 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:com.nesscomputing.mongo.MongoWriter.java

License:Apache License

synchronized void stop() {
    final Thread thread = writerThread.getAndSet(null);
    if (thread != null) {
        LOG.info("Stopping Mongo Writer for collection %s.", collectionName);
        try {/*from  www.  j  av  a 2s  .c om*/
            taskRunning.set(false);
            thread.interrupt();
            thread.join(500L);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }

        final DBCollection collection = dbCollection.getAndSet(null);
        if (collection != null) {
            final Mongo mongo = collection.getDB().getMongo();
            mongo.close();
        }
    } else {
        LOG.debug("Never started, ignoring stop()");
    }
}

From source file:com.ovea.mongodb.EmbeddedMongoDB.java

License:Apache License

public static EmbeddedMongoDB addRunning(int port, String username, String password) {
    try {//from ww w  .  j av  a  2  s.  c o  m
        Mongo mongo = null;
        File path = null;
        try {
            mongo = new Mongo("localhost", port);
            DB db = mongo.getDB("admin");
            if (username != null && password != null)
                db.authenticate(username, password.toCharArray());
            BSONObject obj = (BSONObject) db.command("getCmdLineOpts").get("parsed");
            if (obj != null) {
                String val = (String) obj.get("dbpath");
                if (val != null)
                    path = new File(val);
            }
        } finally {
            if (mongo != null)
                mongo.close();
        }
        return add(new FileEntry(port, -1, path));
    } catch (UnknownHostException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.ovea.mongodb.EmbeddedMongoDBMain.java

License:Apache License

public static void main(String[] args) throws InterruptedException, IOException {
    String path = System.getProperty("os.name").toLowerCase().contains("windows") ? "mongod.exe" : "mongod";

    EmbeddedMongoDB embeddedMongoDB = EmbeddedMongoDB.getOrCreate(path, "--nohttpinterface");
    // add users/* w  w  w  .  jav a2  s  . c  o  m*/
    try {
        Mongo mongo = new Mongo("localhost", embeddedMongoDB.port());
        DB smt = mongo.getDB("smt");
        smt.addUser("smt", "ilovesmt".toCharArray());
        DB admin = mongo.getDB("admin");
        admin.addUser("admin", "admin".toCharArray());
        mongo.close();
    } catch (Exception e) {
    }
    System.out.println("terminate");
    // restart DB with auth option
    embeddedMongoDB.terminate();

    System.out.println("getOrCreate");
    embeddedMongoDB = EmbeddedMongoDB.getOrCreate(path, "--nohttpinterface", "--auth", "--dbpath",
            embeddedMongoDB.dbPath().getAbsolutePath());

    System.out.println("waitFor");
    System.out.println(embeddedMongoDB.port());
    System.out.println(embeddedMongoDB.pid());
    System.out.println(embeddedMongoDB.dbPath());

    System.in.read();

    embeddedMongoDB.terminate();
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

public static void close(final Mongo client) {
    MongoClientURI uri = URI_MAP.get().remove(client);
    if (uri != null) {
        MongoClient remove;//from  ww w  .j  av a2s  . co  m
        remove = CLIENTS.get().remove(uri);
        if (remove != client) {
            throw new IllegalStateException("different clients found");
        }
    }
    client.close();
}

From source file:DataAccess.DAO.LoginDAO.java

public String validate(String username, String password) {

    String returnText = LOGIN_FAILURE;

    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("Restaurant");

    try {//www.  j  a  v  a2s .  c  o  m

        //boolean auth = db.authenticate(username, password.toCharArray());
        MongoCredential credential2 = MongoCredential.createCredential(username, "Restaurant",
                password.toCharArray());
        MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential2));

        DB db2 = mongoClient.getDB("Restaurant");
        System.out.println("Connect to database successfully");

        DBCollection coll = db2.getCollection("Users");
        System.out.println("Collection users selected successfully");
        BasicDBObject document2 = new BasicDBObject();
        document2.put("UserName", username);
        document2.put("Password", password);
        //coll.insert(document2);
        DBCursor cur2 = coll.find(document2);

        System.out.println(cur2.toString());

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

        System.out.println("Login is successful!");

        if (credential2 != null) {

            DBCollection table = db.getCollection("Users");

            BasicDBObject document = new BasicDBObject();
            document.put("UserName", username);
            table.insert(document);
            DBCursor cur = table.find(document);

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

            HttpSession session = SessionBean.getSession();
            session.setAttribute("UserName", user);

            System.out.println("Login is successful!");
            returnText = LOGIN_SUCCESS;

            return "admins";
        } else {

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Incorrect Username and Passowrd", "Please enter correct username and Password"));

            System.out.println("Login is failed!");
            return "login";
        }
        //System.out.println("Done");

        //return returnText;

    } catch (MongoException e) {
        e.printStackTrace();
    } finally {
        mongo.close();
    }
    return returnText;
}

From source file:eu.artist.cloud.auditors.AbstractedAvailabilityLogger.java

License:Open Source License

/**
 * @param args/* w w w  .ja  v  a 2s  .co m*/
 */
public void logAvailability(ArrayList<String> TemplateIDs, String DBuser, String DBpass, String databaseIP)
        throws UnknownHostException, MongoException {
    // TODO Auto-generated method stub

    //needs to be periodic - but periodicity may be on the previous level-> Availability Auditor
    //better on the Availability Auditor level, since it will have refreshed also the state
    //needs to raise one thread per node, concurrent requests for all nodes?
    //sla is per template id? logically yes, so thread must be per template id

    //mongodb connection
    //we need to pass an object that will be the DB record and will contain all necessary information
    //this object will be transformed to json
    //more efficient to pass an arraylist of these objects (for all template IDs in one sample) and make once
    //the connection to the DB (for needed in the basic operation)

    for (String record : TemplateIDs) {
        Mongo mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        System.out.println("Host address for Backend DB:" + databaseIP);
        Set<String> colls = db.getCollectionNames();

        for (String s : colls) {
            System.out.println("These are the collections... " + s);
        }
        DBCollection coll = db.getCollection("log_samples");

        //log sample
        /*BasicDBObject doc = new BasicDBObject("name1", "MongoDB2").
        append("type", "database").
        append("count", 1).
        append("info", new BasicDBObject("x", 203).append("y", 102));
        */
        //DBObject obj=new DBObject();

        JSON jsonObj = new JSON();

        DBObject obj = (DBObject) jsonObj.parse(record);
        //BasicDBObject doc=new BasicDBObject(record);

        ObjectId obid = new ObjectId();
        //System.out.println("This is the id:"+obj.get("_id"));
        coll.insert(obj);

        DBObject myDoc = coll.findOne();
        //System.out.println(myDoc);
        //coll.
        mongoClient.close();
        //log file must be per template ID so that it can be appended each time, if we start stop the auditing action
        //ideally templateID_month_year

        //return 0;
    }
    System.out.println("Records included");
}

From source file:ezbake.deployer.publishers.database.MongoDBDatabaseSetup.java

License:Apache License

@Override
public List<ArtifactDataEntry> setupDatabase(DeploymentArtifact artifact, Properties configuration,
        EzSecurityToken callerToken) throws DeploymentException {
    MongoHelper mongoHelper = new MongoHelper(configuration);
    MongoConfigurationHelper mongoConfiguration = mongoHelper.getMongoConfigurationHelper();

    //Setup new mongo properties
    String databaseName = ArtifactHelpers.getNamespace(artifact);
    String userName = databaseName + "_user";
    String password = new BigInteger(130, random).toString(32);

    //Connect to Mongo DB
    Mongo client = getMongoClient(mongoHelper);
    try {// w  w  w.  java2  s  .  c o m
        //If user exists, re-generate the password and reset the password
        DBObject cmd = new BasicDBObject("updateUser", userName);
        cmd.put("pwd", password);
        cmd.put("roles", DBRole);
        CommandResult result = client.getDB(databaseName).command(cmd);
        if (!result.ok()) {
            logger.warn("Failed to update mongo user. {}.  Attempting to add", result.getErrorMessage());
            //If user doesn't exist, create new Mongo DB User/Password/Database unique for this application
            cmd = new BasicDBObject("createUser", userName);
            cmd.put("pwd", password);
            cmd.put("roles", DBRole);
            result = client.getDB(databaseName).command(cmd);
            result.throwOnError();
        }
    } finally {
        client.close();
    }

    //Create a mongo.properties file with mongo host, username, password(hashed), and database
    Map<String, String> valuesMap = Maps.newHashMap();
    valuesMap.put(EzBakePropertyConstants.MONGODB_DB_NAME, databaseName);
    valuesMap.put(EzBakePropertyConstants.MONGODB_HOST_NAME, mongoConfiguration.getMongoDBHostName());
    valuesMap.put(EzBakePropertyConstants.MONGODB_USE_SSL,
            Boolean.toString(mongoConfiguration.useMongoDBSSL()));

    Map<String, String> encryptedValuesMap = Maps.newHashMap();
    encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_USER_NAME, userName);
    encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_PASSWORD, password);
    String connectionString = String.format("mongodb://%s:%s@%s/%s?ssl=%b", userName, password,
            mongoConfiguration.getMongoDBHostName(), databaseName, mongoConfiguration.useMongoDBSSL());
    encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_CONNECTION_STRING, connectionString);

    String properties = Joiner.on('\n').withKeyValueSeparator("=").join(valuesMap);
    String encryptedProps = Joiner.on('\n').withKeyValueSeparator("=").join(encryptedValuesMap);
    List<ArtifactDataEntry> entries = Lists.newArrayList();
    entries.add(Utilities.createConfCertDataEntry(MONGODB_PROPERTIES_FILE_NAME, properties.getBytes()));
    entries.add(Utilities.createConfCertDataEntry(ENCRYPTED_MONGODB_PROPERTIES_FILE_NAME,
            encryptedProps.getBytes()));
    return entries;
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

@Override
public List<CentralPurgeState> getPurgeState(EzSecurityToken token, List<Long> purgeIds)
        throws EzSecurityTokenException, TException {

    DBCollection purgeColl = null;/*from w w w .  j av a 2 s  .  c o m*/
    Mongo mongoClient = null;
    AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token).arg("event", "getPurgeState")
            .arg("purgeIds", purgeIds);
    try {
        validateCentralPurgeSecurityToken(token);

        // Get access to the purge collection within Mongo
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        purgeColl = mongoDB.getCollection(PURGE_COLLECTION);

        List<CentralPurgeState> result = new ArrayList<CentralPurgeState>();

        // Gets all centralPurgeStates that are in the purgeIds list
        BasicDBObject query = new BasicDBObject(EzCentralPurgeServiceHelpers.PurgeId,
                new BasicDBObject("$in", purgeIds));
        DBCursor cursor = purgeColl.find(query);

        // Decodes each centralPurgeState form how it's stored in MongoDB and adds it to the return variable
        for (DBObject dbObject : cursor) {
            CentralPurgeState centralPurgeState = decodeCentralPurgeState(
                    (DBObject) dbObject.get(CentralPurgeStateString));
            result.add(centralPurgeState);
        }
        return result;
    } catch (EzSecurityTokenException e) {
        logError(e, evt, "CentralPurgeService failed when trying to validate token:[" + e.getClass().getName()
                + ":" + e.getMessage() + "]");
        throw e;
    } catch (UnknownHostException e) {
        logError(e, evt, "CentralPurgeService unable to reach MongoDB in getPurgeState:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException("CentralPurgeService unable to reach MongoDB in getPurgeState:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
    } catch (Exception e) {
        logError(e, evt, "CentralPurgeService encountered an exception in getPurgeState:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException("CentralPurgeService encountered an exception in getPurgeState:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
    } finally {
        auditLogger.logEvent(evt);
        logEventToPlainLogs(logger, evt);
        if (mongoClient != null)
            mongoClient.close();
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

@Override
public void updatePurge(EzSecurityToken token, PurgeState inputPurgeState, String applicationName,
        String serviceName) throws EzSecurityTokenException, TException {
    DBObject dbObject = null;//from   ww w . j  a  v a  2 s.  com
    Map<String, ApplicationPurgeState> appStatesMap = null;
    CentralPurgeState centralPurgeState = null;
    CentralAgeOffEventState centralAgeOffEventState = null;
    Set<Long> centralCompletelyPurgedSet = null;
    Set<Long> centralToBePurgedSet = null;
    DBCollection purgeColl = null;
    DBCollection ageOffColl = null;
    Mongo mongoClient = null;

    AuditEvent evt = event(AuditEventType.FileObjectModify.getName(), token).arg("event", "update purge")
            .arg("purgeId", inputPurgeState.getPurgeId()).arg("service name", serviceName)
            .arg("application name", applicationName);

    ThriftClientPool pool = null;
    try {
        pool = new ThriftClientPool(configuration);
        securityClient.validateReceivedToken(token);
        // Validates that the application that is calling update purge is allowed to update for the passed appName
        String securityId = "";
        EzSecurityTokenWrapper wrapper = new EzSecurityTokenWrapper(token);
        // note: if the  centralPurgeService is calling then any appName can be updated
        if (wrapper.getSecurityId().equals(purgeAppSecurityId)) {
            securityId = purgeAppSecurityId;
        } else {
            securityId = pool.getSecurityId(getSecurityName(applicationName, serviceName));
        }

        if (!securityId.equals(wrapper.getSecurityId())) {
            throw new EzSecurityTokenException(
                    "The security id for the token does match the applicationName passed");
        }

        // Get access to the ageoff collection within Mongo
        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        purgeColl = mongoDB.getCollection(PURGE_COLLECTION);
        ageOffColl = mongoDB.getCollection(AGEOFF_COLLECTION);

        Long purgeId = inputPurgeState.getPurgeId();

        // Attempt to get the CentralPurgeState
        BasicDBObject query = new BasicDBObject(EzCentralPurgeServiceHelpers.PurgeId, purgeId);
        DBCursor cursor = purgeColl.find(query);

        boolean ageOff = false;
        CentralPurgeStatus centralPurgeStatus;

        // Check to see if the id passed corresponds to a purge event
        if (cursor.hasNext()) {
            //Set the map of application states and the set of ids to purge
            dbObject = cursor.next();
            centralPurgeState = decodeCentralPurgeState((DBObject) dbObject.get(CentralPurgeStateString));
            appStatesMap = centralPurgeState.getApplicationStates();

            PurgeInfo purgeInfo = centralPurgeState.getPurgeInfo();
            centralCompletelyPurgedSet = purgeInfo.getPurgeDocumentIds();
            centralToBePurgedSet = purgeInfo.getPurgeDocumentIds();
            centralPurgeStatus = centralPurgeState.getCentralStatus();
        } else {
            query = new BasicDBObject(EzCentralPurgeServiceHelpers.AgeOffEventId, purgeId);
            // If it doesn't exist as a purge, check to see if it is an ageOffEvent
            cursor = ageOffColl.find(query);

            if (cursor.hasNext()) {
                //Set the map of application states and the set of ids to purge
                dbObject = cursor.next();
                centralAgeOffEventState = decodeCentralAgeOffEventState(
                        (DBObject) dbObject.get(CentralAgeOffStateString));
                appStatesMap = centralAgeOffEventState.getApplicationStates();
                AgeOffEventInfo ageOffEventInfo = centralAgeOffEventState.getAgeOffEventInfo();
                centralToBePurgedSet = ageOffEventInfo.getPurgeSet();
                centralCompletelyPurgedSet = ageOffEventInfo.getPurgeSet();
                centralPurgeStatus = centralAgeOffEventState.getCentralStatus();
                ageOff = true;
            } else {
                throw new CentralPurgeServiceException("No purge with purgeId:" + purgeId);
            }
        }

        ServicePurgeState servicePurgeState = null;
        Map<String, ServicePurgeState> servicePurgeStatesMap = null;
        ApplicationPurgeState applicationPurgeState = null;
        // Gets the mongoDB entry for the service that is updating it's purge status.
        try {
            applicationPurgeState = appStatesMap.get(applicationName);
            servicePurgeStatesMap = applicationPurgeState.getServicePurgestates();
            servicePurgeState = servicePurgeStatesMap.get(serviceName);
            if (servicePurgeState == null) {
                throw new NullPointerException("Failed to find [" + applicationName + "_" + serviceName
                        + "] for purgeId" + inputPurgeState.getPurgeId() + " to update");
            }
        } catch (NullPointerException e) {
            throw e;
        }
        // Update the ServicePurgeState and put it back
        servicePurgeState.setTimeLastPoll(getCurrentDateTime());
        servicePurgeState.setPurgeState(inputPurgeState);
        servicePurgeStatesMap.put(serviceName, servicePurgeState);
        appStatesMap.put(applicationName, applicationPurgeState);
        boolean interventionNeeded = false;
        boolean stopped = true;
        Set<Long> servicePurged;

        /* These nested loops check each service to get an update of the CompletelyPurgedSet, see if any purge
         * service is still running and if manual intervention is/will be needed.
         */
        // Loop through all apps
        for (String appNameIter : appStatesMap.keySet()) {
            ApplicationPurgeState applicationPurgeStateInner = appStatesMap.get(appNameIter);
            Map<String, ServicePurgeState> servicePurgeStates = applicationPurgeStateInner
                    .getServicePurgestates();

            //Loop through all services
            for (String serviceNameIter : servicePurgeStates.keySet()) {
                PurgeState applicationServicePurgeState = servicePurgeStates.get(serviceNameIter)
                        .getPurgeState();
                servicePurged = applicationServicePurgeState.getPurged();
                applicationServicePurgeState.getPurged().removeAll(applicationServicePurgeState.getNotPurged());

                //update based on current service
                centralCompletelyPurgedSet = Sets.intersection(centralCompletelyPurgedSet, servicePurged);
                if (serviceStillRunning(applicationServicePurgeState.getPurgeStatus())) {
                    stopped = false;
                }
                if (!(applicationServicePurgeState.getNotPurged().isEmpty())) {
                    interventionNeeded = true;
                }
            }
        }

        // If all of the ids that needed to be purged have been purged then it resolved automatically
        boolean resolved = false;
        if (centralCompletelyPurgedSet.containsAll(centralToBePurgedSet)) {
            resolved = true;
            centralPurgeStatus = CentralPurgeStatus.RESOLVED_AUTOMATICALLY;
        }
        // If one of the services has a document that couldn't be
        // automatically resolved, manual intervention is needed
        if (centralPurgeStatus != CentralPurgeStatus.RESOLVED_MANUALLY
                && centralPurgeStatus != CentralPurgeStatus.RESOLVED_AUTOMATICALLY) {
            if (interventionNeeded) {
                if (stopped) {
                    centralPurgeStatus = CentralPurgeStatus.STOPPED_MANUAL_INTERVENTION_NEEDED;
                } else {
                    centralPurgeStatus = CentralPurgeStatus.ACTIVE_MANUAL_INTERVENTION_WILL_BE_NEEDED;
                }
            }
        } else {
            resolved = true;
        }

        if (ageOff == false) {
            // If it is a purge event, update the CentralPurgeState in MongoDB
            centralPurgeState.setApplicationStates(appStatesMap);
            centralPurgeState.setCentralStatus(centralPurgeStatus);

            dbObject.put(CentralPurgeStateString, encodeCentralPurgeState(centralPurgeState));
            purgeColl.update(query, dbObject, true, false);

            // Also need to update the purge in the ProvenanceService
            ProvenanceService.Client provenanceClient = null;
            try {
                provenanceClient = getProvenanceThriftClient(pool);
                EzSecurityToken centralTokenForProvenance = securityClient.fetchDerivedTokenForApp(token,
                        getProvenanceSecurityId(pool));
                provenanceClient.updatePurge(centralTokenForProvenance, purgeId, centralCompletelyPurgedSet,
                        null, resolved);
                PurgeInfo purgeInfo = provenanceClient.getPurgeInfo(centralTokenForProvenance, purgeId);
                centralPurgeState.setPurgeInfo(purgeInfo);
                updateCentralPurgeState(centralPurgeState, purgeId);
            } finally {
                if (provenanceClient != null)
                    returnClientToPool(provenanceClient, pool);
            }
        } else {
            // If it is an ageOffEvent, update the CentralAgeOffState in MongoDB
            centralAgeOffEventState.setApplicationStates(appStatesMap);
            centralAgeOffEventState.setCentralStatus(centralPurgeStatus);

            AgeOffEventInfo ageOffEventInfo = centralAgeOffEventState.getAgeOffEventInfo();
            ageOffEventInfo.setCompletelyPurgedSet(centralCompletelyPurgedSet);
            ageOffEventInfo.setResolved(resolved);
            centralAgeOffEventState.setAgeOffEventInfo(ageOffEventInfo);
            dbObject.put(CentralAgeOffStateString, encodeCentralAgeOffEventState(centralAgeOffEventState));
            ageOffColl.update(query, dbObject, true, false);

            // If there are ids aged by all services then tell the provenance service
            if (!centralCompletelyPurgedSet.isEmpty()) {
                ProvenanceService.Client provenanceClient = null;
                try {
                    provenanceClient = getProvenanceThriftClient(pool);
                    EzSecurityToken centralTokenForProvenance = securityClient.fetchDerivedTokenForApp(token,
                            getProvenanceSecurityId(pool));
                    provenanceClient.markDocumentAsAged(centralTokenForProvenance, centralCompletelyPurgedSet);
                } finally {
                    if (provenanceClient != null)
                        returnClientToPool(provenanceClient, pool);
                }
            }
        }
        evt.arg("status", servicePurgeState.getPurgeState().getPurgeStatus().name());
        logger.info("[" + applicationName + "_" + serviceName + "] purgeId:" + inputPurgeState.getPurgeId()
                + " purgedIds:" + inputPurgeState.getPurged() + " status:" + inputPurgeState.getPurgeStatus());
    } catch (CentralPurgeServiceException e) {
        logError(e, evt, e.getMessage());
        throw e;
    } catch (NullPointerException e) {
        logError(e, evt, "CentralPurgeService encountered an exception in updatePurge:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException("CentralPurgeService encountered an exception in updatePurge:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
    } catch (EzSecurityTokenException e) {
        logError(e, evt, "CentralPurgeService failed when trying to validate token:[" + e.getClass().getName()
                + ":" + e.getMessage() + "]");
        throw e;
    } catch (UnknownHostException e) {
        logError(e, evt, "CentralPurgeService unable to reach MongoDB in updatePurge:[" + e.getClass().getName()
                + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException("CentralPurgeService unable to reach MongoDB in updatePurge:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
    } catch (Exception e) {
        logError(e, evt, "CentralPurgeService encountered an exception in updatePurge:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException("CentralPurgeService encountered an exception in updatePurge:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
    } finally {
        if (pool != null)
            pool.close();
        auditLogger.logEvent(evt);
        logEventToPlainLogs(logger, evt);
        if (mongoClient != null)
            mongoClient.close();
    }
}

From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java

License:Apache License

@Override
public List<CentralAgeOffEventState> getAgeOffEventState(EzSecurityToken token, List<Long> ageOffEventIds)
        throws EzSecurityTokenException, TException {

    DBCollection ageOffColl = null;/*from www  . ja va2s . co m*/
    Mongo mongoClient = null;
    AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token)
            .arg("event", "get age off event state").arg("age off event ids", ageOffEventIds);
    try {
        validateCentralPurgeSecurityToken(token);

        // Get access to the ageoff collection within Mongo

        MongoConfigurationHelper mongoConfigurationHelper = new MongoConfigurationHelper(configuration);
        MongoHelper mongoHelper = new MongoHelper(configuration);
        mongoClient = mongoHelper.getMongo();
        DB mongoDB = mongoClient.getDB(mongoConfigurationHelper.getMongoDBDatabaseName());
        ageOffColl = mongoDB.getCollection(AGEOFF_COLLECTION);

        List<CentralAgeOffEventState> result = new ArrayList<>();
        BasicDBObject query;
        DBCursor cursor;

        // Just need to get and decode the CentralAgeOffStates matching the ids from MongoDB
        query = new BasicDBObject(EzCentralPurgeServiceHelpers.AgeOffEventId,
                new BasicDBObject("$in", ageOffEventIds));
        cursor = ageOffColl.find(query);
        for (DBObject dbObject : cursor) {
            CentralAgeOffEventState centralAgeOffEventState = decodeCentralAgeOffEventState(
                    (DBObject) dbObject.get(CentralAgeOffStateString));
            result.add(centralAgeOffEventState);
        }

        return result;
    } catch (EzSecurityTokenException e) {
        logError(e, evt, "CentralPurgeService failed when trying to validate token:[" + e.getClass().getName()
                + ":" + e.getMessage() + "]");
        throw e;
    } catch (UnknownHostException e) {
        logError(e, evt, "CentralPurgeService unable to reach MongoDB in getAgeOffEventState:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException(
                "CentralPurgeService unable to reach MongoDB in getAgeOffEventState:[" + e.getClass().getName()
                        + ":" + e.getMessage() + "]");
    } catch (Exception e) {
        logError(e, evt, "CentralPurgeService encountered an exception in getAgeOffEventState:["
                + e.getClass().getName() + ":" + e.getMessage() + "]");
        throw new CentralPurgeServiceException(
                "CentralPurgeService encountered an exception in getAgeOffEventState:[" + e.getClass().getName()
                        + ":" + e.getMessage() + "]");
    } finally {
        auditLogger.logEvent(evt);
        logEventToPlainLogs(logger, evt);
        if (mongoClient != null)
            mongoClient.close();
    }
}