Example usage for com.mongodb WriteConcern NORMAL

List of usage examples for com.mongodb WriteConcern NORMAL

Introduction

In this page you can find the example usage for com.mongodb WriteConcern NORMAL.

Prototype

WriteConcern NORMAL

To view the source code for com.mongodb WriteConcern NORMAL.

Click Source Link

Document

Write operations that use this write concern will return as soon as the message is written to the socket.

Usage

From source file:HAL.libraries.blackboard_client.BlackboardClient.java

License:Open Source License

/**
 * Inserts a number of documents into the currently selected collection.
 * Does not wait for the server to perform write to disk, nor does it check for errors other than networks errors.
 *
 * @param objs DBObjects that should be inserted into the database.
 * @throws InvalidDBNamespaceException No collection has been selected.
 * @throws GeneralMongoException A MongoException occurred.
 **///from  w w  w .  j a v a2s.  com
public void insertDocumentsUnsafe(DBObject... objs) throws InvalidDBNamespaceException, GeneralMongoException {
    if (currentCollection == null) {
        throw new InvalidDBNamespaceException("No collection has been selected.");
    }
    try {
        WriteConcern oldConcern = currentCollection.getWriteConcern();
        currentCollection.setWriteConcern(WriteConcern.NORMAL);
        currentCollection.insert(objs);
        currentCollection.setWriteConcern(oldConcern);
    } catch (MongoException mongoException) {
        throw new GeneralMongoException("An error occurred attempting to insert.", mongoException);
    }
}

From source file:HAL.libraries.blackboard_client.BlackboardClient.java

License:Open Source License

/**
 * Removes all documents matching the provided query from the currently selected collection.
 * Does not wait for the server to perform write to disk, nor does it check for errors other than networks errors.
 *
 * @param query DBObject representing the query used for deleting documents.
 * @throws InvalidDBNamespaceException No collection has been selected.
 * @throws GeneralMongoException A MongoException occurred.
 **//*from  w  ww  . java2s .c om*/
public void removeDocumentsUnsafe(DBObject query) throws InvalidDBNamespaceException, GeneralMongoException {
    if (currentCollection == null) {
        throw new InvalidDBNamespaceException("No collection has been selected.");
    }

    try {
        WriteConcern oldConcern = currentCollection.getWriteConcern();
        currentCollection.setWriteConcern(WriteConcern.NORMAL);
        currentCollection.remove(query);
        currentCollection.setWriteConcern(oldConcern);
    } catch (MongoException mongoException) {
        throw new GeneralMongoException("An error occurred attempting to remove.", mongoException);
    }
}

From source file:HAL.libraries.blackboard_client.BlackboardClient.java

License:Open Source License

/**
 * Updates all documents matching the provided search query within the currently selected collection.
 * Documents are updated according to the query specified in updateQuery.
 * Does not wait for the server to perform write to disk, nor does it check for errors other than networks errors.
 * /*from   w w  w .  j a va  2s . c o  m*/
 * @param searchQuery The query that should be used to select the target documents.
 * @param updateQuery The query that should be used to update the target documents.
 * @return The amount of documents that have been updated.
 * @throws InvalidDBNamespaceException No collection has been selected.
 * @throws GeneralMongoException A MongoException occurred.
 **/
public void updateDocumentsUnsafe(DBObject searchQuery, DBObject updateQuery)
        throws InvalidDBNamespaceException, GeneralMongoException {
    if (currentCollection == null) {
        throw new InvalidDBNamespaceException("No collection has been selected.");
    }

    try {
        WriteConcern oldConcern = currentCollection.getWriteConcern();
        currentCollection.setWriteConcern(WriteConcern.NORMAL);
        currentCollection.updateMulti(searchQuery, updateQuery);
        currentCollection.setWriteConcern(oldConcern);
    } catch (MongoException mongoException) {
        throw new GeneralMongoException("An error occurred attempting to update.", mongoException);
    }
}

From source file:it.marcoberri.mbmeteo.action.Commons.java

License:Apache License

/**
 *
 * @param log/*w w w .  j a  v a2s  .c om*/
 */
public static void importLogEasyWeather(Logger log) {

    try {

        final File importPath = new File(
                ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.filepath"));
        FileUtils.forceMkdir(importPath);
        final File importPathBackup = new File(
                ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.filepath") + File.separator
                        + "old" + File.separator);
        FileUtils.forceMkdir(importPathBackup);
        boolean hasHeader = Default
                .toBoolean(ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.hasHeader"), true);

        final String[] extension = { "csv", "txt" };
        Collection<File> files = FileUtils.listFiles(importPath, extension, false);

        if (files.isEmpty()) {
            log.debug("No file to inport: " + importPath);
            return;
        }

        for (File f : files) {

            log.debug("read file:" + f);

            final List<String> l = FileUtils.readLines(f, "UTF-8");
            log.debug("tot line:" + l.size());

            final Datastore ds = MongoConnectionHelper.ds;

            log.debug("hasHeader: " + hasHeader);
            int lineCount = 0;
            int lineDouble = 0;
            for (String s : l) {

                if (hasHeader) {
                    hasHeader = false;
                    continue;
                }

                final String[] columns = s.split(";");
                List<Meteolog> check = ds.createQuery(Meteolog.class).field("time")
                        .equal(getDate("dd-MM-yyyy HH:mm", columns[1], log)).asList();

                if (check != null && !check.isEmpty()) {
                    log.debug("data exist, continue");
                    lineDouble++;
                    continue;
                }

                final Meteolog meteoLog = new Meteolog();
                try {
                    meteoLog.setN(Integer.valueOf(columns[0]));
                } catch (Exception e) {
                    log.error("line skipped " + lineCount, e);
                    continue;
                }

                try {
                    meteoLog.setTime(getDate("dd-MM-yyyy HH:mm", columns[1], log));
                } catch (Exception e) {
                    log.error("line skipped" + lineCount, e);
                    continue;
                }

                try {
                    meteoLog.setInterval(Integer.valueOf(columns[2]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setIndoorHumidity(Double.valueOf(columns[3]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setIndoorTemperature(Double.valueOf(columns[4]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setOutdoorHumidity(Double.valueOf(columns[5]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setOutdoorTemperature(Double.valueOf(columns[6]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setAbsolutePressure(Double.valueOf(columns[7]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setWind(Double.valueOf(columns[8]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setGust(Double.valueOf(columns[9]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setDirection(columns[10]);
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setRelativePressure(Double.valueOf(columns[11]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setDewpoint(Double.valueOf(columns[12]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setWindChill(Double.valueOf(columns[13]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setHourRainfall(Double.valueOf(columns[14]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setDayRainfall(Double.valueOf(columns[15]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setWeekRainfall(Double.valueOf(columns[16]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setMonthRainfall(Double.valueOf(columns[17]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setTotalRainfall(Double.valueOf(columns[18]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setWindLevel(Double.valueOf(columns[19]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                try {
                    meteoLog.setGustLevel(Double.valueOf(columns[20]));
                } catch (Exception e) {
                    log.error("line " + lineCount, e);
                }

                ds.save(meteoLog, WriteConcern.NORMAL);
                lineCount++;

            }

            log.debug("Tot line insert:" + lineCount);
            log.debug("Tot line scarted:" + lineDouble);

            //move file to backup dir with rename
            final File toMove = new File(
                    importPathBackup + "/" + f.getName() + "_" + System.currentTimeMillis());

            log.debug("Move File to Backup dir" + toMove);
            f.renameTo(toMove);

        }
    } catch (IOException ex) {
        log.fatal(ex);

    }
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

/**
 * Initialize any state for this DB. Called once per DB instance; there is
 * one DB instance per client thread./*from   w  w  w  . j  a  va 2  s .com*/
 */
public boolean init() throws DBException {
    // initialize MongoDb driver
    props = getProperties();
    String url = props.getProperty(MONGODB_URL_PROPERTY);
    database = props.getProperty(MONGODB_DB_PROPERTY);
    String writeConcernType = props.getProperty(MONGODB_WRITE_CONCERN_PROPERTY,
            MONGODB_WRITE_CONCERN_PROPERTY_DEFAULT);
    manipulationArray = Boolean.parseBoolean(props.getProperty(MONGODB_MANIPULATION_ARRAY_PROPERTY,
            MONGODB_MANIPULATION_ARRAY_PROPERTY_DEFAULT));
    friendListReq = Boolean.parseBoolean(
            props.getProperty(MONGODB_FRNDLIST_REQ_PROPERTY, MONGODB_FRNDLIST_REQ_PROPERTY_DEFAULT));
    scanResources = Boolean
            .parseBoolean(props.getProperty(MONGODB_SCANFORRES_PROPERTY, MONGODB_SCANFORRES_PROPERTY_DEFAULT));

    if ("none".equals(writeConcernType)) {
        // don't return error on writes
        writeConcern = WriteConcern.NONE;
    } else if ("strict".equals(writeConcernType)) {
        // The write will wait for a response from the server and raise an
        // exception on any error
        writeConcern = WriteConcern.SAFE;
    } else if ("normal".equals(writeConcernType)) {
        // normal error handling - just raise exceptions when problems, don
        // wait for response form servers
        writeConcern = WriteConcern.NORMAL;
    }

    try {
        // System.out.println("new database url = "+url);
        /*
         * MongoOptions mo = new MongoOptions(); mo.connectionsPerHost =
         * 100; mongo = new Mongo(new DBAddress(url), mo);
         */

        /*
         * List<ServerAddress> addrs = new ArrayList<ServerAddress>();
         * addrs.add( new ServerAddress( "10.0.0.122" , 27017 ) );
         * addrs.add( new ServerAddress( "10.0.0.122" , 10002 ) );
         * addrs.add( new ServerAddress( "10.0.0.120" , 10003 ) );
         * MongoOptions mongoOptions = new MongoOptions(); mongo = new
         * Mongo( addrs, mongoOptions);
         * mongo.setReadPreference(ReadPreference.SECONDARY);
         */
        // System.out.println("mongo connection created with "+url);
        try {
            crtcl.acquire();

            if (NumThreads == null) {
                NumThreads = new AtomicInteger();
                NumThreads.set(0);
                MongoOptions mo = new MongoOptions();
                mo.connectionsPerHost = 100;
                String urls[];
                if (!url.contains(";")) { //multiple mongos servers
                    url += "/" + database;
                    mongo = new Mongo(new DBAddress(url), mo);
                } /*else{ // need to append db to url.
                    urls = url.split(";");
                     List<ServerAddress> addrs = new ArrayList<ServerAddress>();
                     for(int i=0; i< urls.length; i++){
                        addrs.add( new ServerAddress(urls[i].split(":")[0] , Integer.parseInt(urls[i].split(":")[1]) ) );
                        //no need to add the database name here as each action does a mongo.getDB(database)
                     } 
                     mongo = new Mongo( addrs);
                  }*/
                else { // need to append db to url.
                    urls = url.split(";");
                    mo = new MongoOptions();
                    mo.connectionsPerHost = 100;
                    //trying to direct clients to different routers
                    url = urls[(Integer.parseInt(props.getProperty(Client.MACHINE_ID_PROPERTY, "0")))
                            % urls.length];
                    url += "/" + database;
                    mongo = new Mongo(new DBAddress(url), mo);
                }

                //mongo = new MongoClient(new DBAddress(url));
                // checking to see if the connection is established
                try {
                    Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
                    socket.connect(mongo.getAddress().getSocketAddress());
                    socket.close();
                } catch (IOException ex) {
                    System.out.println("ERROR: Can't create connection, check if MongDB is running");
                    return false;
                }
            }
            incrementNumThreads();

        } catch (Exception e) {
            System.out.println("MongoDB init failed to acquire semaphore.");
            e.printStackTrace(System.out);
        } finally {
            crtcl.release();
        }
    } catch (Exception e1) {
        System.out.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
        e1.printStackTrace(System.out);
        return false;
    }
    return true;
}

From source file:mongodbutils.MongodbConnection.java

public boolean insertJSON(String dbName, String collectionName, String json) {
    try {/*from w  w w . j av a 2s.  co m*/
        //System.out.println("mongo start insert");

        if (mongoClient == null) {
            //System.out.println("client is null");
        }

        db = mongoClient.getDB(dbName);

        //System.out.println("mongo get collection");
        DBCollection coll = db.getCollection(collectionName);

        //System.out.println("parse json");
        DBObject dbObject = (DBObject) JSON.parse(json);

        //System.out.println("insert data");
        //coll.insert(dbObject,WriteConcern.JOURNALED);
        coll.insert(dbObject, WriteConcern.NORMAL);

        return true;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

}

From source file:org.apache.metamodel.mongodb.DefaultWriteConcernAdvisor.java

License:Apache License

public DefaultWriteConcernAdvisor() {
    super(WriteConcern.NORMAL);
}

From source file:org.apache.tapestry5.mongodb.modules.MongodbModule.java

License:Apache License

/**
 * Contribute coercions for {@link WriteConcern} and {@link ReadPreference} to have them from
 * {@link org.apache.tapestry5.ioc.annotations.Symbol}
 *
 * @param configuration lets help the {@link org.apache.tapestry5.ioc.services.TypeCoercer} service
 *//*from   ww w .j a  v  a2s  .c om*/
public static void contributeTypeCoercer(Configuration<CoercionTuple> configuration) {
    configuration.add(new CoercionTuple(String.class, WriteConcern.class, new Coercion<String, WriteConcern>() {
        public WriteConcern coerce(String input) {
            if (input.equalsIgnoreCase("FSYNC_SAFE")) {
                return WriteConcern.FSYNC_SAFE;
            } else if (input.equalsIgnoreCase("JOURNAL_SAFE")) {
                return WriteConcern.JOURNAL_SAFE;
            } else if (input.equalsIgnoreCase("MAJORITY")) {
                return WriteConcern.MAJORITY;
            } else if (input.equalsIgnoreCase("NONE")) {
                return WriteConcern.NONE;
            } else if (input.equalsIgnoreCase("REPLICAS_SAFE")) {
                return WriteConcern.REPLICAS_SAFE;
            } else if (input.equalsIgnoreCase("SAFE")) {
                return WriteConcern.SAFE;
            } else if (input.equalsIgnoreCase("NORMAL")) {
                return WriteConcern.NORMAL;
            } else // WriteConcern.ACKNOWLEDGED IS OUR DEFAULT
            {
                return WriteConcern.ACKNOWLEDGED;
            }
        }
    }));

    configuration
            .add(new CoercionTuple(String.class, ReadPreference.class, new Coercion<String, ReadPreference>() {
                public ReadPreference coerce(String input) {
                    if (input.equalsIgnoreCase("SECONDARY")) {
                        return ReadPreference.secondary();
                    } else // PRIMARY IS OUR DEFAULT
                    {
                        return ReadPreference.primary();
                    }
                }
            }));
}

From source file:org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec.java

License:Open Source License

/**
 * Connect with the specified properties and return the Connection.
 *///from  w w  w.  ja  v  a 2  s  .c  om
public Connection connectToDataSource(EISAccessor accessor, Properties properties)
        throws DatabaseException, ValidationException {
    if ((this.connectionFactory == null) && (this.name == null)) {
        this.connectionFactory = new MongoConnectionFactory();
    }
    if (!properties.isEmpty()) {
        if (this.connectionSpec == null) {
            this.connectionSpec = new MongoJCAConnectionSpec();
        }
        MongoJCAConnectionSpec spec = (MongoJCAConnectionSpec) this.connectionSpec;
        String host = (String) properties.get(HOST);
        String port = (String) properties.get(PORT);
        String db = (String) properties.get(DB);
        if (host != null) {
            if (host.indexOf(',') == -1) {
                spec.getHosts().add(host);
                if (port != null) {
                    spec.getPorts().add(new Integer(port));
                }
            } else {
                int startIndex = 0;
                while (startIndex < (host.length() - 1)) {
                    int endIndex = host.indexOf(',', startIndex);
                    if (endIndex == -1) {
                        endIndex = host.length();
                    }
                    String nextHost = host.substring(startIndex, endIndex);
                    spec.getHosts().add(nextHost);
                    startIndex = endIndex + 1;
                }
                while (startIndex < (port.length() - 1)) {
                    int endIndex = port.indexOf(',', startIndex);
                    if (endIndex == -1) {
                        endIndex = port.length();
                    }
                    String nextPort = port.substring(startIndex, endIndex);
                    spec.getPorts().add(new Integer(nextPort));
                    startIndex = endIndex + 1;
                }
            }
        }
        if (db != null) {
            spec.setDB(db);
        }

        String user = (String) properties.get("user");
        Object password = properties.get("password");
        if (password instanceof String) {
            password = ((String) password).toCharArray();
        }
        if ((user != null) && (user.length() != 0)) {
            spec.setUser(user);
            spec.setPassword((char[]) password);
        }

        // Allows setting of read preference as a property.
        Object preference = properties.get(READ_PREFERENCE);
        if (preference instanceof ReadPreference) {
            spec.setReadPreference((ReadPreference) preference);
        } else if (preference instanceof String) {
            String constant = (String) preference;
            if (constant.equals("PRIMARY")) {
                spec.setReadPreference(ReadPreference.PRIMARY);
            } else if (constant.equals("SECONDARY")) {
                spec.setReadPreference(ReadPreference.SECONDARY);
            } else {
                throw new EISException("Invalid read preference property value: " + constant);
            }
        }

        // Allows setting of write concern as a property.
        Object concern = properties.get(WRITE_CONCERN);
        if (concern instanceof WriteConcern) {
            spec.setWriteConcern((WriteConcern) concern);
        } else if (concern instanceof String) {
            String constant = (String) concern;
            if (constant.equals("FSYNC_SAFE")) {
                spec.setWriteConcern(WriteConcern.FSYNC_SAFE);
            } else if (constant.equals("ACKNOWLEDGED")) {
                spec.setWriteConcern(WriteConcern.ACKNOWLEDGED);
            } else if (constant.equals("JOURNAL_SAFE")) {
                spec.setWriteConcern(WriteConcern.JOURNAL_SAFE);
            } else if (constant.equals("MAJORITY")) {
                spec.setWriteConcern(WriteConcern.MAJORITY);
            } else if (constant.equals("NONE")) {
                spec.setWriteConcern(WriteConcern.NONE);
            } else if (constant.equals("NORMAL")) {
                spec.setWriteConcern(WriteConcern.NORMAL);
            } else if (constant.equals("REPLICAS_SAFE")) {
                spec.setWriteConcern(WriteConcern.REPLICAS_SAFE);
            } else if (constant.equals("SAFE")) {
                spec.setWriteConcern(WriteConcern.SAFE);
            } else {
                throw new EISException("Invalid read preference property value: " + constant);
            }
        }

        // Allows setting of options as a property.
        Object options = properties.get(OPTIONS);
        if (options instanceof Number) {
            spec.setOptions(((Number) options).intValue());
        } else if (options instanceof String) {
            spec.setOptions(Integer.valueOf(((String) options)));
        }
    }

    return super.connectToDataSource(accessor, properties);
}

From source file:org.lucee.mongodb.support.ObjectSupport.java

License:Open Source License

public WriteConcern toWriteConcern(Object obj, WriteConcern defaultValue) {
    if (obj instanceof WriteConcern)
        return (WriteConcern) obj;
    if (decision.isSimpleValue(obj)) {
        String str = caster.toString(obj, "");
        str = str.trim().toUpperCase();/*  ww  w  .ja v  a2 s  .  c om*/
        if ("ACKNOWLEDGED".equals(str))
            return WriteConcern.ACKNOWLEDGED;
        else if ("ACKNOWLEDGED".equals(str))
            return WriteConcern.FSYNC_SAFE;
        else if ("FSYNC_SAFE".equals(str) || "FSYNCSAFE".equals(str))
            return WriteConcern.FSYNCED;
        else if ("JOURNAL_SAFE".equals(str) || "JOURNALSAFE".equals(str))
            return WriteConcern.JOURNAL_SAFE;
        else if ("JOURNALED".equals(str))
            return WriteConcern.JOURNALED;
        else if ("MAJORITY".equals(str))
            return WriteConcern.MAJORITY;
        else if ("NORMAL".equals(str))
            return WriteConcern.NORMAL;
        else if ("REPLICA_ACKNOWLEDGED".equals(str) || "REPLICAACKNOWLEDGED".equals(str))
            return WriteConcern.REPLICA_ACKNOWLEDGED;
        else if ("REPLICAS_SAFE".equals(str) || "REPLICASSAFE".equals(str))
            return WriteConcern.REPLICAS_SAFE;
        else if ("SAFE".equals(str))
            return WriteConcern.SAFE;
        else if ("UNACKNOWLEDGED".equals(str))
            return WriteConcern.UNACKNOWLEDGED;
    }
    return defaultValue;
}