List of usage examples for com.mongodb DBCollection getFullName
public String getFullName()
From source file:com.impetus.client.mongodb.MongoDBClient.java
License:Apache License
/** * On collections flush.//from w w w .ja va 2s. co m * * @param collections * collection containing records to be inserted in mongo db. */ private void onFlushCollection(Map<String, List<DBObject>> collections) { for (String tableName : collections.keySet()) { DBCollection dbCollection = mongoDb.getCollection(tableName); KunderaCoreUtils.printQuery("Persist collection:" + tableName, showQuery); try { dbCollection.insert(collections.get(tableName).toArray(new DBObject[0]), getWriteConcern(), encoder); } catch (MongoException ex) { throw new KunderaException( "document is not inserted in " + dbCollection.getFullName() + " collection. Caused By:", ex); } } }
From source file:com.impetus.client.mongodb.MongoDBClient.java
License:Apache License
/** * Creates the unique index gfs.//from w w w.java 2 s. c o m * * @param coll * the coll * @param id * the id */ private void createUniqueIndexGFS(DBCollection coll, String id) { try { coll.createIndex(new BasicDBObject("metadata." + id, 1), new BasicDBObject("unique", true)); } catch (MongoException ex) { throw new KunderaException("Error in creating unique indexes in " + coll.getFullName() + " collection on " + id + " field"); } }
From source file:com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager.java
License:Apache License
private void createUniqueIndexGFS(DBCollection coll, String id) { try {//from www.ja v a 2 s . c om coll.createIndex(new BasicDBObject("metadata." + id, 1), new BasicDBObject("unique", true)); } catch (MongoException ex) { throw new KunderaException("Error in creating unique indexes in " + coll.getFullName() + " collection on " + id + " field"); } }
From source file:com.redhat.lightblue.mongo.crud.MongoSequenceGenerator.java
License:Open Source License
public MongoSequenceGenerator(DBCollection coll) { this.coll = coll; if (!initializedCollections.contains(coll.getFullName())) { // Here, we also make sure we have the indexes setup properly initIndex();//from w w w . j ava 2s . c om initializedCollections.add(coll.getFullName()); LOGGER.info("Initialized sequances collection {}", coll.getFullName()); } }
From source file:com.softinstigate.restheart.db.CollectionDAO.java
License:Open Source License
/** * Upsert the collection properties./*from w w w. j a v a2 s . c om*/ * * @param dbName the database name of the collection * @param collName the collection name * @param content the new collection properties * @param etag the entity tag. must match to allow actual write (otherwise * http error code is returned) * @param updating true if updating existing document * @param patching true if use patch semantic (update only specified fields) * @return the HttpStatus code to set in the http response */ public static int upsertCollection(String dbName, String collName, DBObject content, ObjectId etag, boolean updating, boolean patching) { DB db = DBDAO.getDB(dbName); DBCollection coll = db.getCollection(collName); if (patching && !updating) { return HttpStatus.SC_NOT_FOUND; } if (updating) { if (etag == null) { return HttpStatus.SC_CONFLICT; } BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties"); idAndEtagQuery.append("_etag", etag); if (coll.count(idAndEtagQuery) < 1) { return HttpStatus.SC_PRECONDITION_FAILED; } } ObjectId timestamp = new ObjectId(); Instant now = Instant.ofEpochSecond(timestamp.getTimestamp()); if (content == null) { content = new BasicDBObject(); } content.removeField("_id"); // make sure we don't change this field if (updating) { content.removeField("_crated_on"); // don't allow to update this field content.put("_etag", timestamp); } else { content.put("_id", "_properties"); content.put("_created_on", now.toString()); content.put("_etag", timestamp); } if (patching) { coll.update(PROPS_QUERY, new BasicDBObject("$set", content), true, false); return HttpStatus.SC_OK; } else { // we use findAndModify to get the @created_on field value from the existing properties document // we need to put this field back using a second update // it is not possible in a single update even using $setOnInsert update operator // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) DBObject old = coll.findAndModify(PROPS_QUERY, fieldsToReturn, null, false, content, false, true); if (old != null) { Object oldTimestamp = old.get("_created_on"); if (oldTimestamp == null) { oldTimestamp = now.toString(); logger.warn("properties of collection {} had no @created_on field. set to now", coll.getFullName()); } // need to readd the @created_on field BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp); createdContet.markAsPartialObject(); coll.update(PROPS_QUERY, new BasicDBObject("$set", createdContet), true, false); return HttpStatus.SC_OK; } else { // need to readd the @created_on field BasicDBObject createdContet = new BasicDBObject("_created_on", now.toString()); createdContet.markAsPartialObject(); coll.update(PROPS_QUERY, new BasicDBObject("$set", createdContet), true, false); initDefaultIndexes(coll); return HttpStatus.SC_CREATED; } } }
From source file:com.softinstigate.restheart.db.DBDAO.java
License:Open Source License
/** * * @param dbName//from w ww .j a v a 2 s. co m * @param content * @param etag * @param patching * @return */ public static int upsertDB(String dbName, DBObject content, ObjectId etag, boolean patching) { DB db = client.getDB(dbName); boolean existing = db.getCollectionNames().size() > 0; if (patching && !existing) { return HttpStatus.SC_NOT_FOUND; } DBCollection coll = db.getCollection("_properties"); // check the etag if (db.collectionExists("_properties")) { if (etag == null) { return HttpStatus.SC_CONFLICT; } BasicDBObject idAndEtagQuery = new BasicDBObject("_id", "_properties"); idAndEtagQuery.append("_etag", etag); if (coll.count(idAndEtagQuery) < 1) { return HttpStatus.SC_PRECONDITION_FAILED; } } // apply new values ObjectId timestamp = new ObjectId(); Instant now = Instant.ofEpochSecond(timestamp.getTimestamp()); if (content == null) { content = new BasicDBObject(); } content.put("_etag", timestamp); content.removeField("_created_on"); // make sure we don't change this field content.removeField("_id"); // make sure we don't change this field if (patching) { coll.update(METADATA_QUERY, new BasicDBObject("$set", content), true, false); return HttpStatus.SC_OK; } else { // we use findAndModify to get the @created_on field value from the existing document // we need to put this field back using a second update // it is not possible in a single update even using $setOnInsert update operator // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) DBObject old = coll.findAndModify(METADATA_QUERY, fieldsToReturn, null, false, content, false, true); if (old != null) { Object oldTimestamp = old.get("_created_on"); if (oldTimestamp == null) { oldTimestamp = now.toString(); logger.warn("properties of collection {} had no @created_on field. set to now", coll.getFullName()); } // need to readd the @created_on field BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp); createdContet.markAsPartialObject(); coll.update(METADATA_QUERY, new BasicDBObject("$set", createdContet), true, false); return HttpStatus.SC_OK; } else { // need to readd the @created_on field BasicDBObject createdContet = new BasicDBObject("_created_on", now.toString()); createdContet.markAsPartialObject(); coll.update(METADATA_QUERY, new BasicDBObject("$set", createdContet), true, false); return HttpStatus.SC_CREATED; } } }
From source file:com.softlyinspired.jlw.concerns.concernSet.java
License:Open Source License
public String[][] listall() { String concernText = new String(); String concernList[][] = new String[100][4]; try {/*from www . j a va2s . c o m*/ DBCollection coll = repoConnection.getConcernCollection(); DBObject doc; String[] scriptHeader = new String[3]; try { DBCursor allConcerns = coll.find(); concernCount = allConcerns.count(); for (int i = 0; i < (concernCount); i++) { doc = allConcerns.next(); scriptHeader = getDetails(doc); concernList[i][0] = scriptHeader[0]; concernList[i][1] = scriptHeader[1]; concernList[i][2] = scriptHeader[2]; concernList[i][3] = scriptHeader[3]; } } catch (Exception e) { concernText = "No concerns have yet been defined " + coll.getFullName(); JOptionPane.showMessageDialog(null, concernText, "Error", JOptionPane.PLAIN_MESSAGE); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString(), "Error", JOptionPane.PLAIN_MESSAGE); } return concernList; }
From source file:com.tomtom.speedtools.mongodb.checkdb.CheckDBBase.java
License:Apache License
/** * Execute all checks./*from ww w.j a v a2s . co m*/ * * @param checkAllCollections Used to check collection. * @return Problem report. */ @Nonnull public Report checkAllCollectionsInQueue(final Runnable checkAllCollections) { if (!migrateDB.checkCurrentVersion(db)) { LOG.error(""); LOG.error("The database does not have the right version (or may be empty)!"); final DBCollection collection = db.getCollection(MongoDBMigrator.MIGRATOR_COLLECTION_NAME); errors.add(new Error(new Uid("0-0-0-0-0"), collection.getFullName(), "Incorrect version or empty database", null)); } LOG.info("Checking all collections; all errors are collected and shown at end of run"); workQueue = new WorkQueue(MAX_QUEUE_SIZE); try { checkAllCollections.run(); assert workQueue.isEmptyAndFinished(); } catch (final AssertionError e) { LOG.error("Unexpected assertion error encountered.", e); throw e; } catch (final Exception e) { LOG.error("Unexpected exception encountered.", e); internalErrors.add("Unexpected exception encountered: " + e.getMessage()); } finally { workQueue.scheduleShutdown(); for (final Exception e : workQueue.getExceptions()) { internalErrors.add("Exceptions found: " + e.getMessage()); } } if (!internalErrors.isEmpty()) { LOG.error(""); LOG.error("The following fields were never checked in CheckDB:"); for (final String line : internalErrors) { LOG.error(" {}", line); } LOG.error(""); LOG.error("CheckDB has not been updated after a domain model change!"); LOG.error(""); } return new Report(nrTotalChecks.get(), nrTotalCollections, nrTotalRecords, errors, warnings, !internalErrors.isEmpty()); }
From source file:com.tomtom.speedtools.mongodb.checkdb.CheckDBBase.java
License:Apache License
public void showProgressCollectionStart(@Nonnull final DBCollection collection, final int count) { assert collection != null; LOG.debug(""); LOG.debug("{}:", collection.getFullName()); LOG.info(" | 0% -- processed 0 of {} records ({} errors and {} warnings found so far) - {}", count, errors.size(), warnings.size(), errors.isEmpty() ? "OK" : "not OK"); }
From source file:com.zjy.mongo.splitter.StandaloneMongoSplitter.java
License:Apache License
@Override public List<InputSplit> calculateSplits() throws SplitFailedException { final DBObject splitKey = MongoConfigUtil.getInputSplitKey(getConfiguration()); final DBObject splitKeyMax = MongoConfigUtil.getMaxSplitKey(getConfiguration()); final DBObject splitKeyMin = MongoConfigUtil.getMinSplitKey(getConfiguration()); final int splitSize = MongoConfigUtil.getSplitSize(getConfiguration()); final MongoClientURI inputURI; DBCollection inputCollection = null; final ArrayList<InputSplit> returnVal; try {// ww w. j a v a 2s .c o m inputURI = MongoConfigUtil.getInputURI(getConfiguration()); MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration()); if (authURI != null) { inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI); } else { inputCollection = MongoConfigUtil.getCollection(inputURI); } returnVal = new ArrayList<InputSplit>(); final String ns = inputCollection.getFullName(); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Running splitVector on namespace: %s.%s; hosts: %s", inputURI.getDatabase(), inputURI.getCollection(), inputURI.getHosts())); } final DBObject cmd = BasicDBObjectBuilder.start("splitVector", ns).add("keyPattern", splitKey) .add("min", splitKeyMin).add("max", splitKeyMax) // force:True is misbehaving it seems .add("force", false).add("maxChunkSize", splitSize).get(); CommandResult data; boolean ok = true; try { data = inputCollection.getDB().getSisterDB(inputURI.getDatabase()).command(cmd, ReadPreference.primary()); } catch (final MongoException e) { // 2.0 servers throw exceptions rather than info in a CommandResult data = null; LOG.info(e.getMessage(), e); if (e.getMessage().contains("unrecognized command: splitVector")) { ok = false; } else { throw e; } } if (data != null) { if (data.containsField("$err")) { throw new SplitFailedException("Error calculating splits: " + data); } else if (!data.get("ok").equals(1.0)) { ok = false; } } if (!ok) { final CommandResult stats = inputCollection.getStats(); if (stats.containsField("primary")) { final DBCursor shards = inputCollection.getDB().getSisterDB("config").getCollection("shards") .find(new BasicDBObject("_id", stats.getString("primary"))); try { if (shards.hasNext()) { final DBObject shard = shards.next(); final String host = ((String) shard.get("host")).replace(shard.get("_id") + "/", ""); final MongoClientURI shardHost; if (authURI != null) { shardHost = new MongoClientURIBuilder(authURI).host(host).build(); } else { shardHost = new MongoClientURIBuilder(inputURI).host(host).build(); } MongoClient shardClient = null; try { shardClient = new MongoClient(shardHost); data = shardClient.getDB(shardHost.getDatabase()).command(cmd, ReadPreference.primary()); } catch (final Exception e) { LOG.error(e.getMessage(), e); } finally { if (shardClient != null) { shardClient.close(); } } } } finally { shards.close(); } } if (data != null && !data.get("ok").equals(1.0)) { throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg")); } } // Comes in a format where "min" and "max" are implicit // and each entry is just a boundary key; not ranged final BasicDBList splitData = (BasicDBList) data.get("splitKeys"); if (splitData.size() == 0) { LOG.warn( "WARNING: No Input Splits were calculated by the split code. Proceeding with a *single* split. Data may be too" + " small, try lowering 'mongo.input.split_size' if this is undesirable."); } BasicDBObject lastKey = null; // Lower boundary of the first min split // If splitKeyMin was given, use it as first boundary. if (!splitKeyMin.toMap().isEmpty()) { lastKey = new BasicDBObject(splitKeyMin.toMap()); } for (final Object aSplitData : splitData) { final BasicDBObject currentKey = (BasicDBObject) aSplitData; returnVal.add(createSplitFromBounds(lastKey, currentKey)); lastKey = currentKey; } BasicDBObject maxKey = null; // If splitKeyMax was given, use it as last boundary. if (!splitKeyMax.toMap().isEmpty()) { maxKey = new BasicDBObject(splitKeyMax.toMap()); } // Last max split final MongoInputSplit lastSplit = createSplitFromBounds(lastKey, maxKey); returnVal.add(lastSplit); } finally { if (inputCollection != null) { MongoConfigUtil.close(inputCollection.getDB().getMongo()); } } return returnVal; }