public static Attribute of(final String name, final Object value) { final JsonNode jsonNode = JsonUtils.newObjectMapper().valueToTree(value); return of(name, jsonNode); }
public static <T> T readObjectFromJsonFileInClasspath(final String resourcePath, final TypeReference<T> typeReference) { final URL url = Resources.getResource(resourcePath); try { String jsonAsString = Resources.toString(url, Charsets.UTF_8); return readObjectFromJsonString(typeReference, jsonAsString); } catch (IOException e) { throw new RuntimeException(e); } }
/** Pretty prints given JSON string, replacing passwords by {@code 'xxxxx'}. * @param json JSON code as String which should be formatted * @return <code>json</code> formatted */ public static String prettyPrintJsonStringSecure(String json) { try { ObjectMapper jsonParser = new ObjectMapper(); JsonNode jsonTree = jsonParser.readValue(json, JsonNode.class); secure(jsonTree); ObjectWriter writer = jsonParser.writerWithDefaultPrettyPrinter(); return writer.writeValueAsString(jsonTree); } catch (IOException e) { throw new RuntimeException(e); } }
@Override public <T> CompletableFuture<T> execute(final ClientRequest<T> clientRequest) { final SphereInternalLogger logger = getLogger(clientRequest); logger.debug(() -> clientRequest); logger.trace(() -> { final Optional<String> requestBody = clientRequest.httpRequest().getBody(); return requestBody.map(body -> JsonUtils.prettyPrintJsonStringSecure(body)).orElse("no request body present"); }); return requestExecutor. execute(clientRequest). thenApply(preProcess(clientRequest, clientRequest.resultMapper())); }
public void setUnderlyingHttpRequest(final HttpRequest httpRequest) { final String body = httpRequest.getBody().map(s -> JsonUtils.prettyPrintJsonStringSecureWithFallback(s)).orElse("<no body>"); final String requestAsString = new StringBuilder(httpRequest.getHttpMethod().toString()).append(" ").append(httpRequest.getPath()).append("\n").append(body).toString(); setUnderlyingHttpRequest(requestAsString); }
@Override public T apply(final HttpResponse httpResponse) { final SphereInternalLogger logger = getLogger(httpResponse); logger.debug(() -> httpResponse.withoutRequest()); logger.trace(() -> httpResponse.getStatusCode() + "\n" + JsonUtils.prettyPrintJsonStringSecure(httpResponse.getResponseBody()) + "\n"); final int status = httpResponse.getStatusCode(); final String body = httpResponse.getResponseBody(); final boolean hasError = status / 100 != 2; if (hasError) { SphereErrorResponse errorResponse; try { if (Strings.isNullOrEmpty(body)) {//the /model/id endpoint does not return JSON on 404 errorResponse = new SphereErrorResponse(status, "<no body>", Collections.<SphereError>emptyList()); } else { errorResponse = objectMapper.readValue(body, errorResponseJsonTypeRef); } } catch (final Exception e) { // This can only happen when the backend and SDK don't match. final SphereException exception = new SphereException("Can't parse backend response", e); fillExceptionWithData(httpResponse, exception, clientRequest); throw exception; } final SphereBackendException exception = new SphereBackendException(clientRequest.httpRequest().getPath(), errorResponse); fillExceptionWithData(httpResponse, exception, clientRequest); throw exception; } else { return underlying.apply(httpResponse); } } };
public void setUnderlyingHttpResponse(final HttpResponse httpResponse) { final String s = "status=" + httpResponse.getStatusCode() + " " + JsonUtils.prettyPrintJsonStringSecureWithFallback(httpResponse.getResponseBody()); setUnderlyingHttpResponse(s); } }
@Override public AttributeDefinition deserialize(final JsonParser jsonParser, final DeserializationContext context) throws IOException { final JsonNode jsonNode = jsonParser.<JsonNode>readValueAsTree(); final String name = extractNameFromJson(jsonNode); final Class<? extends AttributeDefinition> clazz = findClassForTypeName(name); //the jsonParser is not reusable after reading a value from it, so an object mapper needs to transform the JSON return JsonUtils.newObjectMapper().treeToValue(jsonNode, clazz); }
/** * Works like {@link JsonUtils#prettyPrintJsonStringSecure(java.lang.String)} but returns the unparsed JSON string if the * formatting fails. * @param json the input json to format * @return the formatted json or in error cases the unformatted json */ //TODO rename public static String prettyPrintJsonStringSecureWithFallback(String json) { String result = json; try { ObjectMapper jsonParser = new ObjectMapper(); JsonNode jsonTree = jsonParser.readValue(json, JsonNode.class); secure(jsonTree); ObjectWriter writer = jsonParser.writerWithDefaultPrettyPrinter(); result = writer.writeValueAsString(jsonTree); } catch (IOException e) { result = json; } return result; }
@Override public AttributeDefinition deserialize(final JsonParser jsonParser, final DeserializationContext context) throws IOException { final JsonNode jsonNode = jsonParser.<JsonNode>readValueAsTree(); final String name = extractNameFromJson(jsonNode); final Class<? extends AttributeDefinition> clazz = findClassForTypeName(name); //the jsonParser is not reusable after reading a value from it, so an object mapper needs to transform the JSON return JsonUtils.newObjectMapper().treeToValue(jsonNode, clazz); }
/** Very simple way to "erase" passwords - * replaces all field values whose names contains {@code 'pass'} by {@code 'xxxxx'}. */ private static JsonNode secure(JsonNode node) { if (node.isObject()) { ObjectNode objectNode = (ObjectNode)node; Iterator<Map.Entry<String, JsonNode>> fields = node.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if (field.getValue().isTextual() && field.getKey().toLowerCase().contains("pass")) { objectNode.put(field.getKey(), "xxxxx"); } else { secure(field.getValue()); } } return objectNode; } else if (node.isArray()) { ArrayNode arrayNode = (ArrayNode)node; Iterator<JsonNode> elements = arrayNode.elements(); while (elements.hasNext()) { secure(elements.next()); } return arrayNode; } else { return node; } } }