Example usage for com.mongodb BasicDBObject getDate

List of usage examples for com.mongodb BasicDBObject getDate

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject getDate.

Prototype

public Date getDate(final String field) 

Source Link

Document

Returns the date or null if not set.

Usage

From source file:com.tml.pathummoto.Dao.CustomDao.java

public Customer searchCustomer(String no) {
    Customer customer = new Customer();
    // To connect to mongodb server
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("customer");
    System.out.println("Collection user selected successfully");

    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("_id", no);
    DBCursor cursor = coll.find(whereQuery);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }//from www. j a  va2s.c  om
    BasicDBObject doc = (BasicDBObject) cursor.curr();
    System.out.println("doc" + doc);
    if (doc != null) {
        customer.setVehicleNo(doc.getString("_id"));
        customer.setName(doc.getString("name"));
        customer.setPayment(doc.getInt("payment"));
        customer.setFreeServiceNo(doc.getInt("freeServiceNo"));
        customer.setServiceNo(doc.getInt("serviceNo"));
        customer.setDateOfDelivery(doc.getDate("dateOfDelivery"));
        customer.setLastKm(doc.getInt("lastKm"));

    }

    return customer;
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private String _computeById(User user, String evtid, Integer dur, Integer accel, Integer gridres, String algo) {
    DBObject eq = db.getCollection("eqs").findOne(new BasicDBObject("_id", evtid));
    if (eq == null)
        return null;

    BasicDBObject process = new BasicDBObject("process", new BasicDBList());
    BasicDBObject set = new BasicDBObject("$set", process);
    db.getCollection("eqs").update(eq, set);

    /* extract properties to pass them to the request method */
    BasicDBObject prop = (BasicDBObject) eq.get("prop");
    double lat = prop.getDouble("latitude");
    double lon = prop.getDouble("longitude");
    double dip = prop.getDouble("dip");
    double strike = prop.getDouble("strike");
    double rake = prop.getDouble("rake");
    double depth = prop.getDouble("depth");
    Date date = prop.getDate("date");

    EQParameter eqp;// w  w w  .jav a2  s.co  m
    double mag = 0.0;
    double slip = 0.0;
    double length = 0.0;
    double width = 0.0;
    if (prop.get("magnitude") == null) {
        slip = prop.getDouble("slip");
        length = prop.getDouble("length");
        width = prop.getDouble("width");
        eqp = new EQParameter(lon, lat, slip, length, width, depth, dip, strike, rake, date);
    } else {
        mag = prop.getDouble("magnitude");
        eqp = new EQParameter(lon, lat, mag, depth, dip, strike, rake, date);
    }

    if (accel == null)
        accel = 1;

    /* start request */
    EQTask task = new EQTask(eqp, evtid, user, dur, accel, gridres);
    task.algo = algo;
    task.setSlots(IScheduler.SLOT_NORMAL, IScheduler.SLOT_EXCLUSIVE);
    return request(evtid, task);
}

From source file:GeoHazardServices.Inst.java

License:Apache License

@POST
@Path("/computeById")
@Produces(MediaType.APPLICATION_JSON)//from   w w w  .j ava 2s. c o m
public String computeById(@Context HttpServletRequest request, @FormParam("inst") String inst,
        @FormParam("secret") String secret, @FormParam("id") String id, @FormParam("refineId") Long refineId,
        @FormParam("dur") Integer dur, @FormParam("accel") Integer accel, @FormParam("apikey") String apikey,
        @FormParam("evtid") String evtid, @FormParam("raw") @DefaultValue("0") Integer raw,
        @FormParam("gridres") Integer gridres, @FormParam("dt_out") @DefaultValue("10") Integer dt_out,
        @FormParam("algo") @DefaultValue("easywave") String algo) {

    /* Check for invalid parameter configurations. */
    if ((inst != null || secret != null) && apikey != null)
        return jsfailure("Don't mix 'apikey' and 'secret'.");

    /* Support 'inst' and 'secret' for compatibility reasons. */
    if (inst != null && secret != null) {
        /* Obtain the 'apikey' and pretend a call to the new api. */
        DBObject query = new BasicDBObject("name", inst).append("secret", secret);
        DBObject tmp_inst = db.getCollection("institutions").findOne(query);
        if (tmp_inst == null)
            return jsdenied();
        apikey = (String) ((DBObject) tmp_inst.get("api")).get("key");
        if (apikey == null)
            return jsfailure("No 'apikey' set for this institution!");
    }

    /* Authenticate user. */
    DBObject db_user = auth_api(apikey, "user");
    DBObject db_inst = auth_api(apikey, "inst");

    User user;
    if (db_user != null) {
        user = new User(db_user, getInst(db_user));
    } else if (db_inst != null) {
        user = new Inst(db_inst);
    } else {
        return jsdenied();
    }

    /* Check for invalid parameter configurations. */
    if ((id != null || refineId != null) && evtid != null)
        return jsfailure("Don't mix 'id' and 'evtid'.");

    if (evtid == null)
        evtid = new CompId(inst, id, refineId).toString();

    /* Check for missing parameters */
    if (evtid == null)
        return jsfailure("Missing parameter.");

    /* search for given id */
    BasicDBObject query = new BasicDBObject("_id", evtid).append("user", user.objId);
    DBObject entry = db.getCollection("eqs").findOne(query);

    /* return if id not found */
    if (entry == null)
        return jsfailure("Event ID not found.");

    /* check if already computed */
    Integer progress = _status(evtid, raw);
    if (progress != STATUS_NO_COMP) {
        if (raw == 0)
            return jsfailure("Re-computation not allowed.");
        if (progress != 100)
            return jsfailure("A computation is currently running.");
    }

    /* Use same duration as in original simulation if available. */
    if (dur == null) {
        Number n = (Number) getField(entry, "process.0.simTime");
        /* Duration could not be determined. */
        if (n == null)
            return jsfailure("Missing parameter.");
        dur = n.intValue();
    }

    /* Use grid resolution of original computation or default to 120 seconds. */
    if (gridres == null) {
        Number res = (Number) getField(entry, "process.0.resolution");
        gridres = res == null ? 120 : (int) (res.doubleValue() * 60);
    }

    /* get properties of returned entry */
    BasicDBObject prop = (BasicDBObject) entry.get("prop");

    BasicDBObject process = new BasicDBObject("raw_progress", 0);
    if (raw == 0) {
        process.append("process", new BasicDBList());
    }

    BasicDBObject set = new BasicDBObject("$set", process);
    db.getCollection("eqs").update(entry, set);

    /* extract properties to pass them to the request method */
    double lat = prop.getDouble("latitude");
    double lon = prop.getDouble("longitude");
    double mag = prop.getDouble("magnitude");
    double dip = prop.getDouble("dip");
    double strike = prop.getDouble("strike");
    double rake = prop.getDouble("rake");
    double depth = prop.getDouble("depth");
    Date date = prop.getDate("date");

    if (accel == null)
        accel = 1;

    /* prepare the simulation for execution */
    EQParameter eqp = new EQParameter(lon, lat, mag, depth, dip, strike, rake, date);
    EQTask task = new EQTask(eqp, evtid, user, dur, accel, gridres);
    task.raw = raw;
    task.dt_out = dt_out;
    task.algo = algo;
    String ret_id = request(evtid, task);
    return jssuccess(new BasicDBObject("_id", ret_id));
}

From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java

/**
 * /*from  w ww  .  ja v a  2s .co  m*/
 * @param parachutistsFromMelwin
 */
public ArrayList<Parachutist> getParachutistsFromDB() {
    // HjelpeLister
    ArrayList<Club> clubs = getClubsFromDb();
    ArrayList<License> licenses = getLicensesFromDb();

    ArrayList<Parachutist> parachutistsInMongoDB = new ArrayList<>();

    DBCollection dbCollectionParachutists = db.getCollection("jumpers");

    DBCursor cursor = dbCollectionParachutists.find();

    BasicDBObject mongoObject = new BasicDBObject();

    try {
        int hoppteller = 0;
        while (cursor.hasNext()) {
            mongoObject = (BasicDBObject) cursor.next();
            hoppteller++;
            ArrayList<Club> memberClubs = new ArrayList<>();
            ArrayList<License> memberLicenses = new ArrayList<>();

            BasicDBList referenceClubs = (BasicDBList) mongoObject.get("memberclubs");
            BasicDBList referenceLicenses = (BasicDBList) mongoObject.get("licenses");

            for (Object clubReference : referenceClubs) {
                for (Club club : clubs) {
                    if ((int) clubReference == club.getId()) {
                        memberClubs.add(club);
                    }
                }
            }

            for (Object licenseReference : referenceLicenses) {
                for (License license : licenses) {
                    if ((int) licenseReference == license.getId()) {
                        memberLicenses.add(license);
                    }
                }

            }

            Parachutist parachutist = new Parachutist(mongoObject.getObjectId("_id"), mongoObject.getInt("id"),
                    mongoObject.getString("melwinId"), null, // nakKey
                    new ArrayList<Club>(), // clubs
                    new ArrayList<License>(), // licenses
                    mongoObject.getString("firstname"), mongoObject.getString("lastname"),
                    mongoObject.getDate("birthdate"), mongoObject.getString("gender"),
                    mongoObject.getString("street"), mongoObject.getString("postnumber"),
                    mongoObject.getString("postplace"), mongoObject.getString("mail"),
                    mongoObject.getString("phone"), mongoObject.getString("password"));

            parachutist.setMemberclubs(memberClubs);
            parachutist.setLicenses(memberLicenses);

            parachutistsInMongoDB.add(parachutist);

        }
    } finally {
        cursor.close();
    }
    return parachutistsInMongoDB;
}

From source file:org.apache.gora.mongodb.utils.BSONDecorator.java

License:Apache License

/**
 * Access field as a date./* w  w w.  ja  v  a  2s . c o  m*/
 *
 * @param fieldName
 *          fully qualified name of the field to be accessed
 * @return value of the field as a date
 */
public Date getDate(String fieldName) {
    BasicDBObject parent = getFieldParent(fieldName);
    return parent.getDate(getLeafName(fieldName));
}

From source file:org.apache.rya.mongodb.instance.MongoDetailsAdapter.java

License:Apache License

public static RyaDetails toRyaDetails(final DBObject mongoObj) throws MalformedRyaDetailsException {
    final BasicDBObject basicObj = (BasicDBObject) mongoObj;
    try {//from w  ww.ja va2  s.  c o m
        return RyaDetails.builder().setRyaInstanceName(basicObj.getString(INSTANCE_KEY))
                .setRyaVersion(basicObj.getString(VERSION_KEY))
                .setEntityCentricIndexDetails(
                        new EntityCentricIndexDetails(basicObj.getBoolean(ENTITY_DETAILS_KEY)))
                //RYA-215            .setGeoIndexDetails(new GeoIndexDetails(basicObj.getBoolean(GEO_DETAILS_KEY)))
                .setPCJIndexDetails(getPCJIndexDetails(basicObj))
                .setTemporalIndexDetails(new TemporalIndexDetails(basicObj.getBoolean(TEMPORAL_DETAILS_KEY)))
                .setFreeTextDetails(new FreeTextIndexDetails(basicObj.getBoolean(FREETEXT_DETAILS_KEY)))
                .setProspectorDetails(new ProspectorDetails(
                        Optional.<Date>fromNullable(basicObj.getDate(PROSPECTOR_DETAILS_KEY))))
                .setJoinSelectivityDetails(new JoinSelectivityDetails(
                        Optional.<Date>fromNullable(basicObj.getDate(JOIN_SELECTIVITY_DETAILS_KEY))))
                .build();
    } catch (final Exception e) {
        throw new MalformedRyaDetailsException("Failed to make RyaDetail from Mongo Object, it is malformed.",
                e);
    }
}

From source file:org.apache.rya.mongodb.instance.MongoDetailsAdapter.java

License:Apache License

static PCJDetails.Builder toPCJDetails(final BasicDBObject dbo) {
    requireNonNull(dbo);//from   w  w w. j  a va  2  s .c  o m

    // PCJ ID.
    final PCJDetails.Builder builder = PCJDetails.builder().setId(dbo.getString(PCJ_ID_KEY));

    // PCJ Update Strategy if present.
    if (dbo.containsField(PCJ_UPDATE_STRAT_KEY)) {
        builder.setUpdateStrategy(PCJUpdateStrategy.valueOf(dbo.getString(PCJ_UPDATE_STRAT_KEY)));
    }

    // Last Update Time if present.
    if (dbo.containsField(PCJ_LAST_UPDATE_KEY)) {
        builder.setLastUpdateTime(dbo.getDate(PCJ_LAST_UPDATE_KEY));
    }

    return builder;
}

From source file:org.graylog2.system.stats.mongo.MongoProbe.java

License:Open Source License

private HostInfo createHostInfo() {
    final HostInfo hostInfo;
    final CommandResult hostInfoResult = adminDb.command("hostInfo");
    if (hostInfoResult.ok()) {
        final BasicDBObject systemMap = (BasicDBObject) hostInfoResult.get("system");
        final HostInfo.System system = HostInfo.System.create(new DateTime(systemMap.getDate("currentTime")),
                systemMap.getString("hostname"), systemMap.getInt("cpuAddrSize"),
                systemMap.getLong("memSizeMB"), systemMap.getInt("numCores"), systemMap.getString("cpuArch"),
                systemMap.getBoolean("numaEnabled"));
        final BasicDBObject osMap = (BasicDBObject) hostInfoResult.get("os");
        final HostInfo.Os os = HostInfo.Os.create(osMap.getString("type"), osMap.getString("name"),
                osMap.getString("version"));

        final BasicDBObject extraMap = (BasicDBObject) hostInfoResult.get("extra");
        final HostInfo.Extra extra = HostInfo.Extra.create(extraMap.getString("versionString"),
                extraMap.getString("libcVersion"), extraMap.getString("kernelVersion"),
                extraMap.getString("cpuFrequencyMHz"), extraMap.getString("cpuFeatures"),
                extraMap.getString("scheduler"), extraMap.getLong("pageSize", -1l),
                extraMap.getLong("numPages", -1l), extraMap.getLong("maxOpenFiles", -1l));

        hostInfo = HostInfo.create(system, os, extra);
    } else {/*from  w  w  w .  jav a  2s . c  o m*/
        hostInfo = null;
    }

    return hostInfo;
}

From source file:org.mybatis.jpetstore.domain.Order.java

License:Apache License

public static Order fromDBObject(@Nonnull final DBObject dbObj) {

    checkNotNull(dbObj, "Argument[dbObj] must not be null");

    BasicDBObject orderObj = (BasicDBObject) dbObj;
    Order order = new Order();

    order.setOrderId(orderObj.getInt("order_id"));
    order.setUsername(orderObj.getString("username"));
    order.setOrderDate(orderObj.getDate("order_date"));
    order.setCourier(orderObj.getString("courier"));

    String totalPrice = orderObj.getString("total_price");
    if (!isNullOrEmpty(totalPrice)) {
        order.setTotalPrice(new BigDecimal(totalPrice));
    }/*from www. j  a  v  a 2  s .c o  m*/
    order.setLocale(orderObj.getString("locale"));
    order.setStatus(orderObj.getString("status"));

    BasicDBObject shipToObj = (BasicDBObject) orderObj.get("shipping_address");
    order.setShipToFirstName(shipToObj.getString("ship_to_firstname"));
    order.setShipToLastName(shipToObj.getString("ship_to_lastname"));
    order.setShipAddress1(shipToObj.getString("ship_address_1"));
    order.setShipAddress2(shipToObj.getString("ship_address_2"));
    order.setShipCity(shipToObj.getString("ship_city"));
    order.setShipState(shipToObj.getString("ship_state"));
    order.setShipZip(shipToObj.getString("ship_zip"));
    order.setShipCountry(shipToObj.getString("ship_country"));

    BasicDBObject billToObj = (BasicDBObject) orderObj.get("billing_address");
    order.setBillToFirstName(billToObj.getString("bill_to_firstname"));
    order.setBillToLastName(billToObj.getString("bill_to_lastname"));
    order.setBillAddress1(billToObj.getString("bill_address_1"));
    order.setBillAddress2(billToObj.getString("bill_address_2"));
    order.setBillCity(billToObj.getString("bill_city"));
    order.setBillState(billToObj.getString("bill_state"));
    order.setBillZip(billToObj.getString("bill_zip"));
    order.setBillCountry(billToObj.getString("bill_country"));

    BasicDBObject paymentInfoObj = (BasicDBObject) orderObj.get("payment_info");
    order.setCreditCard(paymentInfoObj.getString("credit_card"));
    order.setExpiryDate(paymentInfoObj.getString("expiry_date"));
    order.setCardType(paymentInfoObj.getString("card_type"));

    List<DBObject> lineItemObjs = (ArrayList<DBObject>) orderObj.get("line_items");
    List<LineItem> lineItems = new ArrayList<>();

    for (DBObject lineItemObj : lineItemObjs) {
        LineItem lineItem = LineItem.fromDBObject(lineItemObj);
        lineItem.setOrderId(order.getOrderId());
        lineItems.add(lineItem);
    }
    order.setLineItems(lineItems);
    return order;
}

From source file:org.openhab.persistence.mongodb.internal.MongoDBPersistenceService.java

License:Open Source License

@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
    if (!initialized) {
        return Collections.emptyList();
    }//  www  . ja va2 s.c  om

    if (!isConnected()) {
        connectToDatabase();
    }

    if (!isConnected()) {
        return Collections.emptyList();
    }

    String name = filter.getItemName();
    Item item = getItem(name);

    List<HistoricItem> items = new ArrayList<HistoricItem>();
    DBObject query = new BasicDBObject();
    if (filter.getItemName() != null) {
        query.put(FIELD_ITEM, filter.getItemName());
    }
    if (filter.getState() != null && filter.getOperator() != null) {
        String op = convertOperator(filter.getOperator());
        Object value = convertValue(filter.getState());
        query.put(FIELD_VALUE, new BasicDBObject(op, value));
    }
    if (filter.getBeginDate() != null) {
        query.put(FIELD_TIMESTAMP, new BasicDBObject("$gte", filter.getBeginDate()));
    }
    if (filter.getEndDate() != null) {
        query.put(FIELD_TIMESTAMP, new BasicDBObject("$lte", filter.getEndDate()));
    }

    Integer sortDir = (filter.getOrdering() == Ordering.ASCENDING) ? 1 : -1;
    DBCursor cursor = this.mongoCollection.find(query).sort(new BasicDBObject(FIELD_TIMESTAMP, sortDir))
            .skip(filter.getPageNumber() * filter.getPageSize()).limit(filter.getPageSize());

    while (cursor.hasNext()) {
        BasicDBObject obj = (BasicDBObject) cursor.next();

        final State state;
        if (item instanceof NumberItem) {
            state = new DecimalType(obj.getDouble(FIELD_VALUE));
        } else if (item instanceof DimmerItem) {
            state = new PercentType(obj.getInt(FIELD_VALUE));
        } else if (item instanceof SwitchItem) {
            state = OnOffType.valueOf(obj.getString(FIELD_VALUE));
        } else if (item instanceof ContactItem) {
            state = OpenClosedType.valueOf(obj.getString(FIELD_VALUE));
        } else if (item instanceof RollershutterItem) {
            state = new PercentType(obj.getInt(FIELD_VALUE));
        } else if (item instanceof ColorItem) {
            state = new HSBType(obj.getString(FIELD_VALUE));
        } else if (item instanceof DateTimeItem) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(obj.getDate(FIELD_VALUE));
            state = new DateTimeType(cal);
        } else {
            state = new StringType(obj.getString(FIELD_VALUE));
        }

        items.add(new MongoDBItem(name, state, obj.getDate(FIELD_TIMESTAMP)));
    }

    return items;
}