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:org.eclipse.leshan.server.demo.servlet.json.LwM2mNodeDeserializer.java

License:Open Source License

private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
    if (val.isBoolean())
        return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
    if (val.isString())
        return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
    if (val.isNumber()) {
        if (val.getAsDouble() == val.getAsLong()) {
            return org.eclipse.leshan.core.model.ResourceModel.Type.INTEGER;
        } else {/*from   w  w  w.j  ava2  s.c om*/
            return org.eclipse.leshan.core.model.ResourceModel.Type.FLOAT;
        }
    }
    // use string as default value
    return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
}

From source file:org.eclipse.leshan.server.demo.servlet.json.LwM2mNodeDeserializer.java

License:Open Source License

private Object deserializeValue(JsonPrimitive val,
        org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
    switch (expectedType) {
    case BOOLEAN:
        return val.getAsBoolean();
    case STRING://  w w w.  j  a va 2  s. c o  m
        return val.getAsString();
    case INTEGER:
        return val.getAsLong();
    case FLOAT:
        return val.getAsDouble();
    case TIME:
    case OPAQUE:
    default:
        // TODO we need to better handle this.
        return val.getAsString();
    }
}

From source file:org.eclipse.milo.opcua.binaryschema.gson.JsonStructureCodec.java

License:Open Source License

@Override
protected Object memberTypeToOpcUaScalar(JsonElement member, String typeName) {
    if (member == null || member.isJsonNull()) {
        return null;
    } else if (member.isJsonArray()) {
        JsonArray array = member.getAsJsonArray();

        switch (typeName) {
        case "ByteString": {
            byte[] bs = new byte[array.size()];

            for (int i = 0; i < array.size(); i++) {
                bs[i] = array.get(i).getAsByte();
            }//  www  .j av  a 2 s .  c  o  m

            return ByteString.of(bs);
        }

        default:
            return array;
        }
    } else if (member.isJsonObject()) {
        JsonObject jsonObject = member.getAsJsonObject();

        switch (typeName) {
        case "QualifiedName": {
            return new QualifiedName(jsonObject.get("namespaceIndex").getAsInt(),
                    jsonObject.get("name").getAsString());
        }
        case "LocalizedText": {
            return new LocalizedText(jsonObject.get("locale").getAsString(),
                    jsonObject.get("text").getAsString());
        }

        default:
            return jsonObject;
        }
    } else if (member.isJsonPrimitive()) {
        JsonPrimitive primitive = member.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            switch (typeName) {
            case "Guid":
                return UUID.fromString(primitive.getAsString());

            case "NodeId":
                return NodeId.parseSafe(primitive.getAsString()).orElse(NodeId.NULL_VALUE);

            case "ExpandedNodeId":
                return ExpandedNodeId.parse(primitive.getAsString());

            case "XmlElement":
                return new XmlElement(primitive.getAsString());

            default:
                return primitive.getAsString();
            }
        } else if (primitive.isNumber()) {
            switch (typeName) {
            case "SByte":
                return primitive.getAsByte();
            case "Int16":
                return primitive.getAsShort();
            case "Int32":
                return primitive.getAsInt();
            case "Int64":
                return primitive.getAsLong();

            case "Byte":
                return ubyte(primitive.getAsShort());
            case "UInt16":
                return ushort(primitive.getAsInt());
            case "UInt32":
                return uint(primitive.getAsLong());
            case "UInt64":
                return ulong(primitive.getAsBigInteger());

            case "Float":
                return primitive.getAsFloat();
            case "Double":
                return primitive.getAsDouble();

            case "DateTime":
                return new DateTime(primitive.getAsLong());

            case "StatusCode":
                return new StatusCode(primitive.getAsLong());

            default:
                return primitive.getAsNumber();
            }
        }
    }

    return null;
}

From source file:org.eclipse.php.composer.api.json.JsonParser.java

License:Open Source License

private Object buildTree(JsonElement entity) {

    if (entity.isJsonPrimitive()) {
        JsonPrimitive p = entity.getAsJsonPrimitive();
        if (p.isBoolean()) {
            return p.getAsBoolean();
        }/*from w w  w  . jav a2 s  .  com*/
        if (p.isNumber()) {
            return p.getAsLong();
        }
        return p.getAsString();
    } else if (entity.isJsonNull()) {
        return null;
    } else if (entity.isJsonArray()) {
        LinkedList<Object> arr = new LinkedList<Object>();
        for (JsonElement el : entity.getAsJsonArray()) {
            arr.add(buildTree(el));
        }
        return arr;
    } else if (entity.isJsonObject()) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
        for (Entry<String, JsonElement> el : entity.getAsJsonObject().entrySet()) {
            map.put(el.getKey(), buildTree(el.getValue()));
        }
        return map;
    }

    return null;
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

/**
 * Scan snapshot refers to a particular point in history when statistics are 
 * reevaluated, such as when a scan is completed. This call returns different 
 * data structures from the call to retrieve an individual scan by ID from
 * under the Release context path./* ww  w  .  j av a2s .c  o m*/
 * 
 * @throws IOException
 */
public List<ScanSnapshot> getScanSnapshotList() throws IOException {
    String endpoint = baseUrl + "/api/v1/Scan";
    HttpGet connection = (HttpGet) getHttpUriRequest("GET", endpoint);
    InputStream is = null;

    try {
        // Get Response
        HttpResponse response = getHttpClient().execute(connection);
        is = response.getEntity().getContent();
        StringBuffer buffer = collectInputStream(is);
        JsonArray arr = getDataJsonArray(buffer);
        List<ScanSnapshot> snapshots = new LinkedList<ScanSnapshot>();
        for (int ix = 0; ix < arr.size(); ix++) {
            JsonElement entity = arr.get(ix);
            JsonObject obj = entity.getAsJsonObject();

            ScanSnapshot scan = new ScanSnapshot();
            if (!obj.get("ProjectVersionId").isJsonNull()) {
                JsonPrimitive releaseIdObj = obj.getAsJsonPrimitive("ProjectVersionId");
                scan.setProjectVersionId(releaseIdObj.getAsLong());
            }
            if (!obj.get("StaticScanId").isJsonNull()) {
                JsonPrimitive staticScanIdObj = obj.getAsJsonPrimitive("StaticScanId");
                scan.setStaticScanId(staticScanIdObj.getAsLong());
            }
            if (!obj.get("DynamicScanId").isJsonNull()) {
                JsonPrimitive dynamicScanIdObj = obj.getAsJsonPrimitive("DynamicScanId");
                scan.setDynamicScanId(dynamicScanIdObj.getAsLong());
            }
            if (!obj.get("MobileScanId").isJsonNull()) {
                JsonPrimitive mobileScanIdObj = obj.getAsJsonPrimitive("MobileScanId");
                scan.setMobileScanId(mobileScanIdObj.getAsLong());
            }
            //FIXME translate CategoryRollups
            if (!obj.get("RollupHistoryId").isJsonNull()) {
                JsonPrimitive rollupHistoryIdObj = obj.getAsJsonPrimitive("RollupHistoryId");
                scan.setHistoryRollupId(rollupHistoryIdObj.getAsLong());
            }

            snapshots.add(scan);
        }
        return snapshots;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.mobicents.servlet.restcomm.provisioning.number.nexmo.NexmoPhoneNumberProvisioningManager.java

License:Open Source License

@Override
public List<PhoneNumber> searchForNumbers(String country, PhoneNumberSearchFilters listFilters) {
    if (logger.isDebugEnabled()) {
        logger.debug("searchPattern " + listFilters.getFilterPattern());
    }//  w  w w. j a va 2s.c om
    Pattern filterPattern = listFilters.getFilterPattern();
    String filterPatternString = null;
    if (filterPattern != null) {
        filterPatternString = filterPattern.toString().replaceAll("[^\\d]", "");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("searchPattern simplified for nexmo " + filterPatternString);
    }

    String queryUri = searchURI + country;
    boolean queryParamAdded = false;
    if (("US".equalsIgnoreCase(country) || "CA".equalsIgnoreCase(country))
            && listFilters.getAreaCode() != null) {
        // https://github.com/Mobicents/RestComm/issues/551 fixing the search pattern for US when Area Code is selected
        // https://github.com/Mobicents/RestComm/issues/602 fixing the search pattern for CA when Area Code is selected
        queryUri = queryUri + "?pattern=1" + listFilters.getAreaCode() + "&search_pattern=0";
        queryParamAdded = true;
    } else if (filterPatternString != null) {
        queryUri = queryUri + "?pattern=" + filterPatternString + "&search_pattern=1";
        queryParamAdded = true;
    }
    if (listFilters.getSmsEnabled() != null || listFilters.getVoiceEnabled() != null) {
        if (!queryParamAdded) {
            queryUri = queryUri + "?";
            queryParamAdded = true;
        } else {
            queryUri = queryUri + "&";
        }
        if (listFilters.getSmsEnabled() != null && listFilters.getVoiceEnabled() != null) {
            queryUri = queryUri + "features=SMS,VOICE";
        } else if (listFilters.getSmsEnabled() != null) {
            queryUri = queryUri + "features=SMS";
        } else {
            queryUri = queryUri + "features=VOICE";
        }
    }
    if (listFilters.getRangeIndex() != -1) {
        if (!queryParamAdded) {
            queryUri = queryUri + "?";
            queryParamAdded = true;
        } else {
            queryUri = queryUri + "&";
        }
        queryUri = queryUri + "index=" + listFilters.getRangeIndex();
    }
    if (listFilters.getRangeSize() != -1) {
        if (!queryParamAdded) {
            queryUri = queryUri + "?";
            queryParamAdded = true;
        } else {
            queryUri = queryUri + "&";
        }
        queryUri = queryUri + "size=" + listFilters.getRangeSize();
    }
    final HttpGet get = new HttpGet(queryUri);
    try {

        final DefaultHttpClient client = new DefaultHttpClient();
        //                if (telestaxProxyEnabled) {
        //                    // This will work as a flag for LB that this request will need to be modified and proxied to VI
        //                    get.addHeader("TelestaxProxy", String.valueOf(telestaxProxyEnabled));
        //                    // This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request
        //                    get.addHeader("RequestType", "GetAvailablePhoneNumbersByAreaCode");
        //                    //This will let LB match the DID to a node based on the node host+port
        //                    for (SipURI uri: containerConfiguration.getOutboundInterfaces()) {
        //                        get.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam());
        //                    }
        //                }
        if (logger.isDebugEnabled()) {
            logger.debug("Nexmo query " + queryUri);
        }
        final HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            final String content = StringUtils.toString(response.getEntity().getContent());
            JsonParser parser = new JsonParser();
            JsonObject jsonResponse = parser.parse(content).getAsJsonObject();
            if (logger.isDebugEnabled()) {
                logger.debug("Nexmo response " + jsonResponse.toString());
            }
            JsonPrimitive countPrimitive = jsonResponse.getAsJsonPrimitive("count");
            if (countPrimitive == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("No numbers found");
                }
                return new ArrayList<PhoneNumber>();
            }
            long count = countPrimitive.getAsLong();
            if (logger.isDebugEnabled()) {
                logger.debug("Number of numbers found : " + count);
            }
            JsonArray nexmoNumbers = jsonResponse.getAsJsonArray("numbers");
            final List<PhoneNumber> numbers = toAvailablePhoneNumbers(nexmoNumbers, listFilters);
            return numbers;
        } else {
            logger.warn("Couldn't reach uri for getting Phone Numbers. Response status was: "
                    + response.getStatusLine().getStatusCode());
        }
    } catch (final Exception e) {
        logger.warn("Couldn't reach uri for getting Phone Numbers" + uri, e);
    }

    return new ArrayList<PhoneNumber>();
}

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 ww  .  java 2s  .  c  o m*/
    return "string";
}

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();
        }//from   w  w  w. j a v a 2 s.  com
        return json.getAsDouble();
    } else if (json.isString()) {
        return json.getAsString();
    } else {
        return null;
    }
}

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

License:Apache License

public static QueryRequest fromQueryRequest(String json) {
    JsonElement je = new JsonParser().parse(json);
    QueryRequest ret = null;//w  w w  .j a  v  a 2  s.  co m

    if (je instanceof JsonObject) {
        ret = new QueryRequest();
        JsonObject jo = (JsonObject) je;
        ret.setCanonicalID(jo.get(MetaToken.CANONICAL_ID.getName()).getAsString());
        JsonElement batchSize = jo.get("batch_size");

        if (batchSize != null) {
            ret.setBatchSize(batchSize.getAsInt());
        }

        JsonArray jaFNs = (JsonArray) jo.get("field_names");

        if (jaFNs != null) {
            List<String> fieldNames = new ArrayList<String>();

            for (int i = 0; i < jaFNs.size(); i++) {
                fieldNames.add(jaFNs.get(i).getAsString());
            }

            ret.setFieldNames(fieldNames);
        }

        JsonArray jaQuery = (JsonArray) jo.get("query");
        if (jaQuery != null) {
            List<QueryMarker> qms = new ArrayList<QueryMarker>();
            for (int i = 0; i < jaQuery.size(); i++) {
                // get the query marker
                JsonObject joQM = (JsonObject) jaQuery.get(i);
                QueryMarker qm = null;

                JsonPrimitive lo = (JsonPrimitive) joQM.get(MetaToken.LOGICAL_OPERATOR.getName());

                if (lo != null) {
                    qm = Const.LogicalOperator.valueOf(lo.getAsString());
                } else {
                    Const.RelationalOperator ro = null;

                    JsonPrimitive jpRO = (JsonPrimitive) joQM.get(MetaToken.RELATIONAL_OPERATOR.getName());

                    if (jpRO != null) {
                        ro = Const.RelationalOperator.valueOf(jpRO.getAsString());
                    }

                    String name = null;
                    JsonElement value = null;

                    Set<Map.Entry<String, JsonElement>> allParams = joQM.entrySet();

                    for (Map.Entry<String, JsonElement> e : allParams) {
                        if (!e.getKey().equals(MetaToken.RELATIONAL_OPERATOR.getName())) {
                            name = e.getKey();
                            value = e.getValue();
                            break;
                        }
                    }

                    // try to guess the type
                    if (value.isJsonPrimitive()) {
                        JsonPrimitive jp = (JsonPrimitive) value;

                        if (jp.isString()) {
                            qm = new QueryMatchString(ro, jp.getAsString(), name);
                        } else if (jp.isNumber()) {
                            qm = new QueryMatchLong(ro, jp.getAsLong(), name);
                        }
                    }
                }

                if (qm != null) {
                    qms.add(qm);
                }
            }

            ret.setQuery(qms);
        }
    }

    return ret;
}

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 w w  w .  ja v  a2s  .  com
            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;

}