List of usage examples for com.mongodb BasicDBObject getString
public String getString(final String key)
From source file:com.deftlabs.lock.mongo.impl.LockDao.java
License:Apache License
/** * Try and get the lock. If unable to do so, this returns false. *///from ww w .j av a 2s . c o m static synchronized ObjectId lock(final MongoClient pMongo, final String pLockName, final DistributedLockSvcOptions pSvcOptions, final DistributedLockOptions pLockOptions) { try { // Lookup the lock object. BasicDBObject lockDoc = findById(pMongo, pLockName, pSvcOptions); final long serverTime = getServerTime(pMongo, pSvcOptions); final long startTime = System.currentTimeMillis(); // The doc was not there so we are going to try and insert a new doc. if (lockDoc == null) { final ObjectId lockId = tryInsertNew(pMongo, pLockName, pSvcOptions, pLockOptions, serverTime, startTime); if (lockId != null) return lockId; } if (lockDoc == null) lockDoc = findById(pMongo, pLockName, pSvcOptions); // Get the state. final LockState lockState = LockState.findByCode(lockDoc.getString(LockDef.STATE.field)); final ObjectId currentLockId = lockDoc.getObjectId(LockDef.LOCK_ID.field); // If it is unlocked, then try and lock. if (lockState.isUnlocked()) { final ObjectId lockId = tryLockingExisting(pMongo, pLockName, currentLockId, pSvcOptions, pLockOptions, serverTime, startTime); if (lockId != null) return lockId; } final ObjectId lockId = (ObjectId) lockDoc.get(LockDef.LOCK_ID.field); // Could not get the lock. incrementLockAttemptCount(pMongo, pLockName, lockId, pSvcOptions); return null; } finally { } }
From source file:com.deftlabs.lock.mongo.impl.LockDao.java
License:Apache License
/** * Returns true if the lock is locked.//from www. java 2 s .c o m */ static boolean isLocked(final MongoClient pMongo, final String pLockName, final DistributedLockSvcOptions pSvcOptions) { final BasicDBObject lock = (BasicDBObject) getDbCollection(pMongo, pSvcOptions) .findOne(new BasicDBObject(LockDef.ID.field, pLockName), new BasicDBObject(LockDef.STATE.field, 1)); if (lock == null) return false; final LockState state = LockState.findByCode(lock.getString(LockDef.STATE.field)); return state.isLocked(); }
From source file:com.deftlabs.lock.mongo.impl.LockDao.java
License:Apache License
/** * Check for expired/inactive/dead locks and unlock. */// w w w.j ava 2 s .c om static void expireInactiveLocks(final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions) { // Adjust the time buffer to make sure we do not have small time issues. final long queryServerTime = getServerTime(pMongo, pSvcOptions); final BasicDBObject query = new BasicDBObject(LockDef.STATE.field, LockState.LOCKED.code()); query.put(LockDef.LOCK_TIMEOUT_TIME.field, new BasicDBObject(LT, new Date(queryServerTime))); final DBCursor cur = getDbCollection(pMongo, pSvcOptions).find(query).batchSize(10); try { while (cur.hasNext()) { final BasicDBObject lockDoc = (BasicDBObject) cur.next(); final ObjectId lockId = (ObjectId) lockDoc.get(LockDef.LOCK_ID.field); final String lockName = lockDoc.getString(LockDef.ID.field); final long serverTime = getServerTime(pMongo, pSvcOptions); final BasicDBObject toSet = new BasicDBObject(); toSet.put(LockDef.LIBRARY_VERSION.field, null); toSet.put(LockDef.UPDATED.field, new Date(serverTime)); toSet.put(LockDef.LOCK_ACQUIRED_TIME.field, null); toSet.put(LockDef.LOCK_TIMEOUT_TIME.field, null); toSet.put(LockDef.LOCK_ID.field, null); toSet.put(LockDef.STATE.field, LockState.UNLOCKED.code()); toSet.put(LockDef.OWNER_APP_NAME.field, null); toSet.put(LockDef.OWNER_ADDRESS.field, null); toSet.put(LockDef.OWNER_HOSTNAME.field, null); toSet.put(LockDef.OWNER_THREAD_ID.field, null); toSet.put(LockDef.OWNER_THREAD_NAME.field, null); toSet.put(LockDef.OWNER_THREAD_GROUP_NAME.field, null); toSet.put(LockDef.LOCK_ATTEMPT_COUNT.field, 0); toSet.put(LockDef.INACTIVE_LOCK_TIMEOUT.field, null); final BasicDBObject timeoutQuery = new BasicDBObject(LockDef.ID.field, lockName); timeoutQuery.put(LockDef.LOCK_ID.field, lockId); timeoutQuery.put(LockDef.STATE.field, LockState.LOCKED.code()); timeoutQuery.put(LockDef.LOCK_TIMEOUT_TIME.field, new BasicDBObject(LT, new Date(serverTime))); final BasicDBObject previousLockDoc = (BasicDBObject) getDbCollection(pMongo, pSvcOptions) .findAndModify(timeoutQuery, new BasicDBObject(LockDef.INACTIVE_LOCK_TIMEOUT.field, 1), null, false, new BasicDBObject(SET, toSet), false, false); if (previousLockDoc == null) continue; if (!pSvcOptions.getEnableHistory()) continue; // Insert the history state. LockHistoryDao.insert(pMongo, lockName, pSvcOptions, previousLockDoc.getInt(LockDef.INACTIVE_LOCK_TIMEOUT.field), serverTime, LockState.LOCKED, lockId, true); } } finally { if (cur != null) cur.close(); } }
From source file:com.deliveronthego.CommonAPI.java
@POST @Path("/findDrivers") @Consumes(MediaType.APPLICATION_JSON)// w w w . j ava 2 s . c o m @Produces(MediaType.APPLICATION_JSON) public Response doDeliveryDetails(String deliver) { System.out.println("inside delivery details"); String message; GraphTraversal g = new GraphTraversal(); try { System.out.println("inside delivery details"); JSONObject deliverJson = new JSONObject(deliver); boolean var = new DbConnection().deliver(deliverJson.getString("emailId"), Double.valueOf(deliverJson.getString("pickupLatitude")), Double.valueOf(deliverJson.getString("pickupLongitude")), Double.valueOf(deliverJson.getString("dropOffLatitude")), Double.valueOf(deliverJson.getString("dropOffLongitude")), deliverJson.getInt("length"), deliverJson.getInt("breadth"), deliverJson.getInt("width")); System.out.println("after delivery details"); if (var) { System.out.println("in success"); message = "Delivery Details Inserted successfully"; JSONObject statusMessage = new JSONObject(); statusMessage.put("message", message); String res = g.findDriver(deliverJson.getString("emailId"), deliverJson.getDouble("pickupLatitude"), deliverJson.getDouble("pickupLongitude"), deliverJson.getDouble("dropOffLatitude"), deliverJson.getDouble("dropOffLongitude")); System.out.println(res); JSONArray jarr = new JSONArray(res); for (int j = 0; j < jarr.length(); j++) { JSONObject json = new JSONObject(jarr.get(j).toString()); String driverId = json.get("driverId").toString(); System.out.println(driverId); mongoclient = getConnection(); DB db = mongoclient.getDB("deliveronthego"); DBCollection driverSourceDetails = db.getCollection("login"); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("emailId", driverId); whereQuery.put("userType", "Driver"); DBCursor cursor = driverSourceDetails.find(whereQuery); if (cursor.hasNext()) { BasicDBObject obj = (BasicDBObject) cursor.next(); String regId = obj.getString("regId"); String[] gcmIds = regId.split("\\="); System.out.println(gcmIds[1]); String apiKey = "AIzaSyDzXEIMFY3EGbJ4mjc9xBYyeakjggxuTC0"; Content content = createContent(gcmIds[1], deliverJson.getString("emailId")); DotgGCMPost.post(apiKey, content); DBCollection selection = db.getCollection("selection"); BasicDBObject sel = new BasicDBObject() .append("userEmailId", deliverJson.getString("emailId")) .append("driverEmailId", driverId).append("Accepted", "No"); selection.insert(sel); throw new JSONException("gi"); } else { //System.out.println("cursor=="+cursor.toString()); throw new JSONException("No email found"); } } return Response.status(200).entity(statusMessage).build(); } else { System.out.println("in fail"); message = "Delivery Details Insertion Failed"; JSONObject statusMessage = new JSONObject(); statusMessage.put("message", message); return Response.status(404).entity(statusMessage).build(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } message = "Delivery Details Insertion Failed"; return Response.status(404).entity(message).build(); }
From source file:com.dentinium.doctor.Doctor.java
public Doctor(BasicDBObject obj) { doctorID = obj.getString("userid"); doctorName = obj.getString("name"); email = obj.getString("email"); if (obj.getString("phone") != null) { phone = obj.getString("phone"); } else {/*from w w w.j a v a 2 s . c om*/ phone = "not set"; } if (obj.getString("wage") != null) { wage = obj.getInt("wage"); } else { wage = 0; } BasicDBObject tmp = (BasicDBObject) obj.get("works"); companyName = tmp.getString("companyname"); }
From source file:com.edgytech.umongo.DbPanel.java
License:Apache License
void refreshUserList() { ListArea list = (ListArea) getBoundUnit(Item.userList); final DB db = getDbNode().getDb(); DBCursor cur = db.getCollection("system.users").find().sort(new BasicDBObject("user", 1)); ArrayList users = new ArrayList(); while (cur.hasNext()) { BasicDBObject user = (BasicDBObject) cur.next(); users.add(user.getString("user")); }// w w w . j av a 2 s .c o m list.items = (String[]) users.toArray(new String[users.size()]); list.structureComponent(); }
From source file:com.edgytech.umongo.EditAggGeoNearDialog.java
License:Apache License
@Override public void setParameters(Object value) { BasicDBObject cmd = (BasicDBObject) value; ((DocBuilderField) getBoundUnit(Item.near)).setDBObject((DBObject) cmd.get("near")); setStringFieldValue(Item.distanceField, cmd.getString("distanceField")); setDoubleFieldValue(Item.maxDistance, cmd.getDouble("maxDistance")); if (cmd.containsField("distanceMultiplier")) { setDoubleFieldValue(Item.distanceMultiplier, cmd.getDouble("distanceMultiplier")); }//w w w . j a v a 2 s . c o m if (cmd.containsField("query")) { ((DocBuilderField) getBoundUnit(Item.query)).setDBObject((DBObject) cmd.get("query")); } if (cmd.containsField("spherical")) { setBooleanFieldValue(Item.spherical, cmd.getBoolean("spherical")); } if (cmd.containsField("query")) { ((DocBuilderField) getBoundUnit(Item.query)).setDBObject((DBObject) cmd.get("query")); } if (cmd.containsField("includeLocs")) { setStringFieldValue(Item.includeLocs, cmd.getString("includeLocs")); } if (cmd.containsField("uniqueDocs")) { setBooleanFieldValue(Item.uniqueDocs, cmd.getBoolean("uniqueDocs")); } }
From source file:com.edgytech.umongo.ReplicaDialog.java
License:Apache License
public void updateFromReplicaConfig(BasicDBObject member) { // reset//from w ww .j av a 2 s . c o m xmlLoadCheckpoint(); ((TextField) getBoundUnit(Item.host)).editable = false; setStringFieldValue(Item.host, member.getString("host")); setBooleanFieldValue(Item.arbiterOnly, member.getBoolean("arbiterOnly", false)); setBooleanFieldValue(Item.hidden, member.getBoolean("hidden", false)); setBooleanFieldValue(Item.ignoreIndexes, !member.getBoolean("buildIndexes", true)); if (member.containsField("priority")) { setDoubleFieldValue(Item.priority, member.getDouble("priority")); } if (member.containsField("slaveDelay")) { setIntFieldValue(Item.slaveDelay, member.getInt("slaveDelay")); } if (member.containsField("votes")) { setIntFieldValue(Item.votes, member.getInt("votes")); } if (member.containsField("tags")) { ((DocBuilderField) getBoundUnit(Item.tags)).setDBObject((DBObject) member.get("tags")); } }
From source file:com.edgytech.umongo.RouterPanel.java
License:Apache License
public void balancer(ButtonBase button) { final MongoClient mongo = getRouterNode().getMongoClient(); final DB config = mongo.getDB("config"); final DBCollection settings = config.getCollection("settings"); FormDialog diag = (FormDialog) ((MenuItem) getBoundUnit(Item.balancer)).getDialog(); diag.xmlLoadCheckpoint();/* w w w .j ava 2s . c om*/ final BasicDBObject query = new BasicDBObject("_id", "balancer"); BasicDBObject balDoc = (BasicDBObject) settings.findOne(query); if (balDoc != null) { if (balDoc.containsField("stopped")) setIntFieldValue(Item.balStopped, balDoc.getBoolean("stopped") ? 1 : 2); if (balDoc.containsField("_secondaryThrottle")) setIntFieldValue(Item.balSecThrottle, balDoc.getBoolean("_secondaryThrottle") ? 1 : 2); BasicDBObject window = (BasicDBObject) balDoc.get("activeWindow"); if (window != null) { setStringFieldValue(Item.balStartTime, window.getString("start")); setStringFieldValue(Item.balStopTime, window.getString("stop")); } } if (!diag.show()) return; if (balDoc == null) balDoc = new BasicDBObject("_id", "balancer"); int stopped = getIntFieldValue(Item.balStopped); if (stopped > 0) balDoc.put("stopped", stopped == 1 ? true : false); else balDoc.removeField("stopped"); int throttle = getIntFieldValue(Item.balSecThrottle); if (throttle > 0) balDoc.put("_secondaryThrottle", throttle == 1 ? true : false); else balDoc.removeField("_secondaryThrottle"); if (!getStringFieldValue(Item.balStartTime).trim().isEmpty()) { BasicDBObject aw = new BasicDBObject(); aw.put("start", getStringFieldValue(Item.balStartTime).trim()); aw.put("stop", getStringFieldValue(Item.balStopTime).trim()); balDoc.put("activeWindow", aw); } final BasicDBObject newDoc = balDoc; new DbJob() { @Override public Object doRun() throws IOException { return settings.update(query, newDoc, true, false); } @Override public String getNS() { return settings.getFullName(); } @Override public String getShortName() { return "Balancer"; } @Override public void wrapUp(Object res) { updateComponent(); super.wrapUp(res); } }.addJob(); }
From source file:com.edgytech.umongo.RouterPanel.java
License:Apache License
public void regenConfigDB(ButtonBase button) throws UnknownHostException { MongoClient cmongo = getRouterNode().getMongoClient(); String servers = getStringFieldValue(Item.regenServers); final String db = getStringFieldValue(Item.regenDB); final String col = getStringFieldValue(Item.regenCollection); final String ns = db + "." + col; final DBObject shardKey = ((DocBuilderField) getBoundUnit(Item.regenShardKey)).getDBObject(); final boolean unique = getBooleanFieldValue(Item.regenKeyUnique); final BasicDBObject result = new BasicDBObject(); result.put("ns", ns); result.put("shardKey", shardKey); result.put("unique", unique); // create direct mongo for each replica set String[] serverList = servers.split("\n"); List<ServerAddress> list = new ArrayList<ServerAddress>(); String txt = ""; String primaryShard = null;/*from w w w. j a v a 2 s. c o m*/ final BasicDBObject shardList = new BasicDBObject(); HashMap<MongoClient, String> mongoToShard = new HashMap<MongoClient, String>(); sLoop: for (String server : serverList) { server = server.trim(); String[] tokens = server.split("/"); if (tokens.length != 2) { new InfoDialog(null, "Error", null, "Server format must be like 'hostname:port/shard', one by line") .show(); return; } server = tokens[0]; String shard = tokens[1]; if (primaryShard == null) { primaryShard = shard; } ServerAddress addr = new ServerAddress(server); // filter out if replset already exists for (MongoClient replset : mongoToShard.keySet()) { if (replset.getServerAddressList().contains(addr)) { continue sLoop; } } list.clear(); list.add(addr); MongoClient mongo = new MongoClient(list); // UMongo.instance.addMongoClient(mongo, null); // make request to force server detection mongo.getDatabaseNames(); mongoToShard.put(mongo, shard); String desc = null; if (!mongo.getDatabaseNames().contains(db) || !mongo.getDB(db).getCollectionNames().contains(col)) { desc = "Collection not present!"; } else { // try to see if shard key has index DBObject index = mongo.getDB(db).getCollection("system.indexes") .findOne(new BasicDBObject("key", shardKey)); if (index != null) { desc = "shard key found"; } else { desc = "shard key NOT found!"; } } txt += mongo.toString() + " shard=" + shard + " - " + desc + "\n"; BasicDBObject shardObj = new BasicDBObject("servers", mongo.toString()); shardObj.put("status", desc); if (shardList.containsField(shard)) { new InfoDialog(null, "Error", null, "Duplicate Shard name " + shard).show(); return; } shardList.put(shard, shardObj); } result.put("shards", shardList); FormDialog dia = (FormDialog) getBoundUnit(Item.regenRSList); dia.setStringFieldValue(Item.regenRSListArea, txt); if (!dia.show()) { return; } DB config = cmongo.getDB("config"); // add database record BasicDBObject doc = new BasicDBObject("_id", db); doc.put("partitioned", true); doc.put("primary", primaryShard); config.getCollection("databases").save(doc); // add collection record doc = new BasicDBObject("_id", ns); doc.put("lastmod", new Date()); doc.put("dropped", false); doc.put("key", shardKey); doc.put("unique", unique); config.getCollection("collections").save(doc); final DBCollection chunks = config.getCollection("chunks"); long count = chunks.count(new BasicDBObject("ns", ns)); if (count > 0) { dia = (FormDialog) getBoundUnit(Item.regenDeleteChunks); if (dia.show()) { chunks.remove(new BasicDBObject("ns", ns)); } else { return; } } // add temp collection to sort chunks with shard key final DBCollection tmpchunks = config.getCollection("_tmpchunks_" + col); tmpchunks.drop(); // should be safe environment, and dup keys should be ignored tmpchunks.setWriteConcern(WriteConcern.NORMAL); // can use shardKey as unique _id // tmpchunks.ensureIndex(shardKey, "shardKey", true); // create filter for shard fields final DBObject shardKeyFilter = new BasicDBObject(); // final DBObject shardKeyDescend = new BasicDBObject(); boolean hasId = false; for (String key : shardKey.keySet()) { shardKeyFilter.put(key, 1); if (key.equals("_id")) { hasId = true; } } if (!hasId) { shardKeyFilter.put("_id", 0); } dia = (FormDialog) getBoundUnit(Item.regenConfirm); if (!dia.show()) { return; } // now fetch all records from each shard final AtomicInteger todo = new AtomicInteger(mongoToShard.size()); for (Map.Entry<MongoClient, String> entry : mongoToShard.entrySet()) { final MongoClient mongo = entry.getKey(); final String shard = entry.getValue(); new DbJob() { @Override public Object doRun() throws Exception { BasicDBObject shardObj = (BasicDBObject) shardList.get(shard); long count = mongo.getDB(db).getCollection(col).count(); shardObj.put("count", count); DBCursor cur = mongo.getDB(db).getCollection(col).find(new BasicDBObject(), shardKeyFilter); long i = 0; int inserted = 0; long start = System.currentTimeMillis(); while (cur.hasNext() && !isCancelled()) { BasicDBObject key = (BasicDBObject) cur.next(); setProgress((int) ((++i * 100.0f) / count)); try { BasicDBObject entry = new BasicDBObject("_id", key); entry.put("_shard", shard); tmpchunks.insert(entry); ++inserted; } catch (Exception e) { getLogger().log(Level.WARNING, e.getMessage(), e); } } if (isCancelled()) { shardObj.put("cancelled", true); } shardObj.put("inserted", inserted); shardObj.put("scanTime", System.currentTimeMillis() - start); todo.decrementAndGet(); return null; } @Override public String getNS() { return tmpchunks.getFullName(); } @Override public String getShortName() { return "Scanning " + shard; } @Override public boolean isDeterminate() { return true; } }.addJob(); } new DbJob() { @Override public Object doRun() throws Exception { // wait for all shards to be done long start = System.currentTimeMillis(); while (todo.get() > 0 && !isCancelled()) { Thread.sleep(2000); } if (isCancelled()) { result.put("cancelled", true); return result; } // find highest current timestamp DBCursor cur = chunks.find().sort(new BasicDBObject("lastmod", -1)).batchSize(-1); BasicDBObject chunk = (BasicDBObject) (cur.hasNext() ? cur.next() : null); BSONTimestamp ts = (BSONTimestamp) (chunk != null ? chunk.get("lastmod") : null); // now infer chunk ranges long count = tmpchunks.count(); result.put("uniqueKeys", count); int numChunks = 0; cur = tmpchunks.find().sort(new BasicDBObject("_id", 1)); BasicDBObject prev = (BasicDBObject) cur.next(); BasicDBObject next = null; // snap prev to minkey BasicDBObject theid = (BasicDBObject) prev.get("_id"); for (String key : shardKey.keySet()) { theid.put(key, new MinKey()); } String currentShard = prev.getString("_shard"); int i = 1; while (cur.hasNext()) { next = (BasicDBObject) cur.next(); setProgress((int) ((++i * 100.0f) / count)); String newShard = next.getString("_shard"); if (newShard.equals(currentShard)) continue; // add chunk ts = getNextTimestamp(ts); chunk = getChunk(ns, shardKey, prev, next, ts); chunks.insert(chunk); prev = next; currentShard = prev.getString("_shard"); ++numChunks; } // build max next = new BasicDBObject(); for (String key : shardKey.keySet()) { next.put(key, new MaxKey()); } next = new BasicDBObject("_id", next); ts = getNextTimestamp(ts); chunk = getChunk(ns, shardKey, prev, next, ts); chunks.insert(chunk); ++numChunks; result.put("numChunks", numChunks); result.put("totalTime", System.currentTimeMillis() - start); return result; } @Override public String getNS() { return chunks.getFullName(); } @Override public String getShortName() { return "Creating Chunks"; } @Override public boolean isDeterminate() { return true; } }.addJob(); }