Tabnine Logo
JsonUtils
Code IndexAdd Tabnine to your IDE (free)

How to use
JsonUtils
in
io.sphere.sdk.utils

Best Java code snippets using io.sphere.sdk.utils.JsonUtils (Showing top 11 results out of 315)

origin: io.sphere.sdk.jvm/products

public static Attribute of(final String name, final Object value) {
  final JsonNode jsonNode = JsonUtils.newObjectMapper().valueToTree(value);
  return of(name, jsonNode);
}
origin: io.sphere.jvmsdk/common

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);
  }
}
origin: io.sphere.jvmsdk/common

/** 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);
  }
}
origin: io.sphere.jvmsdk/java-client

@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()));
}
origin: io.sphere.jvmsdk/common

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);
}
origin: io.sphere.jvmsdk/java-client

  @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);
    }
  }
};
origin: io.sphere.jvmsdk/common

  public void setUnderlyingHttpResponse(final HttpResponse httpResponse) {
    final String s = "status=" + httpResponse.getStatusCode() + " " + JsonUtils.prettyPrintJsonStringSecureWithFallback(httpResponse.getResponseBody());
    setUnderlyingHttpResponse(s);
  }
}
origin: io.sphere.jvmsdk/product-types

@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);
}
origin: io.sphere.jvmsdk/common

/**
 * 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;
}
origin: io.sphere.sdk.jvm/products

@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);
}
origin: io.sphere.jvmsdk/common

  /** 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;
    }
  }
}
io.sphere.sdk.utilsJsonUtils

Most used methods

  • newObjectMapper
  • prettyPrintJsonStringSecure
    Pretty prints given JSON string, replacing passwords by 'xxxxx'.
  • prettyPrintJsonStringSecureWithFallback
    Works like JsonUtils#prettyPrintJsonStringSecure(java.lang.String) but returns the unparsed JSON str
  • readObjectFromJsonString
  • secure
    Very simple way to "erase" passwords - replaces all field values whose names contains 'pass' by 'xxx

Popular in Java

  • Making http requests using okhttp
  • runOnUiThread (Activity)
  • setRequestProperty (URLConnection)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • Window (java.awt)
    A Window object is a top-level window with no borders and no menubar. The default layout for a windo
  • BufferedImage (java.awt.image)
    The BufferedImage subclass describes an java.awt.Image with an accessible buffer of image data. All
  • PrintStream (java.io)
    Fake signature of an existing Java class.
  • Format (java.text)
    The base class for all formats. This is an abstract base class which specifies the protocol for clas
  • ReentrantLock (java.util.concurrent.locks)
    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor
  • ImageIO (javax.imageio)
  • Top PhpStorm plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now