Example usage for com.mongodb DBCollection getIndexInfo

List of usage examples for com.mongodb DBCollection getIndexInfo

Introduction

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

Prototype

public List<DBObject> getIndexInfo() 

Source Link

Document

Return a list of the indexes for this collection.

Usage

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@GET/* w ww .j  a  v a2s  .co  m*/
@Path("/databases/{dbName}/collections/{collName}/indexes")
@Override
public Response findIndexes(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                List<org.exoplatform.mongo.entity.response.Index> indexes = new ArrayList<org.exoplatform.mongo.entity.response.Index>();
                for (DBObject indexInfo : dbCollection.getIndexInfo()) {
                    String indexName = (String) indexInfo.get("name");
                    if (FILTERED_INDEX.equals(indexName)) {
                        continue;
                    }
                    org.exoplatform.mongo.entity.response.Index index = new org.exoplatform.mongo.entity.response.Index();
                    index.setName(indexName);
                    index.setCollectionName(collName);
                    index.setDbName(dbName);
                    index.setUnique((Boolean) indexInfo.get("unique"));
                    Map<String, Object> keys = (Map<String, Object>) indexInfo.get("key");
                    index.setKeys(keys.keySet());
                    indexes.add(index);
                }
                response = Response.ok(indexes).build();
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "findIndexes");
    }

    return response;
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@DELETE
@Path("/databases/{dbName}/collections/{collName}/indexes")
@Override//from w w  w  .j  av  a 2s .c o m
public Response deleteIndexes(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                List<DBObject> indexInfos = dbCollection.getIndexInfo();
                List<String> indexNames = new ArrayList<String>();
                for (DBObject indexInfo : indexInfos) {
                    String indexName = (String) indexInfo.get("name");
                    if (FILTERED_INDEX.equals(indexName)) {
                        continue;
                    }
                    indexNames.add(indexName);
                    dbCollection.dropIndex(indexName);
                }
                response = Response.ok("Deleted indexes: " + indexNames).build();
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "deleteIndexes");
    }

    return response;
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private org.exoplatform.mongo.entity.response.Collection searchCollection(String collName, String dbName,
        DB db) {// w w  w  .j  a  v a 2s  .  co m
    DBCollection dbCollection = db.getCollection(collName);
    org.exoplatform.mongo.entity.response.Collection collection = new org.exoplatform.mongo.entity.response.Collection();
    collection.setDbName(dbName);
    collection.setName(collName);
    collection.setWriteConcern(org.exoplatform.mongo.entity.response.WriteConcern
            .fromMongoWriteConcern(dbCollection.getWriteConcern()));
    List<DBObject> indexInfos = dbCollection.getIndexInfo();
    List<org.exoplatform.mongo.entity.response.Index> indexes = new ArrayList<org.exoplatform.mongo.entity.response.Index>();
    for (DBObject indexInfo : indexInfos) {
        Map<String, Object> indexed = (Map<String, Object>) indexInfo.get("key");
        if (indexed != null) {
            org.exoplatform.mongo.entity.response.Index index = new org.exoplatform.mongo.entity.response.Index();
            index.setDbName(dbName);
            index.setCollectionName(collName);
            index.setKeys(indexed.keySet());
            indexes.add(index);
        }
    }
    collection.setIndexes(indexes);
    List<org.exoplatform.mongo.entity.response.Document> documents = new ArrayList<org.exoplatform.mongo.entity.response.Document>();
    DBCursor cursor = dbCollection.find();
    while (cursor.hasNext()) {
        org.exoplatform.mongo.entity.response.Document document = new org.exoplatform.mongo.entity.response.Document();
        DBObject dbDoc = cursor.next();
        document.setJson(dbDoc.toString());
        documents.add(document);
    }
    collection.setDocuments(documents);
    return collection;
}

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

License:LGPL

private Map<String, DBObject> getIndexes(DBCollection collection) {
    List<DBObject> indexes = collection.getIndexInfo();
    Map<String, DBObject> indexMap = new HashMap<>();
    for (DBObject index : indexes) {
        indexMap.put(index.get("name").toString(), index);
    }/*from  w  w  w.java 2 s.co m*/
    return indexMap;
}

From source file:org.jmingo.JMingoTemplate.java

License:Apache License

/**
 * Gets all existing indexes for in the collection.
 *
 * @param collectionName the collection name to find indexes
 * @return indexes in the given collection
 *///from   w w w .  j a  va 2  s.c  o m
public List<DBObject> getIndexes(String collectionName) {
    Validate.notBlank(collectionName, "collectionName cannot be null or empty");
    DBCollection dbCollection = mongoDBFactory.getDB().getCollection(collectionName);
    return dbCollection.getIndexInfo();
}

From source file:org.jmingo.JMingoTemplate.java

License:Apache License

/**
 * Gets index by name.//from   w ww  .j a  v a2  s  . c o m
 *
 * @param collectionName the collection name
 * @param indexName      the index name
 * @return index or null if no indexes for the given name
 */
public DBObject getIndex(String collectionName, final String indexName) {
    DBObject index;
    Validate.notBlank(collectionName, "collectionName cannot be null or empty");
    Validate.notBlank(collectionName, "indexName cannot be null or empty");
    DBCollection dbCollection = mongoDBFactory.getDB().getCollection(collectionName);
    List<DBObject> dbObjects = dbCollection.getIndexInfo();
    index = Iterables
            .tryFind(dbObjects,
                    dbObject -> StringUtils.equalsIgnoreCase(dbObject.get("name").toString(), indexName))
            .orNull();
    return index;
}

From source file:org.mongeez.dao.impl.MongeezDaoImpl.java

License:Apache License

/**
 * Removes indices that were generated by versions before 0.9.3, since they're not supported by MongoDB 2.4+
 *///from   w  w  w  .  j  ava  2s.  c o  m
private void dropObsoleteChangeSetExecutionIndices() {
    String indexName = "type_changeSetExecution_file_1_changeId_1_author_1_resourcePath_1";
    DBCollection collection = getMongeezCollection();
    for (DBObject dbObject : collection.getIndexInfo()) {
        if (indexName.equals(dbObject.get("name"))) {
            collection.dropIndex(indexName);
        }
    }
}

From source file:org.pentaho.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Open Source License

public List<String> getIndexInfo(String dbName, String collection) throws MongoDbException {
    try {//from w  ww .j  a v a2  s .com
        DB db = getDb(dbName);

        if (db == null) {
            throw new MongoDbException(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.NonExistentDB", dbName)); //$NON-NLS-1$
        }

        if (Util.isEmpty(collection)) {
            throw new MongoDbException(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.NoCollectionSpecified")); //$NON-NLS-1$
        }

        if (!db.collectionExists(collection)) {
            db.createCollection(collection, null);
        }

        DBCollection coll = db.getCollection(collection);
        if (coll == null) {
            throw new MongoDbException(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.UnableToGetInfoForCollection", //$NON-NLS-1$
                            collection));
        }

        List<DBObject> collInfo = coll.getIndexInfo();
        List<String> result = new ArrayList<String>();
        if (collInfo == null || collInfo.size() == 0) {
            throw new MongoDbException(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.UnableToGetInfoForCollection", //$NON-NLS-1$
                            collection));
        }

        for (DBObject index : collInfo) {
            result.add(index.toString());
        }

        return result;
    } catch (Exception e) {
        log.error(BaseMessages.getString(PKG, "MongoNoAuthWrapper.ErrorMessage.GeneralError.Message") //$NON-NLS-1$
                + ":\n\n" + e.getMessage(), e); //$NON-NLS-1$
        if (e instanceof MongoDbException) {
            throw (MongoDbException) e;
        } else {
            throw new MongoDbException(e);
        }
    }
}

From source file:org.qi4j.entitystore.mongodb.MongoMapEntityStoreMixin.java

License:Apache License

@Override
public void activateService() throws Exception {
    loadConfiguration();/*from   w w w . j  a v a  2 s  .  com*/

    // Create Mongo driver and open the database
    mongo = new Mongo(serverAddresses);
    db = mongo.getDB(databaseName);

    // Authenticate if needed
    if (!username.isEmpty()) {
        if (!db.authenticate(username, password)) {
            LOGGER.warn("Authentication against MongoDB with username '" + username
                    + "' failed. Subsequent requests will be made 'anonymously'.");
        }
    }

    // Create index if needed
    db.requestStart();
    DBCollection entities = db.getCollection(collectionName);
    if (entities.getIndexInfo().isEmpty()) {
        entities.createIndex(new BasicDBObject(IDENTITY_COLUMN, 1));
    }
    db.requestDone();
}

From source file:org.slc.sli.ingestion.validation.indexes.DbIndexValidator.java

License:Apache License

protected static Set<MongoIndex> loadIndexInfoFromDB(DB database) {
    Set<MongoIndex> dbIndexes = new HashSet<MongoIndex>();

    Set<String> collectionNames = database.getCollectionNames();

    for (String collectionName : collectionNames) {
        DBCollection collection = database.getCollection(collectionName);
        List<DBObject> indexList = collection.getIndexInfo();
        for (DBObject dbObject : indexList) {
            DBObject keyObj = (DBObject) dbObject.get("key");
            Object uniqueField = dbObject.get("unique");
            Object sparseField = dbObject.get("sparse");
            boolean unique = false;
            boolean sparse = false;
            if (sparseField != null) {
                sparse = Boolean.parseBoolean(sparseField.toString());
            }/*from   www  . ja v a2  s  .  c om*/
            if (uniqueField != null) {
                unique = Boolean.parseBoolean(uniqueField.toString());
            }
            dbIndexes.add(new MongoIndex(collectionName, unique, keyObj, sparse));
        }
    }
    return dbIndexes;
}