Example usage for com.google.gson JsonPrimitive getAsLong

List of usage examples for com.google.gson JsonPrimitive getAsLong

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsLong.

Prototype

@Override
public long getAsLong() 

Source Link

Document

convenience method to get this element as a primitive long.

Usage

From source file:com.yandex.money.api.typeadapters.JsonUtils.java

License:Open Source License

/**
 * Gets nullable Long from a JSON object.
 *
 * @param object json object/* w w w .  j a va 2  s.c om*/
 * @param memberName member's name
 * @return {@link Long} value
 */
public static Long getLong(JsonObject object, String memberName) {
    JsonPrimitive primitive = getPrimitiveChecked(object, memberName);
    return primitive == null ? null : primitive.getAsLong();
}

From source file:guru.qas.martini.report.DefaultState.java

License:Apache License

@Override
public void updateSuites(Sheet sheet) {
    int lastRowNum = sheet.getLastRowNum();
    Row row = sheet.createRow(0 == lastRowNum ? 0 : lastRowNum + 1);
    row.createCell(0, CellType.STRING).setCellValue("ID");
    row.createCell(1, CellType.STRING).setCellValue("Date");
    row.createCell(2, CellType.STRING).setCellValue("Name");
    row.createCell(3, CellType.STRING).setCellValue("Hostname");
    row.createCell(4, CellType.STRING).setCellValue("IP");
    row.createCell(5, CellType.STRING).setCellValue("Username");
    row.createCell(6, CellType.STRING).setCellValue("Profiles");
    row.createCell(7, CellType.STRING).setCellValue("Environment Variables");

    for (Map.Entry<String, JsonObject> mapEntry : suites.entrySet()) {
        row = sheet.createRow(sheet.getLastRowNum() + 1);

        String id = mapEntry.getKey();
        row.createCell(0, CellType.STRING).setCellValue(id);

        JsonObject suite = mapEntry.getValue();
        JsonPrimitive primitive = suite.getAsJsonPrimitive("startTimestamp");
        Long timestamp = null == primitive ? null : primitive.getAsLong();

        Cell cell = row.createCell(1);/*from  ww w .ja v  a  2 s  .  co m*/
        if (null != timestamp) {
            Workbook workbook = sheet.getWorkbook();
            CellStyle cellStyle = workbook.createCellStyle();
            CreationHelper creationHelper = workbook.getCreationHelper();
            cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm"));
            cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
            cell.setCellValue(new Date(timestamp));
            cell.setCellStyle(cellStyle);
        }

        cell = row.createCell(2);
        primitive = suite.getAsJsonPrimitive("name");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(3);
        JsonObject host = suite.getAsJsonObject("host");
        primitive = null == host ? null : host.getAsJsonPrimitive("name");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(4);
        primitive = null == host ? null : host.getAsJsonPrimitive("ip");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(5);
        primitive = null == host ? null : host.getAsJsonPrimitive("username");
        cell.setCellValue(null == primitive ? "" : primitive.getAsString());

        cell = row.createCell(6);
        JsonArray array = suite.getAsJsonArray("profiles");
        List<String> profiles = Lists.newArrayList();
        if (null != array) {
            int size = array.size();
            for (int i = 0; i < size; i++) {
                JsonElement element = array.get(i);
                String profile = null == element ? null : element.getAsString();
                profiles.add(profile);
            }
            String profilesValue = Joiner.on('\n').skipNulls().join(profiles);
            cell.setCellValue(profilesValue);
        }

        cell = row.createCell(7);
        JsonObject environmentVariables = suite.getAsJsonObject("environment");
        Map<String, String> index = new TreeMap<>();
        if (null != environmentVariables) {
            Set<Map.Entry<String, JsonElement>> entries = environmentVariables.entrySet();
            for (Map.Entry<String, JsonElement> environmentEntry : entries) {
                String key = environmentEntry.getKey();
                JsonElement element = environmentEntry.getValue();
                String value = null == element ? "" : element.getAsString();
                index.put(key, value);
            }

            String variablesValue = Joiner.on('\n').withKeyValueSeparator('=').useForNull("").join(index);
            cell.setCellValue(variablesValue);
        }
    }

    for (int i = 0; i < 8; i++) {
        sheet.autoSizeColumn(i, false);
    }
}

From source file:hu.bme.mit.incqueryd.engine.test.util.TupleDeserializer.java

License:Open Source License

@Override
public Tuple deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject jsonObject = json.getAsJsonObject();
    JsonArray array = jsonObject.getAsJsonArray("tuple");

    ArrayList<Object> list = new ArrayList<Object>();

    for (Object object : array) {
        // checking if the object is a primitive
        if (object instanceof JsonPrimitive) {
            JsonPrimitive primitive = (JsonPrimitive) object;

            // if it is a number, get it as a long
            if (primitive.isNumber()) {
                long i = primitive.getAsLong();
                list.add(i);//from   www .j ava2  s  .co  m
            }
        }
    }

    Tuple tuple = new Tuple(list.toArray());
    return tuple;
}

From source file:jp.yokomark.utils.gson.utils.JsonElementUtils.java

License:Open Source License

public static long getAsLongOrThrow(JsonPrimitive primitive) throws JsonParseException {
    if (!primitive.isNumber()) {
        throw new JsonParseException("this primitive is not a json number: " + primitive);
    }/*  w  w w  . ja v  a 2s  .  c om*/
    return primitive.getAsLong();
}

From source file:net.oauth.jsontoken.JsonToken.java

License:Apache License

private Long getParamAsLong(String param) {
    JsonPrimitive primitive = getParamAsPrimitive(param);
    if (primitive != null && (primitive.isNumber() || primitive.isString())) {
        try {/*from www  . j  av a  2 s .c o  m*/
            return primitive.getAsLong();
        } catch (NumberFormatException e) {
            return null;
        }
    }
    return null;
}

From source file:org.apache.orc.tools.json.JsonSchemaFinder.java

License:Apache License

static HiveType pickType(JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive prim = (JsonPrimitive) json;
        if (prim.isBoolean()) {
            return new BooleanType();
        } else if (prim.isNumber()) {
            Matcher matcher = DECIMAL_PATTERN.matcher(prim.getAsString());
            if (matcher.matches()) {
                int intDigits = matcher.group("int").length();
                String fraction = matcher.group("fraction");
                int scale = fraction == null ? 0 : fraction.length();
                if (scale == 0) {
                    if (intDigits < 19) {
                        long value = prim.getAsLong();
                        if (value >= -128 && value < 128) {
                            return new NumericType(HiveType.Kind.BYTE, intDigits, scale);
                        } else if (value >= -32768 && value < 32768) {
                            return new NumericType(HiveType.Kind.SHORT, intDigits, scale);
                        } else if (value >= -2147483648 && value < 2147483648L) {
                            return new NumericType(HiveType.Kind.INT, intDigits, scale);
                        } else {
                            return new NumericType(HiveType.Kind.LONG, intDigits, scale);
                        }//from www . j a va  2  s  .  c  o m
                    } else if (intDigits == 19) {
                        // at 19 digits, it may fit inside a long, but we need to check
                        BigInteger val = prim.getAsBigInteger();
                        if (val.compareTo(MIN_LONG) >= 0 && val.compareTo(MAX_LONG) <= 0) {
                            return new NumericType(HiveType.Kind.LONG, intDigits, scale);
                        }
                    }
                }
                if (intDigits + scale <= MAX_DECIMAL_DIGITS) {
                    return new NumericType(HiveType.Kind.DECIMAL, intDigits, scale);
                }
            }
            double value = prim.getAsDouble();
            if (value >= Float.MIN_VALUE && value <= Float.MAX_VALUE) {
                return new NumericType(HiveType.Kind.FLOAT, 0, 0);
            } else {
                return new NumericType(HiveType.Kind.DOUBLE, 0, 0);
            }
        } else {
            String str = prim.getAsString();
            if (TIMESTAMP_PATTERN.matcher(str).matches()) {
                return new StringType(HiveType.Kind.TIMESTAMP);
            } else if (HEX_PATTERN.matcher(str).matches()) {
                return new StringType(HiveType.Kind.BINARY);
            } else {
                return new StringType(HiveType.Kind.STRING);
            }
        }
    } else if (json.isJsonNull()) {
        return new NullType();
    } else if (json.isJsonArray()) {
        ListType result = new ListType();
        result.elementType = new NullType();
        for (JsonElement child : ((JsonArray) json)) {
            HiveType sub = pickType(child);
            if (result.elementType.subsumes(sub)) {
                result.elementType.merge(sub);
            } else if (sub.subsumes(result.elementType)) {
                sub.merge(result.elementType);
                result.elementType = sub;
            } else {
                result.elementType = new UnionType(result.elementType, sub);
            }
        }
        return result;
    } else {
        JsonObject obj = (JsonObject) json;
        StructType result = new StructType();
        for (Map.Entry<String, JsonElement> field : obj.entrySet()) {
            String fieldName = field.getKey();
            HiveType type = pickType(field.getValue());
            result.fields.put(fieldName, type);
        }
        return result;
    }
}

From source file:org.apache.qpid.disttest.json.PropertyValueAdapter.java

License:Apache License

@Override
public PropertyValue deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    } else if (json.isJsonPrimitive()) {
        Object result = null;/* ww  w  . j av  a  2  s.  co m*/
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            result = primitive.getAsString();
        } else if (primitive.isNumber()) {
            String asString = primitive.getAsString();
            if (asString.indexOf('.') != -1 || asString.indexOf('e') != -1) {
                result = primitive.getAsDouble();
            } else {
                result = primitive.getAsLong();
            }
        } else if (primitive.isBoolean()) {
            result = primitive.getAsBoolean();
        } else {
            throw new JsonParseException("Unsupported primitive value " + primitive);
        }
        return new SimplePropertyValue(result);
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        List<Object> result = new ArrayList<Object>(array.size());
        for (JsonElement element : array) {
            result.add(context.deserialize(element, Object.class));
        }
        return new SimplePropertyValue(result);
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        JsonElement defElement = object.getAsJsonPrimitive(DEF_FIELD);
        Class<?> classInstance = null;
        if (defElement != null) {
            try {
                classInstance = _factory.getPropertyValueClass(defElement.getAsString());
            } catch (ClassNotFoundException e) {
                // ignore
            }
        }
        if (classInstance == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
                Object value = context.deserialize(entry.getValue(), Object.class);
                result.put(entry.getKey(), value);
            }
            return new SimplePropertyValue(result);
        } else {
            return context.deserialize(json, classInstance);
        }
    } else {
        throw new JsonParseException("Unsupported JSON type " + json);
    }
}

From source file:org.apache.sling.jms.Json.java

License:Apache License

private static <T> T toMapValue(JsonPrimitive p) {
    if (p.isString()) {
        return (T) p.getAsString();
    } else if (p.isBoolean()) {
        return (T) ((Boolean) p.getAsBoolean());
    } else if (p.isNumber()) {
        double d = p.getAsDouble();
        if (Math.floor(d) == d) {
            return (T) ((Long) p.getAsLong());
        }//  w  w  w .  j ava  2s  .  c o m
        return (T) ((Double) d);
    } else {
        return null;
    }
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.client.impl.jest.ElasticSearchJestClient.java

License:Apache License

/**
 * Parses a given value (for a given column type) returned by response JSON query body from EL server.
 *
 * @param column       The data column definition.
 * @param valueElement The value element from JSON query response to format.
 * @return The formatted value for the given column type.
 *///from www . ja  va  2s .  c o m
public static Object parseValue(ElasticSearchDataSetDef definition, ElasticSearchDataSetMetadata metadata,
        DataColumn column, JsonElement valueElement) {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();

    ColumnType columnType = column.getColumnType();

    if (ColumnType.NUMBER.equals(columnType)) {

        return valueElement.getAsDouble();

    } else if (ColumnType.DATE.equals(columnType)) {

        // We can expect two return core types from EL server when handling dates:
        // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations.
        // 2.- Numeric type, when it's result from a scalar function or a value pickup.

        if (valuePrimitive.isString()) {

            DateTimeFormatter formatter = null;
            String datePattern = metadata.getFieldPattern(column.getId());
            if (datePattern == null || datePattern.trim().length() == 0) {
                // If no custom pattern for date field, use the default by EL -> org.joda.time.format.ISODateTimeFormat#dateOptionalTimeParser
                formatter = ElasticSearchDataSetProvider.EL_DEFAULT_DATETIME_FORMATTER;
            } else {
                // Obtain the date value by parsing using the EL pattern specified for this field.
                formatter = DateTimeFormat.forPattern(datePattern);
            }

            DateTime dateTime = formatter.parseDateTime(valuePrimitive.getAsString());
            return dateTime.toDate();
        }

        if (valuePrimitive.isNumber()) {

            return new Date(valuePrimitive.getAsLong());

        }

        throw new UnsupportedOperationException(
                "Value core type not supported. Expecting string or number when using date core field types.");

    }

    // LABEL, TEXT or grouped DATE column types.
    String valueAsString = valueElement.getAsString();
    ColumnGroup columnGroup = column.getColumnGroup();

    // For FIXED date values, remove the unnecessary "0" at first character. (eg: replace month "01" to "1")
    if (columnGroup != null && GroupStrategy.FIXED.equals(columnGroup.getStrategy())
            && valueAsString.startsWith("0"))
        return valueAsString.substring(1);

    return valueAsString;
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.ElasticSearchJestClient.java

License:Apache License

/**
 * Parses a given value (for a given column type) returned by response JSON query body from EL server.
 *
 * @param column       The data column definition.
 * @param valueElement The value element from JSON query response to format.
 * @return The object value for the given column type.
 *///from  ww w.jav  a2s . c om
public Object parseValue(DataSetMetadata metadata, DataColumn column, JsonElement valueElement)
        throws ParseException {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    ElasticSearchDataSetDef def = (ElasticSearchDataSetDef) metadata.getDefinition();
    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();
    ColumnType columnType = column.getColumnType();

    if (ColumnType.TEXT.equals(columnType)) {
        return typeMapper.parseText(def, column.getId(), valueElement.getAsString());
    } else if (ColumnType.LABEL.equals(columnType)) {
        boolean isColumnGroup = column.getColumnGroup() != null
                && column.getColumnGroup().getStrategy().equals(GroupStrategy.FIXED);
        return typeMapper.parseLabel(def, column.getId(), valueElement.getAsString(), isColumnGroup);

    } else if (ColumnType.NUMBER.equals(columnType)) {
        return typeMapper.parseNumeric(def, column.getId(), valueElement.getAsString());

    } else if (ColumnType.DATE.equals(columnType)) {

        // We can expect two return core types from EL server when handling dates:
        // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations.
        // 2.- Numeric type, when it's result from a scalar function or a value pickup.

        if (valuePrimitive.isString()) {
            return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsString());
        }

        if (valuePrimitive.isNumber()) {
            return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsLong());
        }

    }

    throw new UnsupportedOperationException("Cannot parse value for column with id [" + column.getId()
            + "] (Data Set UUID [" + def.getUUID()
            + "]). Value core type not supported. Expecting string or number or date core field types.");

}