List of usage examples for com.mongodb Mongo getDB
@Deprecated public DB getDB(final String dbName)
From source file:eu.delving.services.MockServices.java
License:EUPL
private static void dropMongoDatabase() throws UnknownHostException { LaunchProperties launchProperties = new LaunchProperties(Arrays.asList("services.mongo.dbName")); String mongoName = launchProperties.getProperty("services.mongo.dbName"); Mongo mongo = new Mongo(); DB db = mongo.getDB(mongoName); db.dropDatabase();/*from www .jav a 2 s . c o m*/ }
From source file:examples.QuickTour.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // get handle to "mydb" DB db = m.getDB("mydb"); // Authenticate - optional boolean auth = db.authenticate("foo", new char[] { 'b', 'a', 'r' }); // get a list of the collections in this database and print them out Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s);//from w w w . j a v a 2 s .c o m } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a range query to get a larger subset query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // range query with multiple contstraings query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // create an index on the "i" field coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = coll.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); }
From source file:examples.QuickTourAdmin.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get db names for (String s : m.getDatabaseNames()) { System.out.println(s);/*from w w w .jav a2s . co m*/ } // get a db DB db = m.getDB("com_mongodb_MongoAdmin"); // do an insert so that the db will really be created. Calling getDB() doesn't really take any // action with the server db.getCollection("testcollection").insert(new BasicDBObject("i", 1)); for (String s : m.getDatabaseNames()) { System.out.println(s); } // drop a database m.dropDatabase("com_mongodb_MongoAdmin"); for (String s : m.getDatabaseNames()) { System.out.println(s); } }
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 {//from ww w. j av a 2s .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 ww . j ava 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;// w w w .j a v a 2 s .co m 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.j av a2 s. c o 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(); } }
From source file:ezbake.services.centralPurge.thrift.EzCentralPurgeServiceHandler.java
License:Apache License
@Override public List<Long> getAllAgeOffEvents(EzSecurityToken token) throws TException { List<Long> result = null; DBCollection ageOffColl = null;// w ww . ja va 2s . c o m Mongo mongoClient = null; AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token).arg("event", "get all age off events"); 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); // Just get all ids from MongoDB result = new ArrayList<Long>(); DBCursor cursor = ageOffColl.find(); while (cursor.hasNext()) { result.add((Long) cursor.next().get(EzCentralPurgeServiceHelpers.AgeOffEventId)); } 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 getAllAgeOffEvents:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); throw new CentralPurgeServiceException( "CentralPurgeService unable to reach MongoDB in getAllAgeOffEvents:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); } catch (Exception e) { logError(e, evt, "CentralPurgeService encountered an exception in getAllAgeOffEvents:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); throw new CentralPurgeServiceException( "CentralPurgeService encountered an exception in getAllAgeOffEvents:[" + 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 CentralPurgeQueryResults getPagedSortedFilteredPurgeStates(EzSecurityToken token, List<CentralPurgeStatus> statuses, int pageNum, int numPerPage) throws EzSecurityTokenException, CentralPurgeServiceException { DBCollection purgeColl = null;//from w w w . j ava 2 s. c o m Mongo mongoClient = null; AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token) .arg("event", "getPagedSortedFilteredPurgeStates").arg("statuses", statuses).arg("pageNum", pageNum) .arg("numPerPage", numPerPage); 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<>(); List<Integer> statusesValues = new LinkedList<>(); for (CentralPurgeStatus status : statuses) { statusesValues.add(status.getValue()); } // Gets all centralPurgeStates that are in the statuses and pages BasicDBObject query = new BasicDBObject( EzCentralPurgeServiceHelpers.CentralPurgeStateString + "." + EzCentralPurgeServiceHelpers.CentralPurgeStatusString, new BasicDBObject("$in", statusesValues)); DBCursor cursor = purgeColl.find(query).sort(new BasicDBObject(PurgeId, -1)) .skip(pageNum > 0 ? ((pageNum - 1) * numPerPage) : 0).limit(numPerPage); // Decodes each centralPurgeState from 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); } CentralPurgeQueryResults centralPurgeQueryResults = new CentralPurgeQueryResults(); centralPurgeQueryResults.setPurgeStates(result); centralPurgeQueryResults.setCount(purgeColl.count(query)); return centralPurgeQueryResults; } 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 getPagedSortedFilteredPurgeStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); throw new CentralPurgeServiceException( "CentralPurgeService unable to reach MongoDB in getPagedSortedFilteredPurgeStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); } catch (Exception e) { logError(e, evt, "CentralPurgeService encountered an exception in getPagedSortedFilteredPurgeStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); throw new CentralPurgeServiceException( "CentralPurgeService encountered an exception in getPagedSortedFilteredPurgeStates:[" + 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 CentralAgeOffEventQueryResults getPagedSortedFilteredAgeOffEventStates(EzSecurityToken token, List<CentralPurgeStatus> statuses, int pageNum, int numPerPage) throws EzSecurityTokenException, CentralPurgeServiceException { DBCollection ageOffColl = null;//from w w w .j a v a2 s .co m Mongo mongoClient = null; AuditEvent evt = event(AuditEventType.FileObjectAccess.getName(), token) .arg("event", "getPagedSortedFilteredAgeOffEventStates").arg("statuses", statuses) .arg("pageNum", pageNum).arg("numPerPage", numPerPage); 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<>(); List<Integer> statusesValues = new LinkedList<>(); for (CentralPurgeStatus status : statuses) { statusesValues.add(status.getValue()); } // Gets all centralPurgeStates that are in the statuses and pages BasicDBObject query = new BasicDBObject( EzCentralPurgeServiceHelpers.CentralAgeOffStateString + "." + EzCentralPurgeServiceHelpers.CentralPurgeStatusString, new BasicDBObject("$in", statusesValues)); DBCursor cursor = ageOffColl.find(query).sort(new BasicDBObject(AgeOffEventId, -1)) .skip(pageNum > 0 ? ((pageNum - 1) * numPerPage) : 0).limit(numPerPage); for (DBObject dbObject : cursor) { CentralAgeOffEventState centralAgeOffEventState = decodeCentralAgeOffEventState( (DBObject) dbObject.get(CentralAgeOffStateString)); result.add(centralAgeOffEventState); } CentralAgeOffEventQueryResults centralAgeOffEventQueryResults = new CentralAgeOffEventQueryResults(); centralAgeOffEventQueryResults.setAgeOffEventStates(result); centralAgeOffEventQueryResults.setCount(ageOffColl.count(query)); return centralAgeOffEventQueryResults; } 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 getPagedSortedFilteredAgeOffEventStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); throw new CentralPurgeServiceException( "CentralPurgeService unable to reach MongoDB in getPagedSortedFilteredAgeOffEventStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); } catch (Exception e) { logError(e, evt, "CentralPurgeService encountered an exception in getPagedSortedFilteredAgeOffEventStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); throw new CentralPurgeServiceException( "CentralPurgeService encountered an exception in getPagedSortedFilteredAgeOffEventStates:[" + e.getClass().getName() + ":" + e.getMessage() + "]"); } finally { auditLogger.logEvent(evt); logEventToPlainLogs(logger, evt); if (mongoClient != null) mongoClient.close(); } }