Example usage for com.mongodb BasicDBObject containsField

List of usage examples for com.mongodb BasicDBObject containsField

Introduction

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

Prototype

public boolean containsField(final String field) 

Source Link

Document

Checks if this object contains a given field

Usage

From source file:at.oneminutedistraction.mongodbrealm.UserCollection.java

public String[] authenticate(final String username, final String password) throws LoginException {

    BasicDBObject user = find(username);
    if (null == user)
        throw new LoginException(username + " does not exist");

    if (!(user.containsField(ATTR_PASSWORD) && passwordMgr.isValid(user.getString(ATTR_PASSWORD), password)))
        throw new LoginException("Invalid password");

    return (groups(user));

    //      BasicDBList groups = (BasicDBList)user.get(ATTR_GROUPS);
    //      if (null == groups)
    //         return (new String[]{});
    ////from   w  w  w. j av a  2s . co  m
    //      
    //      List<String> g = groups.stream()
    //            .map(e -> { return (e.toString()); })
    //            .collect(Collectors.toList());
    //      return (g.toArray(new String[g.size()]));
}

From source file:br.bireme.tmp.AddPrettyField.java

License:Open Source License

private static void add(final String mongo_host, final int mongo_port, final String mongo_db,
        final String mongo_col) throws UnknownHostException {
    assert mongo_host != null;
    assert mongo_port > 0;
    assert mongo_db != null;
    assert mongo_col != null;

    final MongoClient client = new MongoClient(mongo_host, mongo_port);
    final DB db = client.getDB(mongo_db);
    final DBCollection coll = db.getCollection(HISTORY_COL);
    final DBCursor cursor = coll.find();
    int total = 0;

    System.out.println("host=" + mongo_host);
    System.out.println("port=" + mongo_port);
    System.out.println("database=" + mongo_db);
    System.out.println("collection=" + mongo_col);
    System.out.println("num of documents=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc1 = (BasicDBObject) cursor.next();
        final BasicDBList list = (BasicDBList) doc1.get(ELEM_LST_FIELD);

        for (Object obj : list) {
            final BasicDBObject doc2 = (BasicDBObject) obj;
            if (!doc2.containsField(PRETTY_BROKEN_URL_FIELD)) {
                final String burl = doc2.getString(BROKEN_URL_FIELD);
                try {
                    final String pburl = EncDecUrl.decodeUrl(burl);
                    doc2.append(PRETTY_BROKEN_URL_FIELD, pburl);

                    final WriteResult wr = coll.save(doc1, WriteConcern.ACKNOWLEDGED);
                    if (wr.getCachedLastError().ok()) {
                        total++;// www  .  j a va2  s  .  c  om
                    } else {
                        System.err.println("Document[" + doc1.getString("_id") + "] update error.");
                    }
                } catch (IOException ioe) {
                    System.err.println("Document[" + doc1.getString("_id") + "] bad encode conversion"
                            + " url=[" + burl + "]");
                }
            }
        }
    }
    cursor.close();
    System.out.println("num of added fields: " + total);
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private StationData createStationData(String stationId) throws DataSourceException {
    BasicDBObject stationJson = findStationJson(stationId);
    BasicDBObject lastDataJson = (BasicDBObject) stationJson.get("last");
    if (lastDataJson == null) {
        throw new DataSourceException(DataSourceException.Error.INVALID_DATA,
                "No last data for station '" + stationId + "'");
    }/*  w  w  w  .jav  a2 s .  co m*/

    StationData stationData = new StationData();
    stationData.setStationId(stationId);

    DateTime lastUpdate = getLastUpdateDateTime(lastDataJson);
    stationData.setLastUpdate(lastUpdate);
    DateTime now = new DateTime();
    DateTime expirationDate = getExpirationDate(now, lastUpdate);
    stationData.setExpirationDate(expirationDate);

    // Status
    stationData.setStatus(getDataStatus(stationJson.getString("status"), now, expirationDate));

    // Wind average
    stationData.setWindAverage((float) lastDataJson.getDouble(DataTypeConstant.windAverage.getJsonKey()));

    // Wind max
    stationData.setWindMax((float) lastDataJson.getDouble(DataTypeConstant.windMax.getJsonKey()));

    List<BasicDBObject> datas = getHistoricData(stationId, lastUpdate, getHistoricDuration());
    if (datas.size() > 0) {
        // Wind direction chart
        Serie windDirectionSerie = createSerie(datas, DataTypeConstant.windDirection.getJsonKey());
        windDirectionSerie.setName(DataTypeConstant.windDirection.getName());
        Chart windDirectionChart = new Chart();
        windDirectionChart.setDuration(getHistoricDuration());
        windDirectionChart.getSeries().add(windDirectionSerie);
        stationData.setWindDirectionChart(windDirectionChart);

        // Wind history min/average
        double minValue = Double.MAX_VALUE;
        double maxValue = Double.MIN_VALUE;
        double sum = 0;
        double[][] windTrendMaxDatas = new double[datas.size()][2];
        // double[][] windTrendAverageDatas = new double[windAverageDatas.size()][2];
        for (int i = 0; i < datas.size(); i++) {
            BasicDBObject data = datas.get(i);
            // JDC unix-time is in seconds, windmobile java-time in millis
            long millis = data.getLong("_id") * 1000;
            double windAverage = data.getDouble(DataTypeConstant.windAverage.getJsonKey());
            double windMax = data.getDouble(DataTypeConstant.windMax.getJsonKey());
            minValue = Math.min(minValue, windAverage);
            maxValue = Math.max(maxValue, windMax);
            sum += windAverage;
            windTrendMaxDatas[i][0] = millis;
            windTrendMaxDatas[i][1] = windMax;
        }
        stationData.setWindHistoryMin((float) minValue);
        stationData.setWindHistoryAverage((float) (sum / datas.size()));
        stationData.setWindHistoryMax((float) maxValue);

        // Wind trend
        LinearRegression linearRegression = new LinearRegression(windTrendMaxDatas);
        linearRegression.compute();
        double slope = linearRegression.getBeta1();
        double angle = Math.toDegrees(Math.atan(slope * getWindTrendScale()));
        stationData.setWindTrend((int) Math.round(angle));
    }

    // Air temperature
    stationData.setAirTemperature(
            (float) lastDataJson.getDouble(DataTypeConstant.airTemperature.getJsonKey(), -1));

    // Air humidity
    stationData.setAirHumidity((float) lastDataJson.getDouble(DataTypeConstant.airHumidity.getJsonKey(), -1));

    // Air pressure
    String key = DataTypeConstant.airPressure.getJsonKey();
    if (lastDataJson.containsField(key)) {
        stationData.setAirPressure((float) lastDataJson.getDouble(key));
    }

    // Rain
    key = DataTypeConstant.rain.getJsonKey();
    if (lastDataJson.containsField(key)) {
        stationData.setRain((float) lastDataJson.getDouble(key));
    }

    return stationData;
}

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

/**
 * /*from   w  ww .ja  v  a2s  .  c o  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.datatorrent.contrib.mongodb.MongoDBPOJOOutputOperator.java

License:Apache License

@Override
public void processTuple(Object tuple) {
    tableToDocument.clear();/*ww w .  jav a 2  s .  co m*/
    BasicDBObject doc;
    BasicDBObject nestedDoc = null;

    if (getterValues.isEmpty()) {
        processFirstTuple(tuple);
    }

    for (int i = 0; i < keys.size(); i++) {
        String key = keys.get(i);
        String table = tablenames.get(i);
        //nested object are stored in a new document in mongo db.
        if (key.contains(".")) {
            String[] subKeys = nestedKeys.get(key);
            if (nestedDoc == null) {
                nestedDoc = new BasicDBObject();
            }
            nestedDoc.put(subKeys[1], (getterValues.get(i)).get(tuple));
            if ((doc = tableToDocument.get(table)) == null) {
                doc = new BasicDBObject();
            }
            if (doc.containsField(subKeys[0])) {
                doc.append(subKeys[0], nestedDoc);
            } else {
                doc.put(subKeys[0], nestedDoc);
            }
        } else {
            if ((doc = tableToDocument.get(table)) == null) {
                doc = new BasicDBObject();
            }
            doc.put(key, (getterValues.get(i)).get(tuple));
        }
        tableToDocument.put(table, doc);
    }
    processTupleCommon();

}

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

License:Apache License

private static ObjectId tryLockingExisting(final MongoClient pMongo, final String pLockName,
        final ObjectId pCurrentLockId, final DistributedLockSvcOptions pSvcOptions,
        final DistributedLockOptions pLockOptions, final long pServerTime, final long pStartTime) {
    final long adjustTime = System.currentTimeMillis() - pStartTime;

    final long serverTime = pServerTime + adjustTime;
    final Date now = new Date(serverTime);

    final ObjectId lockId = ObjectId.get();

    final BasicDBObject query = new BasicDBObject(LockDef.ID.field, pLockName);
    query.put(LockDef.LOCK_ID.field, pCurrentLockId);
    query.put(LockDef.STATE.field, LockState.UNLOCKED.code());

    final BasicDBObject toSet = new BasicDBObject();
    toSet.put(LockDef.LIBRARY_VERSION.field, pSvcOptions.getLibVersion());
    toSet.put(LockDef.UPDATED.field, now);
    toSet.put(LockDef.LAST_HEARTBEAT.field, now);
    toSet.put(LockDef.LOCK_ACQUIRED_TIME.field, now);
    toSet.put(LockDef.LOCK_TIMEOUT_TIME.field, new Date((serverTime + pLockOptions.getInactiveLockTimeout())));
    toSet.put(LockDef.LOCK_ID.field, lockId);
    toSet.put(LockDef.STATE.field, LockState.LOCKED.code());
    toSet.put(LockDef.OWNER_APP_NAME.field, pSvcOptions.getAppName());
    toSet.put(LockDef.OWNER_ADDRESS.field, pSvcOptions.getHostAddress());
    toSet.put(LockDef.OWNER_HOSTNAME.field, pSvcOptions.getHostname());
    toSet.put(LockDef.OWNER_THREAD_ID.field, Thread.currentThread().getId());
    toSet.put(LockDef.OWNER_THREAD_NAME.field, Thread.currentThread().getName());
    toSet.put(LockDef.OWNER_THREAD_GROUP_NAME.field, Thread.currentThread().getThreadGroup().getName());
    toSet.put(LockDef.LOCK_ATTEMPT_COUNT.field, 0);
    toSet.put(LockDef.INACTIVE_LOCK_TIMEOUT.field, pLockOptions.getInactiveLockTimeout());

    // Try and modify the existing lock.
    final BasicDBObject lockDoc = (BasicDBObject) getDbCollection(pMongo, pSvcOptions).findAndModify(query,
            new BasicDBObject(LockDef.LOCK_ID.field, 1), null, false, new BasicDBObject(SET, toSet), true,
            false);//from  w  w w  .  j  a  v  a  2 s .co  m

    if (lockDoc == null)
        return null;
    if (!lockDoc.containsField(LockDef.LOCK_ID.field))
        return null;

    final ObjectId returnedLockId = lockDoc.getObjectId(LockDef.LOCK_ID.field);
    if (returnedLockId == null)
        return null;
    if (!returnedLockId.equals(lockId))
        return null;

    if (pSvcOptions.getEnableHistory()) {
        LockHistoryDao.insert(pMongo, pLockName, pSvcOptions, pLockOptions, serverTime, LockState.LOCKED,
                lockId, false);
    }

    // Yay... we have the lock.
    return lockId;
}

From source file:com.ebay.cloud.cms.dal.entity.flatten.impl.NewBsonEntity.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<?> getFieldValues(String fieldName) {
    // validate the field name
    MetaField metaField = getMetaClass().getFieldByName(fieldName);
    CheckConditions.checkArgument(metaField != null, "Can't find meta field %s", fieldName);
    CheckConditions.checkNotNull(metaField.getDbName(), "Meta field doesn't have db name set!");
    // get parent bson & db name
    BasicDBObject fieldBsonObject = null;
    String dbValName = null;/*  ww  w.j a  v  a2 s.c  o m*/
    if (metaField.isInternal()) {
        dbValName = metaField.getDbName();
        fieldBsonObject = bsonObject;
    } else {
        dbValName = MetaField.VALUE_KEY;
        fieldBsonObject = bsonObject;
        dbValName = metaField.getFlattenValueDbName();
    }
    if (fieldBsonObject == null) {
        return Collections.EMPTY_LIST;
    }
    // get value from parent field
    CardinalityEnum cardinality = metaField.getCardinality();
    DataTypeEnum dataType = metaField.getDataType();
    IDataTypeHandler handler = BsonDataTypeHandlerFactory.getHandler(dataType);
    List<Object> result = Collections.EMPTY_LIST;
    if (fieldBsonObject.containsField(dbValName)) {
        if (cardinality == CardinalityEnum.One) {
            Object bsonValue = fieldBsonObject.get(dbValName);
            // for json type field, if data is Many while metatype changed to One,
            // it still can return not null bsonValue, but should ignore it
            if (!(bsonValue instanceof BasicDBList)) {
                result = new ArrayList<Object>(1);
                Object value = handler.read(this, bsonValue, metaField);
                addReadValue(result, value);
            }
        } else {
            List<Object> bsonList = null;
            if (fieldBsonObject.get(dbValName) instanceof List) {
                bsonList = (List<Object>) fieldBsonObject.get(dbValName);
            } else if (fieldBsonObject.get(dbValName) != null) {
                bsonList = new ArrayList<Object>();
                bsonList.add(fieldBsonObject.get(dbValName));
            }
            if (bsonList != null) {
                result = new ArrayList<Object>();
                for (Object bsonValue : bsonList) {
                    Object value = handler.read(this, bsonValue, metaField);
                    addReadValue(result, value);
                }
            }
        }
    }
    return result;
}

From source file:com.ebay.cloud.cms.dal.entity.impl.BsonEntity.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<?> getFieldValues(String fieldName) {
    // validate the field name
    MetaField metaField = getMetaClass().getFieldByName(fieldName);
    CheckConditions.checkArgument(metaField != null, "Can't find meta field %s", fieldName);
    CheckConditions.checkNotNull(metaField.getDbName(), "Meta field doesn't have db name set!");
    // get parent bson & db name
    BasicDBObject fieldBsonObject = null;
    String dbValName = null;//from  w w  w .  j a va  2  s .c o  m
    if (metaField.isInternal()) {
        dbValName = metaField.getDbName();
        fieldBsonObject = bsonObject;
    } else {
        dbValName = MetaField.VALUE_KEY;
        fieldBsonObject = getBsonField(metaField.getDbName());
    }
    if (fieldBsonObject == null) {
        return Collections.EMPTY_LIST;
    }
    // get value from parent field
    CardinalityEnum cardinality = metaField.getCardinality();
    DataTypeEnum dataType = metaField.getDataType();
    IDataTypeHandler handler = BsonDataTypeHandlerFactory.getHandler(dataType);
    List<Object> result = Collections.EMPTY_LIST;
    // when has field
    if (fieldBsonObject.containsField(dbValName)) {
        if (cardinality == CardinalityEnum.One) {
            Object bsonValue = fieldBsonObject.get(dbValName);
            // for json type field, if data is Many while metatype changed to One,
            // it still can return not null bsonValue, but should ignore it
            if (!(bsonValue instanceof BasicDBList)) {
                result = new ArrayList<Object>(1);
                Object value = handler.read(this, bsonValue, metaField);
                addReadValue(result, value);
            }
        } else {
            // cardinality = many. If there is a given non-list-value, wrapper it as list
            List<Object> bsonList = null;
            if (fieldBsonObject.get(dbValName) instanceof List) {
                bsonList = (List<Object>) fieldBsonObject.get(dbValName);
            } else if (fieldBsonObject.get(dbValName) != null) {
                bsonList = new ArrayList<Object>();
                bsonList.add(fieldBsonObject.get(dbValName));
            }
            if (bsonList != null) {
                result = new ArrayList<Object>();
                for (Object bsonValue : bsonList) {
                    Object value = handler.read(this, bsonValue, metaField);
                    addReadValue(result, value);
                }
            }
        }
    }
    return result;
}

From source file:com.ebay.cloud.cms.dal.entity.impl.BsonEntity.java

License:Apache License

@Override
public boolean hasFieldProperty(String fieldName, String propertyName) {
    FieldProperty property = FieldProperty.fromQueryName(propertyName);
    CheckConditions.checkArgument(property != null,
            MessageFormat.format("field property %s not found!", propertyName));
    MetaField metaField = getMetaClass().getFieldByName(fieldName);
    BasicDBObject fieldBsonObject = getBsonField(metaField.getDbName());
    if (fieldBsonObject != null) {
        return fieldBsonObject.containsField(property.getDbName());
    } else {/*from   w  ww.  j a  v  a2 s  .  com*/
        return false;
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.EmbedFieldModifyCommand.java

License:Apache License

void buildRepalceBody(BasicDBObject embedObject, MetaField field) {
    BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
    Object fieldObject = (Object) enityObject.get(field.getFlattenValueDbName());
    embedObject.put(field.getFlattenValueDbName(), fieldObject);
    // field property
    for (FieldProperty fp : FieldProperty.values()) {
        String fpValueDbName = field.getFlattenPropertyValueDbName(fp);
        if (enityObject.containsField(fpValueDbName)) {
            embedObject.put(fpValueDbName, enityObject.get(fpValueDbName));
        }/*from w w  w  .  j  a  v a2s. c om*/
    }
}