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

The following examples show how to use org.bson.Document#containsKey() . 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: MongoDBSource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private String parseSourceOffset(Document doc, String[] keys, int i) throws StageException {
  if (keys.length-1 == i) {
    if (configBean.offsetType == OffsetFieldType.STRING) {
      return doc.get(keys[i]).toString();
    }
    else if(configBean.offsetType == OffsetFieldType.OBJECTID) {
      return doc.getObjectId(keys[i]).toHexString();
    }
    else if(configBean.offsetType == OffsetFieldType.DATE){
      return dateFormatter.format(doc.getDate(keys[i]));
    }
    else {
      throw new StageException(Errors.MONGODB_20, configBean.offsetType);
    }
  }

  if (!doc.containsKey(keys[i])) {
    errorRecordHandler.onError(Errors.MONGODB_11, configBean.offsetField, doc.toString());
    ++errorRecordsSinceLastNMREvent;
  }

  return parseSourceOffset((Document)doc.get(keys[i]), keys, i+1);
}
 
Example 2
Source File: Mapper.java    From morphia with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a Document back to a type-safe java object (POJO)
 *
 * @param <T>      the type of the entity
 * @param type     the target type
 * @param document the Document containing the document from mongodb
 * @return the new entity
 * @morphia.internal
 */
public <T> T fromDocument(final Class<T> type, final Document document) {
    if (document == null) {
        return null;
    }

    Class<T> aClass = type;
    if (document.containsKey(options.getDiscriminatorKey())) {
        aClass = getClass(document);
    }

    CodecRegistry codecRegistry = getCodecRegistry();

    DocumentReader reader = new DocumentReader(document);

    return codecRegistry
               .get(aClass)
               .decode(reader, DecoderContext.builder().build());
}
 
Example 3
Source File: StitchError.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Private helper method which decodes the Stitch error from the body of an HTTP `Response`
 * object. If the error is successfully decoded, this function will throw the error for the end
 * user to eventually consume. If the error cannot be decoded, this is likely not an error from
 * the Stitch server, and this function will return an error message that the calling function
 * should use as the message of a StitchServiceException with an unknown code.
 */
private static String handleRichError(final Response response, final String body) {
  if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE)
      || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) {
    return body;
  }

  final Document doc;
  try {
    doc = BsonUtils.parseValue(body, Document.class);
  } catch (Exception e) {
    return body;
  }

  if (!doc.containsKey(Fields.ERROR)) {
    return body;
  }
  final String errorMsg = doc.getString(Fields.ERROR);
  if (!doc.containsKey(Fields.ERROR_CODE)) {
    return errorMsg;
  }

  final String errorCode = doc.getString(Fields.ERROR_CODE);
  throw new StitchServiceException(errorMsg, StitchServiceErrorCode.fromCodeName(errorCode));
}
 
Example 4
Source File: TestLegacyQuery.java    From morphia with Apache License 2.0 6 votes vote down vote up
private String getCommentFromProfileRecord(final Document profileRecord) {
    if (profileRecord.containsKey("command")) {
        Document commandDocument = ((Document) profileRecord.get("command"));
        if (commandDocument.containsKey("comment")) {
            return (String) commandDocument.get("comment");
        }
    }
    if (profileRecord.containsKey("query")) {
        Document queryDocument = ((Document) profileRecord.get("query"));
        if (queryDocument.containsKey("comment")) {
            return (String) queryDocument.get("comment");
        } else if (queryDocument.containsKey("$comment")) {
            return (String) queryDocument.get("$comment");
        }
    }
    return null;
}
 
Example 5
Source File: MongoWithReplicasTestBase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static boolean isReplicaSetStarted(final Document setting) {
    if (!setting.containsKey("members")) {
        return false;
    }

    @SuppressWarnings("unchecked")
    final List<Document> members = setting.get("members", List.class);
    for (final Document member : members) {
        LOGGER.infof("replica set member %s", member);
        final int state = member.getInteger("state");
        LOGGER.infof("state: %s", state);
        // 1 - PRIMARY, 2 - SECONDARY, 7 - ARBITER
        if (state != 1 && state != 2 && state != 7) {
            return false;
        }
    }
    return true;
}
 
Example 6
Source File: MongoWithReplicasTestBase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static boolean isReplicaSetStarted(final Document setting) {
    if (!setting.containsKey("members")) {
        return false;
    }

    @SuppressWarnings("unchecked")
    final List<Document> members = setting.get("members", List.class);
    for (final Document member : members) {
        LOGGER.infof("replica set member %s", member);
        final int state = member.getInteger("state");
        LOGGER.infof("state: %s", state);
        // 1 - PRIMARY, 2 - SECONDARY, 7 - ARBITER
        if (state != 1 && state != 2 && state != 7) {
            return false;
        }
    }
    return true;
}
 
Example 7
Source File: TestExpireAfterSeconds.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexedField() {
    getMapper().map(HasExpiryField.class);
    getDs().ensureIndexes();

    getDs().save(new HasExpiryField());

    final List<Document> indexes = getIndexInfo(HasExpiryField.class);

    Assert.assertNotNull(indexes);
    Assert.assertEquals(2, indexes.size());
    Document index = null;
    for (final Document candidateIndex : indexes) {
        if (candidateIndex.containsKey("expireAfterSeconds")) {
            index = candidateIndex;
        }
    }
    Assert.assertNotNull(index);
    Assert.assertEquals(5, ((Number) index.get("expireAfterSeconds")).intValue());
}
 
Example 8
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getAssociatedDocumentStream(String uniqueId, String fileName) {
	GridFSBucket gridFS = createGridFSConnection();
	GridFSFile file = gridFS.find(new Document(ASSOCIATED_METADATA + "." + FILE_UNIQUE_ID_KEY, getGridFsId(uniqueId, fileName))).first();

	if (file == null) {
		return null;
	}

	InputStream is = gridFS.openDownloadStream(file.getObjectId());
	;

	Document metadata = file.getMetadata();
	if (metadata.containsKey(COMPRESSED_FLAG)) {
		boolean compressed = (boolean) metadata.remove(COMPRESSED_FLAG);
		if (compressed) {
			is = new InflaterInputStream(is);
		}
	}

	return is;
}
 
Example 9
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 10
Source File: LocalNodeConfig.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public static LocalNodeConfig fromDocument(Document settings) {
	LocalNodeConfig localNodeConfig = new LocalNodeConfig();
	localNodeConfig.hazelcastPort = (int) settings.get(HAZELCAST_PORT);
	localNodeConfig.internalServicePort = (int) settings.get(INTERNAL_SERVICE_PORT);
	localNodeConfig.externalServicePort = (int) settings.get(EXTERNAL_SERVICE_PORT);
	if (settings.containsKey(REST_PORT)) {
		localNodeConfig.restPort = (int) settings.get(REST_PORT);
	}
	
	return localNodeConfig;
}
 
Example 11
Source File: MongoAuthenticationProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private User createUser(Document document) {
    String username = document.getString(FIELD_USERNAME);
    DefaultUser user = new DefaultUser(username);
    Map<String, Object> claims = new HashMap<>();

    String sub = document.containsKey(FIELD_ID) ?
            document.get(FIELD_ID) instanceof ObjectId ? ((ObjectId) document.get(FIELD_ID)).toString() : document.getString(FIELD_ID)
            : username;
    // set technical id
    user.setId(sub);

    // set user roles
    user.setRoles(getUserRoles(document));

    // set claims
    claims.put(StandardClaims.SUB, sub);
    claims.put(StandardClaims.PREFERRED_USERNAME, username);
    if (this.mapper.getMappers() != null && !this.mapper.getMappers().isEmpty()) {
        this.mapper.getMappers().forEach((k, v) -> claims.put(k, document.get(v)));
    } else {
        // default claims
        // remove reserved claims
        document.remove(FIELD_ID);
        document.remove(FIELD_USERNAME);
        document.remove(configuration.getPasswordField());
        document.remove(FIELD_CREATED_AT);
        if (document.containsKey(FIELD_UPDATED_AT)) {
            document.put(StandardClaims.UPDATED_AT, document.get(FIELD_UPDATED_AT));
            document.remove(FIELD_UPDATED_AT);
        }
        document.entrySet().forEach(entry -> claims.put(entry.getKey(), entry.getValue()));
    }
    user.setAdditionalInformation(claims);

    return user;
}
 
Example 12
Source File: CubotFloppyDrive.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
public CubotFloppyDrive(Document document, ControllableUnit cubot) {
    super(document, cubot);

    if (document.containsKey("floppy")) {
        floppyDisk = new FloppyDisk((Document) document.get("floppy"));
    } else {
        floppyDisk = new FloppyDisk();
    }
}
 
Example 13
Source File: MongoCollectionSave.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase db = getMongoDatabase( _session, argStruct );

	String collection = getNamedStringParam( argStruct, "collection", null );
	if ( collection == null )
		throwException( _session, "please specify a collection" );

	cfData data = getNamedParam( argStruct, "data", null );
	if ( data == null )
		throwException( _session, "please specify data to save" );

	try {
		Document doc = getDocument( data );
		MongoCollection<Document> col = db.getCollection( collection );
		long start = System.currentTimeMillis();

		if ( doc.containsKey( "_id" ) ) {
			col.updateOne( new Document( "_id", doc.get( "_id" ) ), new Document("$set",doc) );
		} else {
			col.insertOne( doc );
		}

		_session.getDebugRecorder().execMongo( col, "save", doc, System.currentTimeMillis() - start );

		return cfBooleanData.TRUE;

	} catch ( Exception me ) {
		throwException( _session, me.getMessage() );
		return null;
	}
}
 
Example 14
Source File: MongoBulkWriter.java    From MongoSyphon with Apache License 2.0 5 votes vote down vote up
public void Save(Document doc) {
	if (!doc.containsKey("_id")) {
		Create(doc);
		return;
	}
	Document find = new Document("_id", doc.get("_id"));
	UpdateOptions uo = new UpdateOptions();
	uo.upsert(true);
	ops.add(new ReplaceOneModel<Document>(find, doc, uo));
	FlushOpsIfFull();
}
 
Example 15
Source File: MongoSession.java    From presto with Apache License 2.0 5 votes vote down vote up
private List<Document> getColumnMetadata(Document doc)
{
    if (!doc.containsKey(FIELDS_KEY)) {
        return ImmutableList.of();
    }

    return (List<Document>) doc.get(FIELDS_KEY);
}
 
Example 16
Source File: DocumentTransferTool.java    From nuls-v2 with MIT License 5 votes vote down vote up
public static <T> T toInfo(Document document, Class<T> clazz) {
    if (null == document) {
        return null;
    }
    try {
        T instance = clazz.getDeclaredConstructor().newInstance();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if ("isNew".equals(field.getName())) {
                continue;
            }
            if (!document.containsKey(field.getName())) {
                continue;
            }
            if (field.getType().getName().equals("java.math.BigInteger")) {
                field.set(instance, new BigInteger(document.get(field.getName()).toString()));
            } else {
                field.set(instance, document.get(field.getName()));
            }

        }
        return instance;
    } catch (Exception e) {
        LoggerUtil.commonLog.error(e);
        throw new NulsRuntimeException(ApiErrorCode.DATA_PARSE_ERROR, "Document to Model fail");
    }
}
 
Example 17
Source File: MongoKafkaTestCase.java    From mongo-kafka with Apache License 2.0 5 votes vote down vote up
public boolean isReplicaSetOrSharded() {
  Document isMaster =
      MONGODB
          .getMongoClient()
          .getDatabase("admin")
          .runCommand(BsonDocument.parse("{isMaster: 1}"));
  return isMaster.containsKey("setName") || isMaster.get("msg", "").equals("isdbgrid");
}
 
Example 18
Source File: ConversationMemoryStore.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public ConversationState getConversationState(String conversationId) {
    Document conversationMemoryDocument = conversationCollectionDocument.find(
            new Document(OBJECT_ID, new ObjectId(conversationId))).
            projection(new Document(CONVERSATION_STATE_FIELD, 1).append(OBJECT_ID, 0)).
            first();
    if (conversationMemoryDocument != null && conversationMemoryDocument.containsKey(CONVERSATION_STATE_FIELD)) {
        return ConversationState.valueOf(conversationMemoryDocument.get(CONVERSATION_STATE_FIELD).toString());
    }

    return null;
}
 
Example 19
Source File: TestSerializedFormat.java    From morphia with Apache License 2.0 5 votes vote down vote up
private void verifyCoverage(final Document document) {
    for (MappedField field : getMapper().getMappedClass(ReferenceType.class).getFields()) {
        String name = field.getMappedFieldName();
        boolean found = document.containsKey(name);
        if (!found) {
            for (String s : document.keySet()) {
                found |= s.startsWith(name + ".");

            }
        }
        assertTrue("Not found in document: " + name, found);
    }
}
 
Example 20
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;
}