Example usage for com.mongodb DBObject toMap

List of usage examples for com.mongodb DBObject toMap

Introduction

In this page you can find the example usage for com.mongodb DBObject toMap.

Prototype

Map toMap();

Source Link

Document

Returns a map representing this BSONObject.

Usage

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<AccessToken> getAccessTokenByUserIdAndClientApp(String userId, String clientId) {
    List<AccessToken> accessTokens = new ArrayList<AccessToken>();
    BasicDBObject dbObject = new BasicDBObject();
    dbObject.put(ACCESS_TOKEN_USER_ID, userId);
    dbObject.put(CLIENTS_CLIENTID, clientId);
    dbObject.put(ACCESS_TOKEN_VALID, true);
    DBCollection coll = db.getCollection(ACCESS_TOKEN_COLLECTION_NAME);
    List<DBObject> list = coll.find(dbObject).toArray();
    for (DBObject object : list) {
        Map<String, Object> mapLoaded = object.toMap();
        // convert details list to String
        if (mapLoaded.get("details") instanceof BasicDBObject) {
            BasicDBObject details = (BasicDBObject) mapLoaded.get("details");
            mapLoaded.put("details", details.toString());
        }//from w  w  w. j  ava  2 s  .  c  om
        AccessToken loadedAccessToken = AccessToken.loadFromMap(mapLoaded);
        accessTokens.add(loadedAccessToken);
    }
    return accessTokens;
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

License:Apache License

private void printServerStats(DBObject serverStats) {
    if (serverStats != null) {
        String metricPath = getServerStatsMetricPrefix();
        printNumericMetricsFromMap(serverStats.toMap(), metricPath);
    }/*from  www.  j av  a 2 s  . c  o m*/
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

License:Apache License

private void printDBStats(DBObject dbStats) {
    if (dbStats != null) {
        String dbStatsPath = getDBStatsMetricPrefix(dbStats.get("db").toString());
        printNumericMetricsFromMap(dbStats.toMap(), dbStatsPath);
    }/*from  w ww .  java  2  s. c  o  m*/
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

License:Apache License

private void printCollectionStats(String dbName, String collectionName, DBObject collectionStats) {
    if (collectionStats != null) {
        String collectionStatsPath = getCollectionStatsMetricPrefix(dbName, collectionName);
        printNumericMetricsFromMap(collectionStats.toMap(), collectionStatsPath);
    } else {/*from   w  ww.  j  ava 2  s .  c  om*/
        logger.info("CollectionStats for db " + dbName + "found to be NULL");
    }
}

From source file:com.avanza.ymer.MirroredObjectLoader.java

License:Apache License

private Optional<LoadedDocument<T>> tryPatchAndConvert(DBObject object) {
    try {/*ww  w.j  av  a2s  .  com*/
        Optional<LoadedDocument<T>> result;
        try {
            result = patchAndConvert(new BasicDBObject(object.toMap()));
        } catch (RuntimeException e) {
            // MongoConverter is not thread-safe due to a bug in AbstractMappingContext.addPersistentEntity().
            // The bug occurs at most once or twice per collection but will produce objects without any properties set
            // Resolve it temporarily by retrying.
            log.warn("Failed to load dbObject=" + object + ". Retrying.", e);
            result = patchAndConvert(new BasicDBObject(object.toMap()));
        }
        long loaded = numLoadedObjects.incrementAndGet();
        if (loaded % 10000 == 0) {
            log.info("Status: loaded {} records for collection {}", loaded, mirroredObject.getCollectionName());
        }
        return result;
    } catch (RuntimeException e) {
        log.error("Unable to load dbObject=" + object, e);
        throw e;
    }
}

From source file:com.avanza.ymer.MirroredObjectLoader.java

License:Apache License

private BasicDBObject findById(Object id) {
    final Object convertedId = documentConverter.convertToMongoObject(id);
    final DBObject dbObject = documentCollection.findById(convertedId);
    return dbObject != null ? new BasicDBObject(dbObject.toMap()) : null;
}

From source file:com.aw.app.action.UserAction.java

/**
 * /*  w ww .ja  v a2 s  .co m*/
 * @param uid
 * @param buildCost
 * @param type
 * @param action
 * @return 
 */
public boolean updateUserResource(Object uid, Object buildCost, String type, String action) {
    boolean state = false;
    boolean townHallPass = false;
    DBObject user = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user")
            .findOne(new BasicDBObject("uid", uid));
    String tid = BuildingAction.resourceStorage[0];
    String maxField = "";
    String townHallStorageField = "";
    long amount = 0;
    if (user != null) {
        type = type.toLowerCase();
        if ("spens".equalsIgnoreCase(type)) {
            if ("increase".equalsIgnoreCase(action)) {
                long spens = (Long) user.get("spens");
                long cost = (Long) buildCost;
                spens += cost;
                BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("spens", spens));
                WriteResult result = MongoDbUtil.updateCollection("aw_user", new BasicDBObject("uid", uid),
                        update);
                return result.getLastError().ok();
            } else {
                long spens = (Long) user.get("spens");
                long cost = (Long) buildCost;
                spens -= cost;
                BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("spens", spens));
                WriteResult result = MongoDbUtil.updateCollection("aw_user", new BasicDBObject("uid", uid),
                        update);
                return result.getLastError().ok();
            }
        } else if ("gold".equalsIgnoreCase(type)) {
            tid = BuildingAction.resourceStorage[0];
            maxField = "max_stored_gold";
            townHallStorageField = "gold_stored";

        } else if ("mithril".equalsIgnoreCase(type)) {
            tid = BuildingAction.resourceStorage[1];
            maxField = "max_stored_mithril";
            townHallStorageField = "mithril_stored";
        } else if ("dark mithril".equalsIgnoreCase(type)) {
            tid = BuildingAction.resourceStorage[2];
            maxField = "max_stored_dark_mithril";
            townHallStorageField = "dark_mithril_stored";
        }

        DBCursor buildings = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                .find(new BasicDBObject().append("uid", uid).append("tid", tid));
        if ("increase".equalsIgnoreCase(action)) {
            DBObject townHallBase = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                    .findOne(new BasicDBObject().append("uid", uid).append("tid", TownHallAction.townHallTid));
            BuildingBase buildingBase = new BuildingBase(townHallBase.toMap());
            if (buildingBase.containsField("buildingTownhalls")) {
                BuildingTownhall townHall = buildingBase.getBuildingTownhalls().get(0);
                if (townHall.getLong("townHallStorageField") < townHall.getLong("maxField")) {
                    amount = (Long) buildCost;
                    long temp = amount;
                    long total = townHall.getLong("townHallStorageField") + amount;
                    if (total > townHall.getLong("maxField")) {
                        amount = amount - townHall.getLong("maxField")
                                - townHall.getLong("townHallStorageField");
                        total = townHall.getLong("maxField");
                    } else {
                        amount = 0;
                    }
                    townHall.put("townHallStorageField", total);
                    // update
                    BasicDBObject query = new BasicDBObject().append("uid", uid).append("tid",
                            TownHallAction.townHallTid);
                    BasicDBObject update = new BasicDBObject("$set",
                            new BasicDBObject("buildingTownhalls", buildingBase.getBuildingTownhalls()));
                    WriteResult result = MongoDbUtil.updateCollection("aw_building_base", query, update);
                    townHallPass = result.getLastError().ok();
                    if (!result.getLastError().ok())
                        amount = temp;
                }
            }
        }
        long subAmount = amount;
        int resourceCount = 0;
        if (buildings != null) {
            while (buildings.hasNext()) {
                DBObject building = buildings.next();
                BuildingBase bb = new BuildingBase(building.toMap());
                List<BuildingResource> resources = (List<BuildingResource>) bb.get("buildingResources");
                BuildingResource resource = new BuildingResource(resources.get(0).toMap());
                if ("decrease".equalsIgnoreCase(action)) {
                    if (resource.getLong("resource_stored") > 0
                            & resource.getLong("resource_stored") <= subAmount) {
                        subAmount -= resource.getLong("resource_stored");
                        resource.put("resource_stored", 0);
                        // Update here...
                        resourceCount++;
                    } else if (resource.getLong("resource_stored") > 0
                            & resource.getLong("resource_stored") > subAmount) {
                        resource.put("resource_stored", resource.getLong("resource_stored") - subAmount);
                        subAmount = 0;
                        // Update here
                        resourceCount++;
                    }
                } else if ("increase".equalsIgnoreCase(action)) {
                    if (subAmount > 0) {
                        long total = resource.getLong("resource_stored") + subAmount;
                        if (resource.getLong("$maxField") == total) {
                            resource.put("resource_stored", total);
                            // update here
                            subAmount = 0;
                            state = true;
                        } else if (total > resource.getLong("$maxField")
                                && resource.getLong("$maxField") > resource.getLong("resource_stored")) {
                            long difference = resource.getLong("$maxField")
                                    - resource.getLong("resource_stored");
                            subAmount -= difference;
                            resource.put("resource_stored", resource.getLong("$maxField"));
                            resourceCount++;
                            // update resouce
                        }
                    }
                }
            }
        }
        /**** First Fill the Town Hall for increase resource action ***/
        if (subAmount > 0 && "decrease".equalsIgnoreCase(action)) {
            DBObject townHallBase = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                    .findOne(new BasicDBObject().append("uid", uid).append("tid", TownHallAction.townHallTid));
            List<BuildingTownhall> townHallList = (List<BuildingTownhall>) townHallBase
                    .get("buildingTownhalls");
            if (townHallList != null) {
                BuildingTownhall townhall = townHallList.get(0);
                townhall.put("townHallStorageField", townhall.getLong("townHallStorageField") - subAmount);
                if (townhall.getLong("townHallStorageField") < 0) {
                    state = false;
                } else {
                    // update town hall
                    townHallPass = true;
                    state = true;
                }
            }
        }
    }
    if (townHallPass && !state)
        state = townHallPass;

    return state;
}

From source file:com.badger.observationmongotest.execute.Main.java

public static void main(String[] args) throws ParseException, UnknownHostException, IOException {

    List<Observation> observations = new LinkedList();

    Customer customer = new Customer();

    customer.setName("Mr Customer");
    customer.setId("cid123");
    customer.setBackOfficeId("boid123");

    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    String dateStr = "2015/08/10";
    Date date = format.parse(dateStr);

    CustomerObservationReport report = new CustomerObservationReport(customer);

    MonthlyProductOrderCountIssue productOrderCountIssue = new MonthlyProductOrderCountIssue();
    productOrderCountIssue.setActionRequired(true);
    productOrderCountIssue.setCatagory("product issue");
    productOrderCountIssue.setCurrentYear(2015);
    productOrderCountIssue.setCurrentYearValue(30);
    productOrderCountIssue.setCustomerId(customer.getId());
    productOrderCountIssue.setDate(date);
    productOrderCountIssue.setDrop(50.0);
    productOrderCountIssue.setLastYearValue(60);
    productOrderCountIssue.setMonth("Feb");
    productOrderCountIssue.setObservationId("oid123");
    productOrderCountIssue.setPreviousYear(2014);
    productOrderCountIssue.setProductName("cool product");
    productOrderCountIssue.setScore(4500);
    productOrderCountIssue.setType("monthy order count");

    MonthlyProductOrderCountIssue monthlyProductOrderCountIssue = new MonthlyProductOrderCountIssue();
    monthlyProductOrderCountIssue.setActionRequired(true);
    monthlyProductOrderCountIssue.setCatagory("product issue");
    monthlyProductOrderCountIssue.setCurrentYear(2015);
    monthlyProductOrderCountIssue.setCurrentYearValue(30);
    monthlyProductOrderCountIssue.setCustomerId(customer.getId());
    monthlyProductOrderCountIssue.setDate(date);
    monthlyProductOrderCountIssue.setDrop(50.0);
    monthlyProductOrderCountIssue.setLastYearValue(60);
    monthlyProductOrderCountIssue.setMonth("March");
    monthlyProductOrderCountIssue.setObservationId("oid456");
    monthlyProductOrderCountIssue.setPreviousYear(2014);
    monthlyProductOrderCountIssue.setProductName("cool product");
    monthlyProductOrderCountIssue.setScore(4500);
    monthlyProductOrderCountIssue.setType("monthy order count");

    MonthlyProductRevenueIssue monthlyProductRevenueIssue = new MonthlyProductRevenueIssue();
    monthlyProductRevenueIssue.setActionRequired(true);
    monthlyProductRevenueIssue.setCatagory("product issue");
    monthlyProductRevenueIssue.setCurrentYear(2015);
    monthlyProductRevenueIssue.setCurrentYearValue(3000.00);
    monthlyProductRevenueIssue.setCustomerId(customer.getId());
    monthlyProductRevenueIssue.setDate(date);
    monthlyProductRevenueIssue.setDrop(50.0);
    monthlyProductRevenueIssue.setLastYearValue(6000.00);
    monthlyProductRevenueIssue.setMonth("Dec");
    monthlyProductRevenueIssue.setObservationId("oid3445");
    monthlyProductRevenueIssue.setPreviousYear(2014);
    monthlyProductRevenueIssue.setProductName("test product");
    monthlyProductRevenueIssue.setScore(5667);
    monthlyProductRevenueIssue.setType("monthly product ervenue");

    MonthlyRevenueIssue monthlyRevenueIssue = new MonthlyRevenueIssue();
    monthlyRevenueIssue.setActionRequired(true);
    monthlyRevenueIssue.setCatagory("Reveue Issue");
    monthlyRevenueIssue.setCurrentValue(3000);
    monthlyRevenueIssue.setCurrentYear(2015);
    monthlyRevenueIssue.setCustomerId(customer.getId());
    monthlyRevenueIssue.setDate(date);/*  w w w  . j av a2 s .c  o m*/
    monthlyRevenueIssue.setDrop(45.0);
    monthlyRevenueIssue.setMonth("Nov");
    monthlyRevenueIssue.setObservationId("oid4646646");
    monthlyRevenueIssue.setPreviousValue(5000);
    monthlyRevenueIssue.setPreviousYear(2014);
    monthlyRevenueIssue.setScore(5600);
    monthlyRevenueIssue.setType("monthly revenue issue");

    observations.add(monthlyRevenueIssue);
    observations.add(monthlyProductRevenueIssue);
    observations.add(monthlyProductOrderCountIssue);
    observations.add(productOrderCountIssue);

    report.setAccountId("acid123");

    report.addObservations(observations);

    // BasicDBObject documentDetail = new BasicDBObject();
    /**
     * documentDetail.put("accountId", report.getAccountId());
     * documentDetail.put("customerId", report.getCustomerId());
     * documentDetail.put("Observations",
     * report.getObservations().toString()); *
     */
    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("ObservationReports");

    DBCollection col = db.getCollection("reports");

    Gson gson = new Gson();

    String json = gson.toJson(report);

    DBObject dbObject = (DBObject) JSON.parse(json);

    col.insert(dbObject);

    //DBObject query = BasicDBObjectBuilder.start().add("_id", report.getId()).get();
    DBCursor cursor = col.find();

    while (cursor.hasNext()) {
        System.out.println("First Cursor: " + cursor.next().get("observations"));
    }

    while (cursor.hasNext()) {

        DBObject dbobj = cursor.next();

        Map map = dbObject.toMap();

        CustomerObservationReport report2 = new CustomerObservationReport(customer);

        //System.out.println("observations " +dbObject.get("observations"));

        List<Observation> dbObservations = (List<Observation>) dbObject.get("observations");

        report2.setAccountId(report.getAccountId());
        report2.setCustomerId(report.getCustomerName());
        report2.setBackOfficeId(report.getBackOfficeId());
        report2.setObservations((dbObservations));

        System.out.println(report2.getClass().getTypeName());
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.EmbedDBObjectFilter.java

License:Apache License

@SuppressWarnings("unchecked")
private static DBObject filterFields(DBObject currObject, Collection<String> fields) {
    if (fields == null || fields.isEmpty()) {
        return currObject;
    }//from   w w w. j  av a 2 s  .  co m

    Set<String> keys = (Set<String>) currObject.toMap().keySet();
    for (String key : keys) {
        if (!fields.contains(key)) {
            currObject.removeField(key);
        }
    }
    return currObject;
}

From source file:com.edduarte.argus.diff.Difference.java

License:Apache License

public Difference(DBObject mongoObject) {
    super(mongoObject.toMap());
}