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:org.exoplatform.chat.services.mongodb.ChatServiceImpl.java

License:Open Source License

public String getTeamCreator(String room) {
    if (room.indexOf(ChatService.TEAM_PREFIX) == 0) {
        room = room.substring(ChatService.TEAM_PREFIX.length());
    }//from   w  ww .j  av  a 2s.  c om
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + M_ROOMS_COLLECTION);
    String creator = "";
    BasicDBObject basicDBObject = new BasicDBObject();
    basicDBObject.put("_id", room);

    DBCursor cursor = coll.find(basicDBObject);
    if (cursor.hasNext()) {
        try {
            DBObject dbo = cursor.next();
            creator = dbo.get("user").toString();
        } catch (MongoException me) {
            LOG.warning(me.getCode() + " : " + room + " : " + me.getMessage());
        }
    }

    return creator;
}

From source file:org.exoplatform.chat.services.mongodb.ChatServiceImpl.java

License:Open Source License

public String getRoom(List<String> users) {
    Collections.sort(users);/*from  ww w  .j a  v  a2 s . co m*/
    String room = ChatUtils.getRoomId(users);
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + M_ROOMS_COLLECTION);

    BasicDBObject basicDBObject = new BasicDBObject();
    basicDBObject.put("_id", room);

    DBCursor cursor = coll.find(basicDBObject);
    if (!cursor.hasNext()) {
        try {
            basicDBObject.put("users", users);
            basicDBObject.put("type", TYPE_ROOM_USER);
            coll.insert(basicDBObject);
            ensureIndexInRoom(room);
        } catch (MongoException me) {
            LOG.warning(me.getCode() + " : " + room + " : " + me.getMessage());
        }
    }

    return room;
}

From source file:org.flywaydb.core.internal.dbsupport.FlywayMongoScriptException.java

License:Apache License

@Override
public String getMessage() {
    String title = resource == null ? "Script failed" : "Migration " + resource.getFilename() + " failed";
    String underline = StringUtils.trimOrPad("", title.length(), '-');

    MongoException cause = (MongoException) getCause();
    String message = "\n" + title + "\n" + underline + "\n";
    message += "Error Code : " + cause.getCode() + "\n";
    if (cause.getMessage() != null) {
        message += "Message    : " + cause.getMessage().trim() + "\n";
    }//w  ww  .j a  va2  s. co m
    if (resource != null) {
        message += "Location   : " + resource.getLocation() + " (" + resource.getLocationOnDisk() + ")\n";
    }
    message += "Line       : " + getLineNumber() + "\n";
    message += "Statement  : " + getStatement() + "\n";

    return message;
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
public void insertUserAccount(UserEntity user) throws MetaStoreException, AlreadyStoredException {
    try {/*from   w  w  w  .  j a v  a2 s  .c  o  m*/
        Date createTime = new Date();
        Document doc = new Document("name", user.getName()).append("password", user.getPassword())
                .append("createTime", createTime);
        userAccountCollection.insertOne(doc);

        user.setId(doc.getObjectId("_id").toString());
        user.setCreateTime(createTime);

        LOG.info("Successful to insert user account '{}'", user.getName());
    } catch (MongoException e) {
        if (e.getCode() == 11000) {
            throw new AlreadyStoredException("'" + user.getName() + "' already exists");
        } else {
            LOG.error("Failed to insert user account", e);
            throw new MetaStoreException("Failed to insert user account", e);
        }
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
public void insertSchema(Schema schema) throws MetaStoreException, AlreadyStoredException {
    try {//w  w  w  .j a  va  2  s .  co  m
        Date createTime = new Date();

        Document doc = new Document("name", schema.getSchemaName()).append("topologies", schema.getTopologies())
                .append("desc", Utils.serialize(schema)).append("owner", schema.getOwner().getId())
                .append("createTime", createTime);
        if (schema.getComment() != null) {
            doc.append("comment", schema.getComment());
        }
        schemaCollection.insertOne(doc);

        schema.setId(doc.getObjectId("_id").toString());
        schema.setCreateTime(createTime);

        LOG.info("Successful to insert schema {} owned by {}", schema.getSchemaName(),
                schema.getOwner().getName());
    } catch (MongoException e) {
        if (e.getCode() == 11000) {
            throw new AlreadyStoredException(schema.getSchemaName() + " already exists");
        } else {
            LOG.error("Failed to insert schema", e);
            throw new MetaStoreException("Failed to insert schema", e);
        }
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

@Override
public void insertTopology(GungnirTopology topology) throws MetaStoreException, AlreadyStoredException {
    try {//from  w  w w .j a  v a 2s.c  om
        Date createTime = new Date();

        Document doc = new Document("name", topology.getName())
                .append("status", topology.getStatus().toString()).append("desc", Utils.serialize(topology))
                .append("owner", topology.getOwner().getId()).append("createTime", createTime);
        if (topology.getComment() != null) {
            doc.append("comment", topology.getComment());
        }
        topologyCollection.insertOne(doc);

        topology.setId(doc.getObjectId("_id").toString());
        topology.setCreateTime(createTime);

        LOG.info("Successful to insert topology '{}'", topology.getId());
    } catch (MongoException e) {
        if (e.getCode() == 11000) {
            throw new AlreadyStoredException(topology.getName() + " already exists");
        } else {
            LOG.error("Failed to insert topology", e);
            throw new MetaStoreException("Failed to insert topology", e);
        }
    }
}

From source file:org.gennai.gungnir.metastore.MongoDbMetaStore.java

License:Apache License

private void createTrackingNoSequence() throws MetaStoreException, AlreadyStoredException {
    try {//from   w  w  w.j  a v  a2s. c o m
        trackingCollection.insertOne(new Document("_id", "_tno").append("sequence", 0));
        LOG.info("Successful to create tracking no sequence");
    } catch (MongoException e) {
        if (e.getCode() == 11000) {
            throw new AlreadyStoredException("Tracking no sequence already exists");
        } else {
            LOG.error("Failed to create tracking no sequence", e);
            throw new MetaStoreException("Failed to create tracking no sequence", e);
        }
    }
}

From source file:org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider.java

License:LGPL

private DB extractDatabase(MongoClient mongo, MongoDBConfiguration config) {
    try {/*from  w w  w .j  a  va  2  s.  c om*/
        String databaseName = config.getDatabaseName();
        log.connectingToMongoDatabase(databaseName);

        Boolean containsDatabase;
        try {
            containsDatabase = mongo.getDatabaseNames().contains(databaseName);
        } catch (MongoException me) {
            // we don't have enough privileges, ignore the database creation
            containsDatabase = null;
        }

        if (containsDatabase != null && containsDatabase == Boolean.FALSE) {
            if (config.isCreateDatabase()) {
                log.creatingDatabase(databaseName);
            } else {
                throw log.databaseDoesNotExistException(config.getDatabaseName());
            }
        }
        DB db = mongo.getDB(databaseName);
        if (containsDatabase == null) {
            // force a connection to make sure we do have read access
            // otherwise the connection failure happens during the first flush
            db.collectionExists("WeDoNotCareWhatItIsWeNeedToConnect");
        }
        return mongo.getDB(databaseName);
    } catch (MongoException me) {
        switch (me.getCode()) {
        case AUTHENTICATION_FAILED_CODE:
            throw log.authenticationFailed(config.getUsername());
        default:
            throw log.unableToConnectToDatastore(config.getHost(), config.getPort(), me);
        }
    }
}

From source file:org.hibernate.ogm.datastore.mongodb.impl.MongoDBSchemaDefiner.java

License:LGPL

public void createIndex(DB database, MongoDBIndexSpec indexSpec) {
    DBCollection collection = database.getCollection(indexSpec.getCollection());
    Map<String, DBObject> preexistingIndexes = getIndexes(collection);
    String preexistingTextIndex = getPreexistingTextIndex(preexistingIndexes);

    // if a text index already exists in the collection, MongoDB silently ignores the creation of the new text index
    // so we might as well log a warning about it
    if (indexSpec.isTextIndex() && preexistingTextIndex != null
            && !preexistingTextIndex.equalsIgnoreCase(indexSpec.getIndexName())) {
        throw log.unableToCreateTextIndex(collection.getName(), indexSpec.getIndexName(), preexistingTextIndex);
    }/*  w  w  w  .  ja  v a  2s  . c o m*/

    try {
        // if the index is already present and with the same definition, MongoDB simply ignores the call
        // if the definition is not the same, MongoDB throws an error, except in the case of a text index
        // where it silently ignores the creation
        collection.createIndex(indexSpec.getIndexKeysDBObject(), indexSpec.getOptions());
    } catch (MongoException e) {
        String indexName = indexSpec.getIndexName();
        if (e.getCode() == INDEX_CREATION_ERROR_CODE && !StringHelper.isNullOrEmptyString(indexName)
                && preexistingIndexes.containsKey(indexName)) {
            // The index already exists with a different definition and has a name: we drop it and we recreate it
            collection.dropIndex(indexName);
            collection.createIndex(indexSpec.getIndexKeysDBObject(), indexSpec.getOptions());
        } else {
            throw log.unableToCreateIndex(collection.getName(), indexName, e);
        }
    }
}

From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java

License:Open Source License

@SuppressWarnings("finally")
private boolean countRawTarget(StatEvent event) throws StatsEngineException {
    boolean processed = false;
    try {/*w w w. j  ava 2  s  . c  o m*/
        BasicDBObject q = new BasicDBObject();
        q.put(EVENT_CLIENT_ID, event.getClientId());
        q.put(EVENT_TARGET, event.getTarget());
        q.put(EVENT_TARGET_TYPE, event.getTargetType());
        q.put(EVENT_ACTION, event.getAction());
        q.put(EVENT_DATE, event.getYearMonthDate().toDate());
        q.put(TARGET_YEAR, event.getYear());
        q.put(TARGET_MONTH, event.getMonth());

        BasicDBObject doc = new BasicDBObject();

        //BasicDBObject docSet = new BasicDBObject();
        doc.put("$addToSet", createAddToSetOwnersTagsDoc(event));
        BasicDBObject incDoc = new BasicDBObject();
        incDoc.put(FIELD_COUNT, 1); //Month count
        String metaBaseKey = "";
        TimeScope precision = getTimeScopePrecision();
        if (precision == TimeScope.DAILY || precision == TimeScope.HOURLY) {
            String dayKey = createDotPath(FIELD_DAYS, event.getDay());
            incDoc.put(createDotPath(dayKey, FIELD_COUNT), 1); //Day count
            if (precision == TimeScope.HOURLY) {
                String hourKey = createDotPath(dayKey, FIELD_HOURS, event.getHour());
                incDoc.put(createDotPath(hourKey, FIELD_COUNT), 1);//Hour count
                metaBaseKey = hourKey;
            } else {
                metaBaseKey = dayKey;
            }
        }
        //Count metadata
        Map<String, Object> metadata = event.getMetadata();
        for (String metaKey : metadata.keySet()) {
            incDoc.put(createDotPath(metaBaseKey, FIELD_META, metaKey,
                    metaKeyValue(metaKey, metadata.get(metaKey))), 1);
        }
        doc.put("$inc", incDoc);
        DBCollection targets = getTargetCollection(event, TimeScope.GLOBAL);
        //TODO externalize write concern to configuration properties:
        WriteResult wr = targets.update(q, doc, true, true, WriteConcern.FSYNC_SAFE);
        processed = wr.getN() > 0;
    } catch (MongoException ex) {
        int errorCode = ex.getCode();
        if (errorCode == ERROR_DUPKEY || errorCode == ERROR_DUPKEY_INSERT) {
            throw new DuplicateEventException("Duplicate event " + event);
        }
        throw new StatsEngineException("countRawTarget failed", ex);
    }
    return processed;
}