Java Code Examples for org.bson.Document#putAll()

The following examples show how to use org.bson.Document#putAll() . 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: MongoDocumentStorage.java    From lumongo with Apache License 2.0 6 votes vote down vote up
@Override
public void storeSourceDocument(String uniqueId, long timeStamp, Document document, List<Metadata> metaDataList) throws Exception {
	MongoDatabase db = mongoClient.getDatabase(database);
	MongoCollection<Document> coll = db.getCollection(rawCollectionName);
	Document mongoDocument = new Document();
	mongoDocument.putAll(document);

	if (!metaDataList.isEmpty()) {
		Document metadataMongoDoc = new Document();
		for (Metadata meta : metaDataList) {
			metadataMongoDoc.put(meta.getKey(), meta.getValue());
		}
		mongoDocument.put(METADATA, metadataMongoDoc);
	}

	mongoDocument.put(TIMESTAMP, timeStamp);
	mongoDocument.put(MongoConstants.StandardFields._ID, uniqueId);

	Document query = new Document(MongoConstants.StandardFields._ID, uniqueId);

	coll.replaceOne(query, mongoDocument, new UpdateOptions().upsert(true));
}
 
Example 2
Source File: Support.java    From immutables with Apache License 2.0 6 votes vote down vote up
private Document mergeConjunctions(List<Document> conjunctions) {
  final Multimap<String, Document> merged = LinkedHashMultimap.create();

  for (Document doc : conjunctions) {
    Preconditions.checkState(doc.keySet().size() == 1, "Invalid constraint %s", doc);
    final String key = doc.keySet().iterator().next();
    merged.put(key, doc);
  }

  final Document result = new Document();

  for (Map.Entry<String, Collection<Document>> entry : merged.asMap().entrySet()) {
    Preconditions.checkState(!entry.getValue().isEmpty(), "empty constraint: %s", entry);

    if (entry.getValue().size() == 1) {
      result.putAll(entry.getValue().iterator().next());
    } else {
      result.putAll(new Document(QueryOperators.AND, entry.getValue()));
    }
  }

  return result;
}
 
Example 3
Source File: Operations.java    From morphia with Apache License 2.0 6 votes vote down vote up
/**
 * @return the Document form of this instance
 * @morphia.internal
 */
Document toDocument() {
    versionUpdate();

    Document document = new Document();
    for (final Entry<String, List<OperationTarget>> entry : ops.entrySet()) {
        Document targets = new Document();
        for (OperationTarget operationTarget : entry.getValue()) {
            Object encode = operationTarget.encode(mapper);
            if (encode instanceof Document) {
                targets.putAll((Document) encode);
            } else {
                document.put(entry.getKey(), encode);
            }
        }
        if (!targets.isEmpty()) {
            document.put(entry.getKey(), targets);
        }
    }
    return document;
}
 
Example 4
Source File: AggregationPipelineImpl.java    From morphia with Apache License 2.0 6 votes vote down vote up
private Document toDocument(final Group group) {
    Document document = new Document();

    if (group.getAccumulator() != null) {
        document.put(group.getName(), group.getAccumulator().toDocument());
    } else if (group.getProjections() != null) {
        final Document projection = new Document();
        for (Projection p : group.getProjections()) {
            projection.putAll(toDocument(p));
        }
        document.put(group.getName(), projection);
    } else if (group.getNested() != null) {
        document.put(group.getName(), toDocument(group.getNested()));
    } else {
        document.put(group.getName(), group.getSourceField());
    }

    return document;
}
 
Example 5
Source File: IndexHelper.java    From morphia with Apache License 2.0 6 votes vote down vote up
Document calculateKeys(final MappedClass mc, final Index index) {
    Document keys = new Document();
    for (Field field : index.fields()) {
        String path;
        try {
            path = findField(mc, index.options(), field.value());
        } catch (Exception e) {
            path = field.value();
            if (!index.options().disableValidation()) {
                throw new MappingException(Sofia.invalidIndexPath(path, mc.getType().getName()));
            }
            LOG.warn(Sofia.invalidIndexPath(path, mc.getType().getName()));
        }
        keys.putAll(new Document(path, field.type().toIndexValue()));
    }
    return keys;
}
 
Example 6
Source File: QueryUtils.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Given a set of Constraints and the projection Schema, create the Query Document that can be used to
 * push predicates into DocumentDB.
 *
 * @param schema The schema containing the requested projection.
 * @param constraintSummary The set of constraints to apply to the query.
 * @return The Document to use as the query.
 */
public static Document makeQuery(Schema schema, Map<String, ValueSet> constraintSummary)
{
    Document query = new Document();
    for (Map.Entry<String, ValueSet> entry : constraintSummary.entrySet()) {
        Document doc = makePredicate(schema.findField(entry.getKey()), entry.getValue());
        if (doc != null) {
            query.putAll(doc);
        }
    }

    return query;
}
 
Example 7
Source File: MongoResultsWriter.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void doWrite(Collection<RunResult> results) throws ParseException {

		Date now = new Date();
		StandardEnvironment env = new StandardEnvironment();

		String projectVersion = env.getProperty("project.version", "unknown");
		String gitBranch = env.getProperty("git.branch", "unknown");
		String gitDirty = env.getProperty("git.dirty", "no");
		String gitCommitId = env.getProperty("git.commit.id", "unknown");

		ConnectionString uri = new ConnectionString(this.uri);
		MongoClient client = MongoClients.create();

		String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase() : "spring-data-mongodb-benchmarks";
		MongoDatabase db = client.getDatabase(dbName);

		String resultsJson = ResultsWriter.jsonifyResults(results).trim();
		JSONArray array = (JSONArray) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(resultsJson);
		for (Object object : array) {
			JSONObject dbo = (JSONObject) object;

			String collectionName = extractClass(dbo.get("benchmark").toString());

			Document sink = new Document();
			sink.append("_version", projectVersion);
			sink.append("_branch", gitBranch);
			sink.append("_commit", gitCommitId);
			sink.append("_dirty", gitDirty);
			sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString()));
			sink.append("_date", now);
			sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot"));

			sink.putAll(dbo);

			db.getCollection(collectionName).insertOne(fixDocumentKeys(sink));
		}

		client.close();
	}
 
Example 8
Source File: RepositoryMinerCPD.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public void run(String snapshot, CPDConfig config) {
	scm.checkout(snapshot);
	Commit commit = scm.resolve(snapshot);

	CPDDAO dao = new CPDDAO();
	dao.deleteByCommit(commit.getHash());

	CPDExecutor cpdExecutor = new CPDExecutor(tmpRepository);
	cpdExecutor.setCharset("UTF-8");

	if (config == null) {
		config = new CPDConfig();
	}

	cpdExecutor.setLanguages(config.getLanguages());
	cpdExecutor.setMinTokens(config.getTokensThreshold());

	List<Match> matches;
	try {
		matches = cpdExecutor.execute();
	} catch (IOException e) {
		throw new RepositoryMinerException("Can not execute PMD/CPD.", e); 
	}

	List<Document> documents = new ArrayList<Document>(matches.size());
	for (Match match : matches) {
		Document doc = new Document();
		doc.append("reference", snapshot).
			append("commit", commit.getHash()).
			append("commit_date", commit.getCommitterDate()).
			append("repository", repositoryId).
			append("tokens_threshold", config.getTokensThreshold());

		doc.putAll(match.toDocument());
		documents.add(doc);
	}

	dao.insertMany(documents);
}
 
Example 9
Source File: RepositoryMinerTechnicalDebt.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public void mine(RMTDConfig config) {
	if (config == null || !config.isValid()) {
		throw new RepositoryMinerException("Invalid configuration, select at least one indicator and a reference.");
	}
	
	ISCM scm = SCMFactory.getSCM(repository.getScm());
	scm.open(repository.getPath());
	Commit commit = scm.resolve(config.getReference());
	scm.close();
	
       checkDuplicatedAnalysis(commit.getHash());
       
       ObjectId reportId = persistAnalysisReport(config.getReference(), commit, config.getIndicators());
       
       Collection<TDItem> items = new TDFinder().find(commit.getHash(), config.getIndicators());
       List<Document> documents = new ArrayList<>(items.size());

       for (TDItem item : items) {
           if (item.isDebt()) {
               Document doc = new Document("analysis_report", reportId);
               doc.append("reference", config.getReference()).
                   append("commit", commit.getHash()).
                   append("commit_date", commit.getCommitterDate()).
                   append("repository", repository.getId()).
                   append("checked", false).
                   append("intentional", 0);
               
               doc.putAll(item.toDocument());
               documents.add(doc);
           }
       }

       new TechnicalDebtDAO().insertMany(documents);
}
 
Example 10
Source File: WriteState.java    From morphia with Apache License 2.0 5 votes vote down vote up
public DocumentState applyValue(final String name, final Object value) {
    if (value instanceof Document && document.get(name) instanceof Document) {
        Document extant = (Document) document.get(name);
        extant.putAll((Document) value);
    } else {
        document.put(name, value);
    }
    getWriter().state(this);
    return this;
}
 
Example 11
Source File: LegacyQuery.java    From morphia with Apache License 2.0 5 votes vote down vote up
private Document getQueryDocument() {
    final Document obj = new Document();

    if (baseQuery != null) {
        obj.putAll(baseQuery);
    }

    obj.putAll(compoundContainer.toDocument());

    return obj;
}
 
Example 12
Source File: AggregationPipelineImpl.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public AggregationPipeline project(final Projection... projections) {
    firstStage = stages.isEmpty();
    Document document = new Document();
    for (Projection projection : projections) {
        document.putAll(toDocument(projection));
    }
    stages.add(new Document("$project", document));
    return this;
}
 
Example 13
Source File: TestDatastore.java    From morphia with Apache License 2.0 5 votes vote down vote up
@PreLoad
Document preLoadWithParamAndReturn(final Document document) {
    final Document retObj = new Document();
    retObj.putAll(document);
    retObj.put("preLoadWithParamAndReturn", true);
    return retObj;
}
 
Example 14
Source File: MongoDBService.java    From nuls-v2 with MIT License 4 votes vote down vote up
public void insertOne(String collName, Map<String, Object> map) {
    Document doc = new Document();
    doc.putAll(map);
    this.insertOne(collName, doc);
}
 
Example 15
Source File: AggregationPipelineImpl.java    From morphia with Apache License 2.0 4 votes vote down vote up
/**
 * Converts a Projection to a Document for use by the Java driver.
 *
 * @param projection the project to apply
 * @return the Document
 */
private Document toDocument(final Projection projection) {
    String target;
    if (firstStage) {
        MappedField field = mapper.getMappedClass(source).getMappedField(projection.getTarget());
        target = field != null ? field.getMappedFieldName() : projection.getTarget();
    } else {
        target = projection.getTarget();
    }

    if (projection.getProjections() != null) {
        List<Projection> list = projection.getProjections();
        Document projections = new Document();
        for (Projection subProjection : list) {
            projections.putAll(toDocument(subProjection));
        }
        return new Document(target, projections);
    } else if (projection.getSource() != null) {
        return new Document(target, projection.getSource());
    } else if (projection.getArguments() != null) {
        List<Object> args = toExpressionArgs(projection.getArguments());
        if (target == null) {
            // Unwrap for single-argument expressions
            if (args.size() == 1) {
                Object firstArg = ((List<?>) args).get(0);
                if (firstArg instanceof Document) {
                    return (Document) firstArg;
                }
            }
            throw new UnsupportedOperationException("aggregation support pending");
            //                return args;
        } else {
            // Unwrap for single-argument expressions
            if (args.size() == 1) {
                return new Document(target, ((List<?>) args).get(0));
            }
            return new Document(target, args);
        }
    } else {
        return new Document(target, projection.isSuppressed() ? 0 : 1);
    }
}