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

The following examples show how to use org.bson.Document#get() . 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: PrimitiveArray.java    From Prism with MIT License 8 votes vote down vote up
public static PrimitiveArray of(Document document) {
    if (document.size() != 2 || !(document.containsKey("key") && document.containsKey("value"))) {
        return null;
    }

    if (!(document.get("key") instanceof String)) {
        return null;
    }

    String key = document.getString("key");
    if (!StringUtils.equalsAny(key, BYTE_ARRAY_ID, INT_ARRAY_ID, LONG_ARRAY_ID)) {
        return null;
    }

    List<Number> value = document.getList("value", Number.class);
    if (value == null) {
        return null;
    }

    return new PrimitiveArray(key, value);
}
 
Example 2
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void setResourceAttributes(Resource resource, Document doc) {

		resource.setCreationTime(doc.getString(this.CREATETIME_KEY));
		resource.setId(doc.get(this.OID_KEY).toString());
		resource.setLastModifiedTime(doc.getString(LASTMODTIME_KEY));
		resource.setParentID(doc.getString(PARENTID_KEY));
		resource.setResourceID(doc.getString(RESID_KEY));
		resource.setResourceName(doc.getString(RESNAME_KEY));
		resource.setUri(doc.getString(URI_KEY));

		List<String> labels = resource.getLabels();
		List<String> lbls = (List<String>) doc.get(LABELS_KEY);
		if (lbls != null) {
			labels.addAll((ArrayList<String>) lbls);
		}

		resource.setResourceType((int) doc.get(RESTYPE_KEY));

	}
 
Example 3
Source File: RefreshOperation.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final MongoDatabase connection, final Document data) {
    for (final String collectionName : data.keySet()) {
        final MongoCollection<Document> collection = connection.getCollection(collectionName);

        @SuppressWarnings("unchecked")
        final List<Document> documents = data.get(collectionName, List.class);

        for (final Document doc : documents) {
            final UpdateResult result = collection.replaceOne(Filters.eq(doc.get("_id")), doc);

            if (result.getMatchedCount() == 0) {
                collection.insertOne(doc);
            }
        }
    }
}
 
Example 4
Source File: Memory.java    From Much-Assembly-Required with GNU General Public License v3.0 6 votes vote down vote up
public Memory(Document document) {

        String zipBytesStr = (String) document.get("zipBytes");

        if (zipBytesStr != null) {
            byte[] compressedBytes = Base64.getDecoder().decode((String) document.get("zipBytes"));

            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Inflater decompressor = new Inflater(true);
                InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
                inflaterOutputStream.write(compressedBytes);
                inflaterOutputStream.close();

                setBytes(baos.toByteArray());

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LogManager.LOGGER.severe("Memory was manually deleted");
            words = new char[GameServer.INSTANCE.getConfig().getInt("memory_size")];
        }
    }
 
Example 5
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public int getResourceType(String key) throws OneM2MException {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		Document doc = collection.find(new BasicDBObject(OneM2mUtil.isUri(key) ? URI_KEY : RESID_KEY, key)).first();

		if (doc == null) {
			throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
					"resource not found(" + key + ")");
		}
		
		int resType = (int) doc.get(Naming.RESOURCETYPE_SN);
		if (resType == RESOURCE_TYPE.MGMT_OBJ.Value()){
			return (int) doc.get(Naming.MGMTDEFINITION_SN);
		}

		// return (int)doc.get("resourceType");
		return (int) doc.get(Naming.RESOURCETYPE_SN);

	}
 
Example 6
Source File: MongoDetailsAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
private static PCJIndexDetails.Builder getPCJIndexDetails(final Document document) {
    final Document pcjIndexDoc = document.get(PCJ_DETAILS_KEY, Document.class);

    final PCJIndexDetails.Builder pcjBuilder = PCJIndexDetails.builder();
    if (!pcjIndexDoc.getBoolean(PCJ_ENABLED_KEY)) {
        pcjBuilder.setEnabled(false);
    } else {
        pcjBuilder.setEnabled(true);//no fluo details to set since mongo has no fluo support
        final List<Document> pcjs = pcjIndexDoc.getList(PCJ_PCJS_KEY, Document.class);
        if (pcjs != null) {
            for (final Document pcj : pcjs) {
                pcjBuilder.addPCJDetails(toPCJDetails(pcj));
            }
        }
    }
    return pcjBuilder;
}
 
Example 7
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public int getResourceType(String key) throws OneM2MException {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		Document doc = collection.find(new BasicDBObject(OneM2mUtil.isUri(key) ? URI_KEY : RESID_KEY, key)).first();

		if (doc == null) {
			throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
					"resource not found(" + key + ")");
		}
		
		int resType = (int) doc.get(Naming.RESOURCETYPE_SN);
		if (resType == RESOURCE_TYPE.MGMT_OBJ.Value()){
			return (int) doc.get(Naming.MGMTDEFINITION_SN);
		}

		// return (int)doc.get("resourceType");
		return (int) doc.get(Naming.RESOURCETYPE_SN);

	}
 
Example 8
Source File: HackedNPC.java    From Much-Assembly-Required with GNU General Public License v3.0 6 votes vote down vote up
public HackedNPC(Document document) {
    super(document);

    setHp(document.getInteger("hp"));
    setDirection(Direction.getDirection(document.getInteger("direction")));

    cpu = new CPU();
    cpu.setHardwareHost(this);
    cpu.setMemory(new Memory((Document) document.get("memory")));
    cpu.setRegisterSet(RegisterSet.deserialize((Document) document.get("registerSet")));

    ArrayList hardwareList = (ArrayList) document.get("hardware");

    for (Object serialisedHw : hardwareList) {
        HardwareModule hardware = GameServer.INSTANCE.getRegistry().deserializeHardware((Document) serialisedHw, this);
        hardware.setCpu(cpu);
        attachHardware(hardware, ((Document) serialisedHw).getInteger("address"));
    }

    setTask(new ExecuteCpuTask());
}
 
Example 9
Source File: DatastoreImpl.java    From morphia with Apache License 2.0 6 votes vote down vote up
/**
 * @return the logged query
 * @morphia.internal
 */
@Override
public String getLoggedQuery(final FindOptions options) {
    if (options != null && options.isLogQuery()) {
        String json = "{}";
        Document first = getDatabase()
                             .getCollection("system.profile")
                             .find(new Document("command.comment", "logged query: " + options.getQueryLogId()),
                                 Document.class)
                             .projection(new Document("command.filter", 1))
                             .first();
        if (first != null) {
            Document command = (Document) first.get("command");
            Document filter = (Document) command.get("filter");
            if (filter != null) {
                json = filter.toJson(mapper.getCodecRegistry().get(Document.class));
            }
        }
        return json;
    } else {
        throw new IllegalStateException(Sofia.queryNotLogged());
    }
}
 
Example 10
Source File: CmdDatabaseStats.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public TableDto runCommand(ProfilingReader profilingReader, MongoDbAccessor mongoDbAccessor) {
    final TableDto table = new TableDto();

    try{
        final Document commandResultDoc = mongoDbAccessor.runCommand("admin", new BasicDBObject("hostInfo", 1));
        final Object system = commandResultDoc.get("system");
        String hostname = "";
        if (system instanceof Document) {
            final Document systemDoc = (Document) system;
            hostname = systemDoc.getString("hostname");
        }


        final MongoDatabase db = mongoDbAccessor.getMongoDatabase(profilingReader.getDatabase());
        final Document dbStats = db.runCommand(new Document("dbStats", 1));
        final List<Object> row = Lists.newArrayList();
        row.add(profilingReader.getProfiledServerDto().getLabel());
        row.add(hostname);
        row.add(profilingReader.getDatabase());
        row.add(dbStats.getInteger("objects"));
        row.add(Util.getNumber(dbStats, "avgObjSize", 0));
        row.add(Util.getNumber(dbStats, "dataSize",0));
        row.add(Util.getNumber(dbStats, "storageSize",0));
        row.add(dbStats.getInteger("indexes"));
        row.add(Util.getNumber(dbStats, "indexSize",0));
        table.addRow(row);

}catch (Exception e){
    LOG.warn("Exception while running command", e);
}

    return table;
}
 
Example 11
Source File: ResultDataHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private Object getSubFieldValues( String fieldFullName, FieldMetaData fieldMD, Document documentObj )
{
    String[] fieldLevelNames = fieldMD != null ?
                fieldMD.getLevelNames() :
                MDbMetaData.splitFieldName( fieldFullName );

    if( fieldLevelNames.length == 1 )
    {
        String fieldSimpleName = fieldMD != null ? fieldMD.getSimpleName() : fieldLevelNames[0];
        return documentObj.get( fieldSimpleName );
    }

    if( fieldLevelNames.length == 2 )
        return documentObj.get( fieldLevelNames[1] );   // get the document field by its simple name

    // field has at least 3 levels or more
    for( int i=fieldLevelNames.length - 2; i >=0 ; i-- )
    {   
        // check the lowest ancestor level that is a flattenable nested collection field, i.e. 
        // the nested level of the specified documentObj
        String ancestorFullName = MDbMetaData.formatFieldLevelNames( fieldLevelNames, 0, i );
        if( isFlattenableLevelField( ancestorFullName ) )
        {   
            // strip the flattenable ancestor segments from the field full name to identify the lower field level(s);
            // get the value of the lower level field from the ancestor documentObj
            String childLevelName = MDbMetaData.formatFieldLevelNames( fieldLevelNames, i+1, fieldLevelNames.length-1 );
            return fetchFieldValues( childLevelName, documentObj );
        }
    }

    // no multi-level field from a flattenable collection
    return documentObj;     // return the document itself
}
 
Example 12
Source File: CPDChecker.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void check(String commit) {
	CPDDAO dao = new CPDDAO();
	List<Document> analysisDoc = dao.findByCommit(commit, Projections.include("filename", "occurrences.filename"));

	for (Document doc : analysisDoc) {
		for (Document occurrence : (List<Document>) doc.get("occurrences", List.class)) {
			TDItem tdItem = searchFile(occurrence.getString("filename"));
			addTDIndicator(tdItem, DUPLICATED_CODE, 1);
		}
	}
}
 
Example 13
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 14
Source File: ProfilingWriter.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 5 votes vote down vote up
public Date getNewest(MongoDbAccessor mongo, ServerAddress adr, String db) {
    try {
        final MongoCollection<Document> profileCollection = getProfileCollection(mongo);

        if(adr != null) {
            final BasicDBObject query = new BasicDBObject();
            final BasicDBObject fields = new BasicDBObject();
            final BasicDBObject sort = new BasicDBObject();
            query.put("adr", adr.getHost() + ":" + adr.getPort());
            query.put("db", db);
            fields.put("_id", Integer.valueOf(0));
            fields.put("ts", Integer.valueOf(1));
            sort.put("ts", Integer.valueOf(-1));
            
            final MongoCursor<Document> c = profileCollection.find(query).projection(fields).sort(sort).limit(1).iterator();
            try {
                if(c.hasNext()) {
                    final Document obj = c.next();
                    final Object ts = obj.get("ts");
                    if(ts != null) {
                        return (Date)ts;
                    }
                }
            }finally {
            	c.close();
            }
        }
    }catch(Exception e) {
        LOG.error("Couldn't get newest entry for {}/{}", new Object[]{adr, db, e});

    }
    return null;
    
}
 
Example 15
Source File: CmdIdxAccessStats.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 5 votes vote down vote up
private TableDto getIndexStats(MongoCollection<Document> collection, String dbsLabel){
    final TableDto result = new TableDto();
    final MongoIterable<Document> stats = collection
            .aggregate(Arrays.asList(
                    new Document("$indexStats", new Document()),
                    new Document("$sort", new Document("accesses.ops", 1))
            ));
    final HashMap<String, Document> indexesProperties = getIndexesProperties(collection);

    for(Document doc : stats){
        LOG.info("doc: {}", JSON.serialize(doc));
        final ArrayList<Object> row = new ArrayList<Object>();
        row.add(dbsLabel);
        row.add(doc.getString("host"));
        row.add(collection.getNamespace().getDatabaseName());
        row.add(collection.getNamespace().getCollectionName());
        final String indexName = doc.getString("name");
        row.add(indexName);
        row.add(((Document)doc.get("key")).toJson());
        row.add(Boolean.toString(isTTL(indexesProperties, indexName)));
        final Object accesses = doc.get("accesses");
        if(accesses instanceof Document){
            final Document accDoc = (Document) accesses;
            row.add(accDoc.getLong("ops"));
            final Date date = accDoc.getDate("since");
            final LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            row.add(localDateTime.format(DATE_TIME_FORMATTER));
        }else{
            row.add(0L);
            row.add("");
        }

        result.addRow(row);

    }

    return result;
}
 
Example 16
Source File: MongoStorage.java    From LuckPerms with MIT License 5 votes vote down vote up
private static List<Node> nodesFromDoc(Document document) {
    List<Node> nodes = new ArrayList<>();
    if (document.containsKey("permissions") && document.get("permissions") instanceof List) {
        //noinspection unchecked
        List<Document> permsList = (List<Document>) document.get("permissions");
        for (Document d : permsList) {
            nodes.add(nodeFromDoc(d));
        }
    }
    return nodes;
}
 
Example 17
Source File: GetSortBsonVisitor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Object seekToPathImpl(final Document document, final String[] segments, final int i) {
    if (document == null) {
        return null;
    } else if (i + 1 == segments.length) {
        return document.get(segments[i]);
    } else {
        return seekToPathImpl(document.get(segments[i], Document.class), segments, i + 1);
    }
}
 
Example 18
Source File: BsonUtil.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static @Nullable <T> T getDocumentValueOrNullAt(final Document document, final String key, final Class<T> clazz) {
    return document.get(key, clazz);
}
 
Example 19
Source File: ConnectionValidator.java    From mongo-kafka with Apache License 2.0 4 votes vote down vote up
/**
 * Checks the roles info document for matching actions and removes them from the provided list
 *
 * <p>See: https://docs.mongodb.com/manual/reference/command/rolesInfo See:
 * https://docs.mongodb.com/manual/reference/resource-document/
 */
private static List<String> removeUserActions(
    final Document rolesInfo,
    final String authDatabase,
    final String databaseName,
    final String collectionName,
    final List<String> userActions) {
  List<Document> privileges =
      rolesInfo.getList("inheritedPrivileges", Document.class, emptyList());
  if (privileges.isEmpty() || userActions.isEmpty()) {
    return userActions;
  }

  List<String> unsupportedUserActions = new ArrayList<>(userActions);
  for (final Document privilege : privileges) {
    Document resource = privilege.get("resource", new Document());
    if (resource.containsKey("cluster") && resource.getBoolean("cluster")) {
      unsupportedUserActions.removeAll(privilege.getList("actions", String.class, emptyList()));
    } else if (resource.containsKey("db") && resource.containsKey("collection")) {
      String database = resource.getString("db");
      String collection = resource.getString("collection");

      boolean resourceMatches = false;
      boolean collectionMatches = collection.isEmpty() || collection.equals(collectionName);
      if (database.isEmpty() && collectionMatches) {
        resourceMatches = true;
      } else if (database.equals(authDatabase) && collection.isEmpty()) {
        resourceMatches = true;
      } else if (database.equals(databaseName) && collectionMatches) {
        resourceMatches = true;
      }

      if (resourceMatches) {
        unsupportedUserActions.removeAll(privilege.getList("actions", String.class, emptyList()));
      }
    }

    if (unsupportedUserActions.isEmpty()) {
      break;
    }
  }

  return unsupportedUserActions;
}
 
Example 20
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
private List<CompensableArchive> constructCompensableList(Document document) throws Exception {
	XidFactory transactionXidFactory = this.beanFactory.getTransactionXidFactory();
	ClassLoader cl = Thread.currentThread().getContextClassLoader();

	List<CompensableArchive> resourceList = new ArrayList<CompensableArchive>();

	Document compensables = document.get("compensables", Document.class);
	for (Iterator<String> itr = compensables.keySet().iterator(); itr.hasNext();) {
		String key = itr.next();
		Document element = compensables.get(key, Document.class);
		CompensableArchive service = new CompensableArchive();

		String gxid = element.getString(CONSTANTS_FD_GLOBAL);
		String bxid = element.getString(CONSTANTS_FD_BRANCH);

		boolean coordinatorFlag = element.getBoolean("coordinator");
		boolean tried = element.getBoolean("tried");
		boolean confirmed = element.getBoolean("confirmed");
		boolean cancelled = element.getBoolean("cancelled");
		String serviceId = element.getString("serviceId");
		boolean simplified = element.getBoolean("simplified");
		String confirmableKey = element.getString("confirmable_key");
		String cancellableKey = element.getString("cancellable_key");
		String argsValue = element.getString("args");
		String clazzName = element.getString("interface");
		String methodDesc = element.getString("method");

		String transactionKey = element.getString("transaction_key");
		String compensableKey = element.getString("compensable_key");

		String transactionXid = element.getString("transaction_xid");
		String compensableXid = element.getString("compensable_xid");

		CompensableInvocationImpl invocation = new CompensableInvocationImpl();
		invocation.setIdentifier(serviceId);
		invocation.setSimplified(simplified);

		Class<?> clazz = cl.loadClass(clazzName);
		Method method = SerializeUtils.deserializeMethod(clazz, methodDesc);
		invocation.setMethod(method);

		byte[] argsByteArray = ByteUtils.stringToByteArray(argsValue);
		Object[] args = (Object[]) SerializeUtils.deserializeObject(argsByteArray);
		invocation.setArgs(args);

		invocation.setConfirmableKey(confirmableKey);
		invocation.setCancellableKey(cancellableKey);

		service.setCompensable(invocation);

		service.setConfirmed(confirmed);
		service.setCancelled(cancelled);
		service.setTried(tried);
		service.setCoordinator(coordinatorFlag);

		service.setTransactionResourceKey(transactionKey);
		service.setCompensableResourceKey(compensableKey);

		String[] transactionArray = transactionXid.split("\\s*\\-\\s*");
		if (transactionArray.length == 3) {
			String transactionGlobalId = transactionArray[1];
			String transactionBranchId = transactionArray[2];
			TransactionXid transactionGlobalXid = transactionXidFactory
					.createGlobalXid(ByteUtils.stringToByteArray(transactionGlobalId));
			if (StringUtils.isNotBlank(transactionBranchId)) {
				TransactionXid transactionBranchXid = transactionXidFactory.createBranchXid(transactionGlobalXid,
						ByteUtils.stringToByteArray(transactionBranchId));
				service.setTransactionXid(transactionBranchXid);
			} else {
				service.setTransactionXid(transactionGlobalXid);
			}
		}

		String[] compensableArray = compensableXid.split("\\s*\\-\\s*");
		if (compensableArray.length == 3) {
			String compensableGlobalId = compensableArray[1];
			String compensableBranchId = compensableArray[2];
			TransactionXid compensableGlobalXid = transactionXidFactory
					.createGlobalXid(ByteUtils.stringToByteArray(compensableGlobalId));
			if (StringUtils.isNotBlank(compensableBranchId)) {
				TransactionXid compensableBranchXid = transactionXidFactory.createBranchXid(compensableGlobalXid,
						ByteUtils.stringToByteArray(compensableBranchId));
				service.setCompensableXid(compensableBranchXid);
			} else {
				service.setCompensableXid(compensableGlobalXid);
			}
		}

		byte[] globalTransactionId = ByteUtils.stringToByteArray(gxid);
		byte[] branchQualifier = ByteUtils.stringToByteArray(bxid);
		TransactionXid globalId = transactionXidFactory.createGlobalXid(globalTransactionId);
		TransactionXid branchId = transactionXidFactory.createBranchXid(globalId, branchQualifier);
		service.setIdentifier(branchId);

		resourceList.add(service);
	}

	return resourceList;
}