Example usage for com.mongodb BasicDBObject getLong

List of usage examples for com.mongodb BasicDBObject getLong

Introduction

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

Prototype

public long getLong(final String key) 

Source Link

Document

Returns the value of a field as a long .

Usage

From source file:com.liferay.mongodb.hook.service.impl.MongoExpandoValueLocalServiceImpl.java

License:Open Source License

@Override
public ExpandoValue addValue(long classNameId, long tableId, long columnId, long classPK, String data)
        throws PortalException {

    ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.getTable(tableId);

    ExpandoColumn expandoColumn = ExpandoColumnLocalServiceUtil.getColumn(columnId);

    ExpandoValue expandoValue = ExpandoValueUtil.create(0);

    expandoValue.setCompanyId(expandoTable.getCompanyId());
    expandoValue.setTableId(tableId);//from ww  w .  j  av a2s. c  om
    expandoValue.setColumnId(columnId);
    expandoValue.setRowId(classPK);
    expandoValue.setClassNameId(classNameId);
    expandoValue.setClassPK(classPK);
    expandoValue.setData(data);

    DBCollection dbCollection = MongoDBUtil.getCollection(expandoTable);

    DBObject queryDBObject = new BasicDBObject();

    queryDBObject.put("companyId", expandoTable.getCompanyId());
    queryDBObject.put("tableId", tableId);
    queryDBObject.put("rowId", classPK);
    queryDBObject.put("classNameId", classNameId);
    queryDBObject.put("classPK", classPK);

    BasicDBObject expandoValueDBObject = (BasicDBObject) dbCollection.findOne(queryDBObject);

    if (expandoValueDBObject != null) {
        expandoValue.setValueId(expandoValueDBObject.getLong("valueId"));

        DBObject operatorDBObject = new BasicDBObject();

        DBObject updateExpandoValueDBObject = new BasicDBObject(expandoColumn.getName(),
                getData(expandoColumn, expandoValue));

        operatorDBObject.put(MongoOperator.SET, updateExpandoValueDBObject);

        dbCollection.update(expandoValueDBObject, operatorDBObject);
    } else {
        long valueId = CounterLocalServiceUtil.increment();

        expandoValue.setValueId(valueId);

        queryDBObject.put("valueId", valueId);
        queryDBObject.put(expandoColumn.getName(), getData(expandoColumn, expandoValue));

        dbCollection.insert(queryDBObject);
    }

    return expandoValue;
}

From source file:com.liferay.mongodb.hook.service.impl.MongoExpandoValueLocalServiceImpl.java

License:Open Source License

@Override
public void addValues(long classNameId, long tableId, List<ExpandoColumn> expandoColumns, long classPK,
        Map<String, String> data) throws PortalException {

    ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.getTable(tableId);

    ExpandoValue expandoValue = ExpandoValueUtil.create(0);

    expandoValue.setCompanyId(expandoTable.getCompanyId());
    expandoValue.setTableId(tableId);// ww w  .jav a2s.c o m
    expandoValue.setRowId(classPK);
    expandoValue.setClassNameId(classNameId);
    expandoValue.setClassPK(classPK);

    DBCollection dbCollection = MongoDBUtil.getCollection(expandoTable);

    DBObject queryDBObject = new BasicDBObject();

    queryDBObject.put("companyId", expandoTable.getCompanyId());
    queryDBObject.put("tableId", tableId);
    queryDBObject.put("rowId", classPK);
    queryDBObject.put("classNameId", classNameId);
    queryDBObject.put("classPK", classPK);

    BasicDBObject expandoValueDBObject = (BasicDBObject) dbCollection.findOne(queryDBObject);

    if (expandoValueDBObject != null) {
        expandoValue.setValueId(expandoValueDBObject.getLong("valueId"));

        DBObject operatorDBObject = new BasicDBObject();

        DBObject updateExpandoValueDBObject = new BasicDBObject();

        updateExpandoValueDBObject(updateExpandoValueDBObject, expandoColumns, data, expandoValue);

        operatorDBObject.put(MongoOperator.SET, updateExpandoValueDBObject);

        dbCollection.update(expandoValueDBObject, operatorDBObject);
    } else {
        long valueId = CounterLocalServiceUtil.increment();

        expandoValue.setValueId(valueId);

        queryDBObject.put("valueId", valueId);

        updateExpandoValueDBObject(queryDBObject, expandoColumns, data, expandoValue);

        dbCollection.insert(queryDBObject);
    }
}

From source file:com.liferay.mongodb.hook.service.impl.MongoExpandoValueLocalServiceImpl.java

License:Open Source License

protected ExpandoValue toExpandoValue(BasicDBObject expandoValueDBObject, ExpandoColumn expandoColumn)
        throws PortalException {

    ExpandoValue expandoValue = ExpandoValueUtil.create(0);

    expandoValue.setCompanyId(expandoValueDBObject.getLong("companyId"));
    expandoValue.setTableId(expandoValueDBObject.getLong("tableId"));
    expandoValue.setColumnId(expandoColumn.getColumnId());
    expandoValue.setRowId(expandoValueDBObject.getLong("rowId"));
    expandoValue.setClassNameId(expandoValueDBObject.getLong("classNameId"));
    expandoValue.setClassPK(expandoValueDBObject.getLong("classPK"));

    Object value = expandoValueDBObject.get(expandoColumn.getName());

    if (value == null) {
        return expandoValue;
    }// w ww  . java  2  s.c  o  m

    int type = expandoColumn.getType();

    if (type == ExpandoColumnConstants.BOOLEAN) {
        expandoValue.setBoolean((Boolean) value);
    } else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) {
        List<Boolean> list = (List<Boolean>) value;

        expandoValue.setBooleanArray(ArrayUtil.toArray(list.toArray(new Boolean[list.size()])));
    } else if (type == ExpandoColumnConstants.DATE) {
        expandoValue.setDate((Date) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.DATE_ARRAY) {
        List<Date> list = (List<Date>) value;

        expandoValue.setDateArray(list.toArray(new Date[list.size()]));
    } else if (type == ExpandoColumnConstants.DOUBLE) {
        expandoValue.setDouble((Double) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) {
        List<Double> list = (List<Double>) value;

        expandoValue.setDoubleArray(ArrayUtil.toArray(list.toArray(new Double[list.size()])));
    } else if (type == ExpandoColumnConstants.FLOAT) {
        expandoValue.setFloat((Float) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.FLOAT_ARRAY) {
        List<Float> list = (List<Float>) value;

        expandoValue.setFloatArray(ArrayUtil.toArray(list.toArray(new Float[list.size()])));
    } else if (type == ExpandoColumnConstants.INTEGER) {
        expandoValue.setInteger((Integer) value);
    } else if (type == ExpandoColumnConstants.INTEGER_ARRAY) {
        List<Integer> list = (List<Integer>) value;

        expandoValue.setIntegerArray(ArrayUtil.toArray(list.toArray(new Integer[list.size()])));
    } else if (type == ExpandoColumnConstants.LONG) {
        expandoValue.setLong((Long) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.LONG_ARRAY) {
        List<Long> list = (List<Long>) value;

        expandoValue.setLongArray(ArrayUtil.toArray(list.toArray(new Long[list.size()])));
    } else if (type == ExpandoColumnConstants.SHORT) {
        expandoValue.setShort((Short) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.SHORT_ARRAY) {
        List<Short> list = (List<Short>) value;

        expandoValue.setShortArray(ArrayUtil.toArray(list.toArray(new Short[list.size()])));
    } else if (type == ExpandoColumnConstants.STRING_ARRAY) {
        List<String> list = (List<String>) value;

        expandoValue.setStringArray(list.toArray(new String[list.size()]));
    } else {
        expandoValue.setString((String) value);
    }

    return expandoValue;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public long countConflicts(Filter filter, List<String> properties) {
    LOG.info("Calculating conflicts count");
    DBCollection collection = this.getCollection(Element.class);
    List<DBObject> list = new ArrayList<DBObject>();
    list.add(new BasicDBObject("$match", this.getCachedFilter(filter)));
    list.add(new BasicDBObject("$unwind", "$metadata"));
    list.add(new BasicDBObject("$project", new BasicDBObject("status", "$metadata.status").append("uid", 1)
            .append("property", "$metadata.property")));
    list.add(new BasicDBObject("$match", new BasicDBObject("property", new BasicDBObject("$in", properties))));
    list.add(new BasicDBObject("$group",
            new BasicDBObject("_id", "$uid").append("statuses", new BasicDBObject("$addToSet", "$status"))));
    BasicDBList in = new BasicDBList();
    in.add("CONFLICT");
    list.add(new BasicDBObject("$match", new BasicDBObject("statuses", new BasicDBObject("$in", in))));
    list.add(new BasicDBObject("$group",
            new BasicDBObject("_id", null).append("count", new BasicDBObject("$sum", 1))));
    Iterable<DBObject> resultIterable = collection.aggregate(list).results();
    BasicDBObject result = (BasicDBObject) resultIterable.iterator().next();
    return result.getLong("count");

}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

/**
 * Parses the histogram results out of a {@link DBObject}. This method assumes
 * that the passed db object contains a list of {@link DBObject}s with every
 * result. (As it is outputted by the map reduce job).
 *
 * @param object the object to parse.//ww w .ja va 2 s .  c  om
 * @return the histogram map.
 */
private Map<String, Long> parseHistogramResults(DBObject object) {
    Map<String, Long> histogram = new HashMap<String, Long>();

    if (object == null) {
        return histogram;
    }

    List<BasicDBObject> results = (List<BasicDBObject>) object;
    for (final BasicDBObject dbo : results) {
        histogram.put(DataHelper.removeTrailingZero(dbo.getString("_id")), dbo.getLong("value"));
    }

    return histogram;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

/**
 * Parses the numeric statistics out of given {@link DBObject}.
 *
 * @param object the object to parse.//from  ww  w. j a  v  a2s .c om
 * @return a {@link NumericStatistics} object that wraps the results.
 */
private NumericStatistics parseNumericStatistics(DBObject object) {
    NumericStatistics result = null;

    if (object == null) {
        result = new NumericStatistics();

    } else {

        BasicDBObject obj = (BasicDBObject) object;

        long count = obj.getLong("count");
        double sum, min, max, avg, std, var;
        try {
            sum = obj.getDouble("sum");
        } catch (Exception e) {
            sum = 0;
        }
        try {
            min = obj.getDouble("min");
        } catch (Exception e) {
            min = 0;
        }
        try {
            max = obj.getDouble("max");
        } catch (Exception e) {
            max = 0;
        }
        try {
            avg = obj.getDouble("avg");
        } catch (Exception e) {
            avg = 0;
        }
        try {
            std = obj.getDouble("stddev");
        } catch (Exception e) {
            std = 0;
        }
        try {
            var = obj.getDouble("variance");
        } catch (Exception e) {
            var = 0;
        }
        result = new NumericStatistics(count, sum, min, max, avg, std, var);
    }

    return result;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public Map<String, Long> parseMapReduce(DBObject object, String property) {

    Map<String, Long> histogram = new HashMap<String, Long>();

    if (object == null) {
        return histogram;
    }/*  ww  w  .j a  va 2s  . co  m*/

    List<BasicDBObject> results = (List<BasicDBObject>) object;
    for (final BasicDBObject dbo : results) {

        String p = ((BasicDBObject) dbo.get("_id")).getString("property");
        String val = ((BasicDBObject) dbo.get("_id")).getString("value");
        try {
            long count = dbo.getLong("value");
            String type = getCache().getProperty(p).getType();
            if (type.equals(PropertyType.DATE.toString())) {
                try {
                    Double v = Double.parseDouble(val);
                    int i = v.intValue();
                    histogram.put(String.valueOf(i), count);
                } catch (NumberFormatException nfe) {
                    histogram.put(val, count);
                }
            } else
                histogram.put(val, count);
        } catch (Exception e) {
            BasicDBObject v = (BasicDBObject) dbo.get("value");
            long sum, min, max, avg, std, var, count;
            try {
                count = v.getLong("count");
            } catch (Exception ex) {
                count = 0;
            }
            try {
                sum = v.getLong("sum");
            } catch (Exception ex) {
                sum = 0;
            }
            try {
                min = v.getLong("min");
            } catch (Exception ex) {
                min = 0;
            }
            try {
                max = v.getLong("max");
            } catch (Exception ex) {
                max = 0;
            }
            try {
                avg = v.getLong("avg");
            } catch (Exception ex) {
                avg = 0;
            }
            try {
                std = v.getLong("stddev");
            } catch (Exception ex) {
                std = 0;
            }
            try {
                var = v.getLong("variance");
            } catch (Exception ex) {
                var = 0;
            }
            histogram.put("sum", sum);
            histogram.put("min", min);
            histogram.put("max", max);
            histogram.put("avg", avg);
            histogram.put("std", std);
            histogram.put("var", var);
            histogram.put("count", count);
        }
    }
    return histogram;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public Map<String, Long> parseAggregation(List<BasicDBObject> aggregation, String propert, Boolean getStats) {
    Map<String, Long> histogram = new HashMap<String, Long>();

    if (aggregation == null) {
        return histogram;
    }//w ww .j a  va 2  s .  c o m
    for (BasicDBObject basicDBObject : aggregation) {
        String id = basicDBObject.getString("_id");
        try {
            if (!getStats) {
                long count = basicDBObject.getLong("count");
                histogram.put(id, count);
            } else {
                long sum, min, max, avg, std, var, count;
                try {
                    count = basicDBObject.getLong("count");
                } catch (Exception ex) {
                    count = 0;
                }
                try {
                    sum = basicDBObject.getLong("sum");
                } catch (Exception ex) {
                    sum = 0;
                }
                try {
                    min = basicDBObject.getLong("min");
                } catch (Exception ex) {
                    min = 0;
                }
                try {
                    max = basicDBObject.getLong("max");
                } catch (Exception ex) {
                    max = 0;
                }
                try {
                    avg = basicDBObject.getLong("avg");
                } catch (Exception ex) {
                    avg = 0;
                }
                try {
                    std = basicDBObject.getLong("stdDev");
                } catch (Exception ex) {
                    std = 0;
                }
                try {
                    var = std * std;
                } catch (Exception ex) {
                    var = 0;
                }
                histogram.put("sum", sum);
                histogram.put("min", min);
                histogram.put("max", max);
                histogram.put("avg", avg);
                histogram.put("std", std);
                histogram.put("var", var);
                histogram.put("count", count);
            }
        } catch (Exception e) {
        }
    }
    return histogram;
}

From source file:com.streamreduce.core.transformer.message.AgentMessageTransformer.java

License:Apache License

/**
 * {@inheritDoc}/*from w ww . ja  v a  2 s  . co m*/
 */
@Override
public String doTransform(Event event) {
    EventId eventId = event.getEventId();
    Map<String, Object> eventMetadata = event.getMetadata();
    String msg = "";

    switch (eventId) {
    case ACTIVITY:
        BasicDBObject payload = (BasicDBObject) eventMetadata.get("payload");
        StringBuilder sb = new StringBuilder();

        sb.append("Current system overview at ").append(eventMetadata.get("activityGenerated")) // Should we format this?
                .append("\n\n");

        sb.append("Uptime: ").append(payload.getString("uptime")).append("s\n").append("Disk usage:\n");

        BasicDBObject partitionsObj = (BasicDBObject) payload.get("partitions");
        Set<String> partitions = new TreeSet<>(partitionsObj.keySet());

        for (String key : partitions) {
            BasicDBObject partition = (BasicDBObject) partitionsObj.get(key);
            double totalAsKb = partition.getDouble("total");

            // Certain devices show as 0.00GB and should be pruned
            if (totalAsKb == 0) {
                continue;
            }

            double totalAsGB = MessageUtils.kbToGB(totalAsKb);
            double usedAsGB = MessageUtils.kbToGB(partition.getDouble("used"));
            double freeAsGB = MessageUtils.kbToGB(partition.getDouble("free"));

            sb.append("  ").append(key).append(": Total ").append(MessageUtils.roundAndTruncate(totalAsGB, 2))
                    .append("GB, Used ").append(MessageUtils.roundAndTruncate(usedAsGB, 2)).append("GB, Free ")
                    .append(MessageUtils.roundAndTruncate(freeAsGB, 2)).append("GB\n");
        }

        sb.append("Disk I/O:\n");

        BasicDBObject diskIO = (BasicDBObject) payload.get("disk_io");
        Set<String> disks = new TreeSet<>(diskIO.keySet());

        if (disks.size() == 0) {
            sb.append("  Unavailable\n");
        } else {
            for (String key : disks) {
                BasicDBObject disk = (BasicDBObject) diskIO.get(key);
                long reads = disk.getLong("read_count");
                long writes = disk.getLong("write_count");
                double gbRead = MessageUtils.kbToGB(disk.getLong("read_kbytes"));
                double gbWrite = MessageUtils.kbToGB(disk.getLong("write_kbytes"));
                long readSecs = disk.getLong("read_time");
                long writeSecs = disk.getLong("write_time");

                sb.append("  ").append(key).append(": Reads ").append(reads).append(", Writes ").append(writes)
                        .append(", GB Read ").append(MessageUtils.roundAndTruncate(gbRead, 2))
                        .append(", GB Written ").append(MessageUtils.roundAndTruncate(gbWrite, 2))
                        .append(", Read Time ").append(readSecs).append("s, Write Time ").append(writeSecs)
                        .append("s\n");
            }
        }

        sb.append("Network I/O:\n");

        BasicDBObject netIO = (BasicDBObject) payload.get("network_io");
        Set<String> nics = new TreeSet<>(netIO.keySet());
        int nicsDisplayed = 0;

        for (String key : nics) {
            BasicDBObject nic = (BasicDBObject) netIO.get(key);
            long packetsIn = nic.getInt("packets_in");
            long packetsOut = nic.getInt("packets_out");

            // Certain devices show 0 packets in/out and should be pruned
            if (packetsIn == 0 && packetsOut == 0) {
                continue;
            }

            double gbIn = MessageUtils.kbToGB(nic.getLong("kbytes_in"));
            double gbOut = MessageUtils.kbToGB(nic.getLong("kbytes_out"));

            sb.append("  ").append(key).append(": Packets In ").append(packetsIn).append(", Packets Out ")
                    .append(packetsOut).append(", GB In ").append(MessageUtils.roundAndTruncate(gbIn, 2))
                    .append(", GB Out ").append(MessageUtils.roundAndTruncate(gbOut, 2)).append("\n");

            nicsDisplayed++;
        }

        if (nicsDisplayed == 0) {
            sb.append("  Unavailable\n");
        }

        sb.append("Load: 1m ").append(MessageUtils.roundAndTruncate(payload.getDouble("load_avg_0"), 2))
                .append(", ").append("5m ")
                .append(MessageUtils.roundAndTruncate(payload.getDouble("load_avg_1"), 2)).append(", ")
                .append("15m ").append(MessageUtils.roundAndTruncate(payload.getDouble("load_avg_2"), 2))
                .append("\n");

        float gbTotalRAM = (float) MessageUtils.kbToGB(payload.getLong("phy_ram_total"));
        float gbUsedRAM = (float) MessageUtils.kbToGB(payload.getLong("phy_ram_used"));
        float gbFreeRAM = (float) MessageUtils.kbToGB(payload.getLong("phy_ram_free"));

        sb.append("Real Mem: Total ").append(MessageUtils.roundAndTruncate(gbTotalRAM, 2)).append("GB, Used ")
                .append(MessageUtils.roundAndTruncate(gbUsedRAM, 2)).append("GB, Free ")
                .append(MessageUtils.roundAndTruncate(gbFreeRAM, 2)).append("GB\n");

        double gbTotalVRAM = MessageUtils.kbToGB(payload.getLong("vir_ram_total"));
        double gbUsedVRAM = MessageUtils.kbToGB(payload.getLong("vir_ram_used"));
        double gbFreeVRAM = MessageUtils.kbToGB(payload.getLong("vir_ram_free"));

        sb.append("Virt Mem: Total ").append(MessageUtils.roundAndTruncate(gbTotalVRAM, 2)).append("GB, Used ")
                .append(MessageUtils.roundAndTruncate(gbUsedVRAM, 2)).append("GB, Free ")
                .append(MessageUtils.roundAndTruncate(gbFreeVRAM, 2)).append("GB\n");

        sb.append("Processes: ").append(payload.getInt("processes")).append("\n");

        sb.append("Users: Total ").append(payload.getInt("users_total")).append(", Unique ")
                .append(payload.getInt("users_unique")).append("\n");

        msg = sb.toString();
        break;
    default:
        super.doTransform(event);
        break;
    }
    return msg;
}

From source file:com.streamreduce.storm.spouts.EventSpout.java

License:Apache License

/**
 * Persists the lastProcessedEventDate to the last entry of the passed in events if we had events or to the end of
 * the sliding window if it isn't null./*from ww w . java 2s .com*/
 *
 * @param endOfSlidingWindow
 * @param events
 */
private void persistLastProcessedEventDate(Date endOfSlidingWindow, List<BasicDBObject> events) {
    if (events.size() > 0) {
        //If we had events to process, lastProcessedEventDate is the date of the last event.
        BasicDBObject mostRecentEntry = getMostRecentEntryFromEvents(events);

        //events.get(events.size() - 1);
        lastProcessedEventDate = new Date(mostRecentEntry.getLong("timestamp"));
    } else if (endOfSlidingWindow != null
            && endOfSlidingWindow.getTime() < (System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1))) {
        //If we didn't have events, only update lastProcessEventDate to the end our hour sliding window
        //if it is before the current system + a buffer of one minute to avoid updating lastProcessedEventDate to
        //a value in the future.
        lastProcessedEventDate = endOfSlidingWindow;
    }

    if (lastProcessedEventDate != null) {
        mongoClient.updateLastProcessedEventDate("EventSpout", lastProcessedEventDate.getTime());
    }
}