List of usage examples for com.mongodb DBObject removeField
Object removeField(String key);
From source file:com.ebay.cloud.cms.dal.persistence.impl.root.RootReplaceCommand.java
License:Apache License
@Override public void execute(PersistenceContext context) { DBObject getResult = RootGetCommand.findDBObject(entity.getId(), entity.getBranchId(), context, entity.getMetaClass(), ROOT_FIELDS, false); if (getResult != null) { // check version int currentVersion = (Integer) getResult.get(InternalFieldEnum.VERSION.getDbName()); int version = entity.getVersion(); if ((version != IEntity.NO_VERSION) && (currentVersion != version)) { throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT, "current version is " + currentVersion + ", but version in repalce body is " + version + "! entity is " + entity.toString()); }//from www .j a v a 2 s . c o m Date createTime = (Date) getResult.get(InternalFieldEnum.CREATETIME.getDbName()); DBObject queryObject = buildReplaceRootQuery(currentVersion); DBObject updateObject = buildReplaceRootUpdate(currentVersion, createTime); try { WriteResult result = MongoExecutor.update(context, entity.getMetaClass(), queryObject, updateObject); if (result.getN() == 0) { throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT, "current version is not " + currentVersion); } //set version for response entity.setVersion(currentVersion + 1); } catch (RuntimeException e) { entity.setVersion(currentVersion); throw e; } catch (Throwable t) { //if anything bad happens, need to set version back entity.setVersion(currentVersion); } finally { //in update scenario, have to set id value back into entity object because we //removed id field before entity.setId(entity.getId()); } } else { // insert //2012/7/13 jianxu1 multi threading issue, if client A and client B send replace at same time //at T1, none of A and B find existing entity, so at T2, both A and B call insert, of we do not have //unique index for combination of _branchId and _oid, we end up with duplicated entities. //FIX is: http://www.mongodb.org/display/DOCS/Indexes, composite unique index //db.branches.ensureIndex({_branchId: 1, _oid: 1}, {unique: true}); //TODO: change create repository to add composite unique index for branches, for main branch, we just need unique index on _oid DBObject insertObject = entity.getNode(); insertObject.removeField("_id"); insertObject.put(InternalFieldEnum.VERSION.getDbName(), IEntity.START_VERSION); MongoExecutor.insert(context, entity.getMetaClass(), insertObject); } }
From source file:com.ebay.cloud.cms.dalapi.persistence.impl.root.RootReplaceCommand.java
License:Apache License
@Override public void execute(PersistenceContext context) { DBObject getResult = RootGetCommand.findDBObject(entity.getId(), entity.getBranchId(), context, entity.getMetaClass(), ROOT_FIELDS, false); if (getResult != null) { // check version int currentVersion = (Integer) getResult.get(InternalFieldEnum.VERSION.getDbName()); int version = entity.getVersion(); if ((version != IEntity.NO_VERSION) && (currentVersion != version)) { throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT, "current version is " + currentVersion + ", but version in repalce body is " + version); }/*from w w w . ja v a 2s . c om*/ Date createTime = (Date) getResult.get(InternalFieldEnum.CREATETIME.getDbName()); DBObject queryObject = buildReplaceRootQuery(currentVersion); DBObject updateObject = buildReplaceRootUpdate(currentVersion, createTime); try { WriteResult result = MongoExecutor.update(context, entity.getMetaClass(), queryObject, updateObject); if (result.getN() == 0) { throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT, "current version is not " + currentVersion); } //set version for response entity.setVersion(currentVersion + 1); } catch (RuntimeException e) { entity.setVersion(currentVersion); throw e; } catch (Throwable t) { //if anything bad happens, need to set version back entity.setVersion(currentVersion); } finally { //in update scenario, have to set id value back into entity object because we //removed id field before entity.setId(entity.getId()); } } else { // insert //2012/7/13 jianxu1 multi threading issue, if client A and client B send replace at same time //at T1, none of A and B find existing entity, so at T2, both A and B call insert, of we do not have //unique index for combination of _branchId and _oid, we end up with duplicated entities. //FIX is: http://www.mongodb.org/display/DOCS/Indexes, composite unique index //db.branches.ensureIndex({_branchId: 1, _oid: 1}, {unique: true}); //TODO: change create repository to add composite unique index for branches, for main branch, we just need unique index on _oid DBObject insertObject = entity.getNode(); insertObject.removeField("_id"); insertObject.put(InternalFieldEnum.VERSION.getDbName(), IEntity.START_VERSION); MongoExecutor.insert(context, entity.getMetaClass(), insertObject); } }
From source file:com.edgytech.umongo.DocFieldObject.java
License:Apache License
void remove(String key) { DBObject doc = (DBObject) value; doc.removeField(key); structureComponent(); }
From source file:com.eywa.impl.app.controllers.session.SessionManager.java
License:Open Source License
public DBObject ping(final String id) throws Exception { final DBObject result = SessionService.ping(id); if (null != result) { // remove not client-used fields (keep only USER_ID) result.removeField(Session.DATA); result.removeField(Session.PING_TIME); result.removeField(Session.IDLE_TIMEOUT); result.removeField(Session.PING_TIME); result.removeField(Session.EXPIRATION_DATE); result.removeField(Session.CREATION_DATE); result.removeField(Session.CREATIONDATE); result.removeField(Session.TYPE); }//from w w w.ja va 2 s . com return result; }
From source file:com.gigaspaces.persistency.datasource.MongoQueryFactory.java
License:Open Source License
@SuppressWarnings("static-access") private static void replaceIdProperty(BasicDBObjectBuilder qResult, SpaceTypeDescriptor typeDescriptor) { DBObject q = qResult.get(); if (q.containsField(typeDescriptor.getIdPropertyName())) { Object value = q.get(typeDescriptor.getIdPropertyName()); q.removeField(typeDescriptor.getIdPropertyName()); q.put(Constants.ID_PROPERTY, value); qResult.start(q.toMap());//from w w w. j a va 2 s. c o m } }
From source file:com.github.camellabs.iot.cloudlet.document.driver.mongodb.BsonMapper.java
License:Apache License
public static DBObject bsonToJson(DBObject bson) { checkNotNull(bson, "BSON passed to the conversion can't be null."); LOG.debug("Converting BSON object to JSON: {}", bson); DBObject json = new BasicDBObject(bson.toMap()); Object id = json.get("_id"); if (id != null) { json.removeField("_id"); json.put("id", id.toString()); }/*w w w .j a v a 2 s. c om*/ return json; }
From source file:com.github.camellabs.iot.cloudlet.document.driver.mongodb.BsonMapper.java
License:Apache License
public static DBObject jsonToBson(DBObject json) { checkNotNull(json, "JSON passed to the conversion can't be null."); LOG.debug("Converting JSON object to BSON: {}", json); DBObject bson = new BasicDBObject(json.toMap()); Object id = bson.get("id"); if (id != null) { bson.removeField("id"); bson.put("_id", new ObjectId(id.toString())); }/*from www. ja va 2s . co m*/ return bson; }
From source file:com.github.jmkgreen.morphia.mapping.DefaultMapper.java
License:Open Source License
/** * <p>/*from w ww .java 2s .c om*/ * Converts a java object to a mongo-compatible object (possibly a DBObject * for complex mappings). Very similar to {@link DefaultMapper#toDBObject} * </p> * <p> * Used (mainly) by query/update operations * </p> */ Object toMongoObject(Object javaObj, boolean includeClassName) { if (javaObj == null) return null; Class origClass = javaObj.getClass(); if (origClass.isAnonymousClass() && origClass.getSuperclass().isEnum()) origClass = origClass.getSuperclass(); Object newObj = converters.encode(origClass, javaObj); if (newObj == null) { log.warning("converted " + javaObj + " to null"); return newObj; } Class type = newObj.getClass(); boolean bSameType = origClass.equals(type); //TODO: think about this logic a bit more. //Even if the converter changed it, should it still be processed? if (!bSameType && !(Map.class.isAssignableFrom(type) || Iterable.class.isAssignableFrom(type))) return newObj; else { //The converter ran, and produced another type, or it is a list/map boolean isSingleValue = true; boolean isMap = false; Class subType = null; if (type.isArray() || Map.class.isAssignableFrom(type) || Iterable.class.isAssignableFrom(type)) { isSingleValue = false; isMap = ReflectionUtils.implementsInterface(type, Map.class); // subtype of Long[], List<Long> is Long subType = (type.isArray()) ? type.getComponentType() : ReflectionUtils.getParameterizedClass(type, (isMap) ? 1 : 0); } if (isSingleValue && !ReflectionUtils.isPropertyType(type)) { DBObject dbObj = toDBObject(newObj); if (!includeClassName) dbObj.removeField(CLASS_NAME_FIELDNAME); return dbObj; } else if (newObj instanceof DBObject) { return newObj; } else if (isMap) { if (ReflectionUtils.isPropertyType(subType)) return toDBObject(newObj); else { HashMap m = new HashMap(); for (Map.Entry e : (Iterable<Map.Entry>) ((Map) newObj).entrySet()) m.put(e.getKey(), toMongoObject(e.getValue(), includeClassName)); return m; } //Set/List but needs elements converted } else if (!isSingleValue && !ReflectionUtils.isPropertyType(subType)) { ArrayList<Object> vals = new ArrayList<Object>(); if (type.isArray()) for (Object obj : (Object[]) newObj) vals.add(toMongoObject(obj, includeClassName)); else for (Object obj : (Iterable) newObj) vals.add(toMongoObject(obj, includeClassName)); return vals; } else { return newObj; } } }
From source file:com.github.torbinsky.morphia.mapping.DefaultMapper.java
License:Open Source License
/** * <p>/* ww w . j a v a2 s. c o m*/ * Converts a java object to a mongo-compatible object (possibly a DBObject * for complex mappings). Very similar to {@link DefaultMapper#toDBObject} * </p> * <p> * Used (mainly) by query/update operations * </p> */ public Object toMongoObject(Object javaObj, boolean includeClassName) { if (javaObj == null) return null; Class origClass = javaObj.getClass(); if (origClass.isAnonymousClass() && origClass.getSuperclass().isEnum()) origClass = origClass.getSuperclass(); Object newObj = converters.encode(origClass, javaObj); if (newObj == null) { log.warn("converted " + javaObj + " to null"); return newObj; } Class type = newObj.getClass(); boolean bSameType = origClass.equals(type); //TODO: think about this logic a bit more. //Even if the converter changed it, should it still be processed? if (!bSameType && !(Map.class.isAssignableFrom(type) || Iterable.class.isAssignableFrom(type))) return newObj; //The converter ran, and produced another type, or it is a list/map boolean isSingleValue = true; boolean isMap = false; Class subType = null; if (type.isArray() || Map.class.isAssignableFrom(type) || Iterable.class.isAssignableFrom(type)) { isSingleValue = false; isMap = ReflectionUtils.implementsInterface(type, Map.class); // subtype of Long[], List<Long> is Long subType = (type.isArray()) ? type.getComponentType() : ReflectionUtils.getParameterizedClass(type, (isMap) ? 1 : 0); } if (isSingleValue && !ReflectionUtils.isPropertyType(type)) { DBObject dbObj = toDBObject(newObj); if (!includeClassName) dbObj.removeField(CLASS_NAME_FIELDNAME); return dbObj; } if (newObj instanceof DBObject) { return newObj; } if (isMap) { if (ReflectionUtils.isPropertyType(subType)) return toDBObject(newObj); HashMap m = new HashMap(); for (Map.Entry e : (Iterable<Map.Entry>) ((Map) newObj).entrySet()) m.put(e.getKey(), toMongoObject(e.getValue(), includeClassName)); return m; //Set/List but needs elements converted } if (!isSingleValue && !ReflectionUtils.isPropertyType(subType)) { ArrayList<Object> vals = new ArrayList<Object>(); if (type.isArray()) for (Object obj : (Object[]) newObj) vals.add(toMongoObject(obj, includeClassName)); else for (Object obj : (Iterable) newObj) vals.add(toMongoObject(obj, includeClassName)); return vals; } return newObj; }
From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java
License:Apache License
/** * Prints all the rows of data returned by the API. * @param gaData the data returned from the API. * @param collection//from www . j a v a 2 s . c o m * @param d */ private static void insertVisitedCompaniesData(GaData gaData, DBCollection collection, Date d) throws JSONException { if (gaData.getTotalResults() > 0) { System.out.println("Data Table: " + collection); for (List<String> rowValues : gaData.getRows()) { Map jsonMap = (Map) JSON.parse(rowValues.get(0)); if (jsonMap.get("demandbase_sid") == null) { continue; } DBObject dbObject = new BasicDBObject(jsonMap); dbObject.removeField("ip"); HashMap<Object, Object> map = new HashMap<Object, Object>(); map.put("demandbase_sid", dbObject.get("demandbase_sid")); BasicDBObject objectToRemove = new BasicDBObject(map); DBObject andRemove = collection.findAndRemove(objectToRemove); if (andRemove == null) { dbObject.put("firstVisitDate", new SimpleDateFormat("yyyy/MM/dd").format(d)); } else { dbObject.put("firstVisitDate", andRemove.get("firstVisitDate")); } collection.insert(dbObject); } } else { System.out.println("No data"); } }