Java Code Examples for org.bson.types.ObjectId

The following examples show how to use org.bson.types.ObjectId. These examples are extracted from open source projects. 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 Project: scava   Source File: InternalValidator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, Float> readDistanceScores(String startingObject, Set<String> others) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(_SIMILARITY_METHOD).orOperator(
			Criteria.where("fromArtifact.$id").is(new ObjectId(startingObject)),
			Criteria.where("toArtifact.$id").is(new ObjectId(startingObject))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
	DBCursor cursor = dbCollection.find(query.getQueryObject());
	List<DBObject> list = cursor.toArray();
	for (DBObject dbObject : list) {
		String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
		double value = ((double) dbObject.get("value"));
		if (toArtifact.equals(startingObject)) {
			if (others.contains(fromArtifact))
				result.put(fromArtifact, (float) (1 - value));
		} else if (others.contains(toArtifact))
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example 2
@Test
public void objectIdInQuery() throws ParseException, JSONException {
    mongoCollection.insertOne(new Document("_id", new ObjectId("54651022bffebc03098b4567")).append("key", "value1"));
    mongoCollection.insertOne(new Document("_id", new ObjectId("54651022bffebc03098b4568")).append("key", "value2"));
    try {
        QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select _id from " + COLLECTION
            + " where ObjectId('_id') IN ('54651022bffebc03098b4567','54651022bffebc03098b4568')").build();
        QueryResultIterator<Document> findIterable = queryConverter.run(mongoDatabase);
        List<Document> documents = Lists.newArrayList(findIterable);
        assertEquals(2, documents.size());
        JSONAssert.assertEquals("{\n" + "\t\"_id\" : {\n" + "\t\t\"$oid\" : \"54651022bffebc03098b4567\"\n"
            + "\t}\n" + "}", documents.get(0).toJson(jsonWriterSettings),false);
        JSONAssert.assertEquals("{\n" + "\t\"_id\" : {\n" + "\t\t\"$oid\" : \"54651022bffebc03098b4568\"\n"
            + "\t}\n" + "}", documents.get(1).toJson(jsonWriterSettings),false);
    } finally {
        mongoCollection.deleteOne(new Document("_id", new ObjectId("54651022bffebc03098b4567")));
        mongoCollection.deleteOne(new Document("_id", new ObjectId("54651022bffebc03098b4568")));
    }
}
 
Example 3
Source Project: jakduk-api   Source File: DefaultViewController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "/${jakduk.api-url-path.user-picture-small}/{id}", method = RequestMethod.GET)
public void getUserSmallPicture(@PathVariable String id,
								HttpServletResponse response) {

	UserPicture userPicture = userPictureService.findOneById(id);

	ObjectId objectId = new ObjectId(userPicture.getId());
	LocalDate localDate = objectId.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

	try {
		ByteArrayOutputStream byteStream = FileUtils.readImageFile(storageProperties.getUserPictureSmallPath(), localDate, userPicture.getId(), userPicture.getContentType());
		response.setContentType(userPicture.getContentType());

		byteStream.writeTo(response.getOutputStream());
	} catch (IOException e) {
		throw new ServiceException(ServiceError.IO_EXCEPTION, e);
	}
}
 
Example 4
protected static int mongoToKettleType( Object fieldValue ) {
  if ( fieldValue == null ) {
    return ValueMetaInterface.TYPE_STRING;
  }

  if ( fieldValue instanceof Symbol || fieldValue instanceof String || fieldValue instanceof Code
        || fieldValue instanceof ObjectId || fieldValue instanceof MinKey || fieldValue instanceof MaxKey ) {
    return ValueMetaInterface.TYPE_STRING;
  } else if ( fieldValue instanceof Date ) {
    return ValueMetaInterface.TYPE_DATE;
  } else if ( fieldValue instanceof Number ) {
    // try to parse as an Integer
    try {
      Integer.parseInt( fieldValue.toString() );
      return ValueMetaInterface.TYPE_INTEGER;
    } catch ( NumberFormatException e ) {
      return ValueMetaInterface.TYPE_NUMBER;
    }
  } else if ( fieldValue instanceof Binary ) {
    return ValueMetaInterface.TYPE_BINARY;
  } else if ( fieldValue instanceof BSONTimestamp ) {
    return ValueMetaInterface.TYPE_INTEGER;
  }

  return ValueMetaInterface.TYPE_STRING;
}
 
Example 5
Source Project: mirrorgate   Source File: ReviewEventHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void processEvents(final List<Event> eventList, final Set<String> dashboardIds) {
    final List<ObjectId> idList = eventList.stream()
        .map(Event::getCollectionId)
        .filter(ObjectId.class::isInstance)
        .map(ObjectId.class::cast)
        .collect(Collectors.toList());

    final Iterable<Review> reviews = reviewService.getReviewsByObjectId(idList);

    final Predicate<Dashboard> filterDashboard = dashboard ->
        dashboard.getApplications() != null && ! dashboard.getApplications().isEmpty()
            && StreamSupport.stream(reviews.spliterator(), false)
            .anyMatch(review -> dashboard.getApplications().contains(review.getAppname()));

    eventsHelper.processEvents(dashboardIds, filterDashboard, EventType.REVIEW);
}
 
Example 6
@Test
public void testDeleteApiKey() {
  final StitchAuthRoutes routes = new StitchAppRoutes("my_app-12345").getAuthRoutes();
  final ObjectId keyToDelete = new ObjectId();

  final StitchAuthRequest.Builder expectedRequestBuilder = new StitchAuthRequest.Builder();
  expectedRequestBuilder
          .withHeaders(null)
          .withMethod(Method.DELETE)
          .withPath(routes.getBaseAuthRoute() + "/api_keys/" + keyToDelete.toHexString())
          .withRefreshToken()
          .withShouldRefreshOnFailure(false);

  testClientCall(
      (client) -> {
        client.deleteApiKeyInternal(keyToDelete);
        return null;
      },
      true,
      expectedRequestBuilder.build()
  );
}
 
Example 7
@Test
public void checkEncryptedSetPrimitive() {
    MyBean bean = new MyBean();
    Set<String> set = new HashSet<>();
    set.add("one");
    set.add("two");
    bean.secretSetPrimitive = set;
    mongoTemplate.save(bean);

    MyBean fromDb = mongoTemplate.findOne(query(where("_id").is(bean.id)), MyBean.class);

    assertThat(fromDb.secretSetPrimitive.contains("one"), is(true));
    assertThat(fromDb.secretSetPrimitive.contains("two"), is(true));
    assertThat(fromDb.secretSetPrimitive.size(), is(2));

    Document fromMongo = mongoTemplate.getCollection(MyBean.MONGO_MYBEAN).find(new BasicDBObject("_id", new ObjectId(bean.id))).first();
    int expectedLength = 12
            + "one".length() + 7
            + "two".length() + 7;

    assertCryptLength(fromMongo.get(MyBean.MONGO_SECRETSETPRIMITIVE), expectedLength);
}
 
Example 8
Source Project: scava   Source File: SimilarityManager.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Table<String, String, Double> getDistanceMatrix(ISimilarityCalculator simCalculator) {
	List<Artifact> arts = artifactRepository.findAll();
	Table<String, String, Double> result = HashBasedTable.create();
	int count = 1;
	for (Artifact artifact : arts) {

		List<Relation> relList = relationRepository.findByToArtifactIdAndTypeName(new ObjectId(artifact.getId()),
				simCalculator.getSimilarityName());
		logger.info("Relations are extracted: " + count);
		count++;
		for (Relation relation : relList) {
			result.put(relation.getFromProject().getId(), relation.getToProject().getId(), relation.getValue());
		}
		artifactRepository.findAll().forEach(z -> result.put(z.getId(), z.getId(), 1.0));
	}
	return result;
}
 
Example 9
Source Project: render   Source File: StackMetaDataService.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Path("v1/likelyUniqueId")
@GET
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "A (very likely) globally unique identifier")
public String getUniqueId() {
    final ObjectId objectId = new ObjectId();
    return objectId.toString();
}
 
Example 10
Source Project: micro-integrator   Source File: MongoDataHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method updates the entity in table when transactional update is necessary.
 *
 * @param tableName     Table Name
 * @param oldProperties Old Properties
 * @param newProperties New Properties
 * @throws ODataServiceFault
 */
@Override
public boolean updateEntityInTableTransactional(String tableName, ODataEntry oldProperties,
                                                ODataEntry newProperties) throws ODataServiceFault {
    String oldPropertyObjectKeyValue = oldProperties.getValue(DOCUMENT_ID);
    StringBuilder updateNewProperties = new StringBuilder();
    updateNewProperties.append("{$set: {");
    boolean propertyMatch = false;
    for (String column : newProperties.getData().keySet()) {
        if (propertyMatch) {
            updateNewProperties.append("', ");
        }
        String propertyValue = newProperties.getValue(column);
        updateNewProperties.append(column).append(": '").append(propertyValue);
        propertyMatch = true;
    }
    updateNewProperties.append("'}}");
    String query = updateNewProperties.toString();
    WriteResult update = jongo.getCollection(tableName).update(new ObjectId(oldPropertyObjectKeyValue)).with(query);
    int wasUpdated = update.getN();
    if (wasUpdated == 1) {
        return update.wasAcknowledged();
    } else {
        throw new ODataServiceFault("Error occured while updating the entity to collection :"
                + tableName + ".");
    }
}
 
Example 11
Source Project: socialite   Source File: ContentTools.java    License: Apache License 2.0 5 votes vote down vote up
public static Content createSequentialPost(User author){
    int postId = idSequence.getAndIncrement();
    Content newPost = new Content(author, "message-" + postId, null);
    ObjectId fakeId = new ObjectId(postId, 0, (short) 0, 0);
    newPost.toDBObject().put(Content.ID_KEY, fakeId);   
    
    return newPost;
}
 
Example 12
Source Project: scava   Source File: ClusterManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Cluster getClusterFromArtifact(Artifact art, ISimilarityCalculator simCalc, IClusterCalculator clusterAlgorithm){
	Clusterization clusterization = clusterizationRepository.findTopBySimilarityMethodAndClusterAlgorithmOrderByClusterizationDate(simCalc.getSimilarityName(), clusterAlgorithm.getClusterName());
	
	Query q1 = new Query();
	q1.addCriteria(Criteria.where("clusterization.$id").is(new ObjectId(clusterization.getId())).orOperator(
			Criteria.where("artifacts._id").is(new ObjectId(art.getId())),
			Criteria.where("mostRepresentative._id").is(new ObjectId(art.getId()))));
	
	Cluster result = mongoOperations.findOne(q1, Cluster.class);
	return result;
}
 
Example 13
Source Project: core-ng-project   Source File: EntityEncoderBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void encode() {
    assertThat(builder.enumCodecFields.keySet()).containsExactly(TestEnum.class);

    TestEntity entity = new TestEntity();
    entity.id = new ObjectId("5627b47d54b92d03adb9e9cf");
    entity.booleanField = Boolean.TRUE;
    entity.longField = 325L;
    entity.stringField = "string";
    entity.zonedDateTimeField = ZonedDateTime.of(LocalDateTime.of(2016, 9, 1, 11, 0, 0), ZoneId.of("America/New_York"));
    entity.child = new TestChildEntity();
    entity.child.enumField = TestEnum.ITEM1;
    entity.child.enumListField = List.of(TestEnum.ITEM2);
    entity.listField = List.of("V1", "V2");
    entity.mapField = Map.of("K1", "V1", "K2", "V2");
    entity.enumMapField = Map.of(TestEnum.ITEM1, "V1");
    entity.mapListField = Map.of("K1", List.of("V1"), "K2", List.of("V2", "V3"));

    var bson = new BsonDocument();
    try (var writer = new BsonDocumentWriter(bson)) {
        encoder.encode(writer, entity);
    }

    var expectedBSON = new BsonDocument();
    try (var writer = new BsonDocumentWriter(expectedBSON)) {
        writer.pipe(new JsonReader(ClasspathResources.text("mongo-test/entity.json")));
    }

    assertThat(bson).isEqualTo(expectedBSON);
}
 
Example 14
@Override
public Publisher<ObjectId> uploadFromStream(final String filename,
                                            final com.mongodb.reactivestreams.client.gridfs.AsyncInputStream source,
                                            final GridFSUploadOptions options) {
    return new ObservableToPublisher<ObjectId>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<ObjectId>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<ObjectId> callback) {
                    wrapped.uploadFromStream(filename, toCallbackAsyncInputStream(source), options, callback);
                }
            }));
}
 
Example 15
Source Project: n2o-framework   Source File: MongoDbDataProviderEngine.java    License: Apache License 2.0 5 votes vote down vote up
private Object deleteMany(Map<String, Object> inParams, MongoCollection<Document> collection) {
    if (!inParams.containsKey("ids"))
        throw new N2oException("Ids is required for operation \"deleteMany\"");

    Object[] ids = ((List) inParams.get("ids")).stream().map(id -> new ObjectId((String) id)).toArray();
    collection.deleteMany(in("_id", ids));
    return null;
}
 
Example 16
Source Project: repositoryminer   Source File: Commit.java    License: Apache License 2.0 5 votes vote down vote up
public Commit(ObjectId id, String hash, Developer author, Developer committer, String message, List<Change> changes,
		List<String> parents, Date authorDate, Date committerDate, boolean merge, ObjectId repository) {
	super();
	this.id = id;
	this.hash = hash;
	this.author = author;
	this.committer = committer;
	this.message = message;
	this.changes = changes;
	this.parents = parents;
	this.authorDate = authorDate;
	this.committerDate = committerDate;
	this.merge = merge;
	this.repository = repository;
}
 
Example 17
Source Project: biliob_backend   Source File: AuthorGroupServiceImpl.java    License: MIT License 5 votes vote down vote up
private void setIsStared(ObjectId userId, AuthorGroup authorGroup) {
    authorGroup.setStared(false);
    for (UserStarAuthorGroup u : authorGroup.getStarList()) {
        if (u.getUserId().equals(userId)) {
            authorGroup.setStared(true);
            break;
        }
    }
}
 
Example 18
Source Project: sample-acmegifts   Source File: User.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Constructor for reading a user from the database */
public User(DBObject user) {
  this.id = ((ObjectId) user.get(DB_ID)).toString();
  this.firstName = (String) user.get(JSON_KEY_USER_FIRST_NAME);
  this.lastName = (String) user.get(JSON_KEY_USER_LAST_NAME);
  this.userName = (String) user.get(JSON_KEY_USER_NAME);
  this.twitterHandle = (String) user.get(JSON_KEY_USER_TWITTER_HANDLE);
  this.wishListLink = (String) user.get(JSON_KEY_USER_WISH_LIST_LINK);
  this.passwordHash = (String) user.get(JSON_KEY_USER_PASSWORD_HASH);
  this.passwordSalt = (String) user.get(JSON_KEY_USER_PASSWORD_SALT);
  this.isTwitterLogin = (Boolean) user.get(JSON_KEY_USER_TWITTER_LOGIN);
}
 
Example 19
Source Project: xian   Source File: HexStringDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ObjectId deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    //这里parser.getInput()获取到的是整个json字符串
    //parser.getLexer().stringVal()获取到的是指定字段的字符串值
    String hexString = parser.getLexer().stringVal();
    return new ObjectId(hexString);
}
 
Example 20
Source Project: hygieia-core   Source File: SyncDashboard.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sync code quality with dashboards
 *
 * @param codeQuality
 */
public void sync(CodeQuality codeQuality) {
    ObjectId buildId = codeQuality.getBuildId();
    if (buildId == null) return;
    Build build = buildRepository.findOne(buildId);
    if (build == null) return;
    relatedCollectorItemRepository.saveRelatedItems(build.getCollectorItemId(), codeQuality.getCollectorItemId(), this.getClass().toString(), Reason.CODEQUALITY_TRIGGERED_REASON.getAction());
}
 
Example 21
Source Project: morphia   Source File: TestMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void serializableId() {
    final CustomId cId = new CustomId();
    cId.id = new ObjectId();
    cId.type = "banker";
    final UsesCustomIdObject object = new UsesCustomIdObject();
    object.id = cId;
    object.text = "hllo";
    getDs().save(object);
}
 
Example 22
Source Project: morphia   Source File: TestLegacyQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexIdQueryWithRenamedField() {
    final CustomId cId = new CustomId();
    cId.setId(new ObjectId());
    cId.setType("banker");

    final UsesCustomIdObject object = new UsesCustomIdObject();
    object.setId(cId);
    object.setText("hllo");
    getDs().save(object);

    assertNotNull(getDs().find(UsesCustomIdObject.class).filter("_id.t", "banker")
                         .execute(new FindOptions().limit(1))
                         .tryNext());
}
 
Example 23
Source Project: ExecDashboard   Source File: DigitalCockpitServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<DigitalCockpitResponse> getFilteredCodeCommitMetricDetails() {
	List<DigitalCockpitResponse> ccRespList = new ArrayList<>();
	try {
		List<MetricsDetail> metricPortfolioDetailResponse = digitalCockpitRepository
				.findByLevelAndType(MetricLevel.PORTFOLIO, MetricType.STASH);
		for (MetricsDetail detailResponse : metricPortfolioDetailResponse) {
			if (detailResponse != null) {
				String eid = detailResponse.getMetricLevelId();
				ObjectId executiveId = new ObjectId();
				PortfolioResponse portfolioResponse = portfolioResponseRepository.findByEid(eid);
				if (portfolioResponse != null)
					executiveId = portfolioResponse.getId();
				List<MetricCount> countsList = (detailResponse != null
						&& detailResponse.getSummary() != null && detailResponse.getSummary().getCounts() != null)
								? detailResponse.getSummary().getCounts() : new ArrayList<>();
				for (MetricCount cnt : countsList) {
					if (cnt.getLabel() != null && cnt.getLabel().get("type") != null
							&& ("uniqueContributors").equals(cnt.getLabel().get("type"))) {
						DigitalCockpitResponse ccRespValue = new DigitalCockpitResponse();
						ccRespValue.setId(executiveId);
						ccRespValue.setValue(cnt.getValue());
						ccRespValue.setEid(eid);
						ccRespList.add(ccRespValue);
					}
				}
			}
		}
	} catch (Exception e) {
		LOG.info("Exception occured : " + e);
	}
	return ccRespList;
}
 
Example 24
Source Project: mirrorgate   Source File: ReviewControllerTests.java    License: Apache License 2.0 5 votes vote down vote up
private Review createReview() {
    final Review review = new Review();
    review.setId(ObjectId.get());
    review.setAppname("MirrorGateApp");
    review.setAuthorName("Author");
    review.setComment("Good App!");
    review.setPlatform(Platform.Android);
    review.setStarrating(4.0);

    return review;
}
 
Example 25
Source Project: nifi   Source File: PutGridFS.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile input = session.get();
    if (input == null) {
        return;
    }

    GridFSBucket bucket = getBucket(input, context);

    if (!canUploadFile(context, input, bucket.getBucketName())) {
        getLogger().error("Cannot upload the file because of the uniqueness policy configured.");
        session.transfer(input, REL_DUPLICATE);
        return;
    }

    final int chunkSize = context.getProperty(CHUNK_SIZE).evaluateAttributeExpressions(input).asDataSize(DataUnit.B).intValue();

    try (InputStream fileInput = session.read(input)) {
        String fileName = context.getProperty(FILE_NAME).evaluateAttributeExpressions(input).getValue();
        GridFSUploadOptions options = new GridFSUploadOptions()
            .chunkSizeBytes(chunkSize)
            .metadata(getMetadata(input, context));
        ObjectId id = bucket.uploadFromStream(fileName, fileInput, options);
        fileInput.close();

        if (id != null) {
            input = session.putAttribute(input, ID_ATTRIBUTE, id.toString());
            session.transfer(input, REL_SUCCESS);
            session.getProvenanceReporter().send(input, getTransitUri(id, input, context));
        } else {
            getLogger().error("ID was null, assuming failure.");
            session.transfer(input, REL_FAILURE);
        }
    } catch (Exception ex) {
        getLogger().error("Failed to upload file", ex);
        session.transfer(input, REL_FAILURE);
    }
}
 
Example 26
Source Project: uncode-dal-all   Source File: MongoDAL.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public int _insert(Table table) {
	try {
		DB db = database.getDB();
		Jongo jongo = new Jongo(db);
		ObjectId newOid = ObjectId.get();
		table.getParams().put("_id", newOid);
		jongo.getCollection(table.getTableName()).save(table.getParams());
		table.getParams().put("id", newOid.toString());
	} catch (MongoException e) {
		LOG.error("mongo insert error", e);
	}
	return 1;
}
 
Example 27
@Override
public Publisher<Success> delete(final ClientSession clientSession, final ObjectId id) {
    return new ObservableToPublisher<Success>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<Success>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<Success> callback) {
                    wrapped.delete(clientSession.getWrapped(), id, voidToSuccessCallback(callback));
                }
            }));
}
 
Example 28
Source Project: morphia   Source File: TestMapping.java    License: Apache License 2.0 5 votes vote down vote up
@Constructor
public ConstructorBased(@Name("id") final ObjectId id,
                        @Name("name") final String name,
                        @Name("reference") final MorphiaReference<ContainsFinalField> reference) {
    this.id = id;
    this.name = name;
    this.reference = reference;
}
 
Example 29
@Override
public Publisher<Long> downloadToStream(final ObjectId id,
                                        final com.mongodb.reactivestreams.client.gridfs.AsyncOutputStream destination) {
    return new ObservableToPublisher<Long>(com.mongodb.async.client.Observables.observe(
            new Block<com.mongodb.async.SingleResultCallback<Long>>() {
                @Override
                public void apply(final com.mongodb.async.SingleResultCallback<Long> callback) {
                    wrapped.downloadToStream(id, toCallbackAsyncOutputStream(destination), callback);
                }
            }));
}
 
Example 30
Source Project: morphia   Source File: ReferenceTest.java    License: Apache License 2.0 4 votes vote down vote up
ObjectId getId() {
    return id;
}