Java 类com.mongodb.MongoException 实例源码

项目:mongodb-crud    文件:QueryDocumentsImpl.java   
/**
 * This method retrieve all the document(s)
 */
@Override
public void getAllDocuments() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        FindIterable<Document> docs = collection.find(); //SELECT * FROM sample;
        for (Document doc : docs) {
            log.info(doc.getString("name"));
        }
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert Value using **BasicDBObject** : " + e, e);
    }
}
项目:mongodb-crud    文件:DeleteDocumentsImpl.java   
/**
 * This is delete the single document, which is first matched
 */
@Override
public void deleteOneDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        query = eq("name", "sundar");
        DeleteResult result = collection.deleteMany(query);
        if (result.wasAcknowledged()) {
            log.info("Single Document deleted successfully \nNo of Document Deleted : " + result.getDeletedCount());
        }
    } catch (MongoException e) {
        log.error("Exception occurred while delete Single Document : " + e, e);
    }
}
项目:mongodb-crud    文件:DeleteDocumentsImpl.java   
/**
 * This is deleted delete all document(s), which is matched
 */
@Override
public void deleteManyDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        query = lt("age", 20);
        DeleteResult result = collection.deleteMany(query);
        if (result.wasAcknowledged()) {
            log.info("Document deleted successfully \nNo of Document(s) Deleted : "
                    + result.getDeletedCount());
        }
    } catch (MongoException e) {
        log.error("Exception occurred while delete Many Document : " + e, e);
    }
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update all the matches document
 */
@Override
public void updateManyDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"));
        UpdateResult result = collection.updateMany(filter, query);
        log.info("UpdateMany Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update Many Document : " + e, e);
    }
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update document with lastmodified properties 
 */
@Override
public void updateDocumentWithCurrentDate() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"),
                currentDate("lastModified"));
        UpdateResult result = collection.updateOne(filter, query);
        log.info("Update with date Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update Many Document with Date : " + e, e);
    }
}
项目:mongodb-crud    文件:InsertDocumentsImpl.java   
/**
 * This method insert the document using Document object
 */
@Override
public void insertUsingDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        Document obj1 = new Document();
        obj1.put("name", "Sivaraman");
        obj1.put("age", 23);
        obj1.put("gender", "male");
        collection.insertOne(obj1);
        log.info("Document Insert Successfully using Document Obj...");
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert Value using **Document** : " + e, e);
    }
}
项目:mongodb-crud    文件:InsertDocumentsImpl.java   
/**
 * This method insert the document using Map
 */
@Override
public void insertUsingMap() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        final Map<String, Object> empMap = new HashMap<>();
        empMap.put("_id", new Random().nextInt(999));
        empMap.put("name", "Vel");
        empMap.put("age", 25);
        empMap.put("desicnation", "Java Developer");
        empMap.put("gender", "Male");
        empMap.put("salary", "10000");
        log.info("Employ Details : " + empMap);
        collection.insertOne(new Document(empMap));
        log.info("Document Insert Successfully using Map...");
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert Value using **UsingMap** : " + e, e);
    }
}
项目:mongodb-crud    文件:InsertDocumentsImpl.java   
/**
 * This method insert the single document
 */
@Override
public void insertSingleDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());

        Document canvas = new Document("item", "canvas").append("qty", 100)
                .append("tags", singletonList("cotton"));

        Document size = new Document("h", 28).append("w", 35.5).append(
                "uom", "cm");

        canvas.append("size", size);
        collection.insertOne(canvas);
        log.info("Single Document Insert Successfully...");
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert **Single Document** : " + e, e);
    }
}
项目:initiatives_backend_auth    文件:UserActivationService.java   
@Transactional
public Mono<Void> activate(String uuid) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication.getPrincipal() instanceof AuthenticatedUser) {
        AuthenticatedUser authenticatedUser = (AuthenticatedUser) authentication.getPrincipal();
        String errorMsg = String.format("Unable to retrieve current user : %s", authenticatedUser.getUsername());
        return userRepository.findByUsernameAndTemporaryCode(authenticatedUser.getUsername(), uuid)
                .flatMap(user -> {
                    user.setTemporaryCode(null);
                    return authorityService.findDefaultOrCreate().map(authority -> {
                        user.getAuthorities().add(authority);
                        return user;
                    });
                })
                .switchIfEmpty(Mono.error(new MongoException(errorMsg)))
                .flatMap(userRepository::save)
                .then();
    }
    return Mono.error(new IllegalStateException("Wrong principal type"));
}
项目:QDrill    文件:MongoSchemaFactory.java   
@Override
public List<String> load(String key) throws Exception {
  if (!DATABASES.equals(key)) {
    throw new UnsupportedOperationException();
  }
  try {
    List<String> dbNames = new ArrayList<>();
    client.listDatabaseNames().into(dbNames);
    return dbNames;
  } catch (MongoException me) {
    logger.warn("Failure while loading databases in Mongo. {}",
        me.getMessage());
    return Collections.emptyList();
  } catch (Exception e) {
    throw new DrillRuntimeException(e.getMessage(), e);
  }
}
项目:appng-tomcat-session    文件:MongoStore.java   
/**
 * {@inheritDoc}
 */
public void remove(String id) throws IOException {
    /* build up the query, looking for all sessions with this app context property and id */
    BasicDBObject sessionQuery = new BasicDBObject();
    sessionQuery.put(idProperty, id);
    sessionQuery.put(appContextProperty, this.getName());

    /* remove all sessions for this context and id */
    try {
        this.collection.remove(sessionQuery);
        if (isDebugEnabled()) {
            getLog().debug("removed session " + id + " (query: " + sessionQuery + ")");
        }
    } catch (MongoException e) {
        /* for some reason we couldn't remove the data */
        getLog().error("Unable to remove sessions for [" + id + ":" + this.getName() + "] from MongoDB", e);
        throw e;
    }
}
项目:appng-tomcat-session    文件:MongoStore.java   
/**
 * {@inheritDoc}
 */
public void clear() throws IOException {
    /* build up the query, looking for all sessions with this app context property */
    BasicDBObject sessionQuery = new BasicDBObject();
    sessionQuery.put(appContextProperty, this.getName());

    /* remove all sessions for this context */
    try {
        this.collection.remove(sessionQuery);
        getLog().debug("removed sessions (query: " + sessionQuery + ")");
    } catch (MongoException e) {
        /* for some reason we couldn't save the data */
        getLog().error("Unable to remove sessions for [" + this.getName() + "] from MongoDB", e);
        throw e;
    }
}
项目:mongodb-broker    文件:MongoAdminService.java   
public DB createDatabase(String databaseName) throws MongoServiceException {
        try {
            DB db = client.getDB(databaseName);

            // save into a collection to force DB creation.
            DBCollection col = db.createCollection("foo", null);
            BasicDBObject obj = new BasicDBObject();
            obj.put("foo", "bar");
            col.insert(obj);
            // drop the collection so the db is empty
//          col.drop();

            return db; 
        } catch (MongoException e) {
            // try to clean up and fail
            try {
                deleteDatabase(databaseName);
            } catch (MongoServiceException ignore) {}
            throw handleException(e);
        }
    }
项目:MCS-Master    文件:MongoDBConnectionTest.java   
public static boolean connectionTest(MongoDBConfig mongoDBConfig) {
    Logging.disableMongoDBLogging();
    boolean success = true;
    MongoClient mongoClient = null;
    try {
        mongoClient = new MongoClient(new MongoClientURI("mongodb://" + mongoDBConfig.getIp() + ":" + mongoDBConfig.getPort()));
        mongoClient.getDatabaseNames();
    } catch (MongoException e) {
        success = false;
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
        Logging.enableMongoDBLogging();
    }
    return success;
}
项目:ugc-bot-redux    文件:MongoDBReporter.java   
private void reportGauge(final String name, final Gauge gauge, final Date timestamp) {
    final DBCollection coll = db.getCollection("metric_gauge");
    final Object value = gauge.getValue();

    if (value == null) {
        // skip report
        return;
    }

    if (!String.class.equals(value.getClass())) {
        final GaugeEntity entity = new GaugeEntity();
        entity.setName(prefix(name));
        entity.setTimestamp(timestamp);
        entity.setValue(value);

        try {
            coll.save(entity.toDBObject());
        } catch (MongoException e) {
            LOGGER.warn("Unable to report gauge {}", name, e);
        }
    }
}
项目:STEM    文件:MongoDBDataSource.java   
@Override
public Record next() {
  try {
    element = cursor.next();
    builder.newRecord();

    for (Column col : getColumns()) {
      // TODO: identify arrays (containing values or DBObjects) in order to add multiple values
      String value = getStringValueFromCursorElement(element, col.getName());
      builder.addValue(col, value);
    }

    hasNext = cursor.hasNext(); // step to next

    return builder.getRecord();
  } catch (MongoException e) {
    throw new RuntimeException(e);
  }
}
项目:Rapture    文件:MongoDbDataStore.java   
@Override
public boolean delete(List<String> keys) {
    Document inClause = new Document($IN, keys);
    Document query = new Document(KEY, inClause);
    try {
        Document result = getCollection().findOneAndDelete(query);
        if ((result != null) && needsFolderHandling) {
            for (String key : keys) {
                dirRepo.dropFileEntry(key);
            }
        }
        return result != null;
    } catch (MongoException me) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, new ExceptionToString(me));
    }

}
项目:Rapture    文件:MongoDBAuditLog.java   
private void fillFromCursor(List<AuditLogEntry> ret, FindIterable<Document> cursor) throws MongoException {
    Iterator<Document> iterator = cursor.iterator();
    while (iterator.hasNext()) {
        Document obj = iterator.next();
        AuditLogEntry entry = new AuditLogEntry();
        entry.setLevel((Integer) obj.get(LEVEL));
        entry.setMessage(safeString(obj, MESSAGE));
        entry.setUser(safeString(obj, USER));
        entry.setLogId(safeString(obj, LOG_ID));
        entry.setWhen((Date) obj.get(WHEN));
        entry.setSource(safeString(obj, SOURCE));
        entry.setEntryId(safeString(obj, ENTRY_ID));
        entry.setCategory(safeString(obj, CATEGORY));
        ret.add(entry);
    }
}
项目:Rapture    文件:MongoDBAuditLog.java   
@Override
public Boolean writeLog(String category, int level, String message, String user) {
    log.debug("Mongo write audit log - " + message);
    Document obj = new Document();
    obj.append(LEVEL, level);
    obj.append(MESSAGE, message);
    obj.append(USER, user);
    obj.append(WHEN, new Date());
    obj.append(LOG_ID, logId);
    obj.append(SOURCE, "");
    obj.append(CATEGORY, category);
    obj.append(ENTRY_ID, IDGenerator.getUUID());
    try {
        getAuditCollection().insertOne(obj);
    } catch (MongoException e) {
        System.err.println("Cannot log " + message + ": " + e.getMessage());
        return false;
    }
    return true;
}
项目:Rapture    文件:MongoSeriesStore.java   
@Override
public boolean deletePointsFromSeriesByPointKey(String key, List<String> pointKeys) {
    MongoCollection<Document> collection = getCollection(key);
    boolean ret = false;
    for (String pointKey : pointKeys) {
        Document victim = new Document(ROWKEY, key).append(COLKEY, pointKey);
        try {
            DeleteResult result = collection.deleteMany(victim);
            log.info("Removed " + result.getDeletedCount() + " rows");
            ret = (result.getDeletedCount() > 0);
        } catch (MongoException me) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, new ExceptionToString(me));
        }
    }
    return ret;
}
项目:Rapture    文件:DocHandler.java   
@Override
public Boolean storeBlob(CallingContext context, String docPath, InputStream content, Boolean append) {
    log.debug("Saving " + docPath);
    byte[] toSave;
    try {
        toSave = IOUtils.toByteArray(content);
        Document toStore = new Document();
        toStore.append(BLOB_NAME, docPath);
        toStore.append(CONTENT, toSave);
        try {
            getCollection().insertOne(toStore);
            return true;
        } catch (MongoException e) {
            log.error("Could not store " + docPath + ": " + e.getMessage());
            log.debug(ExceptionToString.format(e));
        }
    } catch (IOException e1) {
        log.error("Could not read content gto store: " + e1.getMessage());
        log.debug(ExceptionToString.format(e1));
    }
    return false;
}
项目:jpa-unit    文件:CleanupStrategyProviderIT.java   
@Before
public void prepareTest() throws MongoException, IOException {
    mongoClient = factory.newMongo();
    connection = mongoClient.getDatabase(UUID.randomUUID().toString());

    initialDataSet = new DataSetLoaderProvider().jsonLoader().load(new File("src/test/resources/test-data.json"));

    final MongoDbOperation operation = MongoDbOperations.CLEAN_INSERT;
    operation.execute(connection, initialDataSet);

    connection.getCollection("JSON_COLLECTION_1")
            .insertOne(new Document().append("_id", 10).append("version", "Record 10 version").append("value_1", "Record 10 Value 1")
                    .append("value_2", "Record 10 Value 2").append("value_3", "Record 10 Value 3")
                    .append("value_4", "Record 10 Value 4").append("value_5", "Record 10 Value 5"));

    connection.getCollection("JSON_COLLECTION_3").insertOne(new Document().append("_id", 11).append("version", "Record 11 version")
            .append("value_1", "Record 11 Value 8").append("value_2", "Record 11 Value 9"));

    assertThat(connection.getCollection("JSON_COLLECTION_1").count(), equalTo(4l));
    assertThat(connection.getCollection("JSON_COLLECTION_2").count(), equalTo(1l));
    assertThat(connection.getCollection("JSON_COLLECTION_3").count(), equalTo(1l));

    provider = new CleanupStrategyProvider();
}
项目:hawkbit-extensions    文件:MongoDBArtifactStore.java   
@Override
public AbstractDbArtifact store(final String tenant, final InputStream content, final String filename,
        final String contentType, final DbArtifactHash hash) {
    File tempFile = null;
    try {
        LOGGER.debug("storing file {} of content {}", filename, contentType);
        tempFile = File.createTempFile("uploadFile", null);
        try (final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile))) {
            try (BufferedInputStream bis = new BufferedInputStream(content)) {
                return store(tenant, bis, contentType, bos, tempFile, hash);
            }
        }
    } catch (final IOException | MongoException e1) {
        throw new ArtifactStoreException(e1.getMessage(), e1);
    } finally {
        if (tempFile != null && !tempFile.delete()) {
            LOGGER.error("Could not delete temporary file: {}", tempFile);
        }
    }
}
项目:Wiab.pro    文件:MongoDbStore.java   
@Override
public void storeAttachment(AttachmentId attachmentId, InputStream data)
    throws IOException {
  GridFSInputFile file = getAttachmentGrid().createFile(data, attachmentId.serialise());

  try {
    file.save();
  } catch (MongoException e) {
    // Unfortunately, file.save() wraps any IOException thrown in a
    // 'MongoException'. Since the interface explicitly throws IOExceptions,
    // we unwrap any IOExceptions thrown.
    Throwable innerException = e.getCause();
    if (innerException instanceof IOException) {
      throw (IOException) innerException;
    } else {
      throw e;
    }
  }
}
项目:navi    文件:NaviMongoListDriver.java   
public NaviMongoListDriver(ServerUrlUtil.ServerUrl server, String auth, NaviPoolConfig poolConfig) throws NumberFormatException, MongoException, UnknownHostException {
    super(server, auth, poolConfig);

    String masterUrl = null;
    if (server.getHost() != null && server.getPort() != 0)
        masterUrl = server.getHost() + ":" + server.getPort();
    List<ServerAddress> addresslist = new ArrayList<>();
    // 找到master
    List<String> listHostPorts = new ArrayList<>();
    String[] hostPorts = server.getUrl().split(",");
    Collections.addAll(listHostPorts, hostPorts);
    for (int i = 0; i < listHostPorts.size(); i++) {
        if (listHostPorts.get(0).equals(masterUrl))
            break;
        listHostPorts.add(listHostPorts.remove(0));
    }
    for (String hostPort : listHostPorts) {
        addresslist.add(new ServerAddress(hostPort));
    }

    mongo = new Mongo(addresslist, getMongoOptions(poolConfig));
    // mongo.setReadPreference(ReadPreference.SECONDARY);

    startIdleConnCheck();
}
项目:drill    文件:MongoSchemaFactory.java   
@Override
public List<String> load(String key) throws Exception {
  if (!DATABASES.equals(key)) {
    throw new UnsupportedOperationException();
  }
  try {
    List<String> dbNames = new ArrayList<>();
    plugin.getClient().listDatabaseNames().into(dbNames);
    return dbNames;
  } catch (MongoException me) {
    logger.warn("Failure while loading databases in Mongo. {}",
        me.getMessage());
    return Collections.emptyList();
  } catch (Exception e) {
    throw new DrillRuntimeException(e.getMessage(), e);
  }
}
项目:incubator-rya    文件:MongoDBRyaDAO2IT.java   
@Test
public void testAdd() throws RyaDAOException, MongoException, IOException {
    MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();

        final RyaStatementBuilder builder = new RyaStatementBuilder();
        builder.setPredicate(new RyaURI("http://temp.com"));
        builder.setSubject(new RyaURI("http://subject.com"));
        builder.setObject(new RyaURI("http://object.com"));

        final MongoDatabase db = conf.getMongoClient().getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME));
        final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName());

        dao.add(builder.build());

        assertEquals(coll.count(),1);
    }  finally {
        dao.destroy();
    }
}
项目:incubator-rya    文件:MongoDBRyaDAO2IT.java   
@Test
public void testDelete() throws RyaDAOException, MongoException, IOException {
    MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();

        final RyaStatementBuilder builder = new RyaStatementBuilder();
        builder.setPredicate(new RyaURI("http://temp.com"));
        builder.setSubject(new RyaURI("http://subject.com"));
        builder.setObject(new RyaURI("http://object.com"));
        final RyaStatement statement = builder.build();

        final MongoDatabase db = conf.getMongoClient().getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME));
        final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName());

        dao.add(statement);
        assertEquals(coll.count(),1);

        dao.delete(statement, conf);
        assertEquals(coll.count(),0);
    } finally {
        dao.destroy();
    }
}
项目:incubator-rya    文件:EmbeddedMongoSingleton.java   
public static MongoClient getNewMongoClient() throws UnknownHostException, MongoException {
    final MongoClient client = InstanceHolder.SINGLETON.factory.newMongoClient();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                client.close();
            } catch (final Throwable t) {
                // logging frameworks will likely be shut down
                t.printStackTrace(System.err);
            }
        }
    });

    return client;
}
项目:incubator-rya    文件:MongoDBRyaDAOIT.java   
@Test
public void testDelete() throws RyaDAOException, MongoException, IOException {
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();

        final RyaStatementBuilder builder = new RyaStatementBuilder();
        builder.setPredicate(new RyaURI("http://temp.com"));
        builder.setSubject(new RyaURI("http://subject.com"));
        builder.setObject(new RyaURI("http://object.com"));
        builder.setColumnVisibility(new DocumentVisibility("C").flatten());
        final RyaStatement statement = builder.build();
        final MongoDatabase db = conf.getMongoClient().getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME));
        final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName());

        dao.add(statement);
        assertEquals(1, coll.count());

        dao.delete(statement, conf);
        assertEquals(0, coll.count());
    } finally {
        dao.destroy();
    }
}
项目:incubator-rya    文件:MongoTypeStorage.java   
@Override
public Optional<Type> get(final RyaURI typeId) throws TypeStorageException {
    requireNonNull(typeId);

    try {
        final Document document = mongo.getDatabase(ryaInstanceName)
            .getCollection(COLLECTION_NAME)
            .find( makeIdFilter(typeId) )
            .first();

        return document == null ?
                Optional.empty() :
                Optional.of( TYPE_CONVERTER.fromDocument(document) );

    } catch(final MongoException | DocumentConverterException e) {
        throw new TypeStorageException("Could not get the Type with ID '" + typeId.getData() + "'.", e);
    }
}
项目:incubator-rya    文件:MongoEntityStorage.java   
@Override
public void create(final Entity entity) throws EntityStorageException {
    requireNonNull(entity);

    try {
        final boolean hasDuplicate = detectDuplicates(entity);

        if (!hasDuplicate) {
            mongo.getDatabase(ryaInstanceName)
                .getCollection(COLLECTION_NAME)
                .insertOne( ENTITY_CONVERTER.toDocument(entity) );
        } else {
            throw new EntityNearDuplicateException("Duplicate data found and will not be inserted for Entity with Subject: "  + entity);
        }
    } catch(final MongoException e) {
        final ErrorCategory category = ErrorCategory.fromErrorCode( e.getCode() );
        if(category == ErrorCategory.DUPLICATE_KEY) {
            throw new EntityAlreadyExistsException("Failed to create Entity with Subject '" + entity.getSubject().getData() + "'.", e);
        }
        throw new EntityStorageException("Failed to create Entity with Subject '" + entity.getSubject().getData() + "'.", e);
    }
}
项目:incubator-rya    文件:MongoEntityStorage.java   
@Override
public Optional<Entity> get(final RyaURI subject) throws EntityStorageException {
    requireNonNull(subject);

    try {
        final Document document = mongo.getDatabase(ryaInstanceName)
            .getCollection(COLLECTION_NAME)
            .find( Filters.eq(EntityDocumentConverter.SUBJECT, subject.getData()) )
            .first();

        return document == null ?
                Optional.empty() :
                Optional.of( ENTITY_CONVERTER.fromDocument(document) );

    } catch(final MongoException | DocumentConverterException e) {
        throw new EntityStorageException("Could not get the Entity with Subject '" + subject.getData() + "'.", e);
    }
}
项目:incubator-rya    文件:MongoListInstancesIT.java   
@Test
public void listInstances_hasRyaDetailsTable() throws MongoException, DuplicateInstanceNameException, RyaClientException {
    // Install a few instances of Rya using the install command.
    final RyaClient ryaClient = MongoRyaClientFactory.build(getConnectionDetails(), getMongoClient());
    final Install install = ryaClient.getInstall();
    install.install("instance1_", InstallConfiguration.builder().build());
    install.install("instance2_", InstallConfiguration.builder().build());
    install.install("instance3_", InstallConfiguration.builder().build());

    // Fetch the list and verify it matches what is expected.
    final ListInstances listInstances = new MongoListInstances(getMongoClient());
    final List<String> instances = listInstances.listInstances();
    Collections.sort(instances);

    final List<String> expected = Lists.newArrayList("instance1_", "instance2_", "instance3_");
    assertEquals(expected, instances);
}
项目:incubator-rya    文件:MongoEventStorage.java   
@Override
public void create(final Event event) throws EventStorageException {
    requireNonNull(event);

    try {
        mongo.getDatabase(ryaInstanceName)
            .getCollection(COLLECTION_NAME)
            .insertOne(EVENT_CONVERTER.toDocument(event));
    } catch(final MongoException e) {
        final ErrorCategory category = ErrorCategory.fromErrorCode( e.getCode() );
        if(category == ErrorCategory.DUPLICATE_KEY) {
            throw new EventAlreadyExistsException("Failed to create Event with Subject '" + event.getSubject().getData() + "'.", e);
        }
        throw new EventStorageException("Failed to create Event with Subject '" + event.getSubject().getData() + "'.", e);
    }
}
项目:incubator-rya    文件:MongoEventStorage.java   
@Override
public Optional<Event> get(final RyaURI subject) throws EventStorageException {
    requireNonNull(subject);

    try {
        final Document document = mongo.getDatabase(ryaInstanceName)
            .getCollection(COLLECTION_NAME)
            .find( new BsonDocument(EventDocumentConverter.SUBJECT, new BsonString(subject.getData())) )
            .first();

        return document == null ?
                Optional.empty() :
                Optional.of( EVENT_CONVERTER.fromDocument(document) );

    } catch(final MongoException | DocumentConverterException e) {
        throw new EventStorageException("Could not get the Event with Subject '" + subject.getData() + "'.", e);
    }
}
项目:anhalytics-core    文件:MongoManager.java   
public MongoManager(boolean isTest) {
    try {
        CommonsProperties.init("anhalytics.properties", isTest);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

    try {
        mongo = new MongoClient(CommonsProperties.getMongodbServer(), CommonsProperties.getMongodbPort());

    if (!mongo.getDatabaseNames().contains(CommonsProperties.getMongodbDb())) {
        LOGGER.info("MongoDB database " + CommonsProperties.getMongodbDb() + " does not exist and will be created");
    }
    } catch (MongoException|IOException ex) {
        throw new ServiceException("MongoDB is not UP, the process will be halted.");
    }
}
项目:fiware-metaware    文件:DataSourceProvider.java   
/**
     * Initializes the datasource provider.
     *
     * @param props
     * @throws UnknownHostException
     */
    DataSourceProvider(Properties props) throws UnknownHostException { // opening mongodb connection
        log.info(MSG_OPENING_DB_CONNECTION);

        serverAddress = new ServerAddress(props.getProperty(KEY_DB_HOST),
                Integer.parseInt(props.getProperty(KEY_DB_PORT)));
//        mongoCredential = new MongoCredential.createCredential(KEY_DB_USERNAME, KEY_DB_NAME,
//                KEY_DB_PASSWORD.toCharArray());
//        mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        mongoClient = new MongoClient(serverAddress);
        db = mongoClient.getDB(props.getProperty(KEY_DB_NAME));

        try {
            db.getCollectionNames();
        } catch (MongoException e) {
            log.error(MSG_ERR_DB_CONNECTION, e);
            throw new DBConnectionException();
        }

        log.info(MSG_DB_CONNECTION_OPENED);

        // Specify additional unique fields
        db.getCollection(USERS_COLLECTION_NAME).createIndex(new BasicDBObject("username", 1),
                new BasicDBObject("unique", true));
    }
项目:simmo-stream-manager    文件:MongoDbStorage.java   
@Override
public void store(gr.iti.mklab.simmo.core.Object object) throws IOException {
    try {

        if (object instanceof Image) {
            dao.userDAO.save(object.getContributor());
            dao.imageDAO.save((Image) object);
        } else if (object instanceof Video){ 
            dao.userDAO.save(object.getContributor());
            dao.videoDAO.save((Video) object);
        }
        else if (object instanceof Webpage) {
            dao.saveWebpage((Webpage) object);
        }
        else {
            dao.savePost((Post) object);
        }
    } catch (MongoException e) {
        e.printStackTrace();
        logger.error("Storing item " + object.getId() + " failed.");
    }
}
项目:embulk-input-mongodb    文件:MongodbInputPlugin.java   
private MongoDatabase connect(final PluginTask task) throws UnknownHostException, MongoException
{
    MongoClient mongoClient;
    String database;

    if (!task.getUri().isPresent() && !task.getHosts().isPresent()) {
        throw new ConfigException("'uri' or 'hosts' is required");
    }

    if (task.getUri().isPresent()) {
        MongoClientURI uri = new MongoClientURI(task.getUri().get());
        database = uri.getDatabase();
        mongoClient = new MongoClient(uri);
    }
    else {
        mongoClient = createClientFromParams(task);
        database = task.getDatabase().get();
    }

    MongoDatabase db = mongoClient.getDatabase(database);
    // Get collection count for throw Exception
    db.getCollection(task.getCollection()).count();
    return db;
}