List of usage examples for com.mongodb BasicDBObject append
@Override public BasicDBObject append(final String key, final Object val)
From source file:edu.slu.action.ObjectAction.java
private boolean verifyAccess(String access_token) throws IOException, ServletException, Exception { System.out.println("verify a JWT access token"); System.out.println(access_token); boolean verified = false; JSONObject userInfo;//w ww . ja v a 2 s .co m try { DecodedJWT receivedToken = JWT.decode(access_token); System.out.println("initialize cache..."); cache = JCS.getInstance("jwksCache"); String KID = receivedToken.getKeyId(); // Could cache this so we don't have to keep grabbing it since it has to happen on every call. // http://commons.apache.org/proper/commons-jcs/getting_started/intro.html // https://commons.apache.org/proper/commons-jcs/ Jwk jwk; JwkProvider provider; System.out.println("check cache for key..."); RSAPublicKey pubKey = cache.get("pubKey"); //Cache the key so we don't have to keep requesting auth0 for it. Expires in cache every 10 hours. if (null == pubKey) { System.out.println("key not in cache, ask auth0..."); provider = new UrlJwkProvider("https://cubap.auth0.com/.well-known/jwks.json"); jwk = provider.get(KID); pubKey = (RSAPublicKey) jwk.getPublicKey(); cache.put("pubKey", pubKey); System.out.println("key in cache..."); } Algorithm algorithm = Algorithm.RSA256(pubKey, null); JWTVerifier verifier = JWT.require(algorithm).build(); //Reusable verifier instance //.withIssuer("auth0") generatorID = receivedToken.getClaim(Constant.RERUM_AGENT_ClAIM).asString(); //System.out.println("Was I able to pull the agent claim from the token directly without userinfo without verifying? Value below"); //System.out.println("Value: "+generatorID); if (botCheck(generatorID)) { System.out.println( "It passed the bot check, no need to verify the access token. I have the generator ID. "); verified = true; } else { DecodedJWT d_jwt = verifier.verify(access_token); System.out.println("We were able to verify the access token. "); verified = true; } } catch (CacheException e) { System.out.println("Problem initializing cache: " + e.getMessage()); } catch (JwkException | JWTVerificationException | IllegalArgumentException exception) { //Invalid signature/claims/token. Try to authenticate the old way System.out.println( "Verification failed. We were given a bad token. IP fallback. Exception below, but caught."); Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, exception); String requestIP = request.getRemoteAddr(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //check if the domain name and ip is in database BasicDBObject query = new BasicDBObject(); query.append("ip", requestIP); DBObject result = mongoDBService.findOneByExample(Constant.COLLECTION_ACCEPTEDSERVER, query); if (null != result) { System.out.println("[Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ App registered in legacy system"); if (null != result.get("agent") && !"".equals(result.get("agent"))) { //The user registered their IP with the new system System.out.println( "The registered server had an agent ID with it, so it must be from the new system."); userInfo = JSONObject.fromObject(result); } else { //This is a legacy user. //Create agent and write back to server collection //_id is messed up so adding the agent in doesn't always work. System.out.println( "The registered server did not have an agent ID. It must be from the old system."); System.out.println("We will generate a new agent to store with the registered server."); userInfo = generateAgentForLegacyUser(JSONObject.fromObject(result)); } //System.out.println("Grab agent id from"); //System.out.println(userInfo); generatorID = userInfo.getString("agent"); verified = true; } else { System.out.println("[Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ The app needs to register with RERUM"); verified = false; } } System.out.println("I need a generator out of all this. Did I get it: " + generatorID); return verified; }
From source file:edu.slu.action.ServerAction.java
/** * Save a new server's domain and IP/* w w w . j a v a 2s. com*/ * @param acceptedServer */ public void saveNewServer() { //check if the IP is duplicated BasicDBObject query = new BasicDBObject(); query.append("ip", acceptedServer.getIp()); List<DBObject> ls_results = mongoDBService.findByExample(Constant.COLLECTION_ACCEPTEDSERVER, query); if (null != ls_results && ls_results.size() > 0) { JSONObject jo = new JSONObject(); jo.element("code", HttpServletResponse.SC_NOT_ACCEPTABLE); jo.element("info", "duplicated IP"); try { out = response.getWriter(); out.print(jo); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } else { //if the IP is not duplicated, save the info. BasicDBObject dbo = new BasicDBObject(acceptedServer.toMap()); String newObjectID = mongoDBService.save(Constant.COLLECTION_ACCEPTEDSERVER, dbo); JSONObject jo = new JSONObject(); jo.element("code", HttpServletResponse.SC_OK); jo.element("info", "Server saved!"); jo.element("newObjectID", newObjectID); try { out = response.getWriter(); out.print(jo); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:edu.slu.action.ServerAction.java
/** * Update current server info by objectID. * @param acceptedServer//from w w w . j a v a 2 s .c om */ public void updateServerByObjectID() { BasicDBObject query = new BasicDBObject(); query.append("_id", new ObjectId(acceptedServer.getObjectID())); mongoDBService.update(Constant.COLLECTION_ACCEPTEDSERVER, query, new BasicDBObject(acceptedServer.toMap())); JSONObject jo = new JSONObject(); jo.element("info", HttpServletResponse.SC_OK); try { out = response.getWriter(); out.print(jo); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.slu.action.ServerAction.java
/** * Get server info by Ip. //from w w w . j av a2s. co m * @param acceptedServer.ip * @return acceptedServer */ public void getServerByIp() { BasicDBObject query = new BasicDBObject(); query.append("ip", acceptedServer.getIp()); DBObject result = mongoDBService.findOneByExample(Constant.COLLECTION_ACCEPTEDSERVER, query); if (null != result) { BasicDBObject dbo = (BasicDBObject) result; AcceptedServer as = new AcceptedServer(dbo); JSONObject jo = new JSONObject(); jo.element("server", as.toMap()); try { out = response.getWriter(); out.print(jo); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:edu.slu.filter.ClientInfoRecorder.java
@Override protected String doIntercept(ActionInvocation ai) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); String requestIP = request.getRemoteAddr(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //check if the domain name and ip is in database BasicDBObject query = new BasicDBObject(); query.append("ip", requestIP); DB db = MongoDBUtil.getDb();/*www.ja v a 2s . c o m*/ DBCollection coll = db.getCollection(Constant.COLLECTION_ACCEPTEDSERVER); DBCursor cursor = coll.find(query); List<DBObject> ls_results = cursor.toArray(); if (ls_results.size() > 0) { //System.out.println("[Not Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ From Registered Server"); } else { //System.out.println("[Not Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ Not From Registered Server"); } return ai.invoke(); }
From source file:edu.slu.filter.RequestServerAuthenticationFilter.java
@Override protected String doIntercept(ActionInvocation ai) throws Exception { //get remote server host ip HttpServletRequest request = ServletActionContext.getRequest(); String requestIP = request.getRemoteAddr(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //check if the domain name and ip is in database BasicDBObject query = new BasicDBObject(); query.append("ip", requestIP); DB db = MongoDBUtil.getDb();//from w w w . j a v a 2 s . co m DBCollection coll = db.getCollection(Constant.COLLECTION_ACCEPTEDSERVER); DBCursor cursor = coll.find(query); List<DBObject> ls_results = cursor.toArray(); if (ls_results.size() > 0) { System.out.println("[Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ From Registered Server"); } else { System.out.println("[Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ Not From Registered Server"); } if (ls_results.size() > 0) { return ai.invoke(); } else { System.out.println("403 because session ip not registered"); HttpServletResponse respond_403 = ServletActionContext.getResponse(); respond_403.setStatus(403); respond_403.addHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = respond_403.getWriter(); out.write("You must register with this service. Visit <a>" + Constant.RERUM_PREFIX + "</a>"); //return ai.invoke(); return "403"; } }
From source file:edu.ucuenca.storage.services.MongoServiceImpl.java
License:Apache License
@Override public void registerSession(String orcid, String token) { BasicDBObject key = new BasicDBObject(); key.put("orcid", orcid); key.put("token", token); BasicDBObject main = new BasicDBObject(); main.append("_id", key); Document parse = Document.parse(main.toJson()); sessions.insertOne(parse);/* w w w . ja va2s . c o m*/ }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
@Override public HashMap<ColumnField, Object> lookupSomeFields(String collectionName, String guid, ColumnField nameField, ColumnField valuesMapField, ArrayList<ColumnField> valuesMapKeys) throws RecordNotFoundException, FailedDBOperationException { if (guid == null) { DatabaseConfig.getLogger().log(Level.FINE, "{0} GUID is null: {1}", new Object[] { dbName, guid }); throw new RecordNotFoundException(guid); }// w ww . j a v a 2 s . c o m db.requestStart(); try { String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName(); db.requestEnsureConnection(); DBCollection collection = db.getCollection(collectionName); BasicDBObject query = new BasicDBObject(primaryKey, guid); BasicDBObject projection = new BasicDBObject().append("_id", 0); if (valuesMapField != null && valuesMapKeys != null) { for (int i = 0; i < valuesMapKeys.size(); i++) { String fieldName = valuesMapField.getName() + "." + valuesMapKeys.get(i).getName(); projection.append(fieldName, 1); } } DBObject dbObject = collection.findOne(query, projection); if (dbObject == null) { throw new RecordNotFoundException(guid); } HashMap<ColumnField, Object> hashMap = new HashMap<>(); hashMap.put(nameField, guid);// put the name in the hashmap!! very important!! if (valuesMapField != null && valuesMapKeys != null) { // first we pull all the user values from the dbObject and put in a bson object // FIXME: Why not convert this to a JSONObject right now? We know that's what it is. BasicDBObject bson = (BasicDBObject) dbObject.get(valuesMapField.getName()); DatabaseConfig.getLogger().log(Level.FINER, "{0} @@@@@@@@ {1}", new Object[] { dbName, bson }); // then we run thru each userkey in the valuesMapKeys and pull the // value put stuffing it into the values map ValuesMap valuesMap = new ValuesMap(); for (int i = 0; i < valuesMapKeys.size(); i++) { String userKey = valuesMapKeys.get(i).getName(); if (containsFieldDotNotation(userKey, bson) == false) { DatabaseConfig.getLogger().log(Level.FINE, "{0} DBObject doesn't contain {1}", new Object[] { dbName, userKey }); continue; } try { switch (valuesMapKeys.get(i).type()) { case USER_JSON: Object value = getWithDotNotation(userKey, bson); DatabaseConfig.getLogger().log(Level.FINE, "{0} Object is {1}", new Object[] { dbName, value.toString() }); valuesMap.put(userKey, value); break; case LIST_STRING: valuesMap.putAsArray(userKey, JSONUtils.JSONArrayToResultValue( new JSONArray(getWithDotNotation(userKey, bson).toString()))); break; default: DatabaseConfig.getLogger().log(Level.SEVERE, "{0} ERROR: Error: User keys field {1} is not a known type: {2}", new Object[] { dbName, userKey, valuesMapKeys.get(i).type() }); break; } } catch (JSONException e) { DatabaseConfig.getLogger().log(Level.SEVERE, "{0} Error parsing json: {1}", new Object[] { dbName, e.getMessage() }); e.printStackTrace(); } } hashMap.put(valuesMapField, valuesMap); } return hashMap; } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} lookupSomeFields failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, guid, "Original mongo exception:" + e.getMessage()); } finally { db.requestDone(); } }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
@Override public void updateEntireRecord(String collectionName, String guid, ValuesMap valuesMap) throws FailedDBOperationException { BasicDBObject updates = new BasicDBObject(); try {/* ww w . j a va 2s . com*/ updates.append(NameRecord.VALUES_MAP.getName(), JSON.parse(valuesMap.toString())); } catch (Exception e) { throw new FailedDBOperationException(collectionName, guid, "Unable to parse json" + e.getMessage()); } doUpdate(collectionName, guid, updates); }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
@Override public void updateIndividualFields(String collectionName, String guid, ColumnField valuesMapField, ArrayList<ColumnField> valuesMapKeys, ArrayList<Object> valuesMapValues) throws FailedDBOperationException { BasicDBObject updates = new BasicDBObject(); if (valuesMapField != null && valuesMapKeys != null) { for (int i = 0; i < valuesMapKeys.size(); i++) { String fieldName = valuesMapField.getName() + "." + valuesMapKeys.get(i).getName(); switch (valuesMapKeys.get(i).type()) { case LIST_STRING: // special case for old format updates.append(fieldName, valuesMapValues.get(i)); break; case USER_JSON: // value is any valid JSON updates.append(fieldName, JSONParse(valuesMapValues.get(i))); break; default: DatabaseConfig.getLogger().log(Level.WARNING, "{0} Ignoring unknown format: {1}", new Object[] { dbName, valuesMapKeys.get(i).type() }); break; }//from w ww. j a v a 2 s.c o m } } doUpdate(collectionName, guid, updates); }