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());
}
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));
}
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()));
}
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);
}
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);
}
Aggregations