Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.elevenpaths.latch.sdk.impl.LatchSDKImpl.java

License:Open Source License

/**
 * Makes an HTTP GET request to the provided URL, adding the
 * provided headers. The output is parsed and returned as a JSON
 * element with Google GSON library./*w ww. j av a 2  s.  com*/
 * <p>
 * If something goes wrong during the connection a null element
 * will be returned.
 * 
 * @param URL
 *        The URL to where the GET request should be make.
 * @param headers
 *        The headers that should be added to the GET request.
 * 
 * @return The JSON returned by the Latch backend server or a null
 *         element if something has gone wrong.
 */
public JsonElement HTTP_GET(String URL, Map<String, String> headers) {

    Utils.checkMethodRequiredParameter(LOG, "URL", URL);
    Utils.checkMethodRequiredParameter(LOG, "headers", headers);

    JsonElement rv = null;
    InputStream is = null;
    InputStreamReader isr = null;

    try {

        URL theURL = new URL(URL);
        HttpURLConnection theConnection = (HttpURLConnection) theURL.openConnection();

        Iterator<String> iterator = headers.keySet().iterator();

        while (iterator.hasNext()) {
            String headerName = iterator.next();
            theConnection.setRequestProperty(headerName, headers.get(headerName));
        }

        JsonParser parser = new JsonParser();

        is = theConnection.getInputStream();
        isr = new InputStreamReader(is);

        rv = parser.parse(isr);

    } catch (MalformedURLException e) {
        LOG.error("The URL is malformed (" + URL + ")", e);
    } catch (IOException e) {
        LOG.error("And exception has been thrown when communicating with Latch backend", e);
    } finally {

        if (isr != null) {

            try {
                isr.close();
            } catch (IOException e) {
            }

        }

        if (is != null) {

            try {
                is.close();
            } catch (IOException e) {
            }

        }

    }

    return rv;

}

From source file:com.emc.ecs.sync.model.ObjectMetadata.java

License:Open Source License

public static ObjectMetadata fromJson(String json) {
    JsonObject root = new JsonParser().parse(json).getAsJsonObject();
    JsonElement instanceClass = root.get("instanceClass");
    if (instanceClass == null) { // might be data from an older version; make sure user is aware
        throw new RuntimeException(
                "could not parse meta-file. this could mean you used an older version of EcsSync to move data to the source location. either use that same version again or use --no-sync-user-metadata to continue using this version");
    } else {//from   w w  w .j  av a 2s.co m
        try {
            return ((ObjectMetadata) Class.forName(instanceClass.getAsString()).newInstance())
                    .createFromJson(json);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:com.emc.ecs.sync.model.SyncMetadata.java

License:Open Source License

public static SyncMetadata fromJson(String json) {
    JsonObject root = new JsonParser().parse(json).getAsJsonObject();
    JsonElement instanceClass = root.get("instanceClass");
    if (instanceClass == null) { // might be data from an older version; make sure user is aware
        throw new RuntimeException(
                "could not parse meta-file. this could mean you used an older version of EcsSync to move data to the source location. either use that same version again or use --"
                        + CommonOptions.IGNORE_METADATA_OPTION + " to continue using this version");
    } else {/*from w w  w . java 2s .c  o m*/
        try {
            return ((SyncMetadata) Class.forName(instanceClass.getAsString()).newInstance())
                    .createFromJson(json);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:com.enablens.dfa.base.DcnmAuthToken.java

License:Open Source License

/**
 * Authenticate.//  w ww.  j  a  v a 2s .c  o m
 */
private void authenticate() {
    authTime = System.currentTimeMillis();
    HttpResponse<String> response;
    int responseCode;
    try {
        response = Unirest.post("http://" + server + "/rest/logon/").basicAuth(username, password)
                .body("{expiration: " + tokenLife + "}").asString();
        responseCode = response.getCode();
    } catch (final UnirestException e) {
        token = "";
        state = DcnmResponseStates.NET_ERROR;
        return;
    }
    responseCode = response.getCode();
    if (responseCode == HTTP_OK) {
        final JsonParser parser = new JsonParser();
        final JsonObject jsonObject = parser.parse(response.getBody().trim()).getAsJsonObject();
        if (jsonObject.has(DCNM_TOKEN_KEY)) {
            token = jsonObject.get(DCNM_TOKEN_KEY).getAsString();
            state = DcnmResponseStates.VALID;
        } else {
            // No token returned - DCNM returns {}
            // if credentials are incorrect
            token = "";
            state = DcnmResponseStates.SERVERSIDE_ERROR;
        }
    } else {
        // Not Response Code 200
        token = "";
        state = DcnmResponseStates.WEB_FAILURE;
    }

}

From source file:com.epam.wilma.core.processor.entity.PrettyPrintProcessor.java

License:Open Source License

private String tryToParseJson(final WilmaHttpEntity entity, final String body) {
    String result = body;//from   w  w w  .java2s . c  om
    try {
        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
        JsonParser parser = new JsonParser();
        JsonReader reader = new JsonReader(new StringReader(body));
        reader.setLenient(true);
        JsonElement element = parser.parse(reader);
        result = gson.toJson(element);
    } catch (Exception e) {
        logError(entity, e);
    }
    return result;
}

From source file:com.epam.wilma.sequence.formatters.SequenceAwareJsonTemplateFormatter.java

License:Open Source License

@Override
public byte[] formatTemplate(final WilmaHttpRequest wilmaRequest, final HttpServletResponse resp,
        final byte[] templateResource, final ParameterList params) throws Exception {
    JsonElement response = new JsonParser()
            .parse(IOUtils.toString(templateResource, StandardCharsets.UTF_8.name()));
    new SessionAwareJsonTreeEvaluator(wilmaRequest.getBody(), wilmaRequest.getSequence(), params)
            .replaceAllNonRecursive(response);

    return response.toString().getBytes();
}

From source file:com.epam.wilma.webapp.stub.response.formatter.json.JsonTemplateFormatter.java

License:Open Source License

@Override
public byte[] formatTemplate(final WilmaHttpRequest wilmaRequest, final HttpServletResponse resp,
        final byte[] templateResource, final ParameterList params) throws Exception {
    JsonElement response = new JsonParser().parse(new String(templateResource, StandardCharsets.UTF_8));

    new NonRecursiveJsonTreeEvaluator(wilmaRequest.getBody()).replaceAllNonRecursive(response);

    return response.toString().getBytes();
}

From source file:com.ericsson.eiffel.remrem.generate.cli.CLI.java

License:Apache License

/**
 * Send the given json string to message service
 * /*from ww  w .j  a  v a 2s.  c o m*/
 * @param msgType
 *            the Eiffel message type
 * @param filePath
 *            the file path where the message content resides
 * @param responseFilePath
 *            the file path where to store the prepared message, stdout if
 *            null
 */
private void handleJsonString(String jsonString, CommandLine commandLine) {
    String responseFilePath = null;
    if (commandLine.hasOption("r"))
        responseFilePath = commandLine.getOptionValue("r");
    String msgType = handleMsgTypeArgs(commandLine);

    try {
        JsonParser parser = new JsonParser();
        JsonObject jsonContent = parser.parse(jsonString).getAsJsonObject();
        MsgService msgService = getMessageService(commandLine);
        String returnJsonStr = msgService.generateMsg(msgType, jsonContent);
        returnJsonStr = "[" + returnJsonStr + "]";
        if (responseFilePath != null) {
            try (PrintWriter out = new PrintWriter(responseFilePath)) {
                out.println(returnJsonStr);
            }
        } else {
            System.out.println(returnJsonStr);
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        CLIOptions.exit(CLIExitCodes.HANDLE_JSON_STRING_FAILED);
    }
}

From source file:com.ericsson.eiffel.remrem.generate.config.SpringfoxJsonToGsonAdapter.java

License:Apache License

@Override
public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
    final JsonParser parser = new JsonParser();
    return parser.parse(json.value());
}

From source file:com.ericsson.eiffel.remrem.publish.controller.ProducerController.java

License:Apache License

/**
 * @return this method returns the current version of publish and all loaded
 *         protocols.// w ww .  ja  v  a  2s  .co  m
 */
@ApiOperation(value = "To get versions of publish and all loaded protocols", response = String.class)
@RequestMapping(value = "/versions", method = RequestMethod.GET)
public JsonElement getVersions() {
    JsonParser parser = new JsonParser();
    Map<String, Map<String, String>> versions = new VersionService().getMessagingVersions();
    return parser.parse(versions.toString());
}