Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.scvngr.levelup.core.net.JsonElementRequestBody.java

License:Apache License

/**
 * @param jsonElement the element to serialize to the request body.
 *///from  w  w w . ja  v a  2s  .c om
public JsonElementRequestBody(@NonNull final JsonElement jsonElement) {
    super(NullUtils.nonNullContract(jsonElement.toString()));
}

From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java

License:Apache License

/**
 * Calls a CoreServices method./*  w  ww. ja  va2  s  .  c o  m*/
 * 
 * @param method The CoreServices method to call
 * @param params The parameters to pass to the CoreServices call
 * @param token The authentication token. Set to null to perform an unauthenticated call.
 * @param timeoutMillis The read timeout for new data on the connection.
 * @return The call's result JsonElement
 * @throws HttpException if network errors or parsing errors occured on the client.
 * @throws CallErrorException if the server responded with an error.
 */
JsonElement call(String method, JsonElement params, String token, int timeoutMillis)
        throws HttpException, CallErrorException {
    JsonObject header = new JsonObject();
    header.addProperty("user", user);
    if (token != null) {
        header.addProperty("token", token);
    }
    header.addProperty("client", client);

    JsonObject request = new JsonObject();
    request.addProperty("id", uuidGenerator.generate().toString());
    request.addProperty("method", method);
    request.add("params", params);
    request.add("header", header);

    final int effectiveTimeoutMillis = (timeoutMillis > 0) ? timeoutMillis : this.timeoutMillis;

    log.debug("Calling method " + method + " (user: " + user + ")");

    JsonObject responseObj = requestFactory.createPostJson(apiUrl, request)
            .setReadTimeoutMillis(effectiveTimeoutMillis).execute().getBodyAsJsonObject();

    log.debug("Method " + method + " done (user: " + user + ")");

    final JsonElement error = responseObj.get("error");
    if (error != null && !error.isJsonNull()) {
        throw new CallErrorException("Error: " + error.toString());
    }
    return responseObj.get("result");
}

From source file:com.sixt.service.framework.json.JsonUtil.java

License:Apache License

public static JsonRpcResponse parseJsonRpcResponse(String rawResponse) {
    JsonParser parser = new JsonParser();
    JsonObject response = parser.parse(rawResponse).getAsJsonObject();
    JsonElement id = response.get("id");
    JsonElement errorElement = response.get("error");
    int responseStatus = HttpServletResponse.SC_OK;
    String error;//  w ww. ja  v a 2 s.  co  m
    if (!(errorElement instanceof JsonNull)) {
        if (errorElement instanceof JsonObject) {
            error = errorElement.toString();
            // try parsing it into RpcCallException to get the HttpStatus from there
            RpcCallException rpcEx = RpcCallException.fromJson(error);
            if (rpcEx != null) {
                responseStatus = rpcEx.getCategory().getHttpStatus();
                JsonElement resultElement = response.get("result");
                return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement,
                        errorElement, responseStatus);
            }
        }
        error = errorElement.getAsString();
        if (StringUtils.isNotBlank(error)) {
            responseStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    }

    JsonElement resultElement = response.get("result");
    return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement, errorElement,
            responseStatus);
}

From source file:com.sixt.service.framework.rpc.JsonRpcCallExceptionDecoder.java

License:Apache License

@Override
public RpcCallException decodeException(ContentResponse response) {
    if (response != null) {
        try {/* w  w  w. j a  v  a  2s. co m*/
            JsonObject json = (JsonObject) new JsonParser().parse(response.getContentAsString());
            JsonElement error = json.get("error");
            if (error != null) {
                return RpcCallException.fromJson(error.toString());
            }
        } catch (Exception ex) {
            logger.warn("Caught exception decoding json response exception", ex);
        }
    }
    return null;
}

From source file:com.sixt.service.framework.rpc.RpcCallException.java

License:Apache License

public static RpcCallException fromJson(String json) {
    try {//from   ww  w  .j  a  v  a 2  s .c om
        JsonParser parser = new JsonParser();
        JsonElement rawObject = parser.parse(json);
        if (rawObject instanceof JsonObject) {
            JsonObject object = (JsonObject) rawObject;
            Category category = Category.fromStatus(object.get(CATEGORY).getAsInt());
            String message = object.get(MESSAGE).getAsString();
            RpcCallException retval = new RpcCallException(category, message);
            JsonElement element = object.get(SOURCE);
            if (element != null && !(element instanceof JsonNull)) {
                retval.withSource(element.getAsString());
            }
            element = object.get(CODE);
            if (element != null && !(element instanceof JsonNull)) {
                retval.withErrorCode(element.getAsString());
            }
            element = object.get(DATA);
            if (element != null && !(element instanceof JsonNull)) {
                retval.withData(element.getAsString());
            }
            element = object.get(RETRIABLE);
            if (element != null && !(element instanceof JsonNull)) {
                retval.withRetriable(element.getAsBoolean());
            }
            return retval;
        } else if (rawObject instanceof JsonPrimitive) {
            logger.warn("Expected an RpcCallException json object, but received: {}", rawObject.toString());
        }
    } catch (Exception ex) {
        logger.warn("Caught exception parsing RpcCallException: " + json, ex);
    }
    return null;
}

From source file:com.skysql.manager.api.NodeInfo.java

License:Open Source License

public NodeInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException, NullPointerException {
    NodeInfo nodeInfo = new NodeInfo();

    JsonElement element = json.getAsJsonObject().get("node");
    if (element.isJsonNull()) {
        return null;
    } else {//from   w w w.ja v a 2 s  .c  om

        JsonObject jsonObject = element.getAsJsonObject();
        nodeInfo.setName(((element = jsonObject.get("name")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setState(((element = jsonObject.get("state")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setUpdated(((element = jsonObject.get("updated")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setHostname(((element = jsonObject.get("hostname")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setPublicIP(((element = jsonObject.get("publicip")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setPrivateIP(((element = jsonObject.get("privateip")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setPort(((element = jsonObject.get("port")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setInstanceID(((element = jsonObject.get("instanceid")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setDBUsername(((element = jsonObject.get("dbusername")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setDBPassword(((element = jsonObject.get("dbpassword")) == null || element.isJsonNull()) ? null
                : element.getAsString());
        nodeInfo.setRepUsername(
                ((element = jsonObject.get("repusername")) == null || element.isJsonNull()) ? null
                        : element.getAsString());
        nodeInfo.setRepPassword(
                ((element = jsonObject.get("reppassword")) == null || element.isJsonNull()) ? null
                        : element.getAsString());
        nodeInfo.setLastMonitored(
                ((element = jsonObject.get("lastmonitored")) == null || element.isJsonNull()) ? null
                        : element.getAsString());

        if ((element = jsonObject.get("commands")) != null && !element.isJsonNull()) {
            Commands commands = APIrestful.getGson().fromJson("{\"commands\":" + element.toString() + "}",
                    Commands.class);
            nodeInfo.setCommands(commands);
        }

        if ((element = jsonObject.get("monitorlatest")) != null && !element.isJsonNull()) {
            MonitorLatest monitorLatest = APIrestful.getGson().fromJson(element.toString(),
                    MonitorLatest.class);
            nodeInfo.setMonitorLatest(monitorLatest);
        }

        if ((element = jsonObject.get("task")) != null && !element.isJsonNull()
                && !element.getAsJsonObject().entrySet().isEmpty()) {
            TaskInfo taskInfo = APIrestful.getGson().fromJson("{\"task\":" + element.toString() + "}",
                    TaskInfo.class);
            TaskRecord taskRecord = taskInfo.getTasksList().get(0);
            nodeInfo.setTask(taskRecord);
        }

    }
    return nodeInfo;
}

From source file:com.skysql.manager.api.SystemInfo.java

License:Open Source License

public SystemInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException, NullPointerException {
    SystemInfo systemInfo = new SystemInfo();

    JsonArray array = null;/*from   w  w w  .  ja  v a 2s. c om*/

    int length = 0;
    if (json.getAsJsonObject().has("systems")) {
        array = json.getAsJsonObject().get("systems").getAsJsonArray();
        length = array.size();
    } else if (json.getAsJsonObject().has("system")) {
        length = 1;
    }

    LinkedHashMap<String, SystemRecord> systemsMap = new LinkedHashMap<String, SystemRecord>(length);
    systemInfo.setSystemsMap(systemsMap);
    if (length == 0) {
        return systemInfo;
    }

    for (int i = 0; i < length; i++) {

        SystemRecord systemRecord = new SystemRecord(SystemInfo.SYSTEM_ROOT);

        JsonObject systemObject = (array != null) ? array.get(i).getAsJsonObject()
                : json.getAsJsonObject().get("system").getAsJsonObject();
        JsonElement element;
        systemRecord
                .setID((element = systemObject.get("systemid")).isJsonNull() ? null : element.getAsString());
        systemRecord.setSystemType(
                (element = systemObject.get("systemtype")).isJsonNull() ? null : element.getAsString());
        systemRecord.setName((element = systemObject.get("name")).isJsonNull() ? null : element.getAsString());
        systemRecord
                .setState((element = systemObject.get("state")).isJsonNull() ? null : element.getAsString());
        systemRecord.setStartDate(
                (element = systemObject.get("started")).isJsonNull() ? null : element.getAsString());
        systemRecord.setLastAccess(
                (element = systemObject.get("lastaccess")).isJsonNull() ? null : element.getAsString());
        systemRecord.setLastBackup(
                (element = systemObject.get("lastbackup")).isJsonNull() ? null : element.getAsString());
        systemRecord.setDBUsername(
                (element = systemObject.get("dbusername")).isJsonNull() ? null : element.getAsString());
        systemRecord.setDBPassword(
                (element = systemObject.get("dbpassword")).isJsonNull() ? null : element.getAsString());
        systemRecord.setRepUsername(
                (element = systemObject.get("repusername")).isJsonNull() ? null : element.getAsString());
        systemRecord.setRepPassword(
                (element = systemObject.get("reppassword")).isJsonNull() ? null : element.getAsString());
        systemRecord.setLastMonitored(
                ((element = systemObject.get("lastmonitored")).isJsonNull()) ? null : element.getAsString());

        MonitorLatest monitorLatest = null;
        if ((element = systemObject.get("monitorlatest")) != null && !element.isJsonNull()) {
            monitorLatest = APIrestful.getGson().fromJson(element.toString(), MonitorLatest.class);
        }
        systemRecord.setMonitorLatest(monitorLatest);

        String[] nodes = null;
        if ((element = systemObject.get("nodes")) != null && !element.isJsonNull()) {
            JsonArray nodesJson = element.getAsJsonArray();
            int nodesCount = nodesJson.size();

            nodes = new String[nodesCount];
            for (int nodesIndex = 0; nodesIndex < nodesCount; nodesIndex++) {
                nodes[nodesIndex] = nodesJson.get(nodesIndex).getAsString();
            }
        }
        systemRecord.setNodes(nodes);

        LinkedHashMap<String, String> properties = new LinkedHashMap<String, String>();
        if ((element = systemObject.get("properties")) != null && !element.isJsonNull()) {

            JsonObject propertiesJson = element.getAsJsonObject();

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_EIP)) != null) {
                properties.put(SystemInfo.PROPERTY_EIP, element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_MONYOG)) != null) {
                properties.put(SystemInfo.PROPERTY_MONYOG, element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_PHPMYADMIN)) != null) {
                properties.put(SystemInfo.PROPERTY_PHPMYADMIN,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_DEFAULTMONITORINTERVAL)) != null) {
                properties.put(SystemInfo.PROPERTY_DEFAULTMONITORINTERVAL,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_DEFAULTMAXBACKUPCOUNT)) != null) {
                properties.put(SystemInfo.PROPERTY_DEFAULTMAXBACKUPCOUNT,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_DEFAULTMAXBACKUPSIZE)) != null) {
                properties.put(SystemInfo.PROPERTY_DEFAULTMAXBACKUPSIZE,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_VERSION)) != null) {
                properties.put(SystemInfo.PROPERTY_VERSION,
                        element.isJsonNull() ? null : element.getAsString());
            }

            if ((element = propertiesJson.get(SystemInfo.PROPERTY_SKIPLOGIN)) != null) {
                properties.put(SystemInfo.PROPERTY_SKIPLOGIN,
                        element.isJsonNull() ? null : element.getAsString());
            }

        }
        systemRecord.setProperties(properties);

        systemsMap.put(systemRecord.getID(), systemRecord);
    }

    if (array != null) {
        // create a "ROOT" system record to contain the series of flat systems; in a hierarchical organization of systems, this might be provided by the API
        SystemRecord rootRecord = new SystemRecord(null);
        rootRecord.setID(SystemInfo.SYSTEM_ROOT);
        rootRecord.setName("Root");
        String[] systems = new String[systemsMap.keySet().size()];
        int i = 0;
        for (String systemID : systemsMap.keySet()) {
            systems[i++] = systemID;
        }
        rootRecord.setNodes(systems);
        systemsMap.put(SystemInfo.SYSTEM_ROOT, rootRecord);
    }

    return systemInfo;
}

From source file:com.sldeditor.exportdata.esri.symbols.SymbolUtils.java

License:Open Source License

/**
 * Extract name.//from   ww w  .  j a v  a 2  s . c  om
 *
 * @param renderElement the render element
 * @return the string
 */
public static String extractName(JsonElement renderElement) {
    String s = renderElement.toString();

    int beginIndex = s.indexOf("\"") + 1;
    int endIndex = s.indexOf("\"", beginIndex + 1);

    String extractedName = s.substring(beginIndex, endIndex);
    return extractedName;
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

private static void checkJsonMethodParameterTypes(JsonArray jsonData, RegisteredStandardMethod method) {
    assert method != null;
    JsonElement[] jsonParameters = getIndividualRequestJsonParameters(jsonData);
    Class<?>[] parameterTypes = method.getParameterTypes();

    assert jsonParameters.length == parameterTypes.length;

    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> parameterType = parameterTypes[i];
        JsonElement jsonElement = jsonParameters[i];
        if (!isValidJsonTypeForJavaType(jsonElement, parameterType)) {
            throw new IllegalArgumentException("'" + jsonElement.toString()
                    + "' is not a valid json text for the '" + parameterType.getName() + "' Java type");
        }//w  ww.j  ava 2s.  co  m
    }
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

@CheckForNull
private static JsonArray getMethodParametersJsonData(JsonObject object) {
    assert object != null;

    JsonElement data = object.get(JsonRequestData.DATA_ELEMENT);
    if (data == null) {
        RequestException ex = RequestException.forJsonElementMissing(JsonRequestData.DATA_ELEMENT);
        logger.error(ex.getMessage(), ex);
        throw ex;
    }//w  w  w .  j a v a  2s . c o  m

    if (data.isJsonNull()) {
        return null;
    }

    if (!data.isJsonNull() && !data.isJsonArray()) {
        RequestException ex = RequestException.forJsonElementMustBeAJsonArray(JsonRequestData.DATA_ELEMENT,
                data.toString());
        logger.error(ex.getMessage(), ex);
        throw ex;
    }

    return (JsonArray) data;
}