Java Code Examples for org.bson.BsonDocument#append()

The following examples show how to use org.bson.BsonDocument#append() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UpdateDescription.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Convert this update description to an update document.
 *
 * @return an update document with the appropriate $set and $unset documents.
 */
public BsonDocument toUpdateDocument() {
  final List<BsonElement> unsets = new ArrayList<>();
  for (final String removedField : this.removedFields) {
    unsets.add(new BsonElement(removedField, new BsonBoolean(true)));
  }
  final BsonDocument updateDocument = new BsonDocument();

  if (this.updatedFields.size() > 0) {
    updateDocument.append("$set", this.updatedFields);
  }

  if (unsets.size() > 0) {
    updateDocument.append("$unset", new BsonDocument(unsets));
  }

  return updateDocument;
}
 
Example 2
Source File: BsonReaderStreamingTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Test
public void singleValue() throws IOException {
  BsonDocument document = new BsonDocument();
  document.append("value", new BsonInt32(42));

  JsonReader reader = createReader(document);
  check(reader.peek()).is(JsonToken.BEGIN_OBJECT);
  reader.beginObject();
  check(reader.hasNext());
  check(reader.peek()).is(JsonToken.NAME);
  check(reader.nextName()).is("value");
  check(reader.peek()).is(JsonToken.NUMBER);
  check(reader.nextInt()).is(42);
  check(reader.peek()).is(JsonToken.END_OBJECT);
  reader.endObject();
  check(!reader.hasNext());
}
 
Example 3
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Override
public ScheduleState getScheduleState(String versionId) {
    BsonDocument doc = new BsonDocument();
    doc.append("version", new BsonString(versionId));
    ScheduleState state = scheduleStates.find(doc).map(new Function<Document, ScheduleState>() {
        @Override
        public ScheduleState apply(Document t) {
            String json = t.toJson();
            try {
                return mapper.readValue(json, ScheduleState.class);
            } catch (IOException e) {
                LOG.error("deserialize config item failed!", e);
            }
            return null;
        }
    }).first();

    if (state != null) {
        // based on version, to add content from collections of spoutSpecs/alertSpecs/etc..
        state = addDetailForScheduleState(state, versionId);
    }

    return state;
}
 
Example 4
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 6 votes vote down vote up
/**
 * get the basic ScheduleState, and then based on the version to get all sub-part(spoutSpecs/alertSpecs/etc)
 * to form a completed ScheduleState.
 * @return the latest ScheduleState
 */
@Override
public ScheduleState getScheduleState() {
    BsonDocument sort = new BsonDocument();
    sort.append("generateTime", new BsonInt32(-1));
    ScheduleState state = scheduleStates.find().sort(sort).map(new Function<Document, ScheduleState>() {
        @Override
        public ScheduleState apply(Document t) {
            String json = t.toJson();
            try {
                return mapper.readValue(json, ScheduleState.class);
            } catch (IOException e) {
                LOG.error("deserialize config item failed!", e);
            }
            return null;
        }
    }).first();

    if (state != null) {
        String version = state.getVersion();
        // based on version, to add content from collections of spoutSpecs/alertSpecs/etc..
        state = addDetailForScheduleState(state, version);
    }

    return state;
}
 
Example 5
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 6 votes vote down vote up
private <T> List<T> list(MongoCollection<Document> collection, Class<T> clz, String version) {
    BsonDocument doc = new BsonDocument();
    doc.append("version", new BsonString(version));

    List<T> result = new LinkedList<T>();
    collection.find(doc).map(new Function<Document, T>() {
        @Override
        public T apply(Document t) {
            String json = t.toJson();
            try {
                return mapper.readValue(json, clz);
            } catch (IOException e) {
                LOG.error("deserialize config item failed!", e);
            }
            return null;
        }
    }).into(result);
    return result;
}
 
Example 6
Source File: MongoDBInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({
    "rawtypes",
    "unchecked"
})
@Before
public void setUp() throws Exception {

    interceptor = new MongoDBInterceptor();

    Config.Plugin.MongoDB.TRACE_PARAM = true;

    when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");

    BsonDocument document = new BsonDocument();
    document.append("name", new BsonString("by"));
    MongoNamespace mongoNamespace = new MongoNamespace("test.user");
    Decoder decoder = PowerMockito.mock(Decoder.class);
    FindOperation findOperation = new FindOperation(mongoNamespace, decoder);
    findOperation.filter(document);

    arguments = new Object[] {findOperation};
    argumentTypes = new Class[] {findOperation.getClass()};
}
 
Example 7
Source File: MongoDBOperationExecutorInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {

    interceptor = new MongoDBOperationExecutorInterceptor();

    Config.Plugin.MongoDB.TRACE_PARAM = true;

    when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");

    BsonDocument document = new BsonDocument();
    document.append("name", new BsonString("by"));
    MongoNamespace mongoNamespace = new MongoNamespace("test.user");
    Decoder decoder = PowerMockito.mock(Decoder.class);
    FindOperation findOperation = new FindOperation(mongoNamespace, decoder);
    findOperation.filter(document);

    arguments = new Object[] {findOperation};
    argumentTypes = new Class[] {findOperation.getClass()};
}
 
Example 8
Source File: ChronoElement.java    From epcis with Apache License 2.0 6 votes vote down vote up
/**
 * @param timestamp
 * @param projection
 * @return TimestampProperties BsonDocument only containing projection keys
 */
public BsonDocument getTimestampProperties(final Long timestamp, final String[] projection) {
	BsonDocument bsonProjection = new BsonDocument();
	if (projection != null) {
		for (String string : projection) {
			bsonProjection.append(string, new BsonBoolean(true));
		}
	}

	if (this instanceof ChronoVertex)
		return graph.getVertexEvents().find(new BsonDocument(Tokens.VERTEX, new BsonString(this.id))
				.append(Tokens.TIMESTAMP, new BsonDateTime(timestamp))).projection(bsonProjection).first();
	else
		return graph.getEdgeCollection()
				.find(new BsonDocument(Tokens.ID, new BsonString(this.id + "-" + timestamp)))
				.projection(bsonProjection).first();
}
 
Example 9
Source File: BsonReaderTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * Reading from BSON to GSON
 */
@Test
public void bsonToGson() throws Exception {
  BsonDocument document = new BsonDocument();
  document.append("boolean", new BsonBoolean(true));
  document.append("int32", new BsonInt32(32));
  document.append("int64", new BsonInt64(64));
  document.append("double", new BsonDouble(42.42D));
  document.append("string", new BsonString("foo"));
  document.append("null", new BsonNull());
  document.append("array", new BsonArray());
  document.append("object", new BsonDocument());

  JsonElement element = TypeAdapters.JSON_ELEMENT.read(new BsonReader(new BsonDocumentReader(document)));
  check(element.isJsonObject());

  check(element.getAsJsonObject().get("boolean").getAsJsonPrimitive().isBoolean());
  check(element.getAsJsonObject().get("boolean").getAsJsonPrimitive().getAsBoolean());

  check(element.getAsJsonObject().get("int32").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("int32").getAsJsonPrimitive().getAsNumber().intValue()).is(32);

  check(element.getAsJsonObject().get("int64").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("int64").getAsJsonPrimitive().getAsNumber().longValue()).is(64L);

  check(element.getAsJsonObject().get("double").getAsJsonPrimitive().isNumber());
  check(element.getAsJsonObject().get("double").getAsJsonPrimitive().getAsNumber().doubleValue()).is(42.42D);

  check(element.getAsJsonObject().get("string").getAsJsonPrimitive().isString());
  check(element.getAsJsonObject().get("string").getAsJsonPrimitive().getAsString()).is("foo");

  check(element.getAsJsonObject().get("null").isJsonNull());
  check(element.getAsJsonObject().get("array").isJsonArray());
  check(element.getAsJsonObject().get("object").isJsonObject());
}
 
Example 10
Source File: NamespaceSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public boolean isStale() {
  nsLock.readLock().lock();
  try {
    final BsonDocument filter = getNsFilter(getNamespace());
    filter.append(ConfigCodec.Fields.IS_STALE, BsonBoolean.TRUE);
    return docsColl.countDocuments(filter) == 1;
  } finally {
    nsLock.readLock().unlock();
  }
}
 
Example 11
Source File: Utils.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
private static JsonObject convertUpsertId(BsonValue upsertId) {
  JsonObject jsonUpsertId;
  if (upsertId != null) {
    JsonObjectCodec jsonObjectCodec = new JsonObjectCodec(new JsonObject());

    BsonDocument upsertIdDocument = new BsonDocument();
    upsertIdDocument.append(ID_FIELD, upsertId);

    BsonDocumentReader bsonDocumentReader = new BsonDocumentReader(upsertIdDocument);
    jsonUpsertId = jsonObjectCodec.decode(bsonDocumentReader, DecoderContext.builder().build());
  } else {
    jsonUpsertId = null;
  }
  return jsonUpsertId;
}
 
Example 12
Source File: Converter.java    From epcis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
public static BsonDocument makeIndexParamterDocument(Parameter... indexParameters) {
	BsonDocument index = new BsonDocument();
	for (Parameter param : indexParameters) {
		validateIndexParameter(param);
		index.append(param.getKey().toString(), new BsonInt32((Integer) param.getValue()));
	}
	return index;
}
 
Example 13
Source File: VertexEvent.java    From epcis with Apache License 2.0 5 votes vote down vote up
public Set<VertexEvent> getOutVertexEventSet(final String label, final AC tt) {

		// db.edges.createIndex({"_outV" : 1, "_label" : 1, "_t" : 1, "_inV" : 1})
		BsonDocument query = new BsonDocument(Tokens.OUT_VERTEX, new BsonString(vertex.toString()));
		query.append(Tokens.LABEL, new BsonString(label));
		query.append(Tokens.TIMESTAMP, new BsonDocument(tt.toString(), new BsonDateTime(timestamp)));
		BsonDocument proj = new BsonDocument(Tokens.TIMESTAMP, new BsonBoolean(true))
				.append(Tokens.IN_VERTEX, new BsonBoolean(true)).append(Tokens.ID, new BsonBoolean(false));

		HashSet<VertexEvent> ret = new HashSet<VertexEvent>();
		Iterator<BsonDocument> x = vertex.graph.getEdgeEvents().find(query).projection(proj).iterator();
		HashMap<String, Long> map = new HashMap<String, Long>();
		while (x.hasNext()) {
			BsonDocument d = x.next();
			String inV = d.getString(Tokens.IN_VERTEX).getValue();
			Long t = d.getDateTime(Tokens.TIMESTAMP).getValue();
			if (map.containsKey(inV)) {
				if (map.get(inV) > t)
					map.put(inV, t);
			} else
				map.put(inV, t);
		}

		map.entrySet().parallelStream().forEach(entry -> {
			VertexEvent ve = new VertexEvent(graph, entry.getKey() + "-" + entry.getValue());
			ret.add(ve);
		});
		return ret;
	}
 
Example 14
Source File: LongInterval.java    From epcis with Apache License 2.0 5 votes vote down vote up
public static BsonDocument getTemporalRelationFilterQuery(long left, AC ss, AC se) {
	BsonDocument filter = new BsonDocument();
	if (ss != null)
		filter.append(Tokens.START, new BsonDocument(ss.toString(), new BsonDateTime(left)));
	if (se != null)
		filter.append(Tokens.END, new BsonDocument(se.toString(), new BsonDateTime(left)));
	return filter;
}
 
Example 15
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
private <T> OpResult removeObject(MongoCollection<Document> collection, String nameField, String name) {
    BsonDocument filter = new BsonDocument();
    filter.append(nameField, new BsonString(name));
    DeleteResult dr = collection.deleteOne(filter);
    OpResult result = new OpResult();
    result.code = 200;
    result.message = String.format(" %d config item removed!", dr.getDeletedCount());
    return result;
}
 
Example 16
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
private <T> OpResult addOrReplace(MongoCollection<Document> collection, T t) {
    BsonDocument filter = new BsonDocument();
    if (t instanceof StreamDefinition) {
        filter.append("streamId", new BsonString(MetadataUtils.getKey(t)));
    } else if (t instanceof AlertPublishEvent) {
        filter.append("alertId", new BsonString(MetadataUtils.getKey(t)));
    } else {
        filter.append("name", new BsonString(MetadataUtils.getKey(t)));
    }

    String json = "";
    OpResult result = new OpResult();
    try {
        json = mapper.writeValueAsString(t);
        UpdateOptions options = new UpdateOptions();
        options.upsert(true);
        UpdateResult ur = collection.replaceOne(filter, Document.parse(json), options);
        // FIXME: could based on matched count do better matching...
        if (ur.getModifiedCount() > 0 || ur.getUpsertedId() != null) {
            result.code = 200;
            result.message = String.format("update %d configuration item.", ur.getModifiedCount());
        } else {
            result.code = 500;
            result.message = "no configuration item create/updated.";
        }
    } catch (Exception e) {
        result.code = 500;
        result.message = e.getMessage();
        LOG.error("", e);
    }
    return result;
}
 
Example 17
Source File: IndexFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static BsonDocument createKeysDocument(final List<IndexKey> keys) {
    final BsonDocument keysDocument = new BsonDocument();
    for (final IndexKey key : keys) {
        keysDocument.append(key.getFieldName(), key.getBsonValue());
    }
    return keysDocument;
}
 
Example 18
Source File: DocumentVersionInfo.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a BSON version document representing a new version with a new instance ID, and
 * version counter of zero.
 * @return a BsonDocument representing a synchronization version
 */
static BsonDocument getFreshVersionDocument() {
  final BsonDocument versionDoc = new BsonDocument();

  versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1));
  versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString()));
  versionDoc.append(Fields.VERSION_COUNTER_FIELD, new BsonInt64(0L));

  return versionDoc;
}
 
Example 19
Source File: CoreDocumentSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public boolean isStale() {
  docLock.readLock().lock();
  try {
    final BsonDocument filter = getDocFilter(namespace, documentId);
    filter.append(
        CoreDocumentSynchronizationConfig.ConfigCodec.Fields.IS_STALE, BsonBoolean.TRUE);
    return docsColl.countDocuments(filter) == 1;
  } finally {
    docLock.readLock().unlock();
  }
}
 
Example 20
Source File: ChronoVertex.java    From epcis with Apache License 2.0 4 votes vote down vote up
private Stream<ChronoEdge> getOutChronoEdgeStream(final BsonArray labels, final int branchFactor,
		final boolean setParallel) {

	while (true) {
		try {
			HashSet<ChronoEdge> edgeSet = new HashSet<ChronoEdge>();
			BsonDocument filter = new BsonDocument();
			filter.append(Tokens.OUT_VERTEX, new BsonString(this.toString()));

			Iterator<BsonDocument> it = graph.getEdgeCollection()
					.find(new BsonDocument(Tokens.OUT_VERTEX, new BsonString(this.toString())))
					.projection(new BsonDocument(Tokens.LABEL, new BsonBoolean(true))
							.append(Tokens.IN_VERTEX, new BsonBoolean(true))
							.append(Tokens.ID, new BsonBoolean(false)))
					.iterator();
			while (it.hasNext()) {
				BsonDocument doc = it.next();
				String inV = doc.getString(Tokens.IN_VERTEX).getValue();
				String label = doc.getString(Tokens.LABEL).getValue();
				edgeSet.add(new ChronoEdge(this.toString() + "|" + label + "|" + inV, this.toString(), inV, label,
						graph));
			}

			if (setParallel)
				return edgeSet.parallelStream();
			else
				return edgeSet.stream();
		} catch (MongoCursorNotFoundException e1) {
			System.out.println(e1.getErrorMessage());
		}
	}

	// HashSet<ChronoEdge> edgeSet = new HashSet<ChronoEdge>();
	// BsonDocument filter = new BsonDocument();
	// BsonDocument inner = new BsonDocument();
	// filter.put(Tokens.OUT_VERTEX, new BsonString(this.toString()));
	// if (labels != null && labels.size() != 0) {
	// inner.put(Tokens.FC.$in.toString(), labels);
	// filter.put(Tokens.LABEL, inner);
	// }
	//
	// Iterator<BsonDocument> it = null;
	// if (branchFactor == Integer.MAX_VALUE)
	// it =
	// graph.getEdgeCollection().find(filter).projection(Tokens.PRJ_ONLY_ID).iterator();
	// else
	// it =
	// graph.getEdgeCollection().find(filter).projection(Tokens.PRJ_ONLY_ID).limit(branchFactor).iterator();
	//
	// while (it.hasNext()) {
	// BsonDocument d = it.next();
	// edgeSet.add(new ChronoEdge(d.getString(Tokens.ID).getValue(), this.graph));
	// }
	// if (setParallel)
	// return edgeSet.parallelStream();
	// else
	// return edgeSet.stream();
}