Example usage for com.mongodb BasicDBObjectBuilder get

List of usage examples for com.mongodb BasicDBObjectBuilder get

Introduction

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

Prototype

public DBObject get() 

Source Link

Document

Gets the top level document.

Usage

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

/**
 * @param page/*  ww  w. j a va  2 s .com*/
 * @return sort DBObject
 */
protected DBObject createSort(Pageable page) {
    if (page.getSort() == null) {
        return null;
    }

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
    Iterator<Order> orderIter = page.getSort().iterator();
    while (orderIter.hasNext()) {
        Order order = orderIter.next();
        builder.add(order.getProperty(), order.getDirection().equals(Direction.ASC) ? 1 : -1);
    }

    return builder.get();
}

From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}//from  w w  w.j av  a2 s .com
 * @see com.mobileman.kuravis.core.services.user.UserService#findUsersByDiseaseAndTreatment(com.mongodb.DBObject, Pageable)
 */
@Override
public List<DBObject> findUsersByDiseaseAndTreatment(DBObject query, Pageable page) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();

    if (query != null) {
        if (query.containsField("diseaseId")) {
            builder.add("disease." + EntityUtils.ID, query.get("diseaseId"));
        }

        if (query.containsField("treatmentId")) {
            builder.add("treatment." + EntityUtils.ID, query.get("treatmentId"));
        }
    }

    AggregationOutput out = getCollection(TreatmentReview.ENTITY_NAME).aggregate(
            new BasicDBObject("$match", builder.get()),
            new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("_id", "$author._id"))),
            new BasicDBObject("$project", new BasicDBObject(EntityUtils.ID, "$_id._id")),
            new BasicDBObject("$skip", page.getOffset()), new BasicDBObject("$limit", page.getPageSize())

    );

    List<DBObject> result = new ArrayList<>();
    Set<String> userIds = new HashSet<String>();
    for (DBObject dbObject : out.results()) {
        String userId = EntityUtils.getEntityId(dbObject);
        userIds.add(userId);
        result.add(dbObject);
    }

    Map<String, DBObject> usersData = findUsersData(userIds, "name", "gender", "settings.profile");
    for (DBObject user : result) {
        DBObject data = usersData.get(EntityUtils.getEntityId(user));
        if (data != null) {
            user.put("name", data.get("name"));
            user.put("gender", data.get("gender"));
            user.put("settings", data.get("settings"));
        }
    }

    return result;
}

From source file:com.mongodash.appender.MongoDBAppender.java

License:Apache License

@Override
protected void append(LoggingEvent e) {

    BasicDBObjectBuilder objectBuilder = BasicDBObjectBuilder.start().add("ts", new Date(e.getTimeStamp()))
            .add("msg", e.getFormattedMessage()).add("level", e.getLevel().toString())
            .add("logger", e.getLoggerName()).add("thread", e.getThreadName());
    if (e.hasCallerData()) {
        StackTraceElement st = e.getCallerData()[0];
        String callerData = String.format("%s.%s:%d", st.getClassName(), st.getMethodName(),
                st.getLineNumber());//from w  w w .j a v a 2  s  . c o m
        objectBuilder.add("caller", callerData);
    }
    Map<String, String> mdc = e.getMdc();
    if (mdc != null && !mdc.isEmpty()) {
        objectBuilder.add("mdc", new BasicDBObject(mdc));
    }
    if (e.getThrowableProxy() != null && _dbEnableStacktrace) {

        String tpAsString = ThrowableProxyUtil.asString(e.getThrowableProxy()); // the
        // stack
        // trace
        // basically
        List<String> stackTrace = Arrays
                .asList(tpAsString.replace("\t", "").split(CoreConstants.LINE_SEPARATOR));
        if (stackTrace.size() > 0) {
            objectBuilder.add("exception", stackTrace.get(0));
        }
        if (stackTrace.size() > 1) {
            objectBuilder.add("stacktrace", stackTrace.subList(1, stackTrace.size()));
        }
    }
    _collection.insert(objectBuilder.get());
}

From source file:com.mycompany.schools1.SchooltoD.java

public static DBObject toDBObject(School s) {
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().append("name", s.getName())
            .append("code", s.getCode()).append("address", s.getAddress())
            .append("emailDomain", s.getEmailDomain());
    if (s.getId() != null) {
        builder = builder.append("_id", new ObjectId(s.getId()));
    }// w  w  w .  j  a  v  a  2  s  . co m

    return builder.get();

}

From source file:com.packages.mongodb.converter.automobileconverter.java

public static DBObject toDBObject(automobile p) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().append("address", p.getaddress())
            .append("email", p.getemail()).append("type", p.gettype()).append("comment", p.getcomments())
            .append("name", p.getname()).append("dealer", p.getdealer()).append("phone", p.getphone())
            .append("brand", p.getbrand());
    if (p.getid() != null)
        builder = builder.append("_id", new ObjectId(p.getid()));
    return builder.get();
}

From source file:com.packages.mongodb.converter.hotelconverter.java

public static DBObject toDBObject(hotels p) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().append("address", p.getaddress())
            .append("email", p.getemail()).append("rating", p.getrating()).append("message", p.getmessage())
            .append("name", p.getname()).append("budget", p.getbudget()).append("phone", p.getphone());
    if (p.getid() != null)
        builder = builder.append("_id", new ObjectId(p.getid()));
    return builder.get();
}

From source file:com.packages.mongodb.converter.individualconverter.java

public static DBObject toDBObject(individual p) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().append("area", p.getarea())
            .append("city", p.getcity()).append("first_name", p.getfirst_name())
            .append("houseno", p.gethouseno()).append("last_name", p.getlast_name())
            .append("image", p.getimage()).append("email", p.getemail()).append("phone_no", p.getphone_no())
            .append("pincode", p.getpincode());
    if (p.getid() != null)
        builder = builder.append("_id", new ObjectId(p.getid()));
    return builder.get();
}

From source file:com.stratio.tests.ATExampleMongoDB.java

License:Apache License

@BeforeClass
public void setUp() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    mongoClient.dropDatabase(dataBase);/*w  w  w  .j  a  v a 2s  . c  o  m*/
    DB db = mongoClient.getDB(dataBase);
    DBCollection tabletest = db.getCollection("tabletest");
    // DBCollection tabletest = db.createCollection("tabletest");
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    format.setTimeZone(TimeZone.getTimeZone("CET"));
    for (int i = 0; i < 10; i++) {
        Date parsedDate = null;
        String fecha = i + "/" + i + "/200" + i;
        try {
            parsedDate = format.parse(fecha);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(new java.sql.Date(parsedDate.getTime()).toString());
        BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add("ident", i)
                .add("name", "name_" + i).add("money", 10.2 + i).add("new", true)
                .add("date", new java.sql.Date(parsedDate.getTime()));
        tabletest.insert(documentBuilder.get());
    }
    //   DBObject aux = tabletest.findOne();
    //  java.sql.Date aux1 = (java.sql.Date)aux.get("date");
    mongoClient.close();
    String connector = "Mongo";
    //Preparamos las cositas para compartir
    ThreadProperty.set("Host", "127.0.0.1");
    ThreadProperty.set("Connector", connector);

}

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 a va2 s. c om*/

    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();
}