Example usage for com.mongodb MongoException getCode

List of usage examples for com.mongodb MongoException getCode

Introduction

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

Prototype

public int getCode() 

Source Link

Document

Gets the exception code

Usage

From source file:biz.bidi.archivee.commons.exceptions.ArchiveeException.java

License:Open Source License

public boolean isMongodbDuplicateKey() {
    if (e == null) {
        return false;
    }/*from   w w w  .  ja va2s. c  o  m*/

    if (e instanceof MongoException) {
        MongoException me = (MongoException) e;
        if (me.getCode() == 11000) {
            return true;
        }
    }

    return false;
}

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

License:Apache License

void refresh() {
    clearOverlays();//from   ww w.j av a  2 s. co  m

    try {
        refreshNode();
    } catch (MongoException e) {
        //            System.out.println(e.getMessage());
        if (e.getCode() == 10057 || e.getMessage().contains("unauthorized")
                || e.getMessage().contains("not authorized")) {
            addOverlay("overlay/lock_tiny.png");
        } else {
            addOverlay("overlay/error.png");
        }
        getLogger().log(Level.FINE, null, e);
    } catch (Exception e) {
        addOverlay("overlay/error.png");
        getLogger().log(Level.FINE, null, e);
    }
}

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

License:Apache License

public void setException(Exception exception, String in) {
    this.exception = exception;
    label = in;//from ww  w .  ja  v  a2s.  co m
    setStringFieldValue(Item.errorIn, in);
    setStringFieldValue(Item.errorMsg, exception.getMessage());
    String code = "?";
    if (exception instanceof MongoException) {
        MongoException me = (MongoException) exception;
        code = String.valueOf(me.getCode());
    }

    setStringFieldValue(Item.errorCode, code);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter pw = new PrintWriter(baos);
    exception.printStackTrace(pw);
    pw.flush();
    setStringFieldValue(Item.errorTrace, baos.toString());
    updateComponent();
    //        getLogger().log(Level.WARNING, null, exception);
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

License:Open Source License

public void handleMongoException(MongoException me) {
    if (this.isStdoutMongoErrorMessages()) {
        // check error codes that do NOT result in an exception
        switch (me.getCode()) {
        case 10088: // cannot index parallel arrays [b] [d]
        case 10096: // invalid ns to index
        case 10098: // bad index key pattern
        case 10148: // Mod on _id not allowed
        case 10149: // Invalid mod field name, may not end in a period
        case 10159: // multi update only works with $ operators
        case 11000: // E11000 duplicate key error index:
        case 15896: // Modified field name may not start with $
        case 16650: // Cannot apply the positional operator without a
                    // corresponding query field containing an array.
        case 10141: // Cannot apply $push/$pushAll modifier to non-array
        case 16734: // Unknown index plugin '*' in index { *: * }
        case 10089: // can't remove from a capped collection
        case 13023: // 2d has to be first in index
        case 13028: // bits in geo index must be between 1 and 32
        case 13027: // point not in interval of [ -0.99995, 0.99995 ]
        case 16572: // Can't extract geo keys from object, malformed
                    // geometry?
        case 16687: // coarsestIndexedLevel must be >= 0
        case 16688: // finestIndexedLevel must be <= 30
        case 16241: // Currently only single field hashed index supported.
        case 16242: // Currently hashed indexes cannot guarantee uniqueness.
                    // Use a regular index.
        case 15855: // Ambiguous field name found in array (do not use
                    // numeric field names in embedded elements in
                    // an array)
        case 12505: // add index fails, too many indexes
            MongoScope.print(Context.getCurrentContext(), this, new Object[] { me.getMessage() }, null);
            return;
        default:/*from w  ww  .  ja v a2 s . com*/
            throw me;
        }
    } else
        throw me;
}

From source file:com.grallandco.impl.MongoCAPIBehavior.java

License:Apache License

/**
 * Load the documents into MongoDB/*from   w  ww. j a v  a2  s . com*/
 * @param database
 * @param docs
 * @return
 */
@Override
public List<Object> bulkDocs(String database, List<Map<String, Object>> docs) {

    DB db = MongoConnectionManager.getMongoClient().getDB(getDatabaseName(database));
    List<Object> result = new ArrayList<Object>();

    logger.log(Level.INFO, String.format("Replicating %d document(s)", docs.size()));

    for (Map<String, Object> doc : docs) {
        Map<String, Object> meta = (Map<String, Object>) doc.get("meta");
        Map<String, Object> json = (Map<String, Object>) doc.get("json");
        String base64 = (String) doc.get("base64");

        if (meta == null) {
            // if there is no meta-data section, there is nothing we can do
            logger.log(Level.WARNING, "Document without meta in bulk_docs, ignoring....");
            continue;
        } else if ("non-JSON mode".equals(meta.get("att_reason"))
                || "invalid_json".equals(meta.get("att_reason"))) {
            // optimization, this tells us the body isn't json
            json = new HashMap<String, Object>();
        } else if (json == null && base64 != null) {

            // use Java 6/7 XML Base64 library
            // TODO : see if it makes sense to use Java8 Library java.util.Base64
            String jsonValue = new String(DatatypeConverter.parseBase64Binary(base64));
            DBObject o = (DBObject) JSON.parse(jsonValue);
            DBObject mongoJson = BasicDBObjectBuilder.start("_id", meta.get("id")).get();

            // need to check if json keys do not contains . or $ and replace them with other char
            // TODO : Copy the doc, put _id at the top and clean key names
            Set<String> keys = o.keySet();
            for (String key : keys) {
                String newKey = key;
                newKey = newKey.replace(".", MongoDBCouchbaseReplicator.dotReplacement);
                newKey = newKey.replace("$", MongoDBCouchbaseReplicator.dollarReplacement);
                mongoJson.put(newKey, o.get(key));
            }

            // add meta data if configured
            if (MongoDBCouchbaseReplicator.keepMeta) {
                mongoJson.put("meta", new BasicDBObject(meta));
            }

            String collectionName = MongoDBCouchbaseReplicator.defaultCollection;
            if (o.get(MongoDBCouchbaseReplicator.collectionField) != null) {
                collectionName = (String) o.get(MongoDBCouchbaseReplicator.collectionField);
            }

            try {

                if (MongoDBCouchbaseReplicator.replicationType.equalsIgnoreCase("insert_only")) {
                    // this will raise an exception
                    db.getCollection(collectionName).insert(mongoJson);
                } else { // insert & update
                    db.getCollection(collectionName).save(mongoJson);
                }

            } catch (MongoException e) {

                if (e.getCode() == 11000) {
                    logger.log(Level.INFO, "Not replicating updated document " + meta.get("id"));
                } else {
                    logger.log(Level.SEVERE, e.getMessage());
                }

            }

        }

        String id = (String) meta.get("id");
        String rev = (String) meta.get("rev");
        Map<String, Object> itemResponse = new HashMap<String, Object>();
        itemResponse.put("id", id);
        itemResponse.put("rev", rev);
        result.add(itemResponse);
    }

    return result;
}

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

License:Apache License

@Override
public void persist(Object document) {
    doumentManagerFactory.prePersist(document);
    String collectionName = doumentManagerFactory.resolveDocumentName(document.getClass());
    DBCollection collection = getDB().getCollection(collectionName);
    DBObject dbObject = doumentManagerFactory.convertObjectToDocument(document);
    try {/* w  w w .j  a  v a2s . c o m*/
        collection.insert(dbObject);
    } catch (MongoException e) {
        if (e.getCode() == MongoExceptionCode.DOCUMENT_EXISTS) {
            throw new DocumentExistsException(e.getMessage());
        }
    }
    doumentManagerFactory.resolveId(document, dbObject.get(DocumentManagerFactoryImpl.ID));
    doumentManagerFactory.postPersist(document);
}

From source file:com.redhat.lightblue.mongo.crud.MongoCRUDController.java

License:Open Source License

private Error analyzeException(Exception e, final String otherwise, final String msg, boolean specialHandling) {
    if (e instanceof Error) {
        return (Error) e;
    }// w w w  .  j  a  va  2s . c om

    if (e instanceof MongoException) {
        MongoException me = (MongoException) e;
        if (me.getCode() == 18) {
            return Error.get(CrudConstants.ERR_AUTH_FAILED, e.getMessage());
        } else if (me instanceof MongoTimeoutException || me instanceof MongoExecutionTimeoutException) {
            LOGGER.error(CrudConstants.ERR_DATASOURCE_TIMEOUT, e);
            return Error.get(CrudConstants.ERR_DATASOURCE_TIMEOUT, e.getMessage());
        } else if (me instanceof DuplicateKeyException) {
            return Error.get(MongoCrudConstants.ERR_DUPLICATE, e.getMessage());
        } else if (me instanceof MongoSocketException) {
            LOGGER.error(MongoCrudConstants.ERR_CONNECTION_ERROR, e);
            return Error.get(MongoCrudConstants.ERR_CONNECTION_ERROR, e.getMessage());
        } else {
            LOGGER.error(MongoCrudConstants.ERR_MONGO_ERROR, e);
            return Error.get(MongoCrudConstants.ERR_MONGO_ERROR, e.getMessage());
        }
    } else if (msg == null) {
        return Error.get(otherwise, e.getMessage());
    } else if (specialHandling) {
        return Error.get(otherwise, msg, e);
    } else {
        return Error.get(otherwise, msg);
    }
}

From source file:de.otto.mongodb.profiler.DefaultProfilerService.java

License:Apache License

@Override
public ProfiledDatabase addDatabase(final ProfiledConnection connection, final String name,
        final String username, final char[] password) throws DatabaseDoesNotExistException,
        DatabaseAlreadyConfiguredException, AuthenticationException, ConnectivityException {

    final String connectionId = checkNotNull(connection).getId();

    final ReentrantReadWriteLock.WriteLock lock = globalLock.writeLock();
    lock.lock();//from  w  ww .  ja v a 2 s .c  om
    try {

        final DefaultProfiledConnection realConnection = connections.get(connectionId);
        checkArgument(realConnection != null, "Connection [%s] does not exist!", connectionId);

        try {
            if (!containsDb(realConnection, name)) {
                throw new DatabaseDoesNotExistException(String.format("Database [%s] does not exist!", name),
                        name);
            }
        } catch (MongoException e) {
            throw new ConnectivityException(e.getMessage(), e);
        }

        synchronized (realConnection) {
            Map<String, DefaultProfiledDatabase> databases = this.databases.get(connectionId);

            if (databases != null && databases.containsKey(name)) {
                throw new DatabaseAlreadyConfiguredException(
                        String.format("Database [%s] is already configured!", name), realConnection, name);
            }

            if (databases == null) {
                databases = Collections.synchronizedMap(new HashMap<String, DefaultProfiledDatabase>());
                this.databases.put(connectionId, databases);
            }

            final DB db = realConnection.getClient().getDB(name);

            try {
                if (username != null && password != null) {
                    if (!db.authenticate(username, password)) {
                        throw new AuthenticationException("Failed to authenticate against database.");
                    }
                }
            } catch (CommandFailureException e) {
                throw new AuthenticationException("Failed to authenticate against database.", e);
            }

            try {
                db.getCollectionNames();
            } catch (MongoException e) {
                if (e.getCode() == 16550) {
                    throw new AuthenticationException("Database requires authentication.");
                }
                throw new ConnectivityException("Failed to test a database command!", e);
            }

            final CollectionProfiler collectionProfiler = profilerFactory.createCollectionProfiler(db,
                    profilerThreadGroup);
            final OpProfiler opProfiler = profilerFactory.createOpProfiler(db, profilerThreadGroup);

            final DefaultProfiledDatabase database = new DefaultProfiledDatabase(db, realConnection,
                    collectionProfiler, opProfiler);

            database.initialize();
            databases.put(name, database);

            return database;
        }
    } finally {
        lock.unlock();
    }
}

From source file:es.bsc.amon.controller.AppsDBMapper.java

License:Open Source License

private AppsDBMapper() {
    // default table size to 64 MB
    Logger.info("Creating collection '" + COLL_NAME + "'...");
    Properties config = DBManager.instance.getConfig();
    DB database = DBManager.instance.getDatabase();

    try {/*from  w ww .jav a2  s .c om*/

        int collectionSize = Integer.parseInt(config.getProperty("collection.size"));
        colAppInstances = database.createCollection(COLL_NAME, new BasicDBObject("capped", true) //enable round robin database
                .append("size", collectionSize));

    } catch (MongoException cfe) {
        if (cfe.getCode() == DBManager.COLLECTION_ALREADY_EXISTS) {
            Logger.info("Collection '" + COLL_NAME + "' already exists. Continuing normally...");
        }
        colAppInstances = database.getCollection(COLL_NAME);
    }

    // compound index events by timestamp, appId and nodeId
    BasicDBObject indexInfo = new BasicDBObject();
    indexInfo.put(EventsDBMapper.TIMESTAMP, -1); // 1 for ascending, -1 for descending
    colAppInstances.createIndex(indexInfo);
}

From source file:es.bsc.amon.controller.EventsDBMapper.java

License:Open Source License

private EventsDBMapper() {
    // default table size to 64 MB
    Logger.info("Creating collection '" + COLL_NAME + "'...");
    Properties config = DBManager.instance.getConfig();
    DB database = DBManager.instance.getDatabase();

    try {/*from  ww w .  jav a 2 s  . c o  m*/

        int collectionSize = Integer.parseInt(config.getProperty("collection.size"));
        colEvents = database.createCollection(COLL_NAME, new BasicDBObject("capped", true) //enable round robin database
                .append("size", collectionSize));
    } catch (MongoException cfe) {
        if (cfe.getCode() == DBManager.COLLECTION_ALREADY_EXISTS) {
            Logger.info("Collection '" + COLL_NAME + "' already exists. Continuing normally...");
        }
        colEvents = database.getCollection(COLL_NAME);
    }

    // compound index events by timestamp, appId and nodeId
    BasicDBObject indexInfo = new BasicDBObject();
    indexInfo.put(EventsDBMapper.TIMESTAMP, -1); // 1 for ascending, -1 for descending
    indexInfo.put(EventsDBMapper.APPID, 1);
    indexInfo.put(EventsDBMapper.NODEID, 1);

    colEvents.createIndex(indexInfo);
}