Java Code Examples for com.nike.internal.util.StringUtils

The following examples show how to use com.nike.internal.util.StringUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: backstopper   Source File: ApiExceptionHandlerUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The distributed trace ID if available in the request or the SLF4J {@link MDC}, or null if it cannot be
 *          found. Will also return null if the distributed trace ID exists but its trimmed length is 0
 *          (i.e. the distributed trace ID must be non-empty and contain something besides whitespace for it to be
 *          used). If you are using a distributed tracing system that uses different keys or where the trace ID is
 *          otherwise unobtainable using the rules defined here, then you can override this method and provide
 *          whatever rules you want.
 */
public String extractDistributedTraceId(RequestInfoForLogging request) {
    String traceIdToUse = null;

    if (distributedTraceIdHeaderKey != null) {
        String dtraceIdFromHeader = request.getHeader(distributedTraceIdHeaderKey);
        Object dtraceIdFromAttribute = request.getAttribute(distributedTraceIdHeaderKey);
        if (StringUtils.isNotBlank(dtraceIdFromHeader))
            traceIdToUse = dtraceIdFromHeader.trim();
        else if (dtraceIdFromAttribute != null && StringUtils.isNotBlank(dtraceIdFromAttribute.toString()))
            traceIdToUse = dtraceIdFromAttribute.toString().trim();
    }

    if (traceIdToUse == null) {
        // As a last resort try to get it from the MDC since some distributed systems (e.g. Wingtips) put the
        //      trace ID there.
        String fromMdc = MDC.get(TRACE_ID_MDC_KEY);
        if (fromMdc != null)
            traceIdToUse = fromMdc.trim();
    }

    return traceIdToUse;
}
 
Example 2
Source Project: backstopper   Source File: ApiException.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extracts and joins all messages from the input List<{@link ApiError}> if the desired message is null.
 *
 * Will return null if the input error List is null
 */
protected static String extractMessage(List<ApiError> apiErrors, String desiredMessage) {
    if (desiredMessage != null) {
        return desiredMessage;
    }

    if (apiErrors == null || apiErrors.isEmpty()) {
        return null;
    }

    if (apiErrors.size() == 1) {
        return extractMessage(apiErrors.get(0));
    }

    List<String> apiErrorMessages = new ArrayList<>(apiErrors.size());
    for (ApiError error : apiErrors) {
        apiErrorMessages.add(error.getMessage());
    }

    return StringUtils.join(apiErrorMessages, ", ", "[", "]");
}
 
Example 3
Source Project: riposte   Source File: RiposteWingtipsServerTagAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String getRequestUriPathTemplate(
    @Nullable RequestInfo<?> request, @Nullable ResponseInfo<?> response
) {
    if (request == null) {
        return null;
    }

    String pathTemplate = request.getPathTemplate();
    if (StringUtils.isBlank(pathTemplate)) {
        return null;
    }

    return pathTemplate;
}
 
Example 4
Source Project: riposte   Source File: RiposteHandlerInternalUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the name that should be used for the span surrounding the request. Defaults to whatever {@link
 * ServerSpanNamingAndTaggingStrategy#getInitialSpanName(RequestInfo)} returns, with a fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string.
 *
 * @param nettyRequest The Netty {@link HttpRequest}.
 * @param riposteRequestInfo The Riposte {@link RequestInfo} (if this is null, then the tag strategy and adapter
 * will be ignored, and we'll fallback to basic behavior using the {@code nettyRequest}).
 * @param namingStrategy The {@link ServerSpanNamingAndTaggingStrategy} being used.
 * @return The name that should be used for the span surrounding the request.
 */
@NotNull String determineOverallRequestSpanName(
    @NotNull HttpRequest nettyRequest,
    @Nullable RequestInfo<?> riposteRequestInfo,
    @NotNull ServerSpanNamingAndTaggingStrategy<Span> namingStrategy
) {
    // Immediately go to the fallback span name if the Riposte RequestInfo is null.
    if (riposteRequestInfo == null) {
        return determineFallbackOverallRequestSpanName(nettyRequest);
    }

    // We have a Riposte RequestInfo. Try the naming strategy first.
    String spanNameFromStrategy = namingStrategy.getInitialSpanName(riposteRequestInfo);

    if (StringUtils.isNotBlank(spanNameFromStrategy)) {
        return spanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return determineFallbackOverallRequestSpanName(nettyRequest);
}
 
Example 5
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * SpanNamingAndTaggingStrategy#getInitialSpanName(Object)} returns, with a fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string. You can override this method to return something else if you want different
 * behavior and you don't want to adjust the naming strategy or adapter.
 *
 * @param request        The request that is about to be executed.
 * @param namingStrategy The {@link SpanNamingAndTaggingStrategy} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
        @NotNull RequestBuilderWrapper request,
        @NotNull SpanNamingAndTaggingStrategy<RequestBuilderWrapper, ?, ?> namingStrategy
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(
            "async_downstream_call", request.httpMethod
    );
}
 
Example 6
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * SpanNamingAndTaggingStrategy#getInitialSpanName(Object)} returns, with a fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string. You can override this method to return something else if you want different
 * behavior and you don't want to adjust the naming strategy or adapter.
 *
 * @param request The request that is about to be executed.
 * @param namingStrategy The {@link SpanNamingAndTaggingStrategy} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull RequestBuilderWrapper request,
    @NotNull SpanNamingAndTaggingStrategy<RequestBuilderWrapper, ?, ?> namingStrategy
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(
        "async_downstream_call", request.httpMethod
    );
}
 
Example 7
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)} returns, with a fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string. You can override this method to return something else if you want different
 * behavior and you don't want to adjust the naming strategy or adapter.
 *
 * @param request The request that is about to be executed.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} being used.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull ClientRequest request,
    @NotNull HttpTagAndSpanNamingStrategy<ClientRequest, ?> namingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<ClientRequest, ?> adapter
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(
        "webflux_downstream_call", getRequestMethodAsString(request.method())
    );
}
 
Example 8
Source Project: wingtips   Source File: WingtipsSpringWebfluxWebFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param exchange The incoming request.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} that should be used to try and generate the
 * initial span name - cannot be null.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} that should be passed to the given {@code namingStrategy}
 * to try and generate the initial span name - cannot be null.
 * @return The human-readable name to be given to a {@link Span} representing this request. By default this method
 * attempts to use {@link HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}
 * with the given {@code namingStrategy} and {@code adapter} for generating the name, and falls back to
 * {@link HttpRequestTracingUtils#generateSafeSpanName(String, String, Integer)} if the
 * {@link HttpTagAndSpanNamingStrategy} returns null or blank.
 */
protected @NotNull String getInitialSpanName(
    @NotNull ServerWebExchange exchange,
    @NotNull HttpTagAndSpanNamingStrategy<ServerWebExchange, ?> namingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<ServerWebExchange, ?> adapter
) {
    // Try the naming strategy first.
    String spanNameFromStrategy = namingStrategy.getInitialSpanName(exchange, adapter);

    if (StringUtils.isNotBlank(spanNameFromStrategy)) {
        return spanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    String pathTemplate = determineUriPathTemplate(exchange);
    String method = exchange.getRequest().getMethodValue();

    // HttpRequestTracingUtils.generateSafeSpanName() gives us what we want for a fallback, and properly handles
    //      the case where everything passed into it is null.
    return HttpRequestTracingUtils.generateSafeSpanName(method, pathTemplate, (Integer)null);
}
 
Example 9
Source Project: wingtips   Source File: WingtipsSpringWebfluxWebFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tries to determine the low-cardinality path template for the given request. First, it looks for a
 * {@link KnownZipkinTags#HTTP_ROUTE} request attribute - if it finds one, then it uses that (this is not expected
 * under normal circumstances, but could be used to override normal behavior). If that attribute is not set, then
 * it falls back to looking for {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE}, which is the usual way
 * Spring tells you what the path template was. If both of those fail, then null will be returned.
 *
 * @param exchange The {@link ServerWebExchange} for the request.
 * @return The low-cardinality path template for the given request, or null if no such path template could be
 * found.
 */
protected static @Nullable String determineUriPathTemplate(@NotNull ServerWebExchange exchange) {
    // Try the Zipkin http.route attribute first. If this exists, then it is definitively what we want.
    String path = getRequestAttributeAsString(exchange, KnownZipkinTags.HTTP_ROUTE);

    if (StringUtils.isNotBlank(path)) {
        // Found http.route. Use it.
        return path;
    }

    // The Zipkin http.route attribute was null or blank, so try the Spring "best matching pattern" attribute.
    path = getRequestAttributeAsString(exchange, HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

    if (StringUtils.isNotBlank(path)) {
        // Found Spring best matching pattern. Use it.
        return path;
    }

    // At this point we've struck out on finding a path template.
    return null;
}
 
Example 10
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)} returns, with a fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string. You can override this method to return something else if you want different
 * behavior and you don't want to adjust the naming strategy or adapter.
 *
 * @param request The request that is about to be executed.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} being used.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull HttpRequest request,
    @NotNull HttpTagAndSpanNamingStrategy<HttpRequest, ?> namingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<HttpRequest, ?> adapter
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(
        "resttemplate_downstream_call", getRequestMethodAsString(request.getMethod())
    );
}
 
Example 11
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)} returns, with a fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string. You can override this method to return something else if you want different
 * behavior and you don't want to adjust the naming strategy or adapter.
 *
 * @param request The request that is about to be executed.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} being used.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull HttpRequest request,
    @NotNull HttpTagAndSpanNamingStrategy<HttpRequest, ?> namingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<HttpRequest, ?> adapter
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(
        "asyncresttemplate_downstream_call", getRequestMethodAsString(request.getMethod())
    );
}
 
Example 12
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)} returns, with a fallback
 * of {@link WingtipsApacheHttpClientUtil#getFallbackSubspanSpanName(HttpRequest)} if the naming strategy returned
 * null or blank string. You can override this method to return something else if you want different behavior and
 * you don't want to adjust the naming strategy or adapter.
 *
 * @param request The request that is about to be executed.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} being used.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull HttpRequest request,
    @NotNull HttpTagAndSpanNamingStrategy<HttpRequest, ?> namingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<HttpRequest, ?> adapter
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return WingtipsApacheHttpClientUtil.getFallbackSubspanSpanName(request);
}
 
Example 13
Source Project: wingtips   Source File: WingtipsHttpClientBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the name that should be used for the subspan surrounding the call. Defaults to whatever {@link
 * HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)} returns, with a fallback
 * of {@link WingtipsApacheHttpClientUtil#getFallbackSubspanSpanName(HttpRequest)} if the naming strategy returned
 * null or blank string. You can override this method to return something else if you want different behavior and
 * you don't want to adjust the naming strategy or adapter.
 *
 * @param request The request that is about to be executed.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} being used.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} being used.
 * @return The name that should be used for the subspan surrounding the call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull HttpRequest request,
    @NotNull HttpTagAndSpanNamingStrategy<HttpRequest, ?> namingStrategy,
    @NotNull HttpTagAndSpanNamingAdapter<HttpRequest, ?> adapter
) {
    // Try the naming strategy first.
    String subspanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);

    if (StringUtils.isNotBlank(subspanNameFromStrategy)) {
        return subspanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return WingtipsApacheHttpClientUtil.getFallbackSubspanSpanName(request);
}
 
Example 14
Source Project: wingtips   Source File: RequestTracingFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param request The incoming request.
 * @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} that should be used to try and generate the
 * initial span name - cannot be null.
 * @param adapter The {@link HttpTagAndSpanNamingAdapter} that should be passed to the given {@code namingStrategy}
 * to try and generate the initial span name - cannot be null.
 * @return The human-readable name to be given to a {@link Span} representing this request. By default this method
 * attempts to use {@link HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}
 * with the given {@code namingStrategy} and {@code adapter} for generating the name, and falls back to
 * {@link HttpSpanFactory#getSpanName(HttpServletRequest)} if the {@link HttpTagAndSpanNamingStrategy} returns
 * null or blank.
 */
protected String getInitialSpanName(
    HttpServletRequest request,
    HttpTagAndSpanNamingStrategy<HttpServletRequest, ?> namingStrategy,
    HttpTagAndSpanNamingAdapter<HttpServletRequest, ?> adapter
) {
    // Try the naming strategy first.
    String spanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);

    if (StringUtils.isNotBlank(spanNameFromStrategy)) {
        return spanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us. Fall back to something reasonable.
    return HttpSpanFactory.getSpanName(request);
}
 
Example 15
Source Project: wingtips   Source File: ServletRequestTagAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable String getRequestUrl(@Nullable HttpServletRequest request) {
    if (request == null) {
        return null;
    }

    // request.getRequestURL() won't have a query string, so we need to separately look for it and add it
    //      if necessary.
    StringBuffer requestUrl = request.getRequestURL();
    String queryString = request.getQueryString();
    if (StringUtils.isNotBlank(queryString)) {
        requestUrl.append('?').append(queryString);
    }

    return requestUrl.toString();
}
 
Example 16
Source Project: wingtips   Source File: OpenTracingHttpTagStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doHandleResponseAndErrorTagging(
    @NotNull Span span,
    @Nullable REQ request,
    @Nullable RES response,
    @Nullable Throwable error,
    @NotNull HttpTagAndSpanNamingAdapter<REQ, RES> adapter
) {
    putTagIfValueIsNotBlank(span, KnownOpenTracingTags.HTTP_STATUS, adapter.getResponseHttpStatus(response));

    if (error != null || StringUtils.isNotBlank(adapter.getErrorResponseTagValue(response))) {
        // OpenTracing doesn't expect you to pass messages with the error tag, just error=true.
        //      So we don't need to do anything with the given error Throwable or returned
        //      getErrorResponseTagValue(), other than have them trigger adding the error=true tag.
        span.putTag(KnownOpenTracingTags.ERROR, "true");
    }
}
 
Example 17
Source Project: wingtips   Source File: HttpTagAndSpanNamingStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A helper method that can be used by subclasses for putting a tag value on the given span (via {@link
 * Span#putTag(String, String)}) if and only if the tag value is not null and its {@link Object#toString()} is not
 * blank (according to {@link StringUtils#isBlank(CharSequence)}).
 *
 * @param span The span to tag - should never be null.
 * @param tagKey The key to use when calling {@link Span#putTag(String, String)} - should never be null.
 * @param tagValue The tag value to use if and only if it is not null and its {@link Object#toString()} is not
 * blank.
 */
protected void putTagIfValueIsNotBlank(
    @NotNull Span span,
    @NotNull String tagKey,
    @Nullable Object tagValue
) {
    //noinspection ConstantConditions
    if (tagValue == null || span == null || tagKey == null) {
        return;
    }

    // tagValue is not null. Convert to string and check for blank.
    String tagValueString = tagValue.toString();

    if (StringUtils.isBlank(tagValueString)) {
        return;
    }

    // tagValue is not blank. Add it to the given span.
    span.putTag(tagKey, tagValueString);
}
 
Example 18
protected @Nullable HttpTagAndSpanNamingAdapter<ServerWebExchange, ServerHttpResponse> extractTagAndNamingAdapter(
    WingtipsSpringBoot2WebfluxProperties props
) {
    String adapterName = props.getServerSideSpanTaggingAdapter();

    if (StringUtils.isBlank(adapterName)) {
        // Nothing specified, so return null to use the default.
        return null;
    }

    // There are no shortnames for the adapter like there are for strategy. Try instantiating by classname
    try {
        //noinspection unchecked
        return (HttpTagAndSpanNamingAdapter<ServerWebExchange, ServerHttpResponse>)
            Class.forName(adapterName).newInstance();
    }
    catch (Exception ex) {
        // Couldn't instantiate by interpreting it as a class name. Return null so the default gets used.
        logger.warn(
            "Unable to match tagging adapter \"{}\". "
            + "Using the default adapter (SpringWebfluxServerRequestTagAdapter)",
            adapterName, ex
        );
        return null;
    }
}
 
Example 19
@Override
public ApiExceptionHandlerListenerResult shouldHandleException(Throwable ex) {
    // We only care about ApiExceptions.
    if (!(ex instanceof ApiException))
        return ApiExceptionHandlerListenerResult.ignoreResponse();

    ApiException apiException = ((ApiException)ex);

    // Add all the ApiErrors from the exception.
    SortedApiErrorSet errors = new SortedApiErrorSet();
    errors.addAll(apiException.getApiErrors());

    // Add all the extra details for logging from the exception.
    List<Pair<String, String>> messages = new ArrayList<>();
    messages.addAll(apiException.getExtraDetailsForLogging());

    // Add all the extra response headers from the exception.
    List<Pair<String, List<String>>> headers = new ArrayList<>();
    headers.addAll(apiException.getExtraResponseHeaders());

    // Include the ApiException's message as a logged key/value pair.
    if (StringUtils.isNotBlank(ex.getMessage()))
        messages.add(Pair.of("api_exception_message", ex.getMessage()));

    if (ex.getCause() != null) {
        messages.add(Pair.of("exception_cause_class", ex.getCause().getClass().getName()));
        messages.add(Pair.of("exception_cause_message", ex.getCause().getMessage()));
    }

    return ApiExceptionHandlerListenerResult.handleResponse(errors, messages, headers);
}
 
Example 20
@Nullable
@Override
public String getRequestPath(@Nullable HttpRequest request) {
    if (request == null) {
        return null;
    }

    String result = HttpUtils.extractPath(request.uri());
    if (StringUtils.isBlank(result)) {
        return null;
    }

    return result;
}
 
Example 21
Source Project: riposte   Source File: StreamingAsyncHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name that should be used for the span surrounding the downstream call. Defaults to {@link
 * ProxyRouterSpanNamingAndTaggingStrategy#getInitialSpanNameOverride(HttpRequest, RequestInfo, String, String)}
 * if that returns a non-null value, then falls back to whatever {@link
 * ProxyRouterSpanNamingAndTaggingStrategy#getInitialSpanName(HttpRequest)} returns, with a ultimate fallback
 * of {@link HttpRequestTracingUtils#getFallbackSpanNameForHttpRequest(String, String)} if the naming strategy
 * returned null or blank string for both the override and initial span name.
 *
 * @param downstreamRequest The Netty {@link HttpRequest} for the downstream call.
 * @param namingStrategy The {@link ProxyRouterSpanNamingAndTaggingStrategy} being used.
 * @return The name that should be used for the span surrounding the downstream call.
 */
protected @NotNull String getSubspanSpanName(
    @NotNull HttpRequest downstreamRequest,
    @NotNull RequestInfo<?> overallRequest,
    @NotNull ProxyRouterSpanNamingAndTaggingStrategy<Span> namingStrategy
) {
    String spanNameFromStrategy = namingStrategy.getInitialSpanName(downstreamRequest);
    Span overallRequestSpan = Tracer.getInstance().getCurrentSpan();
    String overallRequestSpanName = (overallRequestSpan == null) ? null : overallRequestSpan.getSpanName();

    String spanNameOverride = namingStrategy.getInitialSpanNameOverride(
        downstreamRequest, overallRequest, spanNameFromStrategy, overallRequestSpanName
    );

    if (StringUtils.isNotBlank(spanNameFromStrategy)) {
        // We got a span name from the strategy. See if it should be overridden.
        if (StringUtils.isNotBlank(spanNameOverride)) {
            return spanNameOverride;
        }

        // No override, so just use the name from the strategy.
        return spanNameFromStrategy;
    }

    // The naming strategy didn't have anything for us at all. See if there's an override.
    if (StringUtils.isNotBlank(spanNameOverride)) {
        return spanNameOverride;
    }

    // The naming strategy didn't have anything for us and there was no override. Fall back to something reasonable.
    return getFallbackSpanName(downstreamRequest);
}
 
Example 22
@Test
public void verify_multipart_with_mixed_types_works_properly() throws IOException, InterruptedException {
    String imageName = "someImageFile";
    String imageFilename = "helloWorld.png";
    InputStream imageFileInputStream = VerifyMultipartRequestsWorkComponentTest.class.getClassLoader().getResourceAsStream(imageFilename);
    byte[] imageFileBytes = IOUtils.toByteArray(imageFileInputStream);

    String textName = "someTextFile";
    String textFilename = "testMultipartFile.txt";
    InputStream textFileInputStream = VerifyMultipartRequestsWorkComponentTest.class.getClassLoader().getResourceAsStream(textFilename);
    byte[] textFileBytes = IOUtils.toByteArray(textFileInputStream);

    String attributeName = "someAttribute";
    String attributeString = UUID.randomUUID().toString();

    String responseString =
                given()
                    .baseUri("http://127.0.0.1")
                    .port(serverConfig.endpointsPort())
                    .basePath(MultipartTestEndpoint.MATCHING_PATH)
                    .log().all()
                .when()
                    .multiPart(imageName, imageFilename, imageFileBytes, "image/png")
                    .multiPart(attributeName, attributeString)
                    .multiPart(textName, textFilename, textFileBytes)
                    .post()
                .then()
                    .log().all()
                    .statusCode(200)
                    .extract().asString();

    String expectedImageFileHash = getHashForMultipartPayload(imageName, imageFilename, imageFileBytes);
    String expectedAttributeHash = getHashForMultipartPayload(attributeName, null, attributeString.getBytes(CharsetUtil.UTF_8));
    String expectedTextFileHash = getHashForMultipartPayload(textName, textFilename, textFileBytes);
    String expectedResponse = StringUtils.join(Arrays.asList(expectedImageFileHash, expectedAttributeHash, expectedTextFileHash), ",");
    assertThat(responseString).isEqualTo(expectedResponse);
}
 
Example 23
@Override
public @NotNull CompletableFuture<ResponseInfo<String>> execute(
    @NotNull RequestInfo<String> request,
    @NotNull Executor longRunningTaskExecutor,
    @NotNull ChannelHandlerContext ctx
) {
    List<String> hashesFound = new ArrayList<>();

    for (InterfaceHttpData multipartData : request.getMultipartParts()) {
        String name = multipartData.getName();
        byte[] payloadBytes;
        try {
            payloadBytes = ((HttpData)multipartData).get();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String filename = null;
        switch (multipartData.getHttpDataType()) {
            case Attribute:
                // Do nothing - filename stays null
                break;
            case FileUpload:
                filename = ((FileUpload)multipartData).getFilename();
                break;
            default:
                throw new RuntimeException("Unsupported multipart type: " + multipartData.getHttpDataType().name());
        }

        hashesFound.add(getHashForMultipartPayload(name, filename, payloadBytes));
    }

    return CompletableFuture.completedFuture(ResponseInfo.newBuilder(StringUtils.join(hashesFound, ",")).build());
}
 
Example 24
@Override
public String getQueryString() {
    List<String> queryParams = requestInfo.getQueryParams().parameters().entrySet().stream()
                                          .map(entry -> entry.getKey() + "="
                                                        + StringUtils.join(entry.getValue(), ","))
                                          .collect(Collectors.toList());

    if (queryParams.isEmpty())
        return null;

    return StringUtils.join(queryParams, "&");
}
 
Example 25
Source Project: wingtips   Source File: ZipkinHttpTagStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doHandleResponseAndErrorTagging(
    @NotNull Span span,
    @Nullable REQ request,
    @Nullable RES response,
    @Nullable Throwable error,
    @NotNull HttpTagAndSpanNamingAdapter<REQ, RES> adapter
) {
    // Now that we have both request and response, we'll re-try to get the route.
    putTagIfValueIsNotBlank(span, KnownZipkinTags.HTTP_ROUTE, adapter.getRequestUriPathTemplate(request, response));

    putTagIfValueIsNotBlank(span, KnownZipkinTags.HTTP_STATUS_CODE, adapter.getResponseHttpStatus(response));

    // For error tagging, we'll defer to the error Throwable if it's not null.
    if (error != null) {
        String message = error.getMessage();
        if (message == null) {
            message = error.getClass().getSimpleName();
        }
        addErrorTagToSpan(span, message);
    }
    else {
        // The error Throwable was null, so we'll see if the adapter thinks this is an error response.
        String errorTagValue = adapter.getErrorResponseTagValue(response);
        if (StringUtils.isNotBlank(errorTagValue)) {
            addErrorTagToSpan(span, errorTagValue);
        }
    }
}
 
Example 26
protected @Nullable List<String> extractUserIdHeaderKeysAsList(WingtipsSpringBoot2WebfluxProperties props) {
    if (props.getUserIdHeaderKeys() == null) {
        return null;
    }

    return Stream
        .of(props.getUserIdHeaderKeys().split(","))
        .filter(StringUtils::isNotBlank)
        .map(String::trim)
        .collect(Collectors.toList());
}
 
Example 27
protected @Nullable HttpTagAndSpanNamingStrategy<ServerWebExchange, ServerHttpResponse> extractTagAndNamingStrategy(
    WingtipsSpringBoot2WebfluxProperties props
) {
    String strategyName = props.getServerSideSpanTaggingStrategy();

    if (StringUtils.isBlank(strategyName)) {
        // Nothing specified, so return null to use the default.
        return null;
    }

    // Check for a short-name match first.
    if ("zipkin".equalsIgnoreCase(strategyName)) {
        return ZipkinHttpTagStrategy.getDefaultInstance();
    }

    if("opentracing".equalsIgnoreCase(strategyName)) {
        return OpenTracingHttpTagStrategy.getDefaultInstance();
    }

    if("none".equalsIgnoreCase(strategyName) || "noop".equalsIgnoreCase(strategyName)) {
        return NoOpHttpTagStrategy.getDefaultInstance();
    }

    // At this point there was no short-name match. Try instantiating it by classname.
    try {
        //noinspection unchecked
        return (HttpTagAndSpanNamingStrategy<ServerWebExchange, ServerHttpResponse>)
            Class.forName(strategyName).newInstance();
    }
    catch (Exception ex) {
        // Couldn't instantiate by interpreting it as a class name. Return null so the default gets used.
        logger.warn("Unable to match tagging strategy \"{}\". Using the default strategy (Zipkin)",
                    strategyName, ex);
        return null;
    }
}
 
Example 28
Source Project: riposte   Source File: AsyncHttpClientHelperTagAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public String getRequestPath(@Nullable RequestBuilderWrapper request) {
    if (request == null) {
        return null;
    }

    String result = request.getUrl();
    if (StringUtils.isBlank(result)) {
        return null;
    }

    // Chop out the query string (if any).
    result = HttpUtils.extractPath(result);

    // If it starts with '/' then there's nothing left for us to do - it's already the path.
    if (result.startsWith("/")) {
        return result;
    }

    // Doesn't start with '/'. We expect it to start with http at this point.
    if (!result.toLowerCase().startsWith("http")) {
        // Didn't start with http. Not sure what to do with this at this point, so return null.
        return null;
    }

    // It starts with http. Chop out the scheme and host/port.
    int schemeColonAndDoubleSlashIndex = result.indexOf("://");
    if (schemeColonAndDoubleSlashIndex < 0) {
        // It didn't have a colon-double-slash after the scheme. Not sure what to do at this point, so return null.
        return null;
    }

    int firstSlashIndexAfterSchemeDoubleSlash = result.indexOf('/', (schemeColonAndDoubleSlashIndex + 3));
    if (firstSlashIndexAfterSchemeDoubleSlash < 0) {
        // No other slashes after the scheme colon-double-slash, so no real path. The path at this point is
        //      effectively "/".
        return "/";
    }

    return result.substring(firstSlashIndexAfterSchemeDoubleSlash);
}
 
Example 29
Source Project: riposte   Source File: CodahaleMetricsListener.java    License: Apache License 2.0 4 votes vote down vote up
protected String getMatchingHttpMethodsAsCombinedString(Endpoint<?> endpoint) {
    if (endpoint.requestMatcher().isMatchAllMethods())
        return "ALL";

    return StringUtils.join(endpoint.requestMatcher().matchingMethods(), ",");
}
 
Example 30
Source Project: riposte   Source File: EndpointMetricsHandlerDefaultImpl.java    License: Apache License 2.0 4 votes vote down vote up
protected String getMatchingHttpMethodsAsCombinedString(Endpoint<?> endpoint) {
    if (endpoint.requestMatcher().isMatchAllMethods())
        return "ALL";

    return StringUtils.join(endpoint.requestMatcher().matchingMethods(), ",");
}