Search in sources :

Example 11 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException 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)

Example 12 with SafeIllegalStateException

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

the class ParamTypesResolver method getParameterType.

@SuppressWarnings("CyclomaticComplexity")
public Optional<ParameterType> getParameterType(EndpointName endpointName, VariableElement variableElement) {
    List<AnnotationMirror> paramAnnotationMirrors = new ArrayList<>();
    for (AnnotationMirror annotationMirror : variableElement.getAnnotationMirrors()) {
        TypeElement annotationTypeElement = MoreElements.asType(annotationMirror.getAnnotationType().asElement());
        if (PARAM_ANNOTATIONS.contains(annotationTypeElement.getQualifiedName().toString())) {
            paramAnnotationMirrors.add(annotationMirror);
        }
    }
    if (paramAnnotationMirrors.isEmpty()) {
        if (context.isAssignable(variableElement.asType(), RequestBody.class)) {
            return Optional.of(ParameterTypes.rawBody());
        } else if (context.isSameTypes(variableElement.asType(), AuthHeader.class)) {
            return Optional.of(ParameterTypes.header("Authorization", Optional.empty()));
        } else {
            context.reportError("At least one annotation should be present or type should be RequestBody", variableElement, SafeArg.of("requestBody", RequestBody.class), SafeArg.of("supportedAnnotations", PARAM_ANNOTATION_CLASSES));
            return Optional.empty();
        }
    }
    if (paramAnnotationMirrors.size() > 1) {
        context.reportError("Only single annotation can be used", variableElement, SafeArg.of("annotations", paramAnnotationMirrors));
        return Optional.empty();
    }
    // TODO(12345): More validation of values.
    AnnotationReflector annotationReflector = ImmutableAnnotationReflector.of(Iterables.getOnlyElement(paramAnnotationMirrors));
    if (annotationReflector.isAnnotation(Request.Body.class)) {
        // default annotation param values are not available at annotation processing time
        String serializerName = InstanceVariables.joinCamelCase(endpointName.get(), "Serializer");
        Optional<TypeMirror> customSerializer = annotationReflector.getValueFieldMaybe(TypeMirror.class);
        // match
        return Optional.of(ParameterTypes.body(TypeName.get(customSerializer.orElseGet(() -> context.getTypeMirror(Json.class))), serializerName));
    } else if (annotationReflector.isAnnotation(Request.Header.class)) {
        return Optional.of(ParameterTypes.header(annotationReflector.getStringValueField(), getParameterEncoder(endpointName, variableElement, annotationReflector, EncoderTypeAndMethod.LIST)));
    } else if (annotationReflector.isAnnotation(Request.PathParam.class)) {
        return Optional.of(ParameterTypes.path(getPathParameterEncoder(endpointName, variableElement, annotationReflector, EncoderTypeAndMethod.PARAM, EncoderTypeAndMethod.LIST)));
    } else if (annotationReflector.isAnnotation(Request.QueryParam.class)) {
        return Optional.of(ParameterTypes.query(annotationReflector.getValueStrict(String.class), getParameterEncoder(endpointName, variableElement, annotationReflector, EncoderTypeAndMethod.LIST)));
    } else if (annotationReflector.isAnnotation(Request.QueryMap.class)) {
        // we always want a parameter encoder for map types because it enables us to get compile
        // time safety with the generated code, since we cannot get the default value from the annotation
        // in this code, fall back to what the default would be
        ParameterEncoderType customEncoderType = getParameterEncoder(endpointName, variableElement, annotationReflector, EncoderTypeAndMethod.MULTIMAP).orElseGet(() -> multimapDefaultEncoder(endpointName, variableElement));
        return Optional.of(ParameterTypes.queryMap(customEncoderType));
    }
    throw new SafeIllegalStateException("Not possible");
}
Also used : AuthHeader(com.palantir.tokens.auth.AuthHeader) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) Request(com.palantir.dialogue.annotations.Request) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AuthHeader(com.palantir.tokens.auth.AuthHeader) TypeMirror(javax.lang.model.type.TypeMirror) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException)

Example 13 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project atlasdb by palantir.

the class TransactionAborter method executeWithRetry.

private void executeWithRetry(String keyspace, TransactionsTableInteraction txnInteraction, Statement abortStatement, Statement checkStatement, TransactionTableEntry entry) {
    long startTs = TransactionTableEntries.getStartTimestamp(entry);
    long commitTs = getCommitTimestamp(entry).orElseThrow();
    Preconditions.checkArgument(abortStatement.getSerialConsistencyLevel() == ConsistencyLevel.SERIAL, "Abort statement was not at expected consistency level", SafeArg.of("consistencyLevel", abortStatement.getSerialConsistencyLevel()), SafeArg.of("expectedConsistencyLevel", ConsistencyLevel.SERIAL));
    Preconditions.checkArgument(checkStatement.getSerialConsistencyLevel() == ConsistencyLevel.SERIAL, "Check statement was not at expected consistency level", SafeArg.of("consistencyLevel", checkStatement.getSerialConsistencyLevel()), SafeArg.of("expectedConsistencyLevel", ConsistencyLevel.SERIAL));
    try {
        abortRetryer.call(() -> tryAbortTransactions(keyspace, txnInteraction, abortStatement, checkStatement, startTs, commitTs));
    } catch (ExecutionException e) {
        throw new SafeIllegalStateException("Failed to execute transaction abort", e, SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs), SafeArg.of("retryCount", RETRY_COUNT), SafeArg.of("keyspace", keyspace));
    } catch (RetryException e) {
        throw new SafeIllegalStateException("Unable to abort transactions even with retry", e, SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs), SafeArg.of("retryCount", RETRY_COUNT), SafeArg.of("keyspace", keyspace));
    }
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) RetryException(com.github.rholder.retry.RetryException)

Example 14 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project atlasdb by palantir.

the class ConjureJavaRuntimeTargetFactory method createProxy.

@Override
public <T> InstanceAndVersion<T> createProxy(Optional<TrustContext> trustContext, String uri, Class<T> type, AuxiliaryRemotingParameters parameters) {
    ClientOptions relevantOptions = ClientOptions.fromRemotingParameters(parameters);
    ClientConfiguration clientConfiguration = relevantOptions.create(ImmutableList.of(uri), Optional.empty(), trustContext.orElseThrow(() -> new SafeIllegalStateException("CJR requires a trust context")));
    T client = JaxRsClient.create(type, addAtlasDbRemotingAgent(parameters.userAgent()), NoOpHostEventsSink.INSTANCE, clientConfiguration);
    return wrapWithVersion(client);
}
Also used : SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration)

Example 15 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project atlasdb by palantir.

the class DistributingModulusGenerator method getRandomLeastReferencedReferenceCountingResidue.

private ReferenceCountedResidue getRandomLeastReferencedReferenceCountingResidue() {
    SortedSet<ReferenceCountedResidue> leastReferencedResidues = getAllLeastReferencedResidues();
    int elementIndex = ThreadLocalRandom.current().nextInt(leastReferencedResidues.size());
    return leastReferencedResidues.stream().skip(elementIndex).findFirst().orElseThrow(() -> new SafeIllegalStateException("Attempted to select a random element from an empty collection!"));
}
Also used : SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException)

Aggregations

SafeIllegalStateException (com.palantir.logsafe.exceptions.SafeIllegalStateException)24 VisibleForTesting (com.google.common.annotations.VisibleForTesting)5 ImmutableSet (com.google.common.collect.ImmutableSet)5 Set (java.util.Set)5 ImmutableList (com.google.common.collect.ImmutableList)4 Iterables (com.google.common.collect.Iterables)4 SafeArg (com.palantir.logsafe.SafeArg)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 List (java.util.List)4 Optional (java.util.Optional)4 Collectors (java.util.stream.Collectors)4 Suppliers (com.google.common.base.Suppliers)3 RangeMap (com.google.common.collect.RangeMap)3 Sets (com.google.common.collect.Sets)3 CassandraKeyValueServiceConfig (com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfig)3 Refreshable (com.palantir.refreshable.Refreshable)3 Map (java.util.Map)3 RetryException (com.github.rholder.retry.RetryException)2 ImmutableMap (com.google.common.collect.ImmutableMap)2