Example usage for com.mongodb WriteConcern FSYNC_SAFE

List of usage examples for com.mongodb WriteConcern FSYNC_SAFE

Introduction

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

Prototype

WriteConcern FSYNC_SAFE

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

Click Source Link

Document

Exceptions are raised for network issues, and server errors; the write operation waits for the server to flush the data to disk.

This field has been superseded by WriteConcern.FSYNCED , and may be deprecated in a future release.

Usage

From source file:eu.europeana.corelib.edm.utils.construct.FullBeanHandler.java

public boolean removeRecord(SolrServer solrServer, RDF rdf) {
    try {//  www . j  av a2s  .c  o  m
        solrServer.deleteByQuery(
                "europeana_id:" + ClientUtils.escapeQueryChars(rdf.getProvidedCHOList().get(0).getAbout()));

        DBCollection records = mongoServer.getDatastore().getDB().getCollection("record");
        DBCollection proxies = mongoServer.getDatastore().getDB().getCollection("Proxy");
        DBCollection providedCHOs = mongoServer.getDatastore().getDB().getCollection("ProvidedCHO");
        DBCollection aggregations = mongoServer.getDatastore().getDB().getCollection("Aggregation");
        DBCollection europeanaAggregations = mongoServer.getDatastore().getDB()
                .getCollection("EuropeanaAggregation");
        DBCollection physicalThing = mongoServer.getDatastore().getDB().getCollection("PhysicalThing");
        DBObject query = new BasicDBObject("about", rdf.getProvidedCHOList().get(0).getAbout());
        DBObject proxyQuery = new BasicDBObject("about",
                "/proxy/provider" + rdf.getProvidedCHOList().get(0).getAbout());
        DBObject europeanaProxyQuery = new BasicDBObject("about",
                "/proxy/europeana" + rdf.getProvidedCHOList().get(0).getAbout());

        DBObject providedCHOQuery = new BasicDBObject("about",
                "/item" + rdf.getProvidedCHOList().get(0).getAbout());
        DBObject aggregationQuery = new BasicDBObject("about",
                "/aggregation/provider" + rdf.getProvidedCHOList().get(0).getAbout());
        DBObject europeanaAggregationQuery = new BasicDBObject("about",
                "/aggregation/europeana" + rdf.getProvidedCHOList().get(0).getAbout());
        europeanaAggregations.remove(europeanaAggregationQuery, WriteConcern.FSYNC_SAFE);
        records.remove(query, WriteConcern.FSYNC_SAFE);
        proxies.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        proxies.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        providedCHOs.remove(providedCHOQuery, WriteConcern.FSYNC_SAFE);
        aggregations.remove(aggregationQuery, WriteConcern.FSYNC_SAFE);
        return true;
    } catch (SolrServerException e) {
        log.log(Level.SEVERE, e.getMessage());

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());

    }
    return false;
}

From source file:eu.europeana.corelib.edm.utils.construct.FullBeanHandler.java

public boolean removeRecordById(SolrServer solrServer, String id) {
    try {//from  ww w.ja v a2s .co m
        solrServer.deleteByQuery("europeana_id:" + ClientUtils.escapeQueryChars(id));

        DBCollection records = mongoServer.getDatastore().getDB().getCollection("record");
        DBCollection proxies = mongoServer.getDatastore().getDB().getCollection("Proxy");
        DBCollection providedCHOs = mongoServer.getDatastore().getDB().getCollection("ProvidedCHO");
        DBCollection aggregations = mongoServer.getDatastore().getDB().getCollection("Aggregation");
        DBCollection europeanaAggregations = mongoServer.getDatastore().getDB()
                .getCollection("EuropeanaAggregation");
        DBCollection physicalThing = mongoServer.getDatastore().getDB().getCollection("PhysicalThing");
        DBObject query = new BasicDBObject("about", id);
        DBObject proxyQuery = new BasicDBObject("about", "/proxy/provider" + id);
        DBObject europeanaProxyQuery = new BasicDBObject("about", "/proxy/europeana" + id);

        DBObject providedCHOQuery = new BasicDBObject("about", "/item" + id);
        DBObject aggregationQuery = new BasicDBObject("about", "/aggregation/provider" + id);
        DBObject europeanaAggregationQuery = new BasicDBObject("about", "/aggregation/europeana" + id);
        europeanaAggregations.remove(europeanaAggregationQuery, WriteConcern.FSYNC_SAFE);
        records.remove(query, WriteConcern.FSYNC_SAFE);
        proxies.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        proxies.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
        physicalThing.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
        providedCHOs.remove(providedCHOQuery, WriteConcern.FSYNC_SAFE);
        aggregations.remove(aggregationQuery, WriteConcern.FSYNC_SAFE);
        return true;
    } catch (SolrServerException e) {
        log.log(Level.SEVERE, e.getMessage());

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());

    }
    return false;
}

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
 *///ww w  .j a  va 2s .  co m
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.axonframework.eventsourcing.eventstore.mongo.MongoFactory.java

License:Apache License

private WriteConcern defaultWriteConcern() {
    if (writeConcern != null) {
        return this.writeConcern;
    } else if (mongoAddresses.size() > 1) {
        return WriteConcern.REPLICAS_SAFE;
    } else {/* w ww .  ja v a2 s. c  o m*/
        return WriteConcern.FSYNC_SAFE;
    }
}

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.j a va 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.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@POST
@Path("/databases")
@Override//from  w  w  w.j  a v a2s.c o m
public Response createDatabase(org.exoplatform.mongo.entity.request.Database database,
        @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 dbName = constructDbNamespace(credentials.getUserName(), database.getName());
        if (mongo.getDatabaseNames().contains(dbName)) {
            return Response.status(ClientError.ALREADY_EXISTS.code()).build();
        }

        DB db = mongo.getDB(dbName);
        authServiceAgainstMongo(db);
        if (database.getWriteConcern() != null) {
            db.setWriteConcern(database.getWriteConcern().getMongoWriteConcern());
        } else {
            db.setWriteConcern(WriteConcern.FSYNC_SAFE);
        }
        DBCollection localStats = db.getCollection(STATS_USER_COLLECTION);
        DBObject statsIndex = new BasicDBObject();
        statsIndex.put(STATS_OP_KEY, 1);
        localStats.ensureIndex(statsIndex, null, true);

        URI statusSubResource = uriInfo.getBaseUriBuilder().path(MongoRestServiceImpl.class)
                .path("/databases/" + database.getName()).build();
        response = Response.created(statusSubResource).build();
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "createDatabase");
    }

    return response;
}

From source file:org.jongo.util.MongoResource.java

License:Apache License

private static MongoClient createClient(int port) throws UnknownHostException {
    MongoClient mongo = new MongoClient("127.0.0.1", port);
    mongo.setWriteConcern(WriteConcern.FSYNC_SAFE);
    return mongo;
}

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();/*from  ww  w  .j a v  a  2  s. c o  m*/
        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;
}

From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java

License:Open Source License

@SuppressWarnings("finally")
private boolean countRawTarget(StatEvent event) throws StatsEngineException {
    boolean processed = false;
    try {// ww w .  j  a  va 2  s . c o  m
        BasicDBObject q = new BasicDBObject();
        q.put(EVENT_CLIENT_ID, event.getClientId());
        q.put(EVENT_TARGET, event.getTarget());
        q.put(EVENT_TARGET_TYPE, event.getTargetType());
        q.put(EVENT_ACTION, event.getAction());
        q.put(EVENT_DATE, event.getYearMonthDate().toDate());
        q.put(TARGET_YEAR, event.getYear());
        q.put(TARGET_MONTH, event.getMonth());

        BasicDBObject doc = new BasicDBObject();

        //BasicDBObject docSet = new BasicDBObject();
        doc.put("$addToSet", createAddToSetOwnersTagsDoc(event));
        BasicDBObject incDoc = new BasicDBObject();
        incDoc.put(FIELD_COUNT, 1); //Month count
        String metaBaseKey = "";
        TimeScope precision = getTimeScopePrecision();
        if (precision == TimeScope.DAILY || precision == TimeScope.HOURLY) {
            String dayKey = createDotPath(FIELD_DAYS, event.getDay());
            incDoc.put(createDotPath(dayKey, FIELD_COUNT), 1); //Day count
            if (precision == TimeScope.HOURLY) {
                String hourKey = createDotPath(dayKey, FIELD_HOURS, event.getHour());
                incDoc.put(createDotPath(hourKey, FIELD_COUNT), 1);//Hour count
                metaBaseKey = hourKey;
            } else {
                metaBaseKey = dayKey;
            }
        }
        //Count metadata
        Map<String, Object> metadata = event.getMetadata();
        for (String metaKey : metadata.keySet()) {
            incDoc.put(createDotPath(metaBaseKey, FIELD_META, metaKey,
                    metaKeyValue(metaKey, metadata.get(metaKey))), 1);
        }
        doc.put("$inc", incDoc);
        DBCollection targets = getTargetCollection(event, TimeScope.GLOBAL);
        //TODO externalize write concern to configuration properties:
        WriteResult wr = targets.update(q, doc, true, true, WriteConcern.FSYNC_SAFE);
        processed = wr.getN() > 0;
    } catch (MongoException ex) {
        int errorCode = ex.getCode();
        if (errorCode == ERROR_DUPKEY || errorCode == ERROR_DUPKEY_INSERT) {
            throw new DuplicateEventException("Duplicate event " + event);
        }
        throw new StatsEngineException("countRawTarget failed", ex);
    }
    return processed;
}

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

License:Apache License

private void loadConfiguration() throws UnknownHostException {
    configuration.refresh();/*from w  w  w  .  j a v  a  2s  .  c o  m*/
    MongoEntityStoreConfiguration config = configuration.get();

    // Combine hostname, port and nodes configuration properties
    serverAddresses = new ArrayList<ServerAddress>();
    if (config.hostname().get() != null && !config.hostname().get().isEmpty()) {
        serverAddresses.add(new ServerAddress(config.hostname().get(), config.port().get()));
    }
    serverAddresses.addAll(config.nodes().get());

    // If database name not configured, set it to qi4j:entitystore
    databaseName = config.database().get();
    if (databaseName == null) {
        databaseName = DEFAULT_DATABASE_NAME;
    }

    // If collection name not configured, set it to qi4j:entitystore:entities
    collectionName = config.collection().get();
    if (collectionName == null) {
        collectionName = DEFAULT_COLLECTION_NAME;
    }

    // If write concern not configured, set it to normal
    switch (config.writeConcern().get()) {
    case FSYNC_SAFE:
        writeConcern = WriteConcern.FSYNC_SAFE;
        break;
    case JOURNAL_SAFE:
        writeConcern = WriteConcern.JOURNAL_SAFE;
        break;
    case MAJORITY:
        writeConcern = WriteConcern.MAJORITY;
        break;
    case NONE:
        writeConcern = WriteConcern.NONE;
        break;
    case REPLICAS_SAFE:
        writeConcern = WriteConcern.REPLICAS_SAFE;
        break;
    case SAFE:
        writeConcern = WriteConcern.SAFE;
        break;
    case NORMAL:
    default:
        writeConcern = WriteConcern.NORMAL;
    }

    // Username and password are defaulted to empty strings
    username = config.username().get();
    password = config.password().get().toCharArray();
}