Search in sources :

Example 26 with SafeIllegalArgumentException

use of com.palantir.logsafe.exceptions.SafeIllegalArgumentException in project conjure-java-runtime by palantir.

the class OkHttpClients method createInternal.

private static RemotingOkHttpClient createInternal(OkHttpClient.Builder client, ClientConfiguration config, Class<?> serviceClass, boolean randomizeUrlOrder, boolean reshuffle, Supplier<BackoffStrategy> backoffStrategyFunction) {
    boolean enableClientQoS = shouldEnableQos(config.clientQoS());
    ConcurrencyLimiters concurrencyLimiters = new ConcurrencyLimiters(limitReviver.get(), config.taggedMetricRegistry(), serviceClass, enableClientQoS);
    client.addInterceptor(CatchThrowableInterceptor.INSTANCE);
    client.addInterceptor(SpanTerminatingInterceptor.INSTANCE);
    // Order is important, this interceptor must be applied prior to ConcurrencyLimitingInterceptor
    // in order to prevent concurrency limiters from leaking.
    client.addInterceptor(ResponseCapturingInterceptor.INSTANCE);
    // Routing
    if (config.nodeSelectionStrategy().equals(NodeSelectionStrategy.ROUND_ROBIN)) {
        checkArgument(!config.failedUrlCooldown().isZero(), "If nodeSelectionStrategy is ROUND_ROBIN then failedUrlCooldown must be positive");
    }
    UrlSelectorImpl urlSelector = UrlSelectorImpl.createWithFailedUrlCooldown(randomizeUrlOrder ? UrlSelectorImpl.shuffle(config.uris()) : config.uris(), reshuffle, config.failedUrlCooldown(), Clock.systemUTC());
    if (config.meshProxy().isPresent()) {
        // TODO(rfink): Should this go into the call itself?
        client.addInterceptor(new MeshProxyInterceptor(config.meshProxy().get()));
    }
    // We implement our own redirect logic.
    client.followRedirects(false);
    // SSL
    SSLSocketFactory sslSocketFactory = MetricRegistries.instrument(config.taggedMetricRegistry(), new KeepAliveSslSocketFactory(config.sslSocketFactory()), serviceClass.getSimpleName());
    client.sslSocketFactory(sslSocketFactory, config.trustManager());
    if (config.fallbackToCommonNameVerification()) {
        client.hostnameVerifier(Okhttp39HostnameVerifier.INSTANCE);
    }
    // Intercept calls to augment request meta data
    if (enableClientQoS) {
        client.addInterceptor(new ConcurrencyLimitingInterceptor());
    }
    ClientMetrics clientMetrics = ClientMetrics.of(config.taggedMetricRegistry());
    client.addInterceptor(DeprecationWarningInterceptor.create(clientMetrics, serviceClass));
    client.addInterceptor(InstrumentedInterceptor.create(clientMetrics, config.hostEventsSink().orElse(NoOpHostEventsSink.INSTANCE), serviceClass));
    client.addInterceptor(OkhttpTraceInterceptor.INSTANCE);
    UserAgent agent = config.userAgent().orElseThrow(() -> new SafeIllegalArgumentException("UserAgent is required"));
    client.addInterceptor(UserAgentInterceptor.of(augmentUserAgent(agent, serviceClass)));
    // timeouts
    // Note that Feign overrides OkHttp timeouts with the timeouts given in FeignBuilder#Options if given, or
    // with its own default otherwise.
    client.connectTimeout(config.connectTimeout());
    client.readTimeout(config.readTimeout());
    client.writeTimeout(config.writeTimeout());
    // proxy
    client.proxySelector(config.proxy());
    if (config.proxyCredentials().isPresent()) {
        BasicCredentials basicCreds = config.proxyCredentials().get();
        final String credentials = Credentials.basic(basicCreds.username(), basicCreds.password());
        client.proxyAuthenticator((_route, response) -> response.request().newBuilder().header(HttpHeaders.PROXY_AUTHORIZATION, credentials).build());
    }
    client.connectionSpecs(createConnectionSpecs());
    if (!config.enableHttp2().orElse(DEFAULT_ENABLE_HTTP2)) {
        client.protocols(ImmutableList.of(Protocol.HTTP_1_1));
    }
    // increase default connection pool from 5 @ 5 minutes to 100 @ 10 minutes
    client.connectionPool(connectionPool);
    client.dispatcher(dispatcher);
    // global metrics (addMetrics is idempotent, so this works even when multiple clients are created)
    config.taggedMetricRegistry().addMetrics("from", DispatcherMetricSet.class.getSimpleName(), dispatcherMetricSet);
    return new RemotingOkHttpClient(client.build(), backoffStrategyFunction, config.nodeSelectionStrategy(), urlSelector, schedulingExecutor.get(), executionExecutor, concurrencyLimiters, config.serverQoS(), config.retryOnTimeout(), config.retryOnSocketException());
}
Also used : SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) UserAgent(com.palantir.conjure.java.api.config.service.UserAgent) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicCredentials(com.palantir.conjure.java.api.config.service.BasicCredentials)

Example 27 with SafeIllegalArgumentException

use of com.palantir.logsafe.exceptions.SafeIllegalArgumentException in project dialogue by palantir.

the class Reflection method createFromAnnotation.

private static <T> T createFromAnnotation(Class<T> dialogueInterface, DialogueService dialogueService, Channel channel, ConjureRuntime conjureRuntime) {
    Class<? extends DialogueServiceFactory<?>> serviceFactoryClass = dialogueService.value();
    EndpointChannelFactory factory = endpointChannelFactory(channel);
    Object client;
    try {
        client = serviceFactoryClass.getConstructor().newInstance().create(factory, conjureRuntime);
    } catch (NoSuchMethodException e) {
        throw new SafeIllegalArgumentException("Failed to reflectively construct dialogue client. The service factory class must have a " + "public no-arg constructor.", e, SafeArg.of("dialogueInterface", dialogueInterface), SafeArg.of("serviceFactoryClass", serviceFactoryClass));
    } catch (ReflectiveOperationException e) {
        throw new SafeIllegalArgumentException("Failed to reflectively construct dialogue client.", e, SafeArg.of("dialogueInterface", dialogueInterface), SafeArg.of("serviceFactoryClass", serviceFactoryClass));
    }
    if (dialogueInterface.isInstance(client)) {
        return dialogueInterface.cast(client);
    }
    throw new SafeIllegalArgumentException("Dialogue service factory produced an incompatible service", SafeArg.of("dialogueInterface", dialogueInterface), SafeArg.of("serviceFactoryClass", serviceFactoryClass), SafeArg.of("invalidClientType", client.getClass()), SafeArg.of("invalidClient", client));
}
Also used : EndpointChannelFactory(com.palantir.dialogue.EndpointChannelFactory) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException)

Example 28 with SafeIllegalArgumentException

use of com.palantir.logsafe.exceptions.SafeIllegalArgumentException in project conjure-java by palantir.

the class InstanceVariables method joinCamelCase.

static String joinCamelCase(String... segments) {
    return Joiner.on("").join(IntStream.range(0, segments.length).mapToObj(i -> {
        String segment = segments[i];
        CaseFormat caseFormat = CaseFormats.estimate(segment).orElseThrow(() -> new SafeIllegalArgumentException("Invalid case format", SafeArg.of("segment", segment)));
        if (i == 0) {
            return caseFormat.to(CaseFormat.LOWER_CAMEL, segment);
        }
        return caseFormat.to(CaseFormat.UPPER_CAMEL, segment);
    }).collect(Collectors.toList()));
}
Also used : SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) CaseFormat(com.google.common.base.CaseFormat)

Example 29 with SafeIllegalArgumentException

use of com.palantir.logsafe.exceptions.SafeIllegalArgumentException in project human-readable-types by palantir.

the class HumanReadableDuration method valueOf.

/**
 * Constructs a new {@link HumanReadableByteCount} from the provided string representation.
 *
 * @param duration the string HumanReadableDuration of this duration
 * @return the parsed {@link HumanReadableDuration}
 * @throws SafeIllegalArgumentException if the provided duration is invalid
 */
@JsonCreator
public static HumanReadableDuration valueOf(String duration) {
    final Matcher matcher = DURATION_PATTERN.matcher(duration);
    Preconditions.checkArgument(matcher.matches(), "Invalid duration", SafeArg.of("duration", duration));
    final long count = Long.parseLong(matcher.group(1));
    final TimeUnit unit = SUFFIXES.get(matcher.group(2));
    if (unit == null) {
        throw new SafeIllegalArgumentException("Invalid duration. Wrong time unit", SafeArg.of("duration", duration));
    }
    return new HumanReadableDuration(count, unit);
}
Also used : Matcher(java.util.regex.Matcher) TimeUnit(java.util.concurrent.TimeUnit) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator)

Example 30 with SafeIllegalArgumentException

use of com.palantir.logsafe.exceptions.SafeIllegalArgumentException in project auth-tokens by palantir.

the class BasicAuthToBearerTokenFilter method base64DecodePassword.

private AuthHeader base64DecodePassword(String rawAuthHeader) {
    String base64Credentials = rawAuthHeader.substring(BASIC_AUTH_STR.length()).trim();
    String credentials;
    try {
        credentials = new String(Base64.getUrlDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
    } catch (IllegalArgumentException e) {
        throw new SafeIllegalArgumentException("Could not decode credentials from auth header", e);
    }
    Preconditions.checkArgument(credentials.contains(":"), "Credentials lack colon character (:).");
    String password = credentials.split(":", 2)[1];
    return AuthHeader.valueOf(password);
}
Also used : SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException)

Aggregations

SafeIllegalArgumentException (com.palantir.logsafe.exceptions.SafeIllegalArgumentException)30 Test (org.junit.jupiter.api.Test)5 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableSet (com.google.common.collect.ImmutableSet)3 Range (com.google.common.collect.Range)3 SafeArg (com.palantir.logsafe.SafeArg)3 SafeIllegalStateException (com.palantir.logsafe.exceptions.SafeIllegalStateException)3 InetSocketAddress (java.net.InetSocketAddress)3 List (java.util.List)3 Optional (java.util.Optional)3 Meter (com.codahale.metrics.Meter)2 KeyspaceMetadata (com.datastax.driver.core.KeyspaceMetadata)2 TableMetadata (com.datastax.driver.core.TableMetadata)2 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)2 ImmutableRangeSet.toImmutableRangeSet (com.google.common.collect.ImmutableRangeSet.toImmutableRangeSet)2 MoreCollectors (com.google.common.collect.MoreCollectors)2 Multimap (com.google.common.collect.Multimap)2 RangeSet (com.google.common.collect.RangeSet)2 TableReference (com.palantir.atlasdb.keyvalue.api.TableReference)2