Example usage for com.google.gson JsonElement isJsonPrimitive

List of usage examples for com.google.gson JsonElement isJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonPrimitive.

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:guru.qas.martini.report.column.ScenarioDescriptionColumn.java

License:Apache License

@Override
public void addResult(State state, Cell cell, JsonObject o) {
    JsonElement element = o.get(KEY);
    String description = element.isJsonPrimitive() ? element.getAsString() : null;
    String normalized = null == description ? null : description.trim().replaceAll("\\s+", " ");
    String wrapped = WordUtils.wrap(normalized, 60);
    RichTextString richTextString = new XSSFRichTextString(wrapped);
    cell.setCellValue(richTextString);// www .  j  a  v  a 2  s. c o  m
}

From source file:guru.qas.martini.report.column.TagColumn.java

License:Apache License

protected String getTag(JsonElement element) {
    JsonObject entry = element.getAsJsonObject();
    JsonElement nameElement = entry.get(KEY_NAME);
    String name = null == nameElement ? null : nameElement.getAsString();

    String tag = null;/*from  www. ja  v  a2  s .c  o m*/
    if (null != name) {
        JsonElement argumentElement = entry.get(KEY_ARGUMENT);
        JsonPrimitive primitive = null != argumentElement && argumentElement.isJsonPrimitive()
                ? argumentElement.getAsJsonPrimitive()
                : null;
        String argument = null == primitive ? "" : String.format("\"%s\"", primitive.getAsString());
        tag = String.format("@%s(%s)", name, argument);
    }
    return tag;
}

From source file:hdm.stuttgart.esell.router.GeneralObjectDeserializer.java

License:Apache License

public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    } else if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return primitive.getAsString();
        } else if (primitive.isNumber()) {
            return primitive.getAsNumber();
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        }/*from  www.  ja v a 2s .c  o m*/
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        Object[] result = new Object[array.size()];
        int i = 0;
        for (JsonElement element : array) {
            result[i] = deserialize(element, null, context);
            ++i;
        }
        return result;
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            Object value = deserialize(entry.getValue(), null, context);
            result.put(entry.getKey(), value);
        }
        return result;
    } else {
        throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString());
    }
    return null;
}

From source file:imapi.OnlineDatabaseActions.java

License:Apache License

private int readJsonUriVals(InputStream inputStream, Vector<String> uriVals) {

    try {/*from  ww  w  . j  av  a 2  s . c  o m*/

        JsonReader rdr = new JsonReader(new InputStreamReader(inputStream));
        JsonParser parser = new JsonParser();
        JsonElement jElement = parser.parse(rdr);

        if (jElement.isJsonObject() == false) {
            showContentsOfInputStream(inputStream);
            return ApiConstants.IMAPIFailCode;
        }

        // read head/vars from json in order to get the names of the
        // select clause in the order that they were declared.
        // Store in headVarNames vector
        Vector<String> headVarNames = new Vector<String>();

        JsonObject jRootObject = jElement.getAsJsonObject();
        JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray();

        Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator();
        while (jVarsIter.hasNext()) {
            JsonElement jVarElement = jVarsIter.next();
            if (jVarElement.isJsonPrimitive()) {
                headVarNames.add(jVarElement.getAsString());
            }
        }

        if (jRootObject.has("results") == false
                || jRootObject.get("results").getAsJsonObject().has("bindings") == false) {
            return ApiConstants.IMAPIFailCode;
        }

        // loop over all json bindings
        JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings")
                .getAsJsonArray();
        Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator();
        while (jBindingsIter.hasNext()) {

            // of the binding
            String uri = "";

            JsonElement jBindingElement = jBindingsIter.next();
            if (jBindingElement.isJsonObject() == false) {
                continue;
            }
            JsonObject jBindingObject = jBindingElement.getAsJsonObject();

            for (int k = 0; k < headVarNames.size(); k++) {

                String currentPropertyName = headVarNames.get(k);
                if (jBindingObject.has(currentPropertyName)) {

                    JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject();

                    String valStr = "";
                    if (jObj.has("value")) {
                        valStr = jObj.get("value").getAsString();
                    }

                    if (k == 0) {
                        uri = valStr;
                    }
                }
            }

            if (uri.length() > 0 && uriVals.contains(uri) == false) {
                uriVals.add(uri);
            }

            // end of asking for all predicates of select clause head/vars names 
        } // edn of while llop that iters across all bindings

    } catch (Exception ex) {
        Utilities.handleException(ex);
        return ApiConstants.IMAPIFailCode;
    }

    return ApiConstants.IMAPISuccessCode;
}

From source file:imapi.OnlineDatabaseActions.java

License:Apache License

private int readJsonStartingUriAndValuePairs(InputStream inputStream, String startingUriName, String valueName,
        boolean checkForLang, Vector<DataRecord[]> returnVals) {

    try {//from  w w  w  .  j av  a  2s .  co  m

        JsonReader rdr = new JsonReader(new InputStreamReader(inputStream));
        JsonParser parser = new JsonParser();
        JsonElement jElement = parser.parse(rdr);

        if (jElement.isJsonObject() == false) {
            showContentsOfInputStream(inputStream);
            return ApiConstants.IMAPIFailCode;
        }

        // read head/vars from json in order to get the names of the
        // select clause in the order that they were declared.
        // Store in headVarNames vector
        Vector<String> headVarNames = new Vector<String>();

        JsonObject jRootObject = jElement.getAsJsonObject();
        JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray();

        Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator();
        while (jVarsIter.hasNext()) {
            JsonElement jVarElement = jVarsIter.next();
            if (jVarElement.isJsonPrimitive()) {
                headVarNames.add(jVarElement.getAsString());
            }
        }

        if (jRootObject.has("results") == false
                || jRootObject.get("results").getAsJsonObject().has("bindings") == false) {
            return ApiConstants.IMAPIFailCode;
        }

        // loop over all json bindings
        JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings")
                .getAsJsonArray();
        Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator();
        while (jBindingsIter.hasNext()) {

            // of the binding
            DataRecord start = null;
            DataRecord end = null;

            JsonElement jBindingElement = jBindingsIter.next();
            if (jBindingElement.isJsonObject() == false) {
                continue;
            }
            JsonObject jBindingObject = jBindingElement.getAsJsonObject();

            for (int k = 0; k < headVarNames.size(); k++) {

                String currentPropertyName = headVarNames.get(k);
                if (jBindingObject.has(currentPropertyName)) {

                    JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject();

                    String valStr = "";

                    String langStr = "";
                    if (jObj.has("value")) {
                        valStr = jObj.get("value").getAsString();
                    }

                    if (checkForLang) {
                        //read lang if type is literal
                        if (jObj.has("xml:lang")) {
                            langStr = jObj.get("xml:lang").getAsString();
                        }
                    }

                    if (valStr == null || valStr.trim().length() == 0) {
                        continue;
                    }

                    if (currentPropertyName.equals(startingUriName)) {
                        start = new DataRecord(valStr, "");
                    }

                    if (currentPropertyName.equals(valueName)) {
                        end = new DataRecord(valStr, langStr);
                    }
                }
            }
            if (start != null && end != null) {
                DataRecord[] newVal = { start, end };
                returnVals.add(newVal);
            }

            // end of asking for all predicates of select clause head/vars names 
        } // edn of while llop that iters across all bindings

    } catch (Exception ex) {
        Utilities.handleException(ex);
        return ApiConstants.IMAPIFailCode;
    }

    return ApiConstants.IMAPISuccessCode;
}

From source file:io.datakernel.serializer.GsonSubclassesAdapter.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from   w w w .  j  a va 2 s .c o m*/
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonPrimitive()) {
        if (!((JsonPrimitive) json).isString()) {
            throw new JsonParseException("Inner class name is expected");
        }
        String className = json.getAsString();
        InstanceCreator<T> creator = classCreators.get(className);
        if (creator != null) {
            return creator.createInstance(typeOfT);
        }
        try {
            Class<?> aClass = classTags.get(className);
            if (aClass == null) {
                aClass = Class.forName(className);
            }
            return (T) newInstance(aClass);
        } catch (InvocationTargetException | ClassNotFoundException | InstantiationException
                | IllegalAccessException | NoSuchMethodException e) {
            throw new JsonParseException(e);
        }
    }
    JsonObject object = json.getAsJsonObject();
    String subclassName = object.get(subclassField).getAsString();
    return context.deserialize(json, subclassNames.get(subclassName));
}

From source file:io.dockstore.webservice.helpers.GitHubHelper.java

License:Apache License

/**
 * Executes a GitHub Apps API request, and returns the value of the "repository_selection" property
 * in the response. If the request fails or returns a response that does not include
 * a "repository_selection" property, returns null.
 * @param request/*from   ww w. j a va2  s .  com*/
 * @return
 */
public static String makeGitHubAppRequestAndGetRepositorySelection(Request request) {
    try {
        okhttp3.Response response = DockstoreWebserviceApplication.okHttpClient.newCall(request).execute();
        JsonElement body = new JsonParser().parse(response.body().string());
        if (body.isJsonObject()) {
            JsonObject responseBody = body.getAsJsonObject();
            if (response.isSuccessful()) {
                JsonElement repoSelection = responseBody.get("repository_selection");
                if (repoSelection != null && repoSelection.isJsonPrimitive()) {
                    return repoSelection.getAsString();
                }
            } else {
                JsonElement errorMessage = responseBody.get("message");
                if (errorMessage != null && errorMessage.isJsonPrimitive()) {
                    // This should just mean the org or repo doesn't have GitHub installed, and isn't an error condition AFAIK
                    LOG.warn("Unable to fetch " + request.url().toString() + ": " + errorMessage.getAsString());
                }
            }
        }
    } catch (IOException ex) {
        LOG.error("Unable to get GitHub App installation for  " + request.url().toString(), ex);
    }
    return null;
}

From source file:io.flutter.dart.FlutterDartAnalysisServer.java

License:Open Source License

/**
 * Attempts to handle the given {@link JsonObject} as a notification.
 *//*from w  w w .  j av a  2 s .c om*/
private boolean processNotification(JsonObject response) {
    final JsonElement eventElement = response.get("event");
    if (eventElement == null || !eventElement.isJsonPrimitive()) {
        return false;
    }
    final String event = eventElement.getAsString();
    if (event.equals(FLUTTER_NOTIFICATION_OUTLINE)) {
        final JsonObject paramsObject = response.get("params").getAsJsonObject();
        final String file = paramsObject.get("file").getAsString();

        final JsonElement instrumentedCodeElement = paramsObject.get("instrumentedCode");
        final String instrumentedCode = instrumentedCodeElement != null ? instrumentedCodeElement.getAsString()
                : null;

        final JsonObject outlineObject = paramsObject.get("outline").getAsJsonObject();
        final FlutterOutline outline = FlutterOutline.fromJson(outlineObject);

        final List<FlutterOutlineListener> listeners = fileOutlineListeners.get(file);
        if (listeners != null) {
            for (FlutterOutlineListener listener : Lists.newArrayList(listeners)) {
                listener.outlineUpdated(file, outline, instrumentedCode);
            }
        }
    }
    return true;
}

From source file:io.flutter.server.vmService.VmOpenSourceLocationListener.java

License:Open Source License

private void onMessage(@NotNull final JsonObject message) {
    final JsonElement id = message.get("id");
    final String isolateId;
    final String scriptId;
    final int tokenPos;
    try {//from   www.j  a  v  a2s  .  c  om
        if (id != null && !id.isJsonPrimitive()) {
            return;
        }

        final String jsonrpc = message.get("jsonrpc").getAsString();
        if (!"2.0".equals(jsonrpc)) {
            return;
        }

        final String method = message.get("method").getAsString();
        if (!"openSourceLocation".equals(method)) {
            return;
        }

        final JsonObject params = message.get("params").getAsJsonObject();
        if (params == null) {
            return;
        }

        isolateId = params.get("isolateId").getAsString();
        if (StringUtils.isEmpty(isolateId)) {
            return;
        }

        scriptId = params.get("scriptId").getAsString();
        if (StringUtils.isEmpty(scriptId)) {
            return;
        }

        tokenPos = params.get("tokenPos").getAsInt();

        dispatcher.getMulticaster().onRequest(isolateId, scriptId, tokenPos);

    } catch (Exception e) {
        LOG.warn(e);
    }

    if (id != null) {
        final JsonObject response = new JsonObject();
        response.addProperty("jsonrpc", "2.0");
        response.add("id", id);
        final JsonObject result = new JsonObject();
        result.addProperty("type", "Success");
        response.add("result", result);
        sender.sendMessage(response);
    }
}

From source file:io.hawkcd.core.subscriber.EnvelopeAdapter.java

License:Apache License

@Override
public Envelope deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();
    if (jsonObject == null) {
        return null;
    }//from  ww  w.j a  va 2s.co m

    JsonElement objectAsJsonElement = jsonObject.get("object");
    if (objectAsJsonElement == null || !objectAsJsonElement.isJsonArray() && !objectAsJsonElement.isJsonObject()
            && !objectAsJsonElement.isJsonPrimitive()) {
        return new Envelope();
    }

    Type resultObjectType = null;
    try {
        resultObjectType = Class.forName(jsonObject.get("packageName").getAsString());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Object result;
    if (objectAsJsonElement.isJsonArray()) {
        List<Object> resultAsList = new ArrayList<>();
        JsonArray objectAsJsonArray = objectAsJsonElement.getAsJsonArray();
        for (JsonElement element : objectAsJsonArray) {
            resultAsList.add(context.deserialize(element, resultObjectType));
        }

        result = resultAsList;
    } else {
        result = context.deserialize(objectAsJsonElement, resultObjectType);
    }

    return new Envelope(result);
}