private void logTokenResult(final Tokens nullableTokens, final Throwable nullableThrowable) { if (nullableTokens != null) { AUTH_LOGGER.debug(() -> "Successfully fetched token that expires in " + Optional.ofNullable(nullableTokens.getExpiresIn()).map(x -> x.toString()).orElse("an unknown time") + "."); } else { AUTH_LOGGER.error(() -> "Failed to fetch token.", nullableThrowable); } }
public static SphereInternalLogger getLogger(final HttpRequest httpRequest) { return getLogger(getPathElement(httpRequest) + ".requests." + requestOrCommandScopeSegment(httpRequest)); }
private static <T> T processHttpResponse(final SphereRequest<T> sphereRequest, final ObjectMapper objectMapper, final SphereApiConfig config, final HttpResponse httpResponse) { final SphereInternalLogger logger = getLogger(httpResponse); logger.debug(() -> httpResponse); logger.trace(() -> httpResponse.getStatusCode() + "\n" + Optional.ofNullable(httpResponse.getResponseBody()).map(body -> SphereJsonUtils.prettyPrint(bytesToString(body))).orElse("No body present.") + "\n"); final List<String> notices = httpResponse.getHeaders().getHeadersAsMap().get(SphereHttpHeaders.X_DEPRECATION_NOTICE); if (notices != null) { notices.stream().forEach(message -> logger.warn(() -> "Deprecation notice : " + message)); } return parse(sphereRequest, objectMapper, config, httpResponse); }
@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())); }
/** Parses Tokens from a response from the backend authorization service. * @param resp Response from the authorization service. * @param requestBuilder The request, used for error reporting. */ protected Tokens parseResponse(Response resp, AsyncHttpClient.BoundRequestBuilder requestBuilder) { try { getLogger("oauth").debug(() -> requestBuilder.build().toString() + "\n(auth server response not logged for security reasons)"); if (resp.getStatusCode() != 200) { throw new AuthorizationException(requestBuilder.build().toString() + " " + resp);//TODO } JsonNode json = new ObjectMapper().readValue(resp.getResponseBody(), JsonNode.class); String accessToken = json.path("access_token").textValue(); boolean hasExpiresIn = json.path("expires_in").isNumber(); Optional<Long> expiresIn = hasExpiresIn ? Optional.of(json.path("expires_in").longValue()) : Optional.<Long>empty(); String refreshToken = json.path("refresh_token").textValue(); return new Tokens(accessToken, refreshToken, expiresIn); } catch (IOException e) { throw new RuntimeException(e);//TODO } } }
private void scheduleNextRefresh(Tokens tokens) { if (!tokens.getExpiresIn().isPresent()) { AUTH_LOGGER.warn(() -> "Authorization server did not provide expires_in for the access token."); return; } if (tokens.getExpiresIn().get() * 1000 < TOKEN_ABOUT_TO_EXPIRE_MS) { AUTH_LOGGER.warn(() -> "Authorization server returned an access token with a very short validity of " + tokens.getExpiresIn().get() + "s!"); return; } long refreshTimeout = tokens.getExpiresIn().get() * 1000 - TOKEN_ABOUT_TO_EXPIRE_MS; AUTH_LOGGER.debug(() -> "Scheduling next token refresh " + refreshTimeout / 1000 + "s from now."); refreshTimer.schedule(new TimerTask() { public void run() { beginRefresh(); } }, refreshTimeout); }
public static void logRequestData(final Http.Context ctx) { final List<ReportRawData> rawDatas = (List<ReportRawData>) ctx.args.get(KEY); if (rawDatas != null && rawDatas instanceof List) { final String durations = rawDatas.stream().map(data -> data.getStopTimestamp() - data.getStartTimestamp()).map(l -> Long.toString(l) + " ms").collect(joining(", ")); if (LOGGER.isTraceEnabled()) { final String queriesAsString = rawDatas.stream().map(q -> { final String url = q.getHttpRequest().getUrl(); final String[] split = StringUtils.split(url, "/", 4); final String shortUrl = split.length == 4 ? "/" + split[3] : url; final HttpMethod httpMethod = q.getHttpRequest().getHttpMethod(); final long duration = q.getStopTimestamp() - q.getStartTimestamp(); final Integer bodySize = getBodySize(q); return format(" %s %s %dms %dbytes", httpMethod, shortUrl, duration, bodySize); }).collect(joining("\n")); LOGGER.trace(() -> format("commercetools requests in %s: \n%s", ctx.request(), queriesAsString)); } else { final Pair<List<ReportRawData>, List<ReportRawData>> queryCommandPair = splitByQueriesAndCommands(rawDatas); final List<ReportRawData> queries = queryCommandPair.getLeft(); final List<ReportRawData> commands = queryCommandPair.getRight(); final int size = calculateTotalSize(rawDatas); LOGGER.debug(() -> format("%s used %d requests (%d queries, %d commands, %dbytes fetched, in (%s)).", ctx.request(), rawDatas.size(), queries.size(), commands.size(), size, durations)); } } }
private static List<Category> categoriesOrganizedAsTree(List<Category> allCategoriesAsFlatListWithoutChildrenSettings) { final List<Category> categoriesOrganizedInTrees; if (allCategoriesAsFlatListWithoutChildrenSettings == null) { categoriesOrganizedInTrees = Collections.emptyList(); LOGGER.warn(() -> "null passed for categories."); } else if (allCategoriesAsFlatListWithoutChildrenSettings.size() == 0) { categoriesOrganizedInTrees = Collections.emptyList(); } else { final Pair<List<Category>, List<Category>> partition = partition(allCategoriesAsFlatListWithoutChildrenSettings, new CategoryHasParentPredicate()); final List<Category> rootCategories = partition.getLeft(); final List<Category> categoriesWithoutParents = partition.getRight(); final Multimap<String, Category> categoriesByParentId = buildParentMultiMap(rootCategories); categoriesOrganizedInTrees = buildTreeRecursive(Optional.<Category>empty(), categoriesWithoutParents, new ArrayList<>(), categoriesByParentId); } return categoriesOrganizedInTrees; }
public static SphereInternalLogger getLogger(final Requestable requestable) { final HttpRequest httpRequest = requestable.httpRequest(); final HttpMethod httpMethod = httpRequest.getHttpMethod(); return getLogger(getFirstPathElement(httpRequest) + ".requests." + requestOrCommandScopeSegment(httpMethod)); }
/** * Executes a http auth sphere request and fetches a new access token. * @return future of a token */ @Override public CompletableFuture<Tokens> get() { AUTH_LOGGER.debug(() -> "Fetching new token."); final CompletableFuture<Tokens> result = httpClient.execute(newRequest()).thenApply(this::parseResponse); logTokenResult(result); return result; }
private void process(final FailedTokenFetchMessage m) { isWaitingForToken = false; AUTH_LOGGER.error(() -> "Can't fetch tokens.", m.cause); requestUpdateFailedStatus.accept(m.cause); }
private void log(String message) { logger.trace(() -> message); }
public static SphereInternalLogger getLogger(final String loggerName) { return new SphereInternalLogger(LoggerFactory.getLogger("sphere." + loggerName)); }
public SphereInternalLogger trace(final Supplier<Object> message) { if (isTraceEnabled()) { underlyingLogger.trace(message.get().toString()); } return this; }
private static <T> T processHttpResponse(final SphereRequest<T> sphereRequest, final ObjectMapper objectMapper, final SphereApiConfig config, final HttpResponse httpResponse, final HttpRequest httpRequest) { final SphereInternalLogger logger = getLogger(httpResponse); logger.debug(() -> httpResponse); logger.trace(() -> httpResponse.getStatusCode() + "\n" + Optional.ofNullable(httpResponse.getResponseBody()).map(body -> SphereJsonUtils.prettyPrint(bytesToString(body))).orElse("No body present.")); final List<String> notices = httpResponse.getHeaders().getHeadersAsMap().get(SphereHttpHeaders.X_DEPRECATION_NOTICE); if (notices != null) { notices.forEach(message -> logger.warn(() -> "Deprecation notice : " + message)); } return parse(sphereRequest, objectMapper, config, httpResponse, httpRequest); }
private <T> CompletableFuture<T> execute(final SphereRequest<T> sphereRequest, final String token) { final HttpRequest httpRequest = createHttpRequest(sphereRequest, token); final SphereInternalLogger logger = getLogger(httpRequest); logger.debug(() -> sphereRequest); logger.trace(() -> { final String output; if (httpRequest.getBody().isPresent() && httpRequest.getBody().get() instanceof StringHttpRequestBody) { final StringHttpRequestBody body = (StringHttpRequestBody) httpRequest.getBody().get(); final String unformattedJson = body.getString(); output = "send: " + unformattedJson + "\nformatted: " + JsonUtils.prettyPrintJsonStringSecure(unformattedJson); } else { output = "no request body present"; } return output; }); return httpClient. execute(httpRequest). thenApply(preProcess(sphereRequest, objectMapper, config)); }