com.linecorp.centraldogma.internal.Jackson.writeValueAsBytes()方法的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(150)

本文整理了Java中com.linecorp.centraldogma.internal.Jackson.writeValueAsBytes()方法的一些代码示例,展示了Jackson.writeValueAsBytes()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Jackson.writeValueAsBytes()方法的具体详情如下:
包路径:com.linecorp.centraldogma.internal.Jackson
类名称:Jackson
方法名:writeValueAsBytes

Jackson.writeValueAsBytes介绍

暂无

代码示例

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

private static HttpResponse newResponse0(HttpStatus status,
                     @Nullable Throwable cause,
                     @Nullable String message) {
  final ObjectNode node = JsonNodeFactory.instance.objectNode();
  if (cause != null) {
    node.put("exception", cause.getClass().getName());
    if (message == null) {
      message = cause.getMessage();
    }
  }
  node.put("message", message != null ? message : status.reasonPhrase());
  // TODO(minwoox) refine the error message
  try {
    return HttpResponse.of(status, MediaType.JSON_UTF_8, Jackson.writeValueAsBytes(node));
  } catch (JsonProcessingException e) {
    // should not reach here
    throw new Error(e);
  }
}

代码示例来源:origin: line/centraldogma

private static ObjectId newBlob(ObjectInserter inserter, JsonNode content) {
  try {
    return newBlob(inserter, Jackson.writeValueAsBytes(content));
  } catch (IOException e) {
    throw new StorageException("failed to serialize a JSON value: " + content, e);
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

private static ObjectId newBlob(ObjectInserter inserter, JsonNode content) {
  try {
    return newBlob(inserter, Jackson.writeValueAsBytes(content));
  } catch (IOException e) {
    throw new StorageException("failed to serialize a JSON value: " + content, e);
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

private static ObjectId newBlob(ObjectInserter inserter, JsonNode content) {
  try {
    return newBlob(inserter, Jackson.writeValueAsBytes(content));
  } catch (IOException e) {
    throw new StorageException("failed to serialize a JSON value: " + content, e);
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

@Override
public CompletableFuture<Void> update(Session session) {
  requireNonNull(session, "session");
  return CompletableFuture.supplyAsync(() -> {
    final String sessionId = session.id();
    final Path oldPath = sessionId2Path(sessionId);
    if (!Files.exists(oldPath)) {
      throw new AuthException("unknown session: " + sessionId);
    }
    try {
      final Path newPath = Files.createTempFile(tmpDir, null, null);
      Files.write(newPath, Jackson.writeValueAsBytes(session));
      Files.move(newPath, oldPath,
            StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
      return null;
    } catch (IOException e) {
      throw new AuthException(e);
    }
  });
}

代码示例来源:origin: line/centraldogma

@Override
public CompletableFuture<Void> update(Session session) {
  requireNonNull(session, "session");
  return CompletableFuture.supplyAsync(() -> {
    final String sessionId = session.id();
    final Path oldPath = sessionId2Path(sessionId);
    if (!Files.exists(oldPath)) {
      throw new AuthException("unknown session: " + sessionId);
    }
    try {
      final Path newPath = Files.createTempFile(tmpDir, null, null);
      Files.write(newPath, Jackson.writeValueAsBytes(session));
      Files.move(newPath, oldPath,
            StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
      return null;
    } catch (IOException e) {
      throw new AuthException(e);
    }
  });
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

private long storeLog(ReplicationLog<?> log) {
  try {
    final byte[] bytes = Jackson.writeValueAsBytes(log);
    assert bytes.length > 0;
    final LogMeta logMeta = new LogMeta(log.replicaId(), System.currentTimeMillis(), bytes.length);
    final int count = (bytes.length + MAX_BYTES - 1) / MAX_BYTES;
    for (int i = 0; i < count; ++i) {
      final int start = i * MAX_BYTES;
      final int end = Math.min((i + 1) * MAX_BYTES, bytes.length);
      final byte[] b = Arrays.copyOfRange(bytes, start, end);
      final String blockPath = curator.create()
                      .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                      .forPath(absolutePath(LOG_BLOCK_PATH) + '/', b);
      final long blockId = revisionFromPath(blockPath);
      logMeta.appendBlock(blockId);
    }
    final String logPath =
        curator.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
            .forPath(absolutePath(LOG_PATH) + '/', Jackson.writeValueAsBytes(logMeta));
    return revisionFromPath(logPath);
  } catch (Exception e) {
    logger.error("Failed to store a log; entering read-only mode: {}", log, e);
    stopLater();
    throw new ReplicationException("failed to store a log: " + log, e);
  }
}

代码示例来源:origin: line/centraldogma

private long storeLog(ReplicationLog<?> log) {
  try {
    final byte[] bytes = Jackson.writeValueAsBytes(log);
    assert bytes.length > 0;
    final LogMeta logMeta = new LogMeta(log.replicaId(), System.currentTimeMillis(), bytes.length);
    final int count = (bytes.length + MAX_BYTES - 1) / MAX_BYTES;
    for (int i = 0; i < count; ++i) {
      final int start = i * MAX_BYTES;
      final int end = Math.min((i + 1) * MAX_BYTES, bytes.length);
      final byte[] b = Arrays.copyOfRange(bytes, start, end);
      final String blockPath = curator.create()
                      .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                      .forPath(absolutePath(LOG_BLOCK_PATH) + '/', b);
      final long blockId = revisionFromPath(blockPath);
      logMeta.appendBlock(blockId);
    }
    final String logPath =
        curator.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
            .forPath(absolutePath(LOG_PATH) + '/', Jackson.writeValueAsBytes(logMeta));
    return revisionFromPath(logPath);
  } catch (Exception e) {
    logger.error("Failed to store a log; entering read-only mode: {}", log, e);
    stopLater();
    throw new ReplicationException("failed to store a log: " + log, e);
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

private long storeLog(ReplicationLog<?> log) {
  try {
    final byte[] bytes = Jackson.writeValueAsBytes(log);
    assert bytes.length > 0;
    final LogMeta logMeta = new LogMeta(log.replicaId(), System.currentTimeMillis(), bytes.length);
    final int count = (bytes.length + MAX_BYTES - 1) / MAX_BYTES;
    for (int i = 0; i < count; ++i) {
      final int start = i * MAX_BYTES;
      final int end = Math.min((i + 1) * MAX_BYTES, bytes.length);
      final byte[] b = Arrays.copyOfRange(bytes, start, end);
      final String blockPath = curator.create()
                      .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                      .forPath(absolutePath(LOG_BLOCK_PATH) + '/', b);
      final long blockId = revisionFromPath(blockPath);
      logMeta.appendBlock(blockId);
    }
    final String logPath =
        curator.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
            .forPath(absolutePath(LOG_PATH) + '/', Jackson.writeValueAsBytes(logMeta));
    return revisionFromPath(logPath);
  } catch (Exception e) {
    logger.error("Failed to store a log; entering read-only mode: {}", log, e);
    stopLater();
    throw new ReplicationException("failed to store a log: " + log, e);
  }
}

代码示例来源:origin: line/centraldogma

/**
   * GET /users/me
   * Returns a login {@link User} if the user is authorized. Otherwise, {@code 401 Unauthorized} HTTP
   * response is sent.
   */
  @Get("/users/me")
  public HttpResponse usersMe() throws Exception {
    final User user = AuthUtil.currentUser();
    return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8,
                HttpData.of(Jackson.writeValueAsBytes(user)));
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

/**
   * GET /users/me
   * Returns a login {@link User} if the user is authorized. Otherwise, {@code 401 Unauthorized} HTTP
   * response is sent.
   */
  @Get("/users/me")
  public HttpResponse usersMe() throws Exception {
    final User user = AuthUtil.currentUser();
    return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8,
                HttpData.of(Jackson.writeValueAsBytes(user)));
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

/**
   * GET /users/me
   * Returns a login {@link User} if the user is authorized. Otherwise, {@code 401 Unauthorized} HTTP
   * response is sent.
   */
  @Get("/users/me")
  public HttpResponse usersMe() throws Exception {
    final User user = AuthenticationUtil.currentUser();
    return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8,
                HttpData.of(Jackson.writeValueAsBytes(user)));
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

@Override
  public HttpResponse convertResponse(ServiceRequestContext ctx, Object resObj) throws Exception {
    try {
      final HttpRequest request = RequestContext.current().request();
      final HttpData httpData =
          resObj.getClass() == Object.class ? EMPTY_RESULT
                           : HttpData.of(Jackson.writeValueAsBytes(resObj));
      return HttpResponse.of(HttpMethod.POST == request.method() ? HttpStatus.CREATED
                                    : HttpStatus.OK,
                  MediaType.JSON_UTF_8,
                  httpData);
    } catch (JsonProcessingException e) {
      return HttpApiUtil.newResponse(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, Object resObj) throws Exception {
  try {
    if (resObj instanceof HolderWithLocation) {
      return handleWithLocation((HolderWithLocation<?>) resObj);
    }
    final JsonNode jsonNode = Jackson.valueToTree(resObj);
    final String url = jsonNode.get("url").asText();
    // Remove the url field and send it with the LOCATION header.
    ((ObjectNode) jsonNode).remove("url");
    final HttpHeaders headers = HttpHeaders.of(HttpStatus.CREATED)
                        .add(HttpHeaderNames.LOCATION, url)
                        .contentType(MediaType.JSON_UTF_8);
    return HttpResponse.of(headers, HttpData.of(Jackson.writeValueAsBytes(jsonNode)));
  } catch (JsonProcessingException e) {
    logger.debug("Failed to convert a response:", e);
    return HttpApiUtil.newResponse(HttpStatus.INTERNAL_SERVER_ERROR, e);
  }
}

代码示例来源:origin: line/centraldogma

@Override
  public HttpResponse convertResponse(ServiceRequestContext ctx, HttpHeaders headers,
                    @Nullable Object resObj,
                    HttpHeaders trailingHeaders) throws Exception {
    try {
      final HttpHeaders httpHeaders = toMutableHeaders(headers);
      if (httpHeaders.contentType() == null) {
        httpHeaders.contentType(MediaType.JSON_UTF_8);
      }

      final JsonNode jsonNode = Jackson.valueToTree(resObj);
      if (httpHeaders.get(HttpHeaderNames.LOCATION) == null) {
        final String url = jsonNode.get("url").asText();

        // Remove the url field and send it with the LOCATION header.
        ((ObjectNode) jsonNode).remove("url");
        httpHeaders.add(HttpHeaderNames.LOCATION, url);
      }

      return HttpResponse.of(httpHeaders, HttpData.of(Jackson.writeValueAsBytes(jsonNode)),
                  trailingHeaders);
    } catch (JsonProcessingException e) {
      logger.debug("Failed to convert a response:", e);
      return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

@Override
  public HttpResponse convertResponse(ServiceRequestContext ctx, Object resObj) throws Exception {
    try {
      final HttpRequest request = RequestContext.current().request();
      if (HttpMethod.DELETE == request.method() ||
        (resObj instanceof Iterable && Iterables.size((Iterable<?>) resObj) == 0)) {
        return HttpResponse.of(HttpStatus.NO_CONTENT);
      }

      final HttpData httpData = HttpData.of(Jackson.writeValueAsBytes(resObj));
      return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8, httpData);
    } catch (JsonProcessingException e) {
      logger.debug("Failed to convert a response:", e);
      return HttpApiUtil.newResponse(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
  }
}

代码示例来源:origin: line/centraldogma

@Override
  public HttpResponse convertResponse(ServiceRequestContext ctx, HttpHeaders headers,
                    @Nullable Object resObj,
                    HttpHeaders trailingHeaders) throws Exception {
    try {
      final HttpRequest request = RequestContext.current().request();
      if (resObj == null || HttpMethod.DELETE == request.method() ||
        (resObj instanceof Iterable && Iterables.size((Iterable<?>) resObj) == 0)) {
        return HttpResponse.of(HttpStatus.NO_CONTENT);
      }

      final HttpHeaders resHeaders;
      if (headers.contentType() == null) {
        resHeaders = toMutableHeaders(headers);
        resHeaders.contentType(MediaType.JSON_UTF_8);
      } else {
        resHeaders = headers;
      }

      final HttpData httpData = HttpData.of(Jackson.writeValueAsBytes(resObj));
      return HttpResponse.of(resHeaders, httpData, trailingHeaders);
    } catch (JsonProcessingException e) {
      logger.debug("Failed to convert a response:", e);
      return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server-shaded

private static HttpResponse handleWithLocation(HolderWithLocation<?> holderWithLocation)
      throws JsonProcessingException {
    return HttpResponse.of(
        HttpHeaders.of(HttpStatus.CREATED)
              .add(HttpHeaderNames.LOCATION, holderWithLocation.location())
              .contentType(MediaType.JSON_UTF_8),
        HttpData.of(Jackson.writeValueAsBytes(holderWithLocation.object())));
  }
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-server

@Override
  public HttpResponse convertResponse(ServiceRequestContext ctx, HttpHeaders headers,
                    @Nullable Object resObj,
                    HttpHeaders trailingHeaders) throws Exception {
    try {
      final HttpRequest request = RequestContext.current().request();
      final HttpData httpData =
          resObj != null &&
          resObj.getClass() == Object.class ? EMPTY_RESULT
                           : HttpData.of(Jackson.writeValueAsBytes(resObj));

      final HttpHeaders httpHeaders = toMutableHeaders(headers);
      if (HttpMethod.POST == request.method()) {
        httpHeaders.status(HttpStatus.CREATED);
      }
      if (httpHeaders.contentType() == null) {
        httpHeaders.contentType(MediaType.JSON_UTF_8);
      }
      return HttpResponse.of(httpHeaders, httpData, trailingHeaders);
    } catch (JsonProcessingException e) {
      return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
  }
}

代码示例来源:origin: line/centraldogma

@Override
  public HttpResponse convertResponse(ServiceRequestContext ctx, HttpHeaders headers,
                    @Nullable Object resObj,
                    HttpHeaders trailingHeaders) throws Exception {
    try {
      final HttpRequest request = RequestContext.current().request();
      final HttpData httpData =
          resObj != null &&
          resObj.getClass() == Object.class ? EMPTY_RESULT
                           : HttpData.of(Jackson.writeValueAsBytes(resObj));

      final HttpHeaders httpHeaders = toMutableHeaders(headers);
      if (HttpMethod.POST == request.method()) {
        httpHeaders.status(HttpStatus.CREATED);
      }
      if (httpHeaders.contentType() == null) {
        httpHeaders.contentType(MediaType.JSON_UTF_8);
      }
      return HttpResponse.of(httpHeaders, httpData, trailingHeaders);
    } catch (JsonProcessingException e) {
      return HttpApiUtil.newResponse(ctx, HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
  }
}

相关文章