Example usage for com.mongodb MongoException MongoException

List of usage examples for com.mongodb MongoException MongoException

Introduction

In this page you can find the example usage for com.mongodb MongoException MongoException.

Prototype

public MongoException(final String msg) 

Source Link

Usage

From source file:com.edgytech.umongo.DbPanel.java

License:Apache License

public void downloadFile(final ButtonBase button) {
    final DB db = getDbNode().getDb();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.downloadQuery)).getDBObject();
    final String fname = getStringFieldValue(Item.downloadFileName);
    final String dpath = getStringFieldValue(Item.downloadFilePath);
    if (dpath.isEmpty()) {
        return;//from   w  ww . j av  a2 s .  c  o  m
    }
    final File dfile = new File(dpath);

    new DbJob() {

        @Override
        public Object doRun() throws IOException {
            GridFSDBFile dbfile = null;
            if (query != null) {
                dbfile = getGridFS().findOne(query);
            } else {
                dbfile = getGridFS().findOne(fname);
            }
            if (dbfile == null) {
                throw new MongoException("GridFS cannot find file " + fname);
            }
            dbfile.writeTo(dfile);
            return dbfile;
        }

        @Override
        public String getNS() {
            return db.getName();
        }

        @Override
        public String getShortName() {
            return "Download File";
        }

        @Override
        public DBObject getRoot(Object result) {
            BasicDBObject obj = new BasicDBObject("filename", fname);
            obj.put("query", query);
            obj.put("path", dpath);
            return obj;
        }

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

From source file:com.ga.model.abstractclasses.ModelAbstract.java

@Override
public void init(String dbName, String collectionName) {
    try {/*from w  w w  .ja v  a 2s.  co  m*/
        //            ModelAbstract.conn = new MongoClient(new MongoClientURI("mongodb://116.193.163.66:27017/"));
        ModelAbstract.conn = new MongoClient(new MongoClientURI("mongodb://localhost:27017/"));
        if (ModelAbstract.conn != null) {
            ModelAbstract.db = ModelAbstract.conn.getDB(dbName);
            if (ModelAbstract.db != null) {
                ModelAbstract.collection = ModelAbstract.db.getCollection(collectionName);
                if (ModelAbstract.collection == null) {
                    Exception exCollection = new Exception(
                            "Collection \'" + collectionName + "\' does not exist in \'" + dbName + "\'.");
                    throw exCollection;

                }
            } else {
                Exception exDatabase = new Exception("Database \'" + dbName + "\' not found.");
                throw exDatabase;
            }
        } else {
            ex = new MongoException("Failed to connect with database server.");
            throw ex;
        }
    } catch (UnknownHostException e) {
        Logger.getLogger(ModelAbstract.class.getName()).log(Level.SEVERE, null, e);
    } catch (Exception exCollection) {
        Logger.getLogger(ModelAbstract.class.getName()).log(Level.SEVERE, null, exCollection);
    }

}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

License:Apache License

@Override
public CompletableFuture<Boolean> optimizeQuery(final List<String> ordered_field_list) {

    // Mongo appears to have an ~100 char list on the query, Fongo does not, so add a mannual check
    // so we don't get the situation where the tests work but it fails operationally

    String approx_index_name = ordered_field_list.stream().collect(Collectors.joining("."));
    if (approx_index_name.length() > 100) {
        throw new MongoException(ErrorUtils.get(ErrorUtils.MONGODB_INDEX_TOO_LONG, approx_index_name));
    }//from   w  w w  .j  a  v a 2s  .c o m

    return CompletableFuture.supplyAsync(() -> {
        final BasicDBObject index_keys = new BasicDBObject(ordered_field_list.stream()
                .collect(Collectors.toMap(f -> f, f -> 1, (v1, v2) -> 1, LinkedHashMap::new)));

        _state.orig_coll.createIndex(index_keys, new BasicDBObject("background", true));

        return true;
    });
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

License:Apache License

@Override
public final boolean deregisterOptimizedQuery(final List<String> ordered_field_list) {
    try {//from www.  j av a2 s . c  o m
        final BasicDBObject index_keys = new BasicDBObject(ordered_field_list.stream()
                .collect(Collectors.toMap(f -> f, f -> 1, (v1, v2) -> 1, LinkedHashMap::new)));

        if (_state.orig_coll instanceof FongoDBCollection) { // (doesn't do the exception, so check by hand)
            final String index_keys_str = index_keys.toString();

            final List<DBObject> matching_indexes = _state.orig_coll.getIndexInfo().stream()
                    .filter(dbo -> index_keys_str.equals(dbo.get("key").toString()))
                    .collect(Collectors.toList());
            if (matching_indexes.isEmpty()) {
                throw new MongoException(ErrorUtils.get(ErrorUtils.MISSING_MONGODB_INDEX_KEY, index_keys_str));
            }
        }
        _state.orig_coll.dropIndex(index_keys);

        return true;
    } catch (MongoException ex) {
        return false;
    }
}

From source file:com.nowellpoint.mongodb.persistence.impl.DocumentManagerImpl.java

License:Apache License

@Override
public <T> T merge(T document) {
    doumentManagerFactory.prePersist(document);
    String collectionName = doumentManagerFactory.resolveDocumentName(document.getClass());
    DBCollection collection = getDB().getCollection(collectionName);
    Object documentId = doumentManagerFactory.resolveId(document);
    DBObject dbObject = doumentManagerFactory.convertObjectToDocument(document);
    DBObject query = new BasicDBObject(DocumentManagerFactoryImpl.ID, documentId);
    WriteResult result = collection.update(query, dbObject);
    if (result.getError() != null) {
        throw new MongoException(result.getLastError());
    }// w  ww  .  j  av a2  s.co m
    doumentManagerFactory.postPersist(document);
    return document;
}

From source file:com.nowellpoint.mongodb.persistence.impl.DocumentManagerImpl.java

License:Apache License

@Override
public void remove(Object document) {
    String collectionName = doumentManagerFactory.resolveDocumentName(document.getClass());
    DBCollection collection = getDB().getCollection(collectionName);
    Object documentId = doumentManagerFactory.resolveId(document);
    WriteResult wr = collection.remove(new BasicDBObject(DocumentManagerFactoryImpl.ID, documentId));
    if (wr.getError() != null) {
        throw new MongoException(wr.getLastError());
    }/*from  ww w.j a va  2 s  .c  o m*/
}

From source file:com.streamreduce.datasource.DatastoreFactoryBean.java

License:Apache License

@Override
protected AdvancedDatastore createInstance() throws Exception {
    AdvancedDatastore datastore;/*from   w  ww. j ava2 s.  c om*/

    if (StringUtils.hasText(user)) {
        // If there is a username supplied, we need to authenticate.  Morphia does not
        // allow us to use a MongoDB admin user so we need to do some setup work prior
        // to involving Morphia.  To do this, we will first try to authenticate as a
        // database user and if that fails, we will try to authenticate as an admin
        // user.  If both fail, we let the MongoException bubble up as it is unhandleable.
        logger.debug("Create the morphia datastore with credentials");

        // Try to login as a database user first and fall back to admin user if login fails
        if (mongo.getDB(dbName).authenticate(user, password.toCharArray())) {
            logger.debug("Successfully authenticated to MongoDB database (" + dbName + ") as " + user);
        } else {
            if (mongo.getDB("admin").authenticate(user, password.toCharArray())) {
                logger.debug(
                        "Successfully authenticated to MongoDB database (" + dbName + ") as admin " + user);
            } else {
                throw new MongoException("Unable to authenticate to MongoDB using " + user + "@" + dbName
                        + " or " + user + "@admin.");
            }
        }
    } else {
        logger.debug("Create the morphia datastore WITHOUT credentials");
    }

    datastore = (AdvancedDatastore) morphia.createDatastore(mongo, dbName);

    datastore.ensureCaps();
    datastore.ensureIndexes();

    return datastore;
}

From source file:com.streamreduce.storm.MongoClient.java

License:Apache License

private DB authenticateToDbIfNecessary(String dbName, DB db) {
    // Authenticate if necessary
    if (username != null && password != null) {
        if (db.authenticate(username, password.toCharArray())) {
            logger.debug("Successfully authenticated to MongoDB database (" + dbName + ") as " + username
                    + " on " + host + ":" + port);
        } else {/*w w w. j  a  v  a 2 s  . c  om*/
            db = mongo.getDB("admin");

            if (db.authenticate(username, password.toCharArray())) {
                logger.debug("Successfully authenticated to MongoDB database (" + dbName + ") as admin "
                        + username + " on " + host + ":" + port);
                db = mongo.getDB(dbName);
            } else {
                throw new MongoException("Unable to authenticate to MongoDB using " + username + "@" + dbName
                        + " or " + username + "@admin" + " on " + host + ":" + port + ".");
            }
        }
    }
    return db;
}

From source file:com.zenika.vertx.lib.asongo.then.BasicThenTemplate.java

License:Open Source License

@Override
public void then(final Handler<T> handler) {

    final JsonObject command = getCommand();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("The command " + command + ", is send to " + configuration.getMongoPersistorAdress());

    configuration.getEventBus().send(configuration.getMongoPersistorAdress(), command,
            new Handler<Message<JsonObject>>() {

                @Override//from  w  ww. ja va 2s  .  c  o m
                public void handle(final Message<JsonObject> message) {

                    Unmarshaller unmarshaller = configuration.getMapper().getUnmarshaller();

                    final PersistorResult presult = unmarshaller.unmarshall(message.body().toString(),
                            PersistorResult.class);

                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("The result is " + presult);

                    if (presult.isNotError()) {
                        handler.handle(operator.<T>getResult(presult));
                    } else {
                        String errorMsg = presult.getMessage();
                        LOGGER.error("Bad request to mongo " + errorMsg + " with the command " + command);
                        throw new MongoException(
                                "Bad request to mongo " + errorMsg + " with the command " + command);
                    }

                }
            });
}

From source file:com.zenika.vertx.lib.asongo.then.DocumentThenTemplate.java

License:Open Source License

@Override
public void then(final Handler<T> handler) {

    final JsonObject command = getCommand();
    final Class<K> clazz = getClazz();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("The command " + command + ", is send to " + configuration.getMongoPersistorAdress());

    configuration.getEventBus().send(configuration.getMongoPersistorAdress(), command,
            new Handler<Message<JsonObject>>() {

                @Override/*  w w w . j  a  v a  2  s  . co  m*/
                public void handle(final Message<JsonObject> message) {

                    Unmarshaller unmarshaller = configuration.getMapper().getUnmarshaller();

                    final DocumentResult<K> presult = unmarshaller.unmarshall(message.body().toString(),
                            DocumentResult.class, clazz);

                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("The result is " + presult);

                    if (presult.isNotError()) {
                        handler.handle(operator.<T, K>getResult(presult));
                    } else {
                        String errorMsg = presult.getMessage();
                        LOGGER.error("Bad request to mongo " + errorMsg + " with the command " + command);
                        throw new MongoException(
                                "Bad request to mongo " + errorMsg + " with the command " + command);
                    }

                }
            });
}