Example usage for com.google.gson JsonNull INSTANCE

List of usage examples for com.google.gson JsonNull INSTANCE

Introduction

In this page you can find the example usage for com.google.gson JsonNull INSTANCE.

Prototype

JsonNull INSTANCE

To view the source code for com.google.gson JsonNull INSTANCE.

Click Source Link

Document

singleton for JsonNull

Usage

From source file:org.ballerinalang.composer.service.workspace.langserver.LangServerManager.java

License:Open Source License

/**
 * Process Shutdown notification/*from   w ww.j av a  2  s.c om*/
 *
 * @param message Request Message
 */
private void shutdown(Message message) {
    ResponseMessage responseMessage = new ResponseMessage();
    responseMessage.setResult(JsonNull.INSTANCE);
    pushMessageToClient(langServerSession, responseMessage);
}

From source file:org.ballerinalang.langserver.compiler.format.TextDocumentFormatUtil.java

License:Open Source License

/**
 * Generate json representation for the given node.
 *
 * @param node              Node to get the json representation
 * @param anonStructs       Map of anonymous structs
 * @param symbolMetaInfoMap symbol meta information map
 * @return {@link JsonElement}          Json Representation of the node
 * @throws JSONGenerationException when Json error occurs
 *///from  ww  w . ja va2  s .  co m
public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs,
        Map<BLangNode, List<SymbolMetaInfo>> symbolMetaInfoMap) throws JSONGenerationException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream()
            .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();

    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }

    /* Virtual props */

    // Add UUID for each node.
    nodeJson.addProperty("id", UUID.randomUUID().toString());

    // Add the visible endpoints for a given node
    if (symbolMetaInfoMap.containsKey(node)) {
        List<SymbolMetaInfo> endpointMetaList = symbolMetaInfoMap.get(node);
        JsonArray endpoints = new JsonArray();
        endpointMetaList.forEach(symbolMetaInfo -> endpoints.add(symbolMetaInfo.getJson()));
        nodeJson.add("VisibleEndpoints", endpoints);
    }

    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }

    for (Method m : methods) {
        String name = m.getName();

        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }

        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }

        Object prop = null;
        try {
            prop = m.invoke(node);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new JSONGenerationException("Error occurred while generating JSON", e);
        }

        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if ((node.getKind() == NodeKind.LITERAL || node.getKind() == NodeKind.NUMERIC_LITERAL)
                && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }

        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue)
                    .map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }

        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }

        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs, symbolMetaInfoMap));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangFunction
                                && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof BLangRecordVarRef.BLangRecordVarRefKeyValue) {
                    listPropJson.add(generateJSON(
                            ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getVariableName(),
                            anonStructs, symbolMetaInfoMap));
                    listPropJson.add(generateJSON(
                            ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getBindingPattern(),
                            anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof BLangRecordVariable.BLangRecordVariableKeyValue) {
                    listPropJson.add(generateJSON(
                            ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getKey(),
                            anonStructs, symbolMetaInfoMap));
                    listPropJson.add(generateJSON(
                            ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getValue(),
                            anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof String) {
                    listPropJson.add((String) listPropItem);
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }
            /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());
            /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop instanceof int[]) {
            int[] intArray = ((int[]) prop);
            JsonArray intArrayPropJson = new JsonArray();
            nodeJson.add(jsonName, intArrayPropJson);
            for (int intProp : intArray) {
                intArrayPropJson.add(intProp);
            }
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
        }
    }
    return nodeJson;
}

From source file:org.bimserver.shared.json.JsonConverter.java

License:Open Source License

public JsonElement toJson(Object object) throws IOException {
    if (object instanceof SBase) {
        SBase base = (SBase) object;//www  . jav a 2 s  .  c  o m
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("__type", new JsonPrimitive(base.getSClass().getSimpleName()));
        for (SField field : base.getSClass().getOwnFields()) {
            jsonObject.add(field.getName(), toJson(base.sGet(field)));
        }
        return jsonObject;
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        JsonArray jsonArray = new JsonArray();
        for (Object value : collection) {
            jsonArray.add(toJson(value));
        }
        return jsonArray;
    } else if (object instanceof Date) {
        return new JsonPrimitive(((Date) object).getTime());
    } else if (object instanceof DataHandler) {
        DataHandler dataHandler = (DataHandler) object;
        InputStream inputStream = dataHandler.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, out);
        return new JsonPrimitive(new String(Base64.encodeBase64(out.toByteArray()), Charsets.UTF_8));
    } else if (object instanceof Boolean) {
        return new JsonPrimitive((Boolean) object);
    } else if (object instanceof String) {
        return new JsonPrimitive((String) object);
    } else if (object instanceof Long) {
        return new JsonPrimitive((Long) object);
    } else if (object instanceof Integer) {
        return new JsonPrimitive((Integer) object);
    } else if (object instanceof Double) {
        return new JsonPrimitive((Double) object);
    } else if (object instanceof Enum) {
        return new JsonPrimitive(object.toString());
    } else if (object == null) {
        return JsonNull.INSTANCE;
    } else if (object instanceof byte[]) {
        byte[] data = (byte[]) object;
        return new JsonPrimitive(new String(Base64.encodeBase64(data), Charsets.UTF_8));
    }
    throw new UnsupportedOperationException(object.getClass().getName());
}

From source file:org.broad.igv.feature.AminoAcidManager.java

License:Open Source License

private static void loadDefaultTranslationTables() throws JsonParseException {
    InputStream is = AminoAcidManager.class.getResourceAsStream(DEFAULT_TRANS_TABLE_PATH);
    JsonObject allData = readJSONFromStream(is);
    JsonArray organisms = allData.get("organisms").getAsJsonArray();

    for (int ind = 0; ind < organisms.size(); ind++) {
        JsonObject obj = organisms.get(ind).getAsJsonObject();

        //Process each translation table setting
        String genomeId = obj.get("genomeId").getAsString();

        String codonTablePath = DEFAULT_CODON_TABLE_PATH;
        try {//  w ww  .  j a  va2s  .c  o m
            Object tmpPath = obj.get("codonTablePath");
            if (tmpPath != null && tmpPath != JsonNull.INSTANCE && tmpPath instanceof String) {
                codonTablePath = (String) tmpPath;
            }
        } catch (JsonParseException e) {
            log.error("No codon table path found in " + DEFAULT_TRANS_TABLE_PATH + ". Using default: "
                    + codonTablePath);
        }

        JsonObject chromosomes = obj.get("chromosomes").getAsJsonObject();
        Iterator<Map.Entry<String, JsonElement>> iterator = chromosomes.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonElement> entry = iterator.next();
            String chromoName = entry.getKey();
            int id = entry.getValue().getAsInt();
            CodonTableKey key = new CodonTableKey(codonTablePath, id);
            genomeChromoTable.put(genomeId, chromoName, key);
        }

    }

}

From source file:org.craftercms.core.util.XmlUtils.java

License:Open Source License

private static void addElementTextToJson(JsonObject parentJson, JsonObject elementJson, String elementName,
        String text) {//from   w w w  .jav  a2 s . c o  m
    JsonElement value;
    if (text != null) {
        value = new JsonPrimitive(text);
    } else {
        value = JsonNull.INSTANCE;
    }

    if (elementJson != null) {
        JsonUtils.setOrAccumulate(elementJson, XML_ELEMENT_TEXT_JSON_KEY, value);
    } else {
        JsonUtils.setOrAccumulate(parentJson, elementName, value);
    }
}

From source file:org.eclipse.che.api.core.jsonrpc.impl.GsonJsonRpcMarshaller.java

License:Open Source License

private JsonElement getJsonElement(Object param) {
    if (param == null) {
        return JsonNull.INSTANCE;
    }/*  w w  w .  jav a2 s .  c om*/
    if (param instanceof JsonElement) {
        return cast(param);
    }
    if (param instanceof String) {
        return new JsonPrimitive((String) param);
    }
    if (param instanceof Boolean) {
        return new JsonPrimitive((Boolean) param);
    }
    if (param instanceof Double) {
        return new JsonPrimitive((Double) param);
    }
    try {
        return jsonParser.parse(DtoFactory.getInstance().toJson(param));
    } catch (IllegalArgumentException e) {
        return gson.toJsonTree(param);
    }
}

From source file:org.eclipse.che.jdt.BinaryTypeConvector.java

License:Open Source License

public static String toJsonBinaryType(IBinaryType type) {
    JsonObject object = new JsonObject();
    object.add("annotations", toJsonAnnotations(type.getAnnotations()));
    object.add("enclosingMethod", type.getEnclosingMethod() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getEnclosingMethod())));
    object.add("enclosingTypeName", type.getEnclosingTypeName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getEnclosingTypeName())));
    object.add("fields", toJsonFields(type.getFields()));
    object.add("genericSignature", type.getGenericSignature() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getGenericSignature())));
    object.add("interfaceNames", toJsonArrayString(type.getInterfaceNames()));
    object.add("memberTypes", toJsonMemberTypes(type.getMemberTypes()));
    object.add("methods", toJsonMethods(type.getMethods()));
    object.add("missingTypeNames", toJsonMissingTypeNames(type.getMissingTypeNames()));
    object.add("name",
            type.getName() == null ? JsonNull.INSTANCE : new JsonPrimitive(new String(type.getName())));
    object.add("sourceName", type.getSourceName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getSourceName())));
    object.add("superclassName", type.getSuperclassName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.getSuperclassName())));
    object.add("tagBits", new JsonPrimitive(String.valueOf(type.getTagBits())));
    object.add("anonymous", new JsonPrimitive(type.isAnonymous()));
    object.add("local", new JsonPrimitive(type.isLocal()));
    object.add("member", new JsonPrimitive(type.isMember()));
    object.add("sourceFileName", type.sourceFileName() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(type.sourceFileName())));
    object.add("modifiers", new JsonPrimitive(type.getModifiers()));
    object.add("binaryType", new JsonPrimitive(type.isBinaryType()));
    object.add("fileName",
            type.getFileName() == null ? JsonNull.INSTANCE : new JsonPrimitive(new String(type.getFileName())));
    return gson.toJson(object);
}

From source file:org.eclipse.che.jdt.BinaryTypeConvector.java

License:Open Source License

private static JsonElement toJsonMethods(IBinaryMethod[] methods) {
    if (methods == null)
        return JsonNull.INSTANCE;
    JsonArray jsonElements = new JsonArray();
    for (IBinaryMethod method : methods) {
        jsonElements.add(toJsonMethod(method));
    }/*w w w .ja va 2  s .com*/
    return jsonElements;
}

From source file:org.eclipse.che.jdt.BinaryTypeConvector.java

License:Open Source License

private static JsonElement toJsonMethod(IBinaryMethod method) {
    JsonObject object = new JsonObject();
    object.addProperty("modifiers", method.getModifiers());
    object.addProperty("constructor", method.isConstructor());
    object.add("argumentNames", toJsonArrayString(method.getArgumentNames()));
    object.add("annotations", toJsonAnnotations(method.getAnnotations()));
    object.add("defaultValue", toJsonDefaultValue(method.getDefaultValue()));
    object.add("exceptionTypeNames", toJsonArrayString(method.getExceptionTypeNames()));
    object.add("genericSignature", method.getGenericSignature() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(method.getGenericSignature())));
    object.add("methodDescriptor", method.getMethodDescriptor() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(method.getMethodDescriptor())));
    object.add("parameterAnnotations", toJsonParameterAnnotations(method));
    object.add("selector", method.getSelector() == null ? JsonNull.INSTANCE
            : new JsonPrimitive(new String(method.getSelector())));
    object.addProperty("tagBits", String.valueOf(method.getTagBits()));
    object.addProperty("clinit", method.isClinit());
    return object;
}

From source file:org.eclipse.che.jdt.BinaryTypeConvector.java

License:Open Source License

private static JsonElement toJsonParameterAnnotations(IBinaryMethod method) {
    if (method.getAnnotatedParametersCount() != 0) {
        JsonArray array = new JsonArray();
        int parameterCount = Signature.getParameterCount(method.getMethodDescriptor());
        for (int i = 0; i < parameterCount; i++) {
            array.add(toJsonAnnotations(method.getParameterAnnotations(i)));
        }/*  w  w w . j a v  a2  s .c o  m*/
        return array;
    } else
        return JsonNull.INSTANCE;
}