Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:japura.MonoBugs.MonoBugs.java

License:BSD License

public boolean list(CommandSender sender, String[] args) {

    int myPage = 1;
    if (args.length == CMD_ARGS) {
        try {/* w  w w  .j ava 2s. c  o m*/
            myPage = Integer.parseInt(args[1]);
        } catch (NumberFormatException e) {
            return false;
        }
    } else if (args.length > CMD_ARGS) {
        return false;
    }

    //query all of our user's bug reports
    BasicDBObject query = new BasicDBObject();
    query.put("user", sender.getName());
    DBCursor cursor = table.find(query);

    //if there are none to show..
    if (cursor.count() == 0) {
        sender.sendMessage("there are no reports to show");
        return true;
    }
    //otherwise, list them all together separated by newlines.
    String userReports = "";

    while (cursor.hasNext()) {
        DBObject element = cursor.next();
        userReports += "ID: " + element.get("bugID") + " | " + element.get("status") + " | "
                + element.get("issue") + " | date: " + element.get("createdDate");
        if (element.containsField("reason")) {
            userReports += " | reason: " + element.get("reason");
        }
        userReports += "\n";
    }

    //divy the report into pages and get the desired page
    ChatPage page = ChatPaginator.paginate(userReports, myPage);

    //send each line of our page to the user
    sender.sendMessage("Page " + page.getPageNumber() + " of " + page.getTotalPages() + " for reports:");
    for (String line : page.getLines()) {
        sender.sendMessage(line);
    }

    return true;
}

From source file:jc.mongodb.JacksonDBObjectSerializer.java

License:Apache License

@Override
public E toElement(DBObject dbObject) {
    Object obj;//from   w ww.  j  a v  a 2s .c  o  m

    if (dbObject.containsField(field) && (obj = dbObject.get(field)) != null && obj instanceof DBObject) {
        return mapper.convertValue(((DBObject) obj).toMap(), type);
    }

    return null;
}

From source file:me.lightspeed7.mongofs.gridfs.GridFSFile.java

License:Apache License

/**
 * Verifies that the MD5 matches between the database and the local file. This should be called after transferring a file.
 * // w ww  .  jav  a  2  s  .  c om
 * @throws MongoException
 */
public void validate() {

    if (fs == null) {
        throw new MongoException("no fs");
    }
    if (md5 == null) {
        throw new MongoException("no md5 stored");
    }

    DBObject cmd = new BasicDBObject("filemd5", id);
    cmd.put("root", fs.getBucketName());
    DBObject res = fs.getDB().command(cmd);
    if (res != null && res.containsField("md5")) {
        String m = res.get("md5").toString();
        if (m.equals(md5)) {
            return;
        }
        throw new MongoException("md5 differ.  mine [" + md5 + "] theirs [" + m + "]");
    }

    // no md5 from the server
    throw new MongoException("no md5 returned from server: " + res);

}

From source file:me.philnate.textmanager.updates.Update12_12.java

License:Open Source License

private void updateNames() {
    LOG.info("Going to separate Customer name into first and LastName");
    final String contact = "contactName";
    DBCollection customers = ds.getCollection(Customer.class);
    for (DBObject customer : customers.find()) {
        if (customer.containsField(contact)) {
            String name = (String) customer.get(contact);
            LOG.info(String.format("Customer with contactName '%s' found", name));
            if (name.contains(" ")) {
                // customer has first and last name set so lets split it. We
                // consider that the first name has only one name and not
                // multiple
                String[] parts = name.split(" ", 2);
                customer.put("firstName", parts[0]);
                customer.put("lastName", parts[1]);
                LOG.info(String.format("Updated customer %s, firstName: '%s', lastName: '%s'",
                        customer.get("_id"), parts[0], parts[1]));
            } else {
                customer.put("firstName", "");
                customer.put("lastName", name);
            }//w w w. j  a v a  2 s.c o m
        } else {
            customer.put("firstName", "");
            customer.put("lastName", "");
            LOG.warn(String.format("Customer %s has no contactName", customer.get("_id")));
        }
        // finally remove the legacy contactName and save the customer
        customer.removeField(contact);
        customers.save(customer);
    }
}

From source file:net.scran24.datastore.mongodb.MongoDbDataStore.java

License:Apache License

@Override
public SurveyParameters getSurveyParameters(String survey_id) throws DataStoreException {
    DBCollection col = getSurveyStateCollection();

    BasicDBObject query = new BasicDBObject(FIELD_SURVEY_ID, survey_id);

    DBCursor cursor = col.find(query);/*from  w w  w  .j  a v a  2s  .c o  m*/
    try {
        if (!cursor.hasNext())
            throw new DataStoreException("Survey state record missing");
        else {
            DBObject stateObj = cursor.next();

            String stateStr = stateObj.get(FIELD_SURVEY_STATE).toString();

            SurveyState state;

            switch (stateStr) {
            case STATE_NOT_INITIALISED:
                state = SurveyState.NOT_INITIALISED;
                break;
            case STATE_ACTIVE:
                state = SurveyState.ACTIVE;
                break;
            case STATE_SUSPENDED:
                state = SurveyState.SUSPENDED;
                break;
            default:
                throw new DataStoreException("bad format of survey state object");
            }

            Option<String> surveyMonkeyUrl = Option.none();

            if (stateObj.containsField(FIELD_SURVEY_MONKEY_URL))
                surveyMonkeyUrl = Option.some((String) stateObj.get(FIELD_SURVEY_MONKEY_URL));

            String locale = (String) stateObj.get(FIELD_LOCALE_ID);

            if (locale == null)
                locale = "en_GB"; // use default for old records

            return new SurveyParameters(state, (Long) stateObj.get(FIELD_START_DATE),
                    (Long) stateObj.get(FIELD_END_DATE), (String) stateObj.get(FIELD_SCHEME_NAME), locale,
                    (Boolean) stateObj.get(FIELD_ALLOW_GEN_USERS), "support@intake24.co.uk",
                    (String) stateObj.get(FIELD_SUSPENSION_REASON), surveyMonkeyUrl);

        }
    } catch (MongoException e) {
        throw new DataStoreException(e);
    }
}

From source file:net.scran24.datastore.mongodb.MongoDbDeserializer.java

License:Apache License

public NutritionMappedFood parseFood(DBObject obj) {
    String code = (String) obj.get("code");

    boolean readyMeal = false;

    if (obj.containsField("readyMeal") && obj.get("readyMeal").equals("true"))
        readyMeal = true;/*w  w w  . j a  v a  2s .  co  m*/

    String englishDescription = (String) obj.get("englishDescription");

    if (englishDescription == null)
        englishDescription = (String) obj.get("description"); // fall back to unlocalised version

    String localDescription = (String) obj.get("localDescription");

    String brand = (String) obj.get("brand");
    if (brand == null)
        brand = "";
    String searchTerm = (String) obj.get("searchTerm");

    // Support multiple nutrient tables, but fall back to old NDNS only
    // implementation for old records
    String nutrientTableID = (String) obj.get("nutrientTableID");

    if (nutrientTableID == null)
        nutrientTableID = "NDNS";

    String nutrientTableCode = (String) obj.get("nutrientTableCode");

    if (nutrientTableCode == null)
        nutrientTableCode = Integer.toString((Integer) obj.get("ndnsCode"));

    CompletedPortionSize portionSize = parsePortionSize((DBObject) obj.get("portionSize"));

    DBObject nutrients = (DBObject) obj.get("nutrients");

    Integer foodGroupCode = (Integer) obj.get("foodGroupCode");
    if (foodGroupCode == null)
        foodGroupCode = 0;

    String englishFoodGroupDescription = (String) obj.get("foodGroupEnglishDescription");
    if (englishFoodGroupDescription == null)
        englishFoodGroupDescription = (String) obj.get("foodGroupDescription");
    if (englishFoodGroupDescription == null)
        englishFoodGroupDescription = "N/A";

    String localFoodGroupDescription = (String) obj.get("foodGroupLocalDescription");

    boolean reasonableAmountFlag;

    String reasonableAmount = (String) obj.get("reasonableAmount");
    if (reasonableAmount == null)
        reasonableAmountFlag = true;
    else
        reasonableAmountFlag = reasonableAmount.equals("true");

    return new NutritionMappedFood(code, englishDescription, Option.<String>fromNullable(localDescription),
            nutrientTableID, nutrientTableCode, readyMeal, searchTerm, portionSize, foodGroupCode,
            englishFoodGroupDescription, Option.fromNullable(localFoodGroupDescription), reasonableAmountFlag,
            brand, parseNutrients(nutrients), parseData((DBObject) obj.get("customData")));
}

From source file:net.scran24.datastore.mongodb.MongoDbDeserializer.java

License:Apache License

public NutritionMappedSurveyRecordWithId deserialize(DBObject obj) {
    ArrayList<NutritionMappedMeal> meals = new ArrayList<NutritionMappedMeal>();

    Long startTime = (Long) obj.get("startTime");
    Long endTime = (Long) obj.get("endTime");
    String userName = (String) obj.get("userName");

    BasicDBList mealsList = (BasicDBList) obj.get("meals");

    for (Object m : mealsList) {
        meals.add(parseMeal((DBObject) m));
    }/* w ww. j  a va2  s. c  om*/

    ArrayList<String> log = new ArrayList<String>();

    BasicDBList loglist = (BasicDBList) obj.get("log");

    for (Object o : loglist)
        log.add((String) o);

    Map<String, String> customFields = new HashMap<String, String>();

    if (obj.containsField("userData")) {
        BasicDBObject userCustomFields = (BasicDBObject) obj.get("userData");
        for (String k : userCustomFields.keySet())
            customFields.put(k, userCustomFields.getString(k));
    }

    return new NutritionMappedSurveyRecordWithId(
            new NutritionMappedSurvey(startTime, endTime, meals, log, userName,
                    parseData((DBObject) obj.get("customData"))),
            customFields, ((ObjectId) obj.get("_id")).toString());
}

From source file:net.skyebook.betaville.mongosession.MongoSessionTracker.java

License:Open Source License

@Override
public Session getSession(String sessionToken) {
    DBObject query = new BasicDBObject(SessionConstants.SESSION_TOKEN, sessionToken);
    DBCursor results = collection.find(query);

    // retrieve the session and return it, or return null
    if (results.hasNext()) {
        DBObject result = results.next();
        if (result.containsField(SessionConstants.USER) && result.containsField(SessionConstants.SESSION_ID)
                && result.containsField(SessionConstants.SESSION_TOKEN)) {
            return new Session(result.get(SessionConstants.USER).toString(),
                    Integer.parseInt(result.get(SessionConstants.SESSION_ID).toString()),
                    result.get(SessionConstants.SESSION_TOKEN).toString());
        } else// w  ww . j a  v  a2  s .com
            return null;
    } else
        return null;
}

From source file:net.tbnr.gearz.activerecord.GModel.java

License:Open Source License

/**
 * Loads a GModel from an existing {@link DBObject} in a Database
 *
 * @param database The database to reference for linked objects.
 * @param dBobject The {@link DBObject} to load data from.
 *///from ww  w.  j  a  v a2  s . c om
public GModel(DB database, DBObject dBobject) {
    this.database = database;
    this.objectId = (ObjectId) dBobject.get("_id");
    loadCollection();
    List<BasicAnalyzedField> allFields = getAllFields();
    for (BasicAnalyzedField analyzedField : allFields) {
        if (!dBobject.containsField(analyzedField.getKey())) {
            setupEmptyField(analyzedField.getField());
        }
        Object o = dBobject.get(analyzedField.getKey());
        o = readObjectFromDB(o);
        try {
            analyzedField.getField().set(this, o);
        } catch (IllegalAccessException e) {
            e.printStackTrace(); //TODO remove this
        }
    }
}

From source file:net.tbnr.gearz.arena.ArenaManager.java

License:Open Source License

/**
 * Loads an arena/*from   w  w  w.j a va  2  s. c om*/
 *
 * @param object The DBObject that represents the arena
 * @return The arena object, fully loaded.
 * @throws GearzException When something goes wrong
 */
public static Arena arenaFromDBObject(Class<? extends Arena> arenaClass, DBObject object)
        throws GearzException {
    Arena arena;
    try {
        Constructor constructor = arenaClass.getConstructor(String.class, String.class, String.class,
                String.class, String.class);
        if (constructor == null) {
            return null;
        }
        arena = (Arena) constructor.newInstance(object.get("name"), object.get("author"),
                object.get("description"), object.get("worldId"), object.get("_id").toString());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    for (Field field : arenaClass.getFields()) {
        if (!(field.isAnnotationPresent(ArenaField.class)))
            continue;
        if (!ArenaIterator.class.isAssignableFrom(field.getType()))
            continue;
        ArenaField annotation = field.getAnnotation(ArenaField.class);
        if (!object.containsField(annotation.key()))
            continue;
        Object o = object.get(annotation.key());
        if (!(o instanceof BasicDBList))
            continue;
        BasicDBList list = (BasicDBList) o;
        List<Object> list2 = new ArrayList<>();
        ArenaFieldSerializer.SerializationDelegate serializer = null;
        for (Object lObject : list) {
            if (lObject instanceof DBObject) {
                DBObject lObject1 = (DBObject) lObject;
                if (serializer == null) {
                    serializer = ArenaFieldSerializer.getSerializerFor(lObject1);
                } else if (!ArenaFieldSerializer.getSerializerFor(lObject1).equals(serializer)) {
                    continue; //In case we have a rogue strange value
                }
                list2.add(serializer.getObjectFor(lObject1));
            }
        }
        ArenaIterator iterator;
        if (serializer == null) {
            iterator = new PointIterator();
        } else //noinspection unchecked
        {
            iterator = serializer.getNewIterator(list2);
        }
        iterator.setLoop(annotation.loop()); //Checks the annotation for this new looping thing. :D
        try {
            field.set(arena, field.getType().cast(iterator));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return arena;
}