List of usage examples for com.mongodb DBCollection getIndexInfo
public List<DBObject> getIndexInfo()
From source file:net.autosauler.ballance.server.model.Scripts.java
License:Apache License
/** * Inits the struct./*from w w w.ja va 2s. co m*/ */ private void initStruct() { DB db = Database.get(domain); if (db != null) { Database.retain(); DBCollection coll = db.getCollection(TABLENAME); List<DBObject> indexes = coll.getIndexInfo(); if (indexes.size() < 1) { BasicDBObject i = new BasicDBObject(); i.put("domain", 1); i.put("name", 1); coll.createIndex(i); } Database.release(); } }
From source file:net.kamradtfamily.mongorest.IndexServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doGet()"); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return;/*from w ww . ja v a 2s . com*/ } DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); List<DBObject> info = col.getIndexInfo(); out_json(req, info); }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoUtils.java
License:Apache License
/** * Returns {@code true} if there is an index on the given fields, * {@code false} otherwise. If multiple fields are passed, this method * check if there a compound index on those field. This method does not * check the sequence of fields for a compound index. That is, this method * will return {@code true} as soon as it finds an index that covers the * given fields, no matter their sequence in the compound index. * * @param collection the collection.//w w w . j a v a2 s. com * @param fields the fields of an index. * @return {@code true} if the index exists, {@code false} otherwise. * @throws MongoException if the operation fails. */ static boolean hasIndex(DBCollection collection, String... fields) throws MongoException { Set<String> uniqueFields = Sets.newHashSet(fields); for (DBObject info : collection.getIndexInfo()) { DBObject key = (DBObject) info.get("key"); Set<String> indexFields = Sets.newHashSet(key.keySet()); if (uniqueFields.equals(indexFields)) { return true; } } return false; }
From source file:org.bigmouth.nvwa.log4mongo.MongoDbAppender.java
License:Apache License
public static boolean isExistsIndex(DBCollection dbCollection, String indexName) { List<DBObject> indexes = dbCollection.getIndexInfo(); for (DBObject obj : indexes) { Object value = obj.get("name"); if (StringUtils.equals(String.valueOf(value), indexName)) { return true; }/*from ww w . ja va 2s .com*/ } return false; }
From source file:org.chililog.server.data.RepositoryConfigController.java
License:Apache License
/** * Creates the required repository index * //from w w w . j a v a 2s . c om * @param db * Database connection */ private void createIndexes(DB db) { DBCollection col = db.getCollection(this.getDBCollectionName()); List<DBObject> indexes = col.getIndexInfo(); boolean found = false; for (DBObject idx : indexes) { if (idx.get("name").equals("keyword_ts_index")) { found = true; break; } } if (!found) { BasicDBObject keys = new BasicDBObject(); keys.put(RepositoryEntryBO.KEYWORDS_FIELD_NAME, 1); keys.put(RepositoryEntryBO.TIMESTAMP_FIELD_NAME, 1); col.ensureIndex(keys, "keyword_ts_index"); } }
From source file:org.datanucleus.store.mongodb.MongoDBSchemaHandler.java
License:Open Source License
@Override public void validateSchema(Set<String> classNames, Properties props, Object connection) { boolean success = true; DB db = (DB) connection;/*from w w w.ja v a2 s . c o m*/ ManagedConnection mconn = null; try { if (db == null) { mconn = storeMgr.getConnection(-1); db = (DB) mconn.getConnection(); } Iterator<String> classIter = classNames.iterator(); ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null); while (classIter.hasNext()) { String className = classIter.next(); AbstractClassMetaData cmd = storeMgr.getMetaDataManager().getMetaDataForClass(className, clr); if (cmd != null) { // Validate the schema for the class StoreData storeData = storeMgr.getStoreDataForClass(cmd.getFullClassName()); Table table = null; if (storeData != null) { table = storeData.getTable(); } else { table = new CompleteClassTable(storeMgr, cmd, null); } String tableName = table.getName(); if (!db.collectionExists(tableName)) { success = false; String msg = Localiser.msg("MongoDB.SchemaValidate.Class", cmd.getFullClassName(), tableName); System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); continue; } String msg = "Table for class=" + cmd.getFullClassName() + " with name=" + tableName + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); DBCollection dbColl = db.getCollection(tableName); List<DBObject> indices = new ArrayList(dbColl.getIndexInfo()); IndexMetaData[] idxmds = cmd.getIndexMetaData(); if (idxmds != null && idxmds.length > 0) { for (int i = 0; i < idxmds.length; i++) { DBObject idxObj = getDBObjectForIndex(cmd, idxmds[i], table); DBObject indexObj = getIndexObjectForIndex(indices, idxmds[i].getName(), idxObj, true); if (indexObj != null) { indices.remove(indexObj); msg = "Index for class=" + cmd.getFullClassName() + " with name=" + idxmds[i].getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; msg = "Index missing for class=" + cmd.getFullClassName() + " name=" + idxmds[i].getName() + " key=" + idxObj; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } UniqueMetaData[] unimds = cmd.getUniqueMetaData(); if (unimds != null && unimds.length > 0) { for (int i = 0; i < unimds.length; i++) { DBObject uniObj = getDBObjectForUnique(cmd, unimds[i], table); DBObject indexObj = getIndexObjectForIndex(indices, unimds[i].getName(), uniObj, true); if (indexObj != null) { indices.remove(indexObj); msg = "Unique index for class=" + cmd.getFullClassName() + " with name=" + unimds[i].getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; msg = "Unique index missing for class=" + cmd.getFullClassName() + " name=" + unimds[i].getName() + " key=" + uniObj; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } if (cmd.getIdentityType() == IdentityType.APPLICATION) { // Check unique index on PK BasicDBObject query = new BasicDBObject(); int[] pkFieldNumbers = cmd.getPKMemberPositions(); for (int i = 0; i < pkFieldNumbers.length; i++) { AbstractMemberMetaData pkMmd = cmd .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]); Column[] cols = table.getMemberColumnMappingForMember(pkMmd).getColumns(); String colName = cols[0].getName(); query.append(colName, 1); // TODO Support multicolumn PK field } String pkName = (cmd.getPrimaryKeyMetaData() != null ? cmd.getPrimaryKeyMetaData().getName() : cmd.getName() + "_PK"); // TODO Do through NamingFactory DBObject indexObj = getIndexObjectForIndex(indices, pkName, query, true); if (indexObj != null) { indices.remove(indexObj); msg = "Index for application-identity with name=" + pkName + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; msg = "Index missing for application id name=" + pkName + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } else if (cmd.getIdentityType() == IdentityType.DATASTORE) { if (storeMgr.isStrategyDatastoreAttributed(cmd, -1)) { // Using builtin "_id" field so nothing to do } else { // Check unique index on PK BasicDBObject query = new BasicDBObject(); query.append(table.getDatastoreIdColumn().getName(), 1); String pkName = (cmd.getPrimaryKeyMetaData() != null ? cmd.getPrimaryKeyMetaData().getName() : cmd.getName() + "_PK"); DBObject indexObj = getIndexObjectForIndex(indices, pkName, query, true); if (indexObj != null) { indices.remove(indexObj); msg = "Index for datastore-identity with name=" + pkName + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; msg = "Index missing for datastore id name=" + pkName + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } AbstractMemberMetaData[] mmds = cmd.getManagedMembers(); if (mmds != null && mmds.length > 0) { for (int i = 0; i < mmds.length; i++) { IndexMetaData idxmd = mmds[i].getIndexMetaData(); if (idxmd != null) { Column[] cols = table.getMemberColumnMappingForMember(mmds[i]).getColumns(); // TODO Check for embedded fields BasicDBObject query = new BasicDBObject(); query.append(cols[0].getName(), 1); DBObject indexObj = getIndexObjectForIndex(indices, idxmd.getName(), query, true); if (indexObj != null) { msg = "Index for field=" + mmds[i].getFullFieldName() + " with name=" + idxmd.getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); indices.remove(indexObj); } else { success = false; msg = "Index missing for field=" + mmds[i].getFullFieldName() + " name=" + idxmd.getName() + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } UniqueMetaData unimd = mmds[i].getUniqueMetaData(); if (unimd != null) { Column[] cols = table.getMemberColumnMappingForMember(mmds[i]).getColumns(); // TODO Check for embedded fields BasicDBObject query = new BasicDBObject(); query.append(cols[0].getName(), 1); DBObject indexObj = getIndexObjectForIndex(indices, unimd.getName(), query, true); if (indexObj != null) { msg = "Unique index for field=" + mmds[i].getFullFieldName() + " with name=" + unimd.getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); indices.remove(indexObj); } else { success = false; msg = "Unique index missing for field=" + mmds[i].getFullFieldName() + " name=" + unimd.getName() + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } } // TODO Could extend this and check that we account for all MongoDB generated indices too } } } finally { if (mconn != null) { mconn.release(); } } if (!success) { throw new NucleusException("Errors were encountered during validation of MongoDB schema"); } }
From source file:org.datanucleus.store.mongodb.MongoDBStoreManager.java
License:Open Source License
public void validateSchema(Set<String> classNames, Properties props) { boolean success = true; ManagedConnection mconn = getConnection(-1); try {/*from w w w . j ava 2 s . c om*/ DB db = (DB) mconn.getConnection(); Iterator<String> classIter = classNames.iterator(); ClassLoaderResolver clr = nucleusContext.getClassLoaderResolver(null); while (classIter.hasNext()) { String className = classIter.next(); AbstractClassMetaData cmd = getMetaDataManager().getMetaDataForClass(className, clr); if (cmd != null) { // Validate the schema for the class String tableName = getNamingFactory().getTableName(cmd); if (!db.collectionExists(tableName)) { success = false; String msg = "Table doesn't exist for " + cmd.getFullClassName() + " - should have name=" + tableName; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); continue; } else { String msg = "Table for class=" + cmd.getFullClassName() + " with name=" + tableName + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } DBCollection table = db.getCollection(tableName); List<DBObject> indices = new ArrayList(table.getIndexInfo()); IndexMetaData[] idxmds = cmd.getIndexMetaData(); if (idxmds != null && idxmds.length > 0) { for (int i = 0; i < idxmds.length; i++) { DBObject idxObj = getDBObjectForIndex(cmd, idxmds[i]); DBObject indexObj = getIndexObjectForIndex(indices, idxmds[i].getName(), idxObj, true); if (indexObj != null) { indices.remove(indexObj); String msg = "Index for class=" + cmd.getFullClassName() + " with name=" + idxmds[i].getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; String msg = "Index missing for class=" + cmd.getFullClassName() + " name=" + idxmds[i].getName() + " key=" + idxObj; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } UniqueMetaData[] unimds = cmd.getUniqueMetaData(); if (unimds != null && unimds.length > 0) { for (int i = 0; i < unimds.length; i++) { DBObject uniObj = getDBObjectForUnique(cmd, unimds[i]); DBObject indexObj = getIndexObjectForIndex(indices, unimds[i].getName(), uniObj, true); if (indexObj != null) { indices.remove(indexObj); String msg = "Unique index for class=" + cmd.getFullClassName() + " with name=" + unimds[i].getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; String msg = "Unique index missing for class=" + cmd.getFullClassName() + " name=" + unimds[i].getName() + " key=" + uniObj; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } if (cmd.getIdentityType() == IdentityType.APPLICATION) { // Check unique index on PK BasicDBObject query = new BasicDBObject(); int[] pkFieldNumbers = cmd.getPKMemberPositions(); for (int i = 0; i < pkFieldNumbers.length; i++) { AbstractMemberMetaData pkMmd = cmd .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]); query.append(getNamingFactory().getColumnName(pkMmd, ColumnType.COLUMN), 1); } String pkName = (cmd.getPrimaryKeyMetaData() != null ? cmd.getPrimaryKeyMetaData().getName() : cmd.getName() + "_PK"); DBObject indexObj = getIndexObjectForIndex(indices, pkName, query, true); if (indexObj != null) { indices.remove(indexObj); String msg = "Index for application-identity with name=" + pkName + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; String msg = "Index missing for application id name=" + pkName + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } else if (cmd.getIdentityType() == IdentityType.DATASTORE) { if (isStrategyDatastoreAttributed(cmd, -1)) { // Using builtin "_id" field so nothing to do } else { // Check unique index on PK BasicDBObject query = new BasicDBObject(); query.append(getNamingFactory().getColumnName(cmd, ColumnType.DATASTOREID_COLUMN), 1); String pkName = (cmd.getPrimaryKeyMetaData() != null ? cmd.getPrimaryKeyMetaData().getName() : cmd.getName() + "_PK"); DBObject indexObj = getIndexObjectForIndex(indices, pkName, query, true); if (indexObj != null) { indices.remove(indexObj); String msg = "Index for datastore-identity with name=" + pkName + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); } else { success = false; String msg = "Index missing for datastore id name=" + pkName + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } AbstractMemberMetaData[] mmds = cmd.getManagedMembers(); if (mmds != null && mmds.length > 0) { for (int i = 0; i < mmds.length; i++) { IndexMetaData idxmd = mmds[i].getIndexMetaData(); if (idxmd != null) { BasicDBObject query = new BasicDBObject(); query.append(getNamingFactory().getColumnName(mmds[i], ColumnType.COLUMN), 1); DBObject indexObj = getIndexObjectForIndex(indices, idxmd.getName(), query, true); if (indexObj != null) { String msg = "Index for field=" + mmds[i].getFullFieldName() + " with name=" + idxmd.getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); indices.remove(indexObj); } else { success = false; String msg = "Index missing for field=" + mmds[i].getFullFieldName() + " name=" + idxmd.getName() + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } UniqueMetaData unimd = mmds[i].getUniqueMetaData(); if (unimd != null) { BasicDBObject query = new BasicDBObject(); query.append(getNamingFactory().getColumnName(mmds[i], ColumnType.COLUMN), 1); DBObject indexObj = getIndexObjectForIndex(indices, unimd.getName(), query, true); if (indexObj != null) { String msg = "Unique index for field=" + mmds[i].getFullFieldName() + " with name=" + unimd.getName() + " validated"; NucleusLogger.DATASTORE_SCHEMA.info(msg); indices.remove(indexObj); } else { success = false; String msg = "Unique index missing for field=" + mmds[i].getFullFieldName() + " name=" + unimd.getName() + " key=" + query; System.out.println(msg); NucleusLogger.DATASTORE_SCHEMA.error(msg); } } } } // TODO Could extend this and check that we account for all MongoDB generated indices too } } } finally { mconn.release(); } if (!success) { throw new NucleusException("Errors were encountered during validation of MongoDB schema"); } }
From source file:org.eclipse.emf.cdo.server.internal.mongodb.MongoDBBrowserPage.java
License:Open Source License
protected void showIndexes(CDOServerBrowser browser, PrintStream pout, DBCollection coll) { pout.print("<tr><td colspan=\"2\" align=\"center\" bgcolor=\"EEEEEE\"><h4>Indexes</h4></td></tr>\r\n"); int i = 0;/*from www. j a v a 2s .c om*/ for (DBObject index : coll.getIndexInfo()) { ++i; String bg = (i & 1) == 1 ? "bgcolor=\"DDDDDD\"" : "bgcolor=\"EEEEEE\""; pout.print("<tr><td valign=\"top\" " + bg + "><b>" + i + " </b></td><td valign=\"top\">"); showObject(browser, pout, index, ""); pout.print("</td></tr>\r\n"); } }
From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @GET//from w w w. ja v a 2 s. com @Path("/databases/{dbName}/collections/{collName}/indexes/{indexName}") @Override public Response findIndex(@PathParam("dbName") String dbName, @PathParam("collName") String collName, @PathParam("indexName") String indexName, @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(); boolean indexFound = false; org.exoplatform.mongo.entity.response.Index foundIndex = new org.exoplatform.mongo.entity.response.Index(); for (DBObject indexInfo : indexInfos) { String foundIndexName = (String) indexInfo.get("name"); if (foundIndexName.equals(indexName)) { Map<String, Object> keys = (Map<String, Object>) indexInfo.get("key"); foundIndex.setName(indexName); foundIndex.setCollectionName(collName); foundIndex.setDbName(dbName); foundIndex.setKeys(keys.keySet()); foundIndex.setUnique((Boolean) indexInfo.get("unique")); indexFound = true; break; } } if (indexFound) { response = Response.ok(foundIndex).build(); } else { response = Response.status(ClientError.NOT_FOUND.code()) .entity(indexName + " does not exist for " + collName).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, "findIndex"); } return response; }
From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java
License:Open Source License
@DELETE @Path("/databases/{dbName}/collections/{collName}/indexes/{indexName}") @Override//from ww w . j a v a2 s .co m public Response deleteIndex(@PathParam("dbName") String dbName, @PathParam("collName") String collName, @PathParam("indexName") String indexName, @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(); boolean indexFound = false; for (DBObject indexInfo : indexInfos) { String foundIndexName = (String) indexInfo.get("name"); if (foundIndexName.equals(indexName)) { indexFound = true; dbCollection.dropIndex(indexName); break; } } if (indexFound) { response = Response.ok().build(); } else { response = Response.status(ClientError.NOT_FOUND.code()) .entity(indexName + " does not exist for " + collName).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, "deleteIndex"); } return response; }