Search in sources :

Example 11 with SafeIllegalArgumentException

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

the class MetricRegistries method registerOrReplace.

private static <T extends Metric> T registerOrReplace(MetricRegistry registry, @Safe String name, T metric, boolean replace) {
    synchronized (registry) {
        Map<String, Metric> metrics = registry.getMetrics();
        Metric existingMetric = metrics.get(name);
        if (existingMetric == null) {
            return registry.register(name, metric);
        } else {
            Set<Class<?>> existingMetricInterfaces = Collections.newSetFromMap(new IdentityHashMap<>());
            existingMetricInterfaces.addAll(Arrays.asList(existingMetric.getClass().getInterfaces()));
            Set<Class<?>> newMetricInterfaces = Collections.newSetFromMap(new IdentityHashMap<>());
            newMetricInterfaces.addAll(Arrays.asList(metric.getClass().getInterfaces()));
            if (!existingMetricInterfaces.equals(newMetricInterfaces)) {
                throw new SafeIllegalArgumentException("Metric already registered at this name that implements a different set of interfaces", SafeArg.of("name", name), SafeArg.of("existingMetric", String.valueOf(existingMetric)));
            }
            if (replace && registry.remove(name)) {
                log.info("Removed existing registered metric with name {}: {}", SafeArg.of("name", name), // #256: Metric implementations are necessarily json serializable
                SafeArg.of("existingMetric", String.valueOf(existingMetric)));
                registry.register(name, metric);
                return metric;
            } else {
                log.warn("Metric already registered at this name. Name: {}, existing metric: {}", SafeArg.of("name", name), // #256: Metric implementations are necessarily json serializable
                SafeArg.of("existingMetric", String.valueOf(existingMetric)));
                @SuppressWarnings("unchecked") T registeredMetric = (T) existingMetric;
                return registeredMetric;
            }
        }
    }
}
Also used : Metric(com.codahale.metrics.Metric) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException)

Example 12 with SafeIllegalArgumentException

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

the class MetricRegistries method registerAll.

/**
 * Registers a Dropwizard {@link MetricSet} with a Tritium {@link TaggedMetricRegistry}. Semantics match calling
 * {@link MetricRegistry#register(String, Metric)} with a {@link MetricSet}.
 *
 * @param registry Target Tritium registry
 * @param prefix Metric name prefix
 * @param metricSet Set to register with the tagged registry
 */
public static void registerAll(TaggedMetricRegistry registry, @Safe String prefix, MetricSet metricSet) {
    Preconditions.checkNotNull(registry, "TaggedMetricRegistry is required");
    Preconditions.checkNotNull(prefix, "Prefix is required");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(prefix), "Prefix cannot be blank");
    Preconditions.checkNotNull(metricSet, "MetricSet is required");
    metricSet.getMetrics().forEach((name, metric) -> {
        String safeName = MetricRegistry.name(prefix, name);
        MetricName metricName = MetricName.builder().safeName(safeName).build();
        if (metric instanceof Gauge) {
            registry.registerWithReplacement(metricName, (Gauge<?>) metric);
        } else if (metric instanceof Counter) {
            registry.counter(metricName, () -> (Counter) metric);
        } else if (metric instanceof Histogram) {
            registry.histogram(metricName, () -> (Histogram) metric);
        } else if (metric instanceof Meter) {
            registry.meter(metricName, () -> (Meter) metric);
        } else if (metric instanceof Timer) {
            registry.timer(metricName, () -> (Timer) metric);
        } else if (metric instanceof MetricSet) {
            registerAll(registry, safeName, (MetricSet) metric);
        } else {
            throw new SafeIllegalArgumentException("Unknown Metric Type", SafeArg.of("type", metric.getClass()));
        }
    });
}
Also used : MetricName(com.palantir.tritium.metrics.registry.MetricName) Histogram(com.codahale.metrics.Histogram) Counter(com.codahale.metrics.Counter) Timer(com.codahale.metrics.Timer) Meter(com.codahale.metrics.Meter) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) Gauge(com.codahale.metrics.Gauge) MetricSet(com.codahale.metrics.MetricSet)

Example 13 with SafeIllegalArgumentException

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

the class EndpointNameHeaderEnrichmentContract method processMetadata.

@Override
protected void processMetadata(Class<?> targetType, Method method, MethodMetadata metadata) {
    String httpMethod = metadata.template().method();
    if (httpMethod == null) {
        throw new SafeNullPointerException("An HTTP method is required", SafeArg.of("class", targetType.getSimpleName()), SafeArg.of("method", method.getName()));
    }
    try {
        HttpMethod.valueOf(httpMethod.toUpperCase(Locale.ENGLISH));
    } catch (IllegalArgumentException e) {
        throw new SafeIllegalArgumentException("Unsupported HTTP method", SafeArg.of("class", targetType.getSimpleName()), SafeArg.of("method", method.getName()), SafeArg.of("httpMethod", httpMethod));
    }
    metadata.template().header(ENDPOINT_NAME_HEADER, method.getName());
}
Also used : SafeNullPointerException(com.palantir.logsafe.exceptions.SafeNullPointerException) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException)

Example 14 with SafeIllegalArgumentException

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

the class ClientConfigurations method createProxySelector.

public static ProxySelector createProxySelector(ProxyConfiguration proxyConfig) {
    switch(proxyConfig.type()) {
        case DIRECT:
            return fixedProxySelectorFor(Proxy.NO_PROXY);
        case FROM_ENVIRONMENT:
            String defaultEnvProxy = System.getenv(ENV_HTTPS_PROXY);
            if (defaultEnvProxy == null) {
                log.info("Proxy environment variable not set, using no proxy");
                return fixedProxySelectorFor(Proxy.NO_PROXY);
            }
            log.info("Using proxy from environment variable", UnsafeArg.of("proxy", defaultEnvProxy));
            InetSocketAddress address = createInetSocketAddress(defaultEnvProxy);
            return fixedProxySelectorFor(new Proxy(Proxy.Type.HTTP, address));
        case HTTP:
            HostAndPort hostAndPort = HostAndPort.fromString(proxyConfig.hostAndPort().orElseThrow(() -> new SafeIllegalArgumentException("Expected to find proxy hostAndPort configuration for HTTP proxy")));
            InetSocketAddress addr = // is running are ignored by the application.
            InetSocketAddress.createUnresolved(hostAndPort.getHost(), hostAndPort.getPort());
            return fixedProxySelectorFor(new Proxy(Proxy.Type.HTTP, addr));
        case MESH:
            // MESH proxy is not a Java proxy
            return ProxySelector.getDefault();
        case SOCKS:
            HostAndPort socksHostAndPort = HostAndPort.fromString(proxyConfig.hostAndPort().orElseThrow(() -> new SafeIllegalArgumentException("Expected to find proxy hostAndPort configuration for SOCKS proxy")));
            InetSocketAddress socksAddress = // is running are ignored by the application.
            InetSocketAddress.createUnresolved(socksHostAndPort.getHost(), socksHostAndPort.getPort());
            return fixedProxySelectorFor(new Proxy(Proxy.Type.SOCKS, socksAddress));
        default:
    }
    throw new IllegalStateException("Failed to create ProxySelector for proxy configuration: " + proxyConfig);
}
Also used : HostAndPort(com.google.common.net.HostAndPort) Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException)

Example 15 with SafeIllegalArgumentException

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

the class Reflection method callStaticFactoryMethod.

static <T> T callStaticFactoryMethod(Class<T> dialogueInterface, Channel channel, ConjureRuntime conjureRuntime) {
    Preconditions.checkNotNull(dialogueInterface, "dialogueInterface");
    Preconditions.checkNotNull(channel, "channel");
    DialogueService annotation = dialogueInterface.getAnnotation(DialogueService.class);
    if (annotation != null) {
        return createFromAnnotation(dialogueInterface, annotation, channel, conjureRuntime);
    }
    try {
        Optional<Method> legacyMethod = getLegacyStaticOfMethod(dialogueInterface);
        if (legacyMethod.isPresent()) {
            return dialogueInterface.cast(legacyMethod.get().invoke(null, channel, conjureRuntime));
        }
        Method method = getStaticOfMethod(dialogueInterface).orElseThrow(() -> new SafeIllegalStateException("A static 'of(Channel, ConjureRuntime)' method is required", SafeArg.of("dialogueInterface", dialogueInterface)));
        return dialogueInterface.cast(method.invoke(null, endpointChannelFactory(channel), conjureRuntime));
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new SafeIllegalArgumentException("Failed to reflectively construct dialogue client. Please check the " + "dialogue interface class has a public static of(Channel, ConjureRuntime) method", e, SafeArg.of("dialogueInterface", dialogueInterface));
    }
}
Also used : DialogueService(com.palantir.dialogue.DialogueService) Method(java.lang.reflect.Method) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

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