Example usage for com.mongodb BasicDBObject get

List of usage examples for com.mongodb BasicDBObject get

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject get.

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

From source file:com.aw.services.AncientWarServiceImpl.java

/**
 * //from   w  w w.  java  2 s .  co m
 * @param deviceId
 * @return
 * @throws JSONException 
 */
@Override
public JSONObject login(String deviceId) throws JSONException {
    JSONObject response = new JSONObject();
    if (deviceId != null && !deviceId.equals("")) {
        DBCollection users = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user");
        BasicDBObject filter = new BasicDBObject("selected_market_id", deviceId);
        BasicDBObject user = (BasicDBObject) users.findOne(filter);

        DBCollection devices = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_devices");
        BasicDBObject deviceQuery = new BasicDBObject("device_id", deviceId);
        BasicDBObject device = (BasicDBObject) devices.findOne(deviceQuery);
        /// System.out.println("Device Id: "+device.get("device_id"));
        long uid = 0;
        if (device != null && device.containsField("uid") && device.get("uid") != null) {
            uid = (Long) device.get("uid");
            user = (BasicDBObject) users.findOne(new User("uid", uid));

            DBCollection troopsDetailsCollection = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName,
                    "aw_user_troops_details");
            UserTroopsDetails userTroopsDetails;
            userTroopsDetails = new UserTroopsDetails("uid", user.get("uid"));
            BasicDBObject details = (BasicDBObject) troopsDetailsCollection.findOne(userTroopsDetails);
            if (details == null) {
                details = new UserTroopsDetails();
                details.put("uid", user.get("uid"));
                details.put("titan_level", 1);
                MongoDbUtil.saveCollection(MongoDbUtil.defaultDBName, "aw_user_troops_details", details);
            }
            user.put("last_visited", new Date().getTime());
            // update user
            BasicDBObject query = new BasicDBObject().append("uid", user.get("uid"));
            BasicDBObject updateUser = new BasicDBObject();
            updateUser.append("$set", new BasicDBObject("last_visited", user.get("last_visited")));
            MongoDbUtil.updateCollection("aw_user", query, updateUser);
            new StrategyAction().bootStrapAction((Long) user.get("uid"));
            return getUserVillage(uid, "login");
        } else {
            JSONObject json = new JSONObject();
            json.put("device_id", deviceId);
            User createdUser = this.createUser(json);
            if (createdUser != null) {
                return this.getUserVillage((Long) createdUser.get("uid"), "login");
            } else {
                response.put("status", false);
                response.put("message", "User is not found and unable to create the user.");
                return response;
            }
        }
    } else if (deviceId == null || deviceId.equals("")) {
        response.put("status", false);
        response.put("message", "Device id is required.");
        return response;
    } else {
        response.put("status", false);
        response.put("message", "No input information provided.");
        return response;
    }
}

From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Calculate splits./*from  w ww  .  ja  v  a  2s .c  o  m*/
 *
 * @param collection the collection
 * @return the deep partition [ ]
 */
private HadoopPartition[] calculateSplits(DBCollection collection) {

    BasicDBList splitData = getSplitData(collection);
    List<ServerAddress> serverAddressList = collection.getDB().getMongo().getServerAddressList();

    if (splitData == null) {
        Pair<BasicDBList, List<ServerAddress>> pair = getSplitDataCollectionShardEnviroment(
                getShards(collection), collection.getDB().getName(), collection.getName());
        splitData = pair.left;
        serverAddressList = pair.right;
    }

    Object lastKey = null; // Lower boundary of the first min split

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

    for (ServerAddress serverAddress : serverAddressList) {
        stringHosts.add(serverAddress.toString());
    }
    int i = 0;

    MongoPartition[] partitions = new MongoPartition[splitData.size() + 1];

    for (Object aSplitData : splitData) {

        BasicDBObject currentKey = (BasicDBObject) aSplitData;

        Object currentO = currentKey.get(MONGO_DEFAULT_ID);

        partitions[i] = new MongoPartition(mongoDeepJobConfig.getRddId(), i,
                new TokenRange(lastKey, currentO, stringHosts), MONGO_DEFAULT_ID);

        lastKey = currentO;
        i++;
    }
    QueryBuilder queryBuilder = QueryBuilder.start(MONGO_DEFAULT_ID);
    queryBuilder.greaterThanEquals(lastKey);
    partitions[i] = new MongoPartition(0, i, new TokenRange(lastKey, null, stringHosts), MONGO_DEFAULT_ID);
    return partitions;
}

From source file:com.buzz.buzzdata.MongoBuzz.java

@Override
public void Insert(String userid, String header, String content, Double lat, Double lng, String tags,
        String[] files) {/*from  ww w  .ja v  a  2s  .c  o m*/
    BasicDBObject document = new BasicDBObject();
    document.put("userid", userid);
    document.put("header", header);
    document.put("content", content);
    document.put("tags", tags.split(","));
    document.put("created", (new Date()));
    document.put("modified", (new Date()));
    BasicDBObject lng_obj = new BasicDBObject();
    lng_obj.put("lng", lng);
    BasicDBObject lat_obj = new BasicDBObject();
    lat_obj.put("lat", lat);
    document.put("loc", (new Double[] { lng, lat }));
    document.put("FilesCount", files.length);
    DBCollection coll = mongoDB.getCollection("BuzzInfo");
    coll.insert(document);
    ObjectId buzz_id = (ObjectId) document.get("_id");
    int i = 0;
    for (String file : files) {
        try {
            GridFS gridFS = new GridFS(mongoDB);
            InputStream file_stream = getFTPInputStream(file);
            String caption_filename = FilenameUtils.removeExtension(file) + "_caption.txt";
            InputStream caption_stream = getFTPInputStream(caption_filename);
            StringWriter writer = new StringWriter();
            Charset par = null;
            IOUtils.copy(caption_stream, writer, par);
            String caption = writer.toString();
            GridFSInputFile in = gridFS.createFile(file_stream);
            in.setFilename(file);
            in.put("BuzzID", buzz_id);
            in.put("Caption", caption);
            in.put("PicNum", i);
            in.save();
        } catch (IOException ex) {
            Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
        i++;
    }
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private boolean isValidData(BasicDBObject bdo) {
    Object ok = bdo.get("ok");
    Object error = bdo.get("errmsg");
    if (ok != null && ((Number) ok).intValue() == 1 && error == null) {
        bdo.removeField("ok");
        return true;
    }/*from  w  w  w. j  a  v  a2 s  . com*/
    if (error != null) {
        logger.log(Level.WARNING, "Error from mongo command: {0}", error);
    } else {
        logger.log(Level.WARNING, "Invalid/unexpected mongo command output: {0}", bdo);
    }
    return false;
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private void makeMetrics(final MetricFeedBundle mfb, final String basePath, final BasicDBObject bdo)
        throws Exception {
    for (String s : bdo.keySet()) {
        final MetricPath metricPath = new MetricPath(basePath);
        final Object o = bdo.get(s);
        if (o instanceof BasicDBObject) {
            metricPath.addElement(s);/*from   ww w  . ja  va  2  s .  c om*/
            makeMetrics(mfb, metricPath.toString(), (BasicDBObject) o);
        } else if (o instanceof BasicDBList) {
            metricPath.addElement(s);
            processBasicDBList(mfb, metricPath.toString(), (BasicDBList) o);
        } else if (isKnownDataType(o)) {
            metricPath.addMetric(s);
            makeMetric(metricPath.toString(), o, mfb);
        } else {
            logger.log(Level.WARNING, "Unknown type in mongo output for key {0}: {1}",
                    new Object[] { s, o.getClass().getName() });
        }
    }
}

From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java

License:Open Source License

private boolean isReplicaSetStarted(BasicDBObject setting) {
    if (setting.get("members") == null) {
        return false;
    }//from w  w w  . ja  va 2s .  co  m

    BasicDBList members = (BasicDBList) setting.get("members");
    for (Object m : members.toArray()) {
        BasicDBObject member = (BasicDBObject) m;
        logger.info(member.toString());
        int state = member.getInt("state");
        logger.info("state: " + state);
        // 1 - PRIMARY, 2 - SECONDARY, 7 - ARBITER
        if (state != 1 && state != 2 && state != 7) {
            return false;
        }
    }
    return true;
}

From source file:com.daprota.m2.manager.MongoManager.java

License:Apache License

/**
 * Retrieves user via spceified userName.
 *
 * @param userName A user's userName.//from w  ww. ja  va2s .c o  m
* @return user if exists. Otherwise returns null.
 */
public User findUserByUserName(String userName) throws MongoException {
    DBCursor dbCur = null;

    try {
        // get a user collection
        DBCollection coll = _db.getCollection("user");
        DBObject query = new BasicDBObject("userName", userName);
        dbCur = coll.find(query);
        boolean hasNext;
        try {
            logger.debug("Call dbCur.hasNext().");
            hasNext = dbCur.hasNext();
        } catch (MongoException ex) {
            logger.error("Search for user {} failed.\n" + ex.toString(), userName);
            throw new MongoException("Search for user " + userName + " failed.");
        }
        if (hasNext) {
            DBObject user = dbCur.next();
            ArrayList<BasicDBObject> roles = (ArrayList<BasicDBObject>) user.get("roles");
            ArrayList<Role> roles2 = new ArrayList<Role>();
            if (roles != null) {
                for (BasicDBObject role : roles) {
                    Role role3 = new Role(role.get("_id").toString(), (String) role.get("name"),
                            (String) role.get("description"));
                    roles2.add(role3);
                }
                logger.debug("User {} roles added.", userName);
            }
            return (new User(user.get("_id").toString(), (String) user.get("userName"),
                    (String) user.get("password"), roles2));
        } else {
            logger.warn("User {} could not be found", userName);
            return null;
        }
    } catch (MongoException ex) {
        logger.error("Search for user {} failed.\n" + ex.toString(), userName);
        throw new MongoException("Search for user " + userName + " failed.");
    } finally {
        dbCur.close();
    }
}

From source file:com.deftlabs.lock.mongo.impl.BaseDao.java

License:Apache License

/**
 * Returns the current server time. This makes a few requests to the server to try and adjust for
 * network latency.//w w  w .  j a  v a  2s  .  c o m
 */
protected final static long getServerTime(final MongoClient pMongo,
        final DistributedLockSvcOptions pSvcOptions) {

    final long[] localTimes = new long[SERVER_TIME_TRIES];
    final int[] latency = new int[SERVER_TIME_TRIES];

    long startTime;
    BasicDBObject serverStatus;

    for (int idx = 0; idx < SERVER_TIME_TRIES; idx++) {
        startTime = System.currentTimeMillis();
        serverStatus = getDb(pMongo, pSvcOptions).command(_serverStatusCmd);
        latency[idx] = (int) (System.currentTimeMillis() - startTime);
        localTimes[idx] = ((Date) serverStatus.get(LOCAL_TIME_FIELD)).getTime();
    }

    final long serverTime = localTimes[(SERVER_TIME_TRIES - 1)];

    // Adjust based on latency.
    return (serverTime + getHalfRoundedAvg(latency));
}

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   w ww  . j  a  v a2  s  .  co  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

/**
 * Check for expired/inactive/dead locks and unlock.
 *//*from  ww  w .ja  v  a2 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();
    }
}