List of usage examples for com.mongodb DBObject keySet
Set<String> keySet();
From source file:com.stratio.connector.mongodb.core.engine.storage.MongoInsertHandler.java
License:Apache License
/** * Upsert.//from w w w. ja v a 2 s.c o m * * @param targetTable * the target table * @param row * the row * @param pk * the pk * @throws MongoInsertException * if the insertion fails * @throws MongoValidationException * if the operation is not supported by the connector */ public void upsert(TableMetadata targetTable, Row row, Object pk) throws MongoInsertException, MongoValidationException { // Upsert searching for _id DBObject doc = getBSONFromRow(targetTable, row); BasicDBObject find = new BasicDBObject("_id", pk); try { if (bulkWriteOperation != null) { bulkWriteOperation.find(find).upsert().update(new BasicDBObject("$set", doc)); } else { collection.update(find, new BasicDBObject("$set", doc), true, false); } if (logger.isDebugEnabled()) { logger.debug("Row updated with fields: " + doc.keySet()); } } catch (MongoException e) { logger.error("Error inserting data: " + e.getMessage()); throw new MongoInsertException(e.getMessage(), e); } }
From source file:com.stratio.connector.mongodb.core.engine.storage.MongoInsertHandler.java
License:Apache License
/** * Insert without pk.//ww w . jav a2 s. c om * * @param targetTable * the target table * @param row * the row * @throws MongoValidationException * if the operation is not supported by the connector * @throws MongoInsertException * if the insertion fails */ public void insertWithoutPK(TableMetadata targetTable, Row row) throws MongoValidationException, MongoInsertException { DBObject doc = getBSONFromRow(targetTable, row); try { if (bulkWriteOperation != null) { bulkWriteOperation.insert(doc); } else { collection.insert(doc); } if (logger.isDebugEnabled()) { logger.debug("Row inserted with fields: " + doc.keySet()); } } catch (MongoException e) { logger.error("Error inserting data: " + e.getMessage()); throw new MongoInsertException(e.getMessage(), e); } }
From source file:com.stratio.qa.assertions.DBObjectsAssert.java
License:Apache License
private boolean isContained(List<DBObject> item, BasicDBObject doc) { boolean res = false; for (int i = 0; i < item.size() && !res; i++) { DBObject aux = item.get(i); aux.removeField("_id"); aux.removeField("timestamp"); if (aux.keySet().equals(doc.keySet())) { res = true;//w w w . j av a 2 s. c o m } // Obtenemos los columnNames List<String> cols = new ArrayList<String>(doc.keySet()); for (int x = 0; x < cols.size() && res; x++) { if (!aux.get(cols.get(x)).equals(doc.get(cols.get(x)))) { res = false; } else { res = true; } } } return res; }
From source file:com.tomtom.speedtools.mongodb.mappers.EntityMapper.java
License:Apache License
/** * Loops over all registered superEntity mappings, and sets entity properties accordingly. * * @param entity Entity to merge into. * @param dbObject Data object to read data from. * @param initializedFields Fields that should not be set because they have already been initialized. The fields * that are actually set by this method will be added to it. * @param version Version of database object. * @param errors Container for errors. * @param checkExistingFields Whether this recursion should check all fields of the dbObject are mapped to fields in * the field extend. * @return Resulting entity.//from w w w. j a va2s . c om */ @Nonnull @SuppressWarnings("unchecked") private T setAll(@Nonnull final T entity, @Nonnull final DBObject dbObject, @Nonnull final Set<EntityMapper<?>.Field<?>> initializedFields, final int version, @Nonnull final List<MapperError> errors, final boolean checkExistingFields) { assert entity != null; assert dbObject != null; assert initializedFields != null; assert errors != null; // Result can be built incrementally. T result = entity; // Loop over super entities. for (final SuperEntity superEntity : superEntities) { // Valid version? if (superEntity.isCompatible(version)) { // Delegate to super entity. final EntityMapper<? super T> superMapper = superEntity.getSuperMapper(); result = (T) superMapper.setAll(result, dbObject, initializedFields, version, errors, false); } } // Check that all keys are mapped to fields. if (checkExistingFields) { for (final String keyName : dbObject.keySet()) { if (!predefinedFieldNames.contains(keyName)) { if (!fieldExtent.containsKey(keyName)) { errors.add(new MapperError(this, keyName, "Database field was not mapped.")); } } } } // Loop over fields that are not excluded. final List<Field<?>> remainingFields = new ArrayList<>(fields); //noinspection SuspiciousMethodCalls remainingFields.removeAll(initializedFields); for (final Field<?> field : remainingFields) { // Is the field compatible with database object version? if (field.isCompatible(version)) { // If so, use the field to set the value according to the field's (sub)mapper. result = field.dbToEntity(result, dbObject, errors); // Remember that we set it. initializedFields.add(field); } } return result; }
From source file:com.trenako.mapping.LocalizedFieldReadConverter.java
License:Apache License
@SuppressWarnings("unchecked") @Override//w ww . ja v a2 s.co m public LocalizedField<T> convert(DBObject dbo) { LocalizedField<T> field = new LocalizedField<T>(); Set<String> fieldNames = dbo.keySet(); for (String lang : fieldNames) { field.put(lang, (T) dbo.get(lang)); } return field; }
From source file:com.wenwo.platform.dao.util.WenwoQueryMapper.java
License:Apache License
/** * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the * {@link PersistentEntity} metadata./*from w w w .j a va 2 s. c o m*/ * * @param query must not be {@literal null}. * @param entity can be {@literal null}. * @return */ public DBObject getMappedObject(DBObject query, MongoPersistentEntity<?> entity) { if (Keyword.isKeyword(query)) { return getMappedKeyword(new Keyword(query), entity); } DBObject result = new BasicDBObject(); for (String key : query.keySet()) { MongoPersistentProperty targetProperty = getTargetProperty(key, entity); String newKey = determineKey(key, entity); Object value = query.get(key); result.put(newKey, getMappedValue(value, targetProperty, newKey)); } return result; }
From source file:com.xinqihd.sns.gameserver.util.JSON.java
License:Apache License
@SuppressWarnings("unchecked") public static void serialize(Object o, StringBuilder buf) { o = Bytes.applyEncodingHooks(o);//w w w. ja v a 2 s . c o m if (o == null) { buf.append(" null "); return; } if (o instanceof Number) { buf.append(o); return; } if (o instanceof String) { string(buf, o.toString()); return; } if (o instanceof Iterable) { boolean first = true; buf.append("[ "); for (Object n : (Iterable) o) { if (first) first = false; else buf.append(" , "); serialize(n, buf); } buf.append("]"); return; } if (o instanceof ObjectId) { serialize(new BasicDBObject("$oid", o.toString()), buf); return; } if (o instanceof DBObject) { boolean first = true; buf.append("{ "); DBObject dbo = (DBObject) o; for (String name : dbo.keySet()) { if (first) first = false; else buf.append(" , "); string(buf, name); buf.append(" : "); serialize(dbo.get(name), buf); } buf.append("}"); return; } if (o instanceof Map) { boolean first = true; buf.append("{ "); Map m = (Map) o; for (Map.Entry entry : (Set<Map.Entry>) m.entrySet()) { if (first) first = false; else buf.append(" , "); string(buf, entry.getKey().toString()); buf.append(" : "); serialize(entry.getValue(), buf); } buf.append("}"); return; } if (o instanceof Date) { Date d = (Date) o; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); serialize(new BasicDBObject("$date", format.format(d)), buf); return; } if (o instanceof DBRefBase) { DBRefBase ref = (DBRefBase) o; BasicDBObject temp = new BasicDBObject(); temp.put("$ref", ref.getRef()); temp.put("$id", ref.getId()); serialize(temp, buf); return; } if (o instanceof Boolean) { buf.append(o); return; } if (o instanceof byte[] || o instanceof Binary) { byte[] array = null; if (o instanceof byte[]) { array = (byte[]) o; } else { array = ((Binary) o).getData(); } buf.append("\"").append(StringUtil.bytesToHexString(array)).append("\""); return; } if (o instanceof Pattern) { DBObject externalForm = new BasicDBObject(); externalForm.put("$regex", o.toString()); externalForm.put("$options", Bytes.regexFlags(((Pattern) o).flags())); serialize(externalForm, buf); return; } if (o.getClass().isArray()) { buf.append("[ "); for (int i = 0; i < Array.getLength(o); i++) { if (i > 0) buf.append(" , "); serialize(Array.get(o, i), buf); } buf.append("]"); return; } if (o instanceof BSONTimestamp) { BSONTimestamp t = (BSONTimestamp) o; BasicDBObject temp = new BasicDBObject(); temp.put("$ts", t.getTime()); temp.put("$inc", t.getInc()); serialize(temp, buf); return; } if (o instanceof UUID) { UUID uuid = (UUID) o; BasicDBObject temp = new BasicDBObject(); temp.put("$uuid", uuid.toString()); serialize(temp, buf); return; } if (o instanceof CodeWScope) { CodeWScope c = (CodeWScope) o; BasicDBObject temp = new BasicDBObject(); temp.put("$code", c.getCode()); temp.put("$scope", c.getScope()); serialize(temp, buf); return; } if (o instanceof Code) { Code c = (Code) o; BasicDBObject temp = new BasicDBObject(); temp.put("$code", c.getCode()); serialize(temp, buf); return; } if (o instanceof MinKey) { serialize(new BasicDBObject("$minKey", 1), buf); return; } if (o instanceof MaxKey) { serialize(new BasicDBObject("$maxKey", 1), buf); return; } throw new RuntimeException("json can't serialize type : " + o.getClass()); }
From source file:de.belaso.mongolyn.ui.RepositoryConnector.java
License:Open Source License
@Override public TaskData getTaskData(TaskRepository taskRepository, String taskId, IProgressMonitor monitor) throws CoreException { DBCollection dbCollection = MongolynUtils.getDBCollection(taskRepository); DBObject dbObject = dbCollection.findOne(new ObjectId(taskId)); if (dbObject != null) { TaskData taskData = new TaskData(getTaskDataHandler().getAttributeMapper(taskRepository), KIND, taskRepository.getRepositoryUrl(), taskId); taskData.setPartial(false);// www. j a v a2 s.com taskData.setVersion("1"); getTaskDataHandler().initializeTaskData(taskRepository, taskData, null, monitor); for (String key : dbObject.keySet()) { if (!"_id".equals(key)) taskData.getRoot().getAttribute(key.replace('_', '.')).setValue(dbObject.get(key).toString()); } return taskData; } else { throw new CoreException( Activator.INSTANCE.getErrorStatus("MongoDB document " + taskId + " not found.")); } }
From source file:de.belaso.mongolyn.ui.RepositoryConnector.java
License:Open Source License
@Override public IStatus performQuery(TaskRepository taskRepository, IRepositoryQuery query, TaskDataCollector collector, ISynchronizationSession session, IProgressMonitor monitor) { try {//w w w. jav a2 s . c o m DBCollection dbCollection = MongolynUtils.getDBCollection(taskRepository); DBCursor dbCursor = dbCollection.find(); while (dbCursor.hasNext()) { DBObject dbObject = dbCursor.next(); TaskData taskData = new TaskData(getTaskDataHandler().getAttributeMapper(taskRepository), KIND, taskRepository.getRepositoryUrl(), dbObject.get("_id").toString()); taskData.setPartial(false); taskData.setVersion("1"); getTaskDataHandler().initializeTaskData(taskRepository, taskData, null, monitor); for (String key : dbObject.keySet()) { if (!"_id".equals(key)) taskData.getRoot().getAttribute(key.replace('_', '.')) .setValue(dbObject.get(key).toString()); } collector.accept(taskData); } } catch (CoreException coreException) { // nothing to do } return Status.OK_STATUS; }
From source file:de.cubeisland.engine.reflect.codec.mongo.MongoDBCodec.java
License:Open Source License
private MapNode convertDBObjectToNode(DBObject dbObject) throws ConversionException { MapNode mapNode = MapNode.emptyMap(); for (String key : dbObject.keySet()) { Object value = dbObject.get(key); Node nodeValue = this.convertObjectToNode(value); if (!(nodeValue instanceof NullNode)) { mapNode.set(key, nodeValue); }/*from w w w . java2s . co m*/ } return mapNode; }