org.bson.types.ObjectId Java Examples
The following examples show how to use
org.bson.types.ObjectId.
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: InternalValidator.java From scava with Eclipse Public License 2.0 | 8 votes |
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
Source File: EncryptSystemTest.java From spring-data-mongodb-encrypt with Apache License 2.0 | 6 votes |
@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 #3
Source File: MongodbInputDiscoverFieldsImpl.java From pentaho-mongodb-plugin with Apache License 2.0 | 6 votes |
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 #4
Source File: CoreUserApiKeyAuthProviderClientUnitTests.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
@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 #5
Source File: SimilarityManager.java From scava with Eclipse Public License 2.0 | 6 votes |
@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 #6
Source File: DefaultViewController.java From jakduk-api with MIT License | 6 votes |
@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 #7
Source File: QueryConverterIT.java From sql-to-mongo-db-query-converter with Apache License 2.0 | 6 votes |
@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 #8
Source File: ReviewEventHandler.java From mirrorgate with Apache License 2.0 | 6 votes |
@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 #9
Source File: TestMapping.java From morphia with Apache License 2.0 | 5 votes |
@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 #10
Source File: MongoDbDataProviderEngine.java From n2o-framework with Apache License 2.0 | 5 votes |
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 #11
Source File: TestMapper.java From morphia with Apache License 2.0 | 5 votes |
@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 #12
Source File: GridFSBucketImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@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 #13
Source File: DigitalCockpitServiceImpl.java From ExecDashboard with Apache License 2.0 | 5 votes |
@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 #14
Source File: MongoDataHandler.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * 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 #15
Source File: ReviewControllerTests.java From mirrorgate with Apache License 2.0 | 5 votes |
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 #16
Source File: TestLegacyQuery.java From morphia with Apache License 2.0 | 5 votes |
@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 #17
Source File: PutGridFS.java From nifi with Apache License 2.0 | 5 votes |
@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 #18
Source File: StackMetaDataService.java From render with GNU General Public License v2.0 | 5 votes |
@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 #19
Source File: ClusterManager.java From scava with Eclipse Public License 2.0 | 5 votes |
@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 #20
Source File: EntityEncoderBuilderTest.java From core-ng-project with Apache License 2.0 | 5 votes |
@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 #21
Source File: GridFSBucketImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@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 #22
Source File: GridFSBucketImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@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 #23
Source File: MongoDAL.java From uncode-dal-all with GNU General Public License v2.0 | 5 votes |
@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 #24
Source File: Commit.java From repositoryminer with Apache License 2.0 | 5 votes |
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 #25
Source File: AuthorGroupServiceImpl.java From biliob_backend with MIT License | 5 votes |
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 #26
Source File: User.java From sample-acmegifts with Eclipse Public License 1.0 | 5 votes |
/** 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 #27
Source File: HexStringDeserializer.java From xian with Apache License 2.0 | 5 votes |
@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 #28
Source File: SyncDashboard.java From hygieia-core with Apache License 2.0 | 5 votes |
/** * 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 #29
Source File: ContentTools.java From socialite with Apache License 2.0 | 5 votes |
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 #30
Source File: Repository.java From repositoryminer with Apache License 2.0 | 4 votes |
public void setId(ObjectId id) { this.id = id; }