List of usage examples for com.google.gson JsonParser parse
@Deprecated public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException
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.//from www .jav a 2 s . c om * <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.enablens.dfa.base.DcnmAuthToken.java
License:Open Source License
/** * Authenticate./* w ww .j a v a2 s . co 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. j av a2 s . 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.ericsson.eiffel.remrem.generate.cli.CLI.java
License:Apache License
/** * Send the given json string to message service * /*from w w w . ja va 2 s . 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.//from w ww . ja v a2s . 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()); }
From source file:com.ericsson.eiffel.remrem.publish.service.MessageServiceRMQImpl.java
License:Apache License
@Override public SendResult send(String jsonContent, MsgService msgService, String userDomainSuffix, String tag, String routingKey) {//from www.j a v a 2 s . c om JsonParser parser = new JsonParser(); try { JsonElement json = parser.parse(jsonContent); if (json.isJsonArray()) { return send(json, msgService, userDomainSuffix, tag, routingKey); } else { Map<String, String> map = new HashMap<>(); Map<String, String> routingKeyMap = new HashMap<>(); String eventId = msgService.getEventId(json.getAsJsonObject()); if (StringUtils.isNotBlank(eventId)) { String routing_key = PublishUtils.getRoutingKey(msgService, json.getAsJsonObject(), rmqHelper, userDomainSuffix, tag, routingKey); if (StringUtils.isNotBlank(routing_key)) { map.put(eventId, json.toString()); routingKeyMap.put(eventId, routing_key); } else if (routing_key == null) { List<PublishResultItem> resultItemList = new ArrayList<>(); routingKeyGenerationFailure(resultItemList); return new SendResult(resultItemList); } else { List<PublishResultItem> resultItemList = new ArrayList<>(); PublishResultItem resultItem = rabbitmqConfigurationNotFound(msgService); resultItemList.add(resultItem); return new SendResult(resultItemList); } } else { List<PublishResultItem> resultItemList = new ArrayList<>(); createFailureResult(resultItemList); return new SendResult(resultItemList); } return send(routingKeyMap, map, msgService); } } catch (final JsonSyntaxException e) { String resultMsg = "Could not parse JSON."; if (e.getCause() != null) { resultMsg = resultMsg + " Cause: " + e.getCause().getMessage(); } log.error(resultMsg, e.getMessage()); List<PublishResultItem> resultItemList = new ArrayList<>(); createFailureResult(resultItemList); return new SendResult(resultItemList); } }
From source file:com.ericsson.eiffel.remrem.semantics.schemas.SchemaFile.java
License:Apache License
/** * @param jsonFileName// w ww . j a va 2s. c om * -name of the input json file is to be created is an input * parameter to this method * @param jsonObject * -josnObject having required properties to generate events is * an input parameter to this method */ public void createNewInputJsonSchema(String jsonFileName, JsonObject jsonObject) { String currentWorkingDir = EiffelConstants.USER_DIR; FileWriter writer = null; String copyFilePath = currentWorkingDir + File.separator + EiffelConstants.INPUT_EIFFEL_SCHEMAS; String newFileName = copyFilePath + File.separator + jsonFileName + EiffelConstants.JSON_MIME_TYPE; Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(jsonObject.toString()); String prettyJsonString = gson.toJson(je); try { writer = new FileWriter(newFileName); writer.write(prettyJsonString); } catch (Exception e) { e.printStackTrace(); } finally { try { writer.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:com.ericsson.eiffel.remrem.semantics.SemanticsService.java
License:Apache License
/** * Gets the path to an event template file that must be in lowercase * and read through a resource stream. Stream is parsed into a * JsonElement.//from ww w. ja v a2 s. com * * @param String eventType * * @return json element containing an event template */ @Override public JsonElement getEventTemplate(String eventType) { String path = "templates/" + eventType.toLowerCase() + ".json"; InputStream fileStream = getClass().getClassLoader().getResourceAsStream(path); JsonElement json = null; JsonParser parser = new JsonParser(); try { json = parser.parse(new InputStreamReader(fileStream)); } catch (Exception e) { log.error(e.getMessage()); return json; } return json; }
From source file:com.ericsson.eiffel.remrem.semantics.validator.EiffelValidator.java
License:Apache License
/** * * @param report json validation report/* www . ja v a 2 s. c o m*/ * @return error message */ private String getErrorsList(ProcessingReport report) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser parser = new JsonParser(); String message = ""; for (ProcessingMessage processingMessage : report) { if (LogLevel.ERROR.equals(processingMessage.getLogLevel())) { JsonElement element = parser.parse(processingMessage.asJson().toString()); element.getAsJsonObject().remove("schema"); element.getAsJsonObject().remove("level"); message = gson.toJson(element); log.debug(message); } } return message; }