Java 类com.mongodb.MongoWriteException 实例源码

项目:rebase-server    文件:WebExceptionMapper.java   
@Override
public Response toResponse(final Exception exception) {
    Log.e(TAG, "[toResponse]" + exception.getMessage());
    if (exception instanceof WebApplicationException) {
        Response _response = ((WebApplicationException) exception).getResponse();
        return Response.fromResponse(_response)
            .entity(new Failure(_response.getStatusInfo().getReasonPhrase()))
            .build();

    } else if (exception instanceof MongoWriteException) {
        MongoWriteException _exception = (MongoWriteException) exception;
        return Response.status(BAD_REQUEST)
            .entity(new Failure(_exception.getError().getMessage()))
            .build();

    } else if (exception instanceof NullPointerException) {
        return Response.status(NOT_FOUND)
            .entity(new Failure(exception.getMessage()))
            .build();

    } else {
        return Response.status(BAD_REQUEST)
            .entity(new Failure(exception.getMessage()))
            .build();
    }
}
项目:Babler    文件:DAO.java   
/**
 * Saves an entry to file
 * @param entry
 * @param dbName usually scrapig
 * @return true if success
 */
public static boolean saveEntry(DBEntry entry, String dbName){

    if(entry == null || !entry.isValid())
        return false;

    Logger log = Logger.getLogger(DAO.class);

    MongoDatabase db = MongoDB.INSTANCE.getDatabase(dbName);

    String collectionName = getCollectionName(entry);


    MongoCollection collection = db.getCollection(collectionName,BasicDBObject.class);

    try {
        collection.insertOne(entry);
        return true;
    }
    catch (MongoWriteException ex){
        if (ex.getCode() != 11000) // Ignore errors about duplicates
            log.error(ex.getError().getMessage());
        return false;
    }

}
项目:mongo-obj-framework    文件:Smof.java   
/**
 * Inserts a new element in the database. The element's type must be mapped to an already
 * existent collection, otherwise {@link NoSuchCollection} will be thrown. If the element
 * already exists (i.e. a unique constraint is violated), mongoDB will throw an exception.
 * 
 * @param element element to insert
 */
@SuppressWarnings("unchecked")
public <T extends Element> boolean insert(T element) {
    Preconditions.checkArgument(element != null, "Cannot insert a null element");
    final SmofCollection<T> collection = (SmofCollection<T>) dispatcher.getCollection(element.getClass());
    final CollectionOptions<T> options = collection.getCollectionOptions();
    boolean success = false;
    try {
        success = dispatcher.insert(element);
    } catch(MongoWriteException e) {
        if(options.isThrowOnInsertDuplicate()) {
            parser.reset();
            throw e;
        }
    }
    parser.reset();
    return success;
}
项目:airvisprocessing    文件:AllParsersAir.java   
/**
 * removeDuplicate
 * by add a unique index
 */
private static void removeDuplicate(){
    MongoClient client = new MongoClient("127.0.0.1");
    MongoDatabase db = client.getDatabase("airvis");
    MongoCollection preprocess = db.getCollection("pm_preProcess");
    MongoCollection process = db.getCollection("pmProcess");
    IndexOptions option = new IndexOptions();
    option.unique(true);
    process.createIndex(new Document().append("time",1).append("code",1), option);
    MongoCursor cur = preprocess.find().iterator();

    while(cur.hasNext()){
        Document obj = (Document)cur.next();
        try {
            process.insertOne(obj);
        }catch(MongoWriteException e){
            //duplicate error
            System.out.println(obj.toString());
        }
    }
}
项目:airvisprocessing    文件:AllParsers.java   
/**
 * removeDuplicate
 * by add a unique index
 */
private static void removeDuplicate(){
    MongoClient client = new MongoClient("127.0.0.1");
    MongoDatabase db = client.getDatabase("pm");
    MongoCollection preprocess = db.getCollection("pm_preProcess");
    MongoCollection process = db.getCollection("pmProcess");
    IndexOptions option = new IndexOptions();
    option.unique(true);
    process.createIndex(new Document().append("time",1).append("code",1), option);
    MongoCursor cur = preprocess.find().iterator();

    while(cur.hasNext()){
        Document obj = (Document)cur.next();
        try {
            process.insertOne(obj);
        }catch(MongoWriteException e){
            //duplicate error
            System.out.println(obj.toString());
        }
    }
}
项目:mongobee    文件:LockDao.java   
public boolean acquireLock(MongoDatabase db) {

    Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD");

    // acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held)
    // there will be an exception
    try {
      db.getCollection(lockCollectionName).insertOne(insertObj);
    } catch (MongoWriteException ex) {
      if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
        logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired.");
      }
      return false;
    }
    return true;
  }
项目:epcis    文件:ChronoElement.java   
/**
 * Un-assigns a key/value property from the element. The object value of the
 * removed property is returned.
 *
 * @param key
 *            the key of the property to remove from the element
 * @return the object value associated with that key prior to removal. Should be
 *         instance of BsonValue
 */
@Override
public <T> T removeProperty(final String key) {
    try {
        BsonValue value = getProperty(key);
        BsonDocument filter = new BsonDocument();
        filter.put(Tokens.ID, new BsonString(this.id));
        BsonDocument update = new BsonDocument();
        update.put("$unset", new BsonDocument(key, new BsonNull()));
        if (this instanceof ChronoVertex) {
            graph.getVertexCollection().updateOne(filter, update, new UpdateOptions().upsert(true));
            return (T) value;
        } else {
            graph.getEdgeCollection().updateOne(filter, update, new UpdateOptions().upsert(true));
            return (T) value;
        }
    } catch (MongoWriteException e) {
        throw e;
    }
}
项目:Babler    文件:TestBlogPosts.java   
@Test(expected = MongoWriteException.class)
public void noDuplicatesAllowed() {
    String data = "this is a blog post !";
    String url = "http://www.columbia.edu";
    BlogPost post = new BlogPost(data,"tst",null,"source",url,"GUID231253423","");
    posts.insertOne(post);
    String data2 = "this is a blog post !";
    String url2 = "http://www.columbia.edu";
    BlogPost post2 = new BlogPost(data,"tst",null,"source",url,"GUID231253423","");
    posts.insertOne(post2);
}
项目:Babler    文件:TestTweets.java   
@Test(expected = MongoWriteException.class)
public void noDuplicatesAllowed() {
        String data = "this is a tweet !";
        String url = "http://www.columbia.edu";
        Tweet tweet = new Tweet(data,data,"tst","test",null,"topsy",url,"123456","filename");
        tweets.insertOne(tweet);
        String data2 = "this is a tweet !";
        String url2 = "http://www.columbia.edu";
        Tweet tweet2 = new Tweet(data2,data,"tst","test",null,"topsy",url2,"123456","filename");
        tweets.insertOne(tweet2);
    }
项目:restheart    文件:PutFileHandler.java   
@Override
public void handleRequest(
        HttpServerExchange exchange,
        RequestContext context)
        throws Exception {
    if (context.isInError()) {
        next(exchange, context);
        return;
    }

    final BsonValue _metadata = context.getContent();

    // must be an object
    if (!_metadata.isDocument()) {
        ResponseHelper.endExchangeWithMessage(
                exchange,
                context,
                HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        next(exchange, context);
        return;
    }

    BsonDocument metadata = _metadata.asDocument();

    BsonValue id = context.getDocumentId();

    if (metadata.get("_id") != null
            && metadata.get("_id").equals(id)) {
        ResponseHelper.endExchangeWithMessage(
                exchange,
                context,
                HttpStatus.SC_NOT_ACCEPTABLE,
                "_id in content body is different than id in URL");
        next(exchange, context);
        return;
    }

    metadata.put("_id", id);

    OperationResult result;

    try {
        if (context.getFilePath() != null) {
            result = gridFsDAO
                    .createFile(getDatabase(),
                            context.getDBName(),
                            context.getCollectionName(),
                            metadata,
                            context.getFilePath());
        } else {
            // throw new RuntimeException("error. file data is null");
            // try to pass to next handler in order to PUT new metadata on existing file.
            next(exchange, context);
            return;
        }
    } catch (IOException | RuntimeException t) {
        if (t instanceof MongoWriteException
                && ((MongoException) t).getCode() == 11000) {
            // update not supported
            String errMsg = "file resource update is not yet implemented";
            ResponseHelper.endExchangeWithMessage(
                    exchange,
                    context,
                    HttpStatus.SC_NOT_IMPLEMENTED,
                    errMsg);
            next(exchange, context);
            return;
        }

        throw t;
    }

    context.setDbOperationResult(result);

    context.setResponseStatusCode(result.getHttpCode());

    next(exchange, context);
}