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

The following examples show how to use org.bson.Document#getObjectId() . 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: TodoItem.java    From stitch-examples with Apache License 2.0 5 votes vote down vote up
public TodoItem(final Document document) {
    _id = document.getObjectId("_id");
    _text = document.getString("text");
    if (document.containsKey("checked")) {
        _checked = document.getBoolean("checked");
    } else {
        _checked = false;
    }
}
 
Example 2
Source File: TodoItem.java    From stitch-examples with Apache License 2.0 5 votes vote down vote up
public TodoItem(final Document document) {
    _id = document.getObjectId("_id");
    _text = document.getString("text");
    if (document.containsKey("checked")) {
        _checked = document.getBoolean("checked");
    } else {
        _checked = false;
    }
}
 
Example 3
Source File: TodoItem.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Constructs a todo item from a MongoDB document. */
TodoItem(final Document todoItemDoc) {
  this.id = todoItemDoc.getObjectId(ID_KEY);
  this.task = todoItemDoc.getString(TASK_KEY);
  this.checked = todoItemDoc.getBoolean(CHECKED_KEY);
  if (todoItemDoc.containsKey(DONE_DATE_KEY)) {
    this.doneDate = todoItemDoc.getDate(DONE_DATE_KEY);
  }
}
 
Example 4
Source File: Settlement.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
public Settlement(Document document) {

        world = GameServer.INSTANCE.getGameUniverse().getWorld(document.getString("world"), false);
        ObjectId radioTowerId = document.getObjectId("radio_tower");
        if (radioTowerId != null) {
            radioTower = (RadioTower) GameServer.INSTANCE.getGameUniverse().getObject(radioTowerId);
        }
        ObjectId vaultDoorId = document.getObjectId("vault_door");
        if (vaultDoorId != null) {
            vaultDoor = (VaultDoor) GameServer.INSTANCE.getGameUniverse().getObject(vaultDoorId);
        }
        ObjectId factoryId = document.getObjectId("factory");
        factory = (Factory) GameServer.INSTANCE.getGameUniverse().getObject(factoryId);

        difficultyLevel = DifficultyLevel.values()[document.getInteger("difficulty_level")];

        Object[] npcArray = ((ArrayList) document.get("npcs")).toArray();
        for (Object id : npcArray) {

            NonPlayerCharacter npc = (NonPlayerCharacter) GameServer.INSTANCE.getGameUniverse().getObject((ObjectId) id);

            if (npc != null) {
                addNpc(npc);
            }
        }

        password = document.getString("password").toCharArray();
    }
 
Example 5
Source File: RemoveDuplicatedBuildsId.java    From repairnator with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Set<Integer> buildIds = new HashSet<>();

    String dbCollectionUrl = args[0];
    String dbName = args[1];
    String collectionName = args[2];

    MongoConnection mongoConnection = new MongoConnection(dbCollectionUrl, dbName);
    MongoDatabase database = mongoConnection.getMongoDatabase();
    MongoCollection collection = database.getCollection(collectionName);


    Block<Document> block = new Block<Document>(){

        @Override
        public void apply(Document document) {
            int buildId = document.getInteger("buildId");
            ObjectId id = document.getObjectId("_id");

            if (buildIds.contains(buildId)) {
                collection.deleteOne(eq("_id", id));
                counterDeleted++;
                return;
            } else {
                buildIds.add(buildId);
                counterKept++;
            }
        }
    };
    collection.find().sort(orderBy(descending("buildReproductionDate"))).forEach(
            block
    );

    System.out.println(counterDeleted+" entries deleted and "+counterKept+" kept.");
}
 
Example 6
Source File: OldMongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Find documents of which type of _id is object ID, and change it to note ID.
 * Since updating _id field is not allowed, remove original documents and insert
 * new ones with string _id(note ID)
 */
private void syncId() {
  // find documents whose id type is object id
  MongoCursor<Document> cursor =  coll.find(type("_id", BsonType.OBJECT_ID)).iterator();
  // if there is no such document, exit
  if (!cursor.hasNext())
    return;

  List<ObjectId> oldDocIds = new LinkedList<>();    // document ids need to update
  List<Document> updatedDocs = new LinkedList<>();  // new documents to be inserted

  while (cursor.hasNext()) {
    Document doc = cursor.next();
    // store original _id
    ObjectId oldId = doc.getObjectId("_id");
    oldDocIds.add(oldId);
    // store the document with string _id (note id)
    String noteId = doc.getString("id");
    doc.put("_id", noteId);
    updatedDocs.add(doc);
  }

  coll.insertMany(updatedDocs);
  coll.deleteMany(in("_id", oldDocIds));

  cursor.close();
}
 
Example 7
Source File: MatchDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public MatchTrial insertMatchTrial(final MatchTrial matchTrial)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("matchTrial", matchTrial);

    final MongoCollection<Document> collection = getMatchTrialCollection();
    final MatchTrial copyWithNullId = matchTrial.getCopyWithId(null);
    final Document matchTrialDocument = Document.parse(copyWithNullId.toJson());

    collection.insertOne(matchTrialDocument);

    final ObjectId id = matchTrialDocument.getObjectId("_id");
    return matchTrial.getCopyWithId(String.valueOf(id));
}
 
Example 8
Source File: Reference.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a document to a reference.
 * 
 * @param document
 * 
 * @return a reference.
 */
@SuppressWarnings("unchecked")
public static Reference parseDocument(Document document) {
	Reference r = new Reference(document.getObjectId("_id"),
			document.getObjectId("repository"),
			document.getString("name"),
			document.getString("path"),
			ReferenceType.valueOf(document.getString("type")),
			document.getDate("last_commit_date"),
			document.get("commits", List.class));

	return r;
}
 
Example 9
Source File: Repository.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a document to a repository.
 * 
 * @param doc
 * 
 * @return a repository.
 */
@SuppressWarnings("unchecked")
public static Repository parseDocument(Document doc) {
	if (doc == null) {
		return null;
	}

	return new Repository(doc.getObjectId("_id"), doc.getString("key"), doc.getString("name"),
			doc.getString("path"), SCMType.parse(doc.getString("scm")), doc.getString("description"),
			Developer.parseDocuments(doc.get("contributors", List.class)));
}
 
Example 10
Source File: Commit.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a document to a commit.
 * 
 * @param document
 * 
 * @return a commit.
 */
@SuppressWarnings("unchecked")
public static Commit parseDocument(Document document) {
	Commit commit = new Commit(document.getObjectId("_id"), document.getString("hash"),
			Developer.parseDocument(document.get("author", Document.class)),
			Developer.parseDocument(document.get("committer", Document.class)), document.getString("message"),
			Change.parseDocuments(document.get("changes", List.class)), document.get("parents", List.class),
			document.getDate("author_date"), document.getDate("committer_date"),
			document.getBoolean("merge", false), document.getObjectId("repository"));
	return commit;
}
 
Example 11
Source File: RepositoryMinerMetrics.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
private ObjectId persistAnalysisReport(String reference, List<Parser> usedParsers,
		Collection<CodeMetric> calculatedMetrics, Collection<CodeSmell> detectedCodeSmells, Commit commit) {
	CodeAnalysisReportDAO configDao = new CodeAnalysisReportDAO();

	List<String> metricsNames = new ArrayList<>();
	for (CodeMetric cm : calculatedMetrics) {
		metricsNames.add(cm.getId().name());
	}

	List<String> parsersNames = new ArrayList<>();
	for (Parser p : usedParsers) {
		parsersNames.add(p.getId().name());
	}

	List<Document> codeSmellsDoc = new ArrayList<>();
	for (CodeSmell codeSmell : detectedCodeSmells) {
		codeSmellsDoc.add(new Document("codesmell", codeSmell.getId().name()).append("thresholds",
				codeSmell.getThresholds()));
	}

	Document doc = new Document();
	doc.append("reference", reference).
		append("commit", commit.getHash()).
		append("commit_date", commit.getCommitterDate()).
		append("analysis_date", new Date(System.currentTimeMillis())).
		append("repository", repositoryId).
		append("parsers", parsersNames).
		append("metrics", metricsNames).
		append("codesmells", codeSmellsDoc);

	configDao.insert(doc);

	return doc.getObjectId("_id");
}
 
Example 12
Source File: CustomType.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public CustomType decode(final BsonReader reader, final DecoderContext decoderContext) {
  final Document document = (new DocumentCodec()).decode(reader, decoderContext);
  return new CustomType(document.getObjectId("_id"), document.getInteger("intValue"));
}
 
Example 13
Source File: GameObject.java    From Much-Assembly-Required with GNU General Public License v3.0 4 votes vote down vote up
public GameObject(Document document) {
    objectId = document.getObjectId("id");
    x = document.getInteger("x");
    y = document.getInteger("y");
}
 
Example 14
Source File: UpdateDataForSpecifyingLastReproduction.java    From repairnator with MIT License 4 votes vote down vote up
public static void main(String[] args) {
    String dbConnectionUrl = args[0];
    String dbName = args[1];
    String collectionName = args[2];

    MongoConnection mongoConnection = new MongoConnection(dbConnectionUrl, dbName);
    MongoDatabase database = mongoConnection.getMongoDatabase();
    MongoCollection collection = database.getCollection(collectionName);

    Calendar limitDateMay = Calendar.getInstance();
    limitDateMay.set(2017, Calendar.MAY, 10);

    final List<ObjectId> updatedDocs = new ArrayList<>();

    Set<Integer> ids = new HashSet<>();

    Block<Document> block = new Block<Document>() {

        @Override
        public void apply(Document document) {
            ObjectId documentId = document.getObjectId("_id");

            Object pBuildId = document.get("previousBuildId");

            if (pBuildId instanceof Integer) {
                int previousBuildId = document.getInteger("previousBuildId", -1);
                if (previousBuildId != -1) {
                    boolean lastReproducedBuggyBuild = !ids.contains(previousBuildId);
                    ids.add(previousBuildId);

                    document.append("lastReproducedBuggyBuild", lastReproducedBuggyBuild);
                    collection.replaceOne(eq("_id", documentId), document, new UpdateOptions().upsert( true ));
                    updatedDocs.add(documentId);
                }
            }

        }
    };

    collection.find().sort(orderBy(descending("buildReproductionDate"))).forEach(
            block
    );

    System.out.println("Updated docs: "+updatedDocs.size());

}
 
Example 15
Source File: SnapshotAnalysisPlugin.java    From repositoryminer with Apache License 2.0 4 votes vote down vote up
/**
 * This method is responsible for preparing the repository to run the plugin,
 * and should be called only once.
 * 
 * @param repositoryKey
 *            the repository key
 * @throws IOException
 */
public void init(String repositoryKey) throws IOException {
	Document repoDoc = new RepositoryDAO().findByKey(repositoryKey, Projections.include("_id", "path", "scm"));
	if (repoDoc == null) {
		throw new RepositoryMinerException("Repository with the key " + repositoryKey + " does not exists");
	}

	scm = SCMFactory.getSCM(SCMType.valueOf(repoDoc.getString("scm")));
	repositoryId = repoDoc.getObjectId("_id");
	tmpRepository = RMFileUtils.copyFolderToTmp(repoDoc.getString("path"),
			StringUtils.encodeToSHA1(repositoryId.toHexString()));

	scm.open(tmpRepository);
}