Example usage for com.mongodb BasicDBObjectBuilder start

List of usage examples for com.mongodb BasicDBObjectBuilder start

Introduction

In this page you can find the example usage for com.mongodb BasicDBObjectBuilder start.

Prototype

public static BasicDBObjectBuilder start() 

Source Link

Document

Creates a builder intialized with an empty document.

Usage

From source file:com.tadamski.glassfish.mongo.realm.api.MongoRealmApi.java

License:Open Source License

public DBCursor getUsers() {
    return getUsers(BasicDBObjectBuilder.start().get());

}

From source file:com.tadamski.glassfish.mongo.realm.api.MongoRealmApi.java

License:Open Source License

private DBObject excludePasswordAndSaltProperties() {
    return BasicDBObjectBuilder.start().append(getProperty(MongoRealmProperties.PASSWORD_PROPERTY), 0)
            .append(getProperty(MongoRealmProperties.SALT_PROPERTY), 0).get();
}

From source file:com.ultratechnica.mongodb.Main.java

License:Apache License

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();//from   ww  w  .  j  av a 2  s  .co m

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:com.vidico.jsp.service.UserConverter.java

public static DBObject toDBObject(User u) {
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().append("username", u.getUsername())
            .append("password", u.getPassword()).append("firstname", u.getFirstName())
            .append("lastname", u.getLastName()).append("email", u.getEmail()).append("isAdmin", u.isIsAdmin())
            .append("lastAccessTime", new Date()).append("rating", 0).append("verified", u.isVerified())
            .append("registeredTime", new Date()).append("reportedSpamCount", u.getReportedSpamCount())
            .append("_id", u.getId());

    return builder.get();
}

From source file:com.zjy.mongo.input.MongoInputSplit.java

License:Apache License

public void write(final DataOutput out) throws IOException {
    BSONObject spec = BasicDBObjectBuilder.start().add("inputURI", getInputURI().toString())
            .add("authURI", getAuthURI() != null ? getAuthURI().toString() : null)
            .add("keyField", getKeyField()).add("fields", getFields()).add("query", getQuery())
            .add("sort", getSort()).add("min", getMin()).add("max", getMax()).add("notimeout", getNoTimeout())
            .get();//from   w ww  .j a  v  a 2  s.  com
    byte[] buf = _bsonEncoder.encode(spec);
    out.write(buf);
}

From source file:com.zjy.mongo.output.BSONFileRecordWriter.java

License:Apache License

private void writeSplitData(final int docSize, final boolean force) throws IOException {
    //If no split file is being written, bail out now
    if (this.splitsFile == null) {
        return;/*from   w  ww .  ja v  a 2  s  .c o  m*/
    }

    // hit the threshold of a split, write it to the metadata file
    if (force || currentSplitLen + docSize >= this.splitSize) {
        BSONObject splitObj = BasicDBObjectBuilder.start().add("s", currentSplitStart).add("l", currentSplitLen)
                .get();
        byte[] encodedObj = this.bsonEnc.encode(splitObj);
        this.splitsFile.write(encodedObj, 0, encodedObj.length);

        //reset the split len and start
        this.currentSplitLen = 0;
        this.currentSplitStart = bytesWritten - docSize;
    } else {
        // Split hasn't hit threshold yet, just add size
        this.currentSplitLen += docSize;
    }
}

From source file:com.zjy.mongo.splitter.BSONSplitter.java

License:Apache License

/**
 * Write out the splits file, if doing so has been enabled. Splits must
 * already have been calculated previously by a call to {@link
 * #readSplitsForFile readSplitsForFile} or {@link #readSplits readSplits}.
 *
 * @see com.zjy.mongo.util.MongoConfigUtil#BSON_WRITE_SPLITS
 *
 * @throws IOException when an error occurs writing the file
 *///from   w w w. j  av a2s. com
public void writeSplits() throws IOException {
    if (getConf().getBoolean("bson.split.write_splits", true)) {
        LOG.info("Writing splits to disk.");
    } else {
        LOG.info("bson.split.write_splits is set to false - skipping writing splits to disk.");
        return;
    }

    if (splitsList == null) {
        LOG.info("No splits found, skipping write of splits file.");
    }

    Path outputPath = getSplitsFilePath(inputPath, getConf());
    FileSystem pathFileSystem = outputPath.getFileSystem(getConf());
    FSDataOutputStream fsDataOut = null;
    try {
        fsDataOut = pathFileSystem.create(outputPath, false);
        for (FileSplit inputSplit : splitsList) {
            BSONObject splitObj = BasicDBObjectBuilder.start().add("s", inputSplit.getStart())
                    .add("l", inputSplit.getLength()).get();
            byte[] encodedObj = bsonEnc.encode(splitObj);
            fsDataOut.write(encodedObj, 0, encodedObj.length);
        }
    } catch (IOException e) {
        LOG.error("Could not create splits file: " + e.getMessage());
        throw e;
    } finally {
        if (fsDataOut != null) {
            fsDataOut.close();
        }
    }
}

From source file:com.zuehlke.sbdfx.dataaccess.mongo.MongoCitiesDao.java

@Override
public City findByGeoNameId(final int geonameid) {
    final DBObject query = BasicDBObjectBuilder.start().add("geonameid", geonameid).get();
    final DBObject found = cities.findOne(query);
    return toCity(found);
}

From source file:converter.AtmConverter.java

public static DBObject toDBObject(Atm a) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start()
            .append("walk", WalkConverter.toDBObject(a.getWalk()))
            .append("drive", DriveConverter.toDBObject(a.getDrive()));

    return builder.get();
}

From source file:converter.DoctorConverter.java

public static DBObject toDBObject(Doctor d) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start()
            .append("walk", WalkConverter.toDBObject(d.getWalk()))
            .append("drive", DriveConverter.toDBObject(d.getDrive()));

    return builder.get();
}