Example usage for com.google.gson JsonPrimitive getAsDouble

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

Introduction

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

Prototype

@Override
public double getAsDouble() 

Source Link

Document

convenience method to get this element as a primitive double.

Usage

From source file:org.hibernate.search.elasticsearch.schema.impl.Elasticsearch56SchemaValidator.java

License:LGPL

private void doValidateJsonPrimitive(ValidationErrorCollector errorCollector, DataType type,
        String attributeName, JsonPrimitive expectedValue, JsonPrimitive actualValue) {
    // We can't just use equal, mainly because of floating-point numbers

    switch (type) {
    case TEXT://  w w w . j  a  v  a 2s. c  o m
    case KEYWORD:
        validateEqualWithDefault(errorCollector, attributeName, expectedValue, actualValue, null);
        break;
    case DOUBLE:
        if (expectedValue.isNumber() && actualValue.isNumber()) {
            validateEqualWithDefault(errorCollector, attributeName, expectedValue.getAsDouble(),
                    actualValue.getAsDouble(), DEFAULT_DOUBLE_DELTA, null);
        } else {
            errorCollector.addError(MESSAGES.invalidAttributeValue(attributeName, expectedValue, actualValue));
        }
        break;
    case FLOAT:
        if (expectedValue.isNumber() && actualValue.isNumber()) {
            validateEqualWithDefault(errorCollector, attributeName, expectedValue.getAsFloat(),
                    actualValue.getAsFloat(), DEFAULT_FLOAT_DELTA, null);
        } else {
            errorCollector.addError(MESSAGES.invalidAttributeValue(attributeName, expectedValue, actualValue));
        }
        break;
    case INTEGER:
    case LONG:
    case DATE:
    case BOOLEAN:
    case OBJECT:
    case GEO_POINT:
    default:
        validateEqualWithDefault(errorCollector, attributeName, expectedValue, actualValue, null);
        break;
    }
}

From source file:org.hillview.storage.JsonFileLoader.java

License:Open Source License

void append(IAppendableColumn[] columns, JsonElement e) {
    if (!e.isJsonObject())
        this.error("JSON array element is not a JsonObject");
    JsonObject obj = e.getAsJsonObject();
    for (IAppendableColumn col : columns) {
        JsonElement el = obj.get(col.getName());
        if (el == null || el.isJsonNull()) {
            col.appendMissing();/*from   w  ww .j a  v  a  2s  .  c  o m*/
            continue;
        }

        if (!el.isJsonPrimitive())
            this.error("JSON array element is a non-primitive field");
        JsonPrimitive prim = el.getAsJsonPrimitive();

        if (prim.isBoolean()) {
            col.append(prim.getAsBoolean() ? "true" : "false");
        } else if (prim.isNumber()) {
            col.append(prim.getAsDouble());
        } else if (prim.isString()) {
            col.parseAndAppendString(prim.getAsString());
        } else {
            this.error("Unexpected Json value" + prim.toString());
        }
    }
}

From source file:org.ms123.common.datamapper.JsonMetaData.java

License:Open Source License

private String getType(JsonPrimitive primitive) {
    if (primitive.isString())
        return "string";
    if (primitive.isBoolean())
        return "boolean";
    if (primitive.isNumber()) {
        System.out.println("primitive:" + primitive.getAsLong() + "/" + primitive.getAsDouble());
        return "double";
    }/*  w w w.  jav  a 2  s  . c  o m*/
    return "string";
}

From source file:org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter.java

License:Open Source License

public Object json2JavaPrimitive(JsonPrimitive prim) {
    if (prim.isBoolean()) {
        return prim.getAsBoolean();
    } else if (prim.isString()) {
        return prim.getAsString();
    } else if (prim.isNumber()) {
        String strRepesentation = prim.getAsString();
        if (strRepesentation.contains(".")) {
            return prim.getAsDouble();
        } else {/* ww  w.j  a  v  a 2  s.  c  om*/
            return prim.getAsInt();
        }
    } else {
        throw new IllegalStateException();
    }
}

From source file:org.openqa.selenium.json.JsonToBeanConverter.java

License:Apache License

private Object convertJsonPrimitive(JsonPrimitive json) {
    if (json.isBoolean()) {
        return json.getAsBoolean();
    } else if (json.isNumber()) {
        if (json.getAsLong() == json.getAsDouble()) {
            return json.getAsLong();
        }/*  www. j a  va2  s. c  o m*/
        return json.getAsDouble();
    } else if (json.isString()) {
        return json.getAsString();
    } else {
        return null;
    }
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static KeyValueProto buildNumericKeyValueProto(JsonPrimitive value, String key) {
    if (value.getAsString().contains(".")) {
        return KeyValueProto.newBuilder().setKey(key).setType(KeyValueType.DOUBLE_V)
                .setDoubleV(value.getAsDouble()).build();
    } else {// ww  w.jav a  2 s . co m
        try {
            long longValue = Long.parseLong(value.getAsString());
            return KeyValueProto.newBuilder().setKey(key).setType(KeyValueType.LONG_V).setLongV(longValue)
                    .build();
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException("Big integer values are not supported!");
        }
    }
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static void parseNumericValue(List<KvEntry> result, Entry<String, JsonElement> valueEntry,
        JsonPrimitive value) {
    if (value.getAsString().contains(".")) {
        result.add(new DoubleDataEntry(valueEntry.getKey(), value.getAsDouble()));
    } else {/*from  w ww .  j  a v a  2 s. co m*/
        try {
            long longValue = Long.parseLong(value.getAsString());
            result.add(new LongDataEntry(valueEntry.getKey(), longValue));
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException("Big integer values are not supported!");
        }
    }
}

From source file:org.wso2.carbon.identity.entitlement.endpoint.util.JSONRequestParser.java

License:Open Source License

/**
 * Converts a given <code>{@link JsonElement}</code> to a <code>String</code> DataType
 * Predicted based on XACML 3.0 JSON profile
 *
 * @param element//from   w ww  .j av a2s .  c  om
 * @return
 */
private static String jsonElementToDataType(JsonPrimitive element) {
    if (element.isString()) {
        return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_STRING;
    } else if (element.isBoolean()) {
        return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_BOOLEAN;
    } else if (element.isNumber()) {
        double n1 = element.getAsDouble();
        int n2 = element.getAsInt();
        if (Math.ceil(n1) == n2) {
            return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_INTEGER;
        } else {
            return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_DOUBLE;
        }
    }

    return null;
}

From source file:org.zoxweb.server.util.GSONUtil.java

License:Apache License

public static NVBase<?> guessPrimitive(String name, NVConfig nvc, JsonPrimitive jp) {
    GNVType gnvType = nvc != null ? GNVType.toGNVType(nvc) : null;

    if (gnvType == null) {
        GNVTypeName tn = GNVType.toGNVTypeName(name, ':');
        if (tn != null) {
            gnvType = tn.getType();//from www  . j  av  a  2  s  .co  m
            name = tn.getName();
        }
    }

    if (gnvType != null) {
        switch (gnvType) {
        case NVBLOB:
            try {
                byte value[] = SharedBase64.decode(Base64Type.URL, jp.getAsString());
                return new NVBlob(name, value);
            } catch (Exception e) {

            }
            break;
        case NVBOOLEAN:
            return new NVBoolean(name, jp.getAsBoolean());
        case NVDOUBLE:
            return new NVDouble(name, jp.getAsDouble());
        case NVFLOAT:
            return new NVFloat(name, jp.getAsFloat());
        case NVINT:
            return new NVInt(name, jp.getAsInt());
        case NVLONG:
            return new NVLong(name, jp.getAsLong());

        }
    }

    if (jp.isBoolean()) {
        return new NVBoolean(name, jp.getAsBoolean());
    } else if (jp.isNumber()) {
        // if there is no dots it should be a 
        //if (jp.getAsString().indexOf(".") == -1)
        {
            try {
                Number number = SharedUtil.parseNumber(jp.getAsString());
                return SharedUtil.numberToNVBase(name, number);

            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        //else
        {
            try {
                return new NVDouble(name, jp.getAsDouble());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    } else if (jp.isString()) {
        try {
            byte value[] = SharedBase64.decodeWrappedAsString(jp.getAsString());
            return new NVBlob(name, value);
        } catch (Exception e) {

        }
        try {
            Long.parseLong(jp.getAsString());
        } catch (Exception e) {
            if (TimestampFilter.SINGLETON.isValid(jp.getAsString())) {
                return new NVLong(name, TimestampFilter.SINGLETON.validate(jp.getAsString()));
            }
        }

        return new NVPair(name, jp.getAsString());
    }

    return null;

}

From source file:qa.qcri.qnoise.util.NoiseJsonAdapterDeserializer.java

License:MIT License

@Override
public NoiseJsonAdapter deserialize(JsonElement rootElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    NoiseJsonAdapter adapter = new NoiseJsonAdapter();

    JsonObject rootObj = (JsonObject) rootElement;

    // ---------------- parsing source --------------------- //
    JsonObject source = (JsonObject) (rootObj.get("source"));
    Preconditions.checkNotNull(source != null, "Source is not found.");

    JsonPrimitive pathPrimitive = source.getAsJsonPrimitive("path");
    Preconditions.checkNotNull(pathPrimitive);
    adapter.inputFile = pathPrimitive.getAsString();

    JsonArray schemaArray = source.getAsJsonArray("type");
    if (schemaArray != null) {
        adapter.schema = Lists.newArrayList();
        for (JsonElement primitive : schemaArray) {
            adapter.schema.add(primitive.getAsString());
        }/*from   w w  w  .  jav  a2s .com*/
    }

    JsonPrimitive csvSeparator = source.getAsJsonPrimitive("csvSeparator");
    if (csvSeparator != null) {
        adapter.csvSeparator = csvSeparator.getAsCharacter();
    } else {
        adapter.csvSeparator = NoiseJsonAdapter.DEFAULT_CSV_SEPARATOR;
    }

    // ---------------- parsing noises --------------------- //
    JsonElement noiseElement = rootObj.get("noise");
    JsonArray noiseArray;
    if (noiseElement instanceof JsonArray) {
        noiseArray = (JsonArray) (rootObj.get("noise"));
    } else {
        noiseArray = new JsonArray();
        noiseArray.add(noiseElement);
    }

    Preconditions.checkArgument(noiseArray != null && noiseArray.size() > 0,
            "Noise specification is null or empty.");

    adapter.specs = Lists.newArrayList();
    for (JsonElement specJson : noiseArray) {
        JsonObject noiseObj = (JsonObject) specJson;
        NoiseSpec spec = new NoiseSpec();

        JsonPrimitive noiseType = noiseObj.getAsJsonPrimitive("noiseType");
        Preconditions.checkNotNull(noiseType);
        spec.noiseType = NoiseType.fromString(noiseType.getAsString());

        JsonPrimitive granularity = noiseObj.getAsJsonPrimitive("granularity");
        if (granularity != null) {
            spec.granularity = GranularityType.fromString(granularity.getAsString());
        } else {
            // assign default granularity
            if (spec.noiseType == NoiseType.Duplicate)
                spec.granularity = GranularityType.Row;
            else
                spec.granularity = GranularityType.Cell;
        }

        JsonPrimitive percentage = noiseObj.getAsJsonPrimitive("percentage");
        if (percentage != null)
            spec.percentage = percentage.getAsDouble();
        else
            throw new IllegalArgumentException("Percentage cannot be null.");

        JsonPrimitive model = noiseObj.getAsJsonPrimitive("model");
        if (model != null) {
            spec.model = NoiseModel.fromString(model.getAsString());
        } else {
            spec.model = NoiseModel.Random;
        }

        JsonArray column = noiseObj.getAsJsonArray("column");
        if (column != null) {
            spec.filteredColumns = new String[column.size()];
            for (int i = 0; i < column.size(); i++)
                spec.filteredColumns[i] = column.get(i).getAsString();
        }

        JsonPrimitive numberOfSeed = noiseObj.getAsJsonPrimitive("numberOfSeed");
        if (numberOfSeed != null) {
            spec.numberOfSeed = numberOfSeed.getAsDouble();
        }

        JsonArray distance = noiseObj.getAsJsonArray("distance");
        if (distance != null) {
            spec.distance = new double[distance.size()];
            for (int i = 0; i < distance.size(); i++)
                spec.distance[i] = distance.get(i).getAsDouble();
        } else if (spec.filteredColumns != null)
            spec.distance = new double[spec.filteredColumns.length];

        // domain or distance
        if (spec.distance == null) {
            JsonArray domain = noiseObj.getAsJsonArray("domain");
            if (domain != null) {
                spec.distance = new double[domain.size()];
                for (int i = 0; i < domain.size(); i++)
                    spec.distance[i] = domain.get(i).getAsDouble();
            } else if (spec.filteredColumns != null)
                spec.distance = new double[spec.filteredColumns.length];
        }

        JsonArray constraints = noiseObj.getAsJsonArray("constraint");
        if (constraints != null) {
            spec.constraint = new Constraint[constraints.size()];
            for (int i = 0; i < constraints.size(); i++)
                spec.constraint[i] = ConstraintFactory
                        .createConstraintFromString(constraints.get(i).getAsString());
        }

        JsonPrimitive logFile = noiseObj.getAsJsonPrimitive("logFile");
        if (logFile != null) {
            spec.logFile = logFile.getAsString();
        } else {
            Calendar calendar = Calendar.getInstance();
            DateFormat dateFormat = new SimpleDateFormat("MMddHHmmss");
            spec.logFile = "log" + dateFormat.format(calendar.getTime()) + ".csv";
        }
        adapter.specs.add(spec);
    }

    // -------------- verify specifications ------------------- //
    for (NoiseSpec spec : adapter.specs) {
        String errorMessage = NoiseHelper.verify(spec);
        if (errorMessage != null)
            throw new IllegalArgumentException(errorMessage);
    }

    return adapter;
}