Search in sources :

Example 1 with Safe

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

the class ParamTypesResolver method getParameterType.

@SuppressWarnings("CyclomaticComplexity")
public Optional<ParameterType> getParameterType(VariableElement variableElement) {
    List<AnnotationMirror> paramAnnotationMirrors = new ArrayList<>();
    for (AnnotationMirror annotationMirror : variableElement.getAnnotationMirrors()) {
        TypeElement annotationTypeElement = MoreElements.asType(annotationMirror.getAnnotationType().asElement());
        if (SUPPORTED_ANNOTATIONS.contains(annotationTypeElement.getQualifiedName().toString())) {
            paramAnnotationMirrors.add(annotationMirror);
        }
    }
    List<AnnotationReflector> annotationReflectors = paramAnnotationMirrors.stream().map(ImmutableAnnotationReflector::of).collect(Collectors.toList());
    boolean isSafe = annotationReflectors.stream().anyMatch(annotation -> annotation.isAnnotation(Safe.class));
    boolean isUnsafe = annotationReflectors.stream().anyMatch(annotation -> annotation.isAnnotation(Unsafe.class));
    SafeLoggingAnnotation safeLoggable = isUnsafe ? SafeLoggingAnnotation.UNSAFE : isSafe ? SafeLoggingAnnotation.SAFE : SafeLoggingAnnotation.UNKNOWN;
    List<AnnotationReflector> otherAnnotationReflectors = annotationReflectors.stream().filter(annotation -> !annotation.isAnnotation(Safe.class) && !annotation.isAnnotation(Unsafe.class)).collect(Collectors.toList());
    if (otherAnnotationReflectors.isEmpty()) {
        if (!safeLoggable.equals(SafeLoggingAnnotation.UNKNOWN)) {
            context.reportError("Parameter type cannot be annotated with safe logging annotations", variableElement, SafeArg.of("type", variableElement.asType()));
            return Optional.empty();
        }
        if (context.isSameTypes(variableElement.asType(), AuthHeader.class)) {
            return Optional.of(ParameterTypes.authHeader(variableElement.getSimpleName().toString()));
        } else if (context.isSameTypes(variableElement.asType(), HttpServerExchange.class)) {
            return Optional.of(ParameterTypes.exchange());
        } else if (context.isSameTypes(variableElement.asType(), RequestContext.class)) {
            return Optional.of(ParameterTypes.context());
        } else {
            context.reportError("At least one annotation should be present or type should be InputStream", variableElement, SafeArg.of("requestBody", InputStream.class), SafeArg.of("supportedAnnotations", PARAM_ANNOTATION_CLASSES));
            return Optional.empty();
        }
    }
    if (otherAnnotationReflectors.size() > 1) {
        context.reportError("Only single annotation can be used", variableElement, SafeArg.of("annotations", otherAnnotationReflectors));
        return Optional.empty();
    }
    // TODO(ckozak): More validation of values.
    AnnotationReflector annotationReflector = Iterables.getOnlyElement(otherAnnotationReflectors);
    if (annotationReflector.isAnnotation(Handle.Body.class)) {
        return Optional.of(bodyParameter(variableElement, annotationReflector));
    } else if (annotationReflector.isAnnotation(Handle.Header.class)) {
        return Optional.of(headerParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.PathParam.class)) {
        return Optional.of(pathParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.PathMultiParam.class)) {
        return Optional.of(pathMultiParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.QueryParam.class)) {
        return Optional.of(queryParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.Cookie.class)) {
        return cookieParameter(variableElement, annotationReflector, safeLoggable);
    }
    throw new SafeIllegalStateException("Not possible");
}
Also used : SafeLoggingAnnotation(com.palantir.conjure.java.undertow.processor.data.ParameterType.SafeLoggingAnnotation) Iterables(com.google.common.collect.Iterables) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) HttpServerExchange(io.undertow.server.HttpServerExchange) VariableElement(javax.lang.model.element.VariableElement) AuthHeader(com.palantir.tokens.auth.AuthHeader) TypeElement(javax.lang.model.element.TypeElement) RequestContext(com.palantir.conjure.java.undertow.lib.RequestContext) ArrayList(java.util.ArrayList) SafeArg(com.palantir.logsafe.SafeArg) BearerToken(com.palantir.tokens.auth.BearerToken) CodeBlock(com.squareup.javapoet.CodeBlock) Handle(com.palantir.conjure.java.undertow.annotations.Handle) MoreElements(com.google.auto.common.MoreElements) ImmutableSet(com.google.common.collect.ImmutableSet) ContainerType(com.palantir.conjure.java.undertow.processor.data.DefaultDecoderNames.ContainerType) Set(java.util.Set) Collectors(java.util.stream.Collectors) AnnotationMirror(javax.lang.model.element.AnnotationMirror) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) Safe(com.palantir.logsafe.Safe) Stream(java.util.stream.Stream) Unsafe(com.palantir.logsafe.Unsafe) Optional(java.util.Optional) DefaultParamDecoder(com.palantir.conjure.java.undertow.annotations.DefaultParamDecoder) InputStream(java.io.InputStream) SafeLoggingAnnotation(com.palantir.conjure.java.undertow.processor.data.ParameterType.SafeLoggingAnnotation) TypeElement(javax.lang.model.element.TypeElement) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Unsafe(com.palantir.logsafe.Unsafe) Safe(com.palantir.logsafe.Safe) Handle(com.palantir.conjure.java.undertow.annotations.Handle) HttpServerExchange(io.undertow.server.HttpServerExchange) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AuthHeader(com.palantir.tokens.auth.AuthHeader) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException)

Example 2 with Safe

use of com.palantir.logsafe.Safe in project safe-logging by palantir.

the class LoggerGenerator method generateLoggerImplementation.

private static JavaFile generateLoggerImplementation() {
    TypeSpec.Builder loggerBuilder = TypeSpec.classBuilder(LOGGER_NAME).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addJavadoc("Safe-logging logger API used to produce log events with safe-classified {@link Arg} values.").addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", LoggerGenerator.class.getName()).build()).addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "TooManyArguments").build()).addField(FieldSpec.builder(BRIDGE_NAME, DELEGATE).addModifiers(Modifier.PRIVATE, Modifier.FINAL).build()).addMethod(MethodSpec.constructorBuilder().addJavadoc("Internal package-private constructor for {@link SafeLoggerFactory}.").addParameter(ParameterSpec.builder(BRIDGE_NAME, DELEGATE).build()).addStatement("this.$1N = $2T.requireNonNull($1N, $3S)", DELEGATE, Objects.class, "SafeLoggerBridge is required").build());
    for (MethodSpec spec : createLoggerBridge().methodSpecs) {
        MethodSpec.Builder methodBuilder = spec.toBuilder();
        methodBuilder.modifiers.clear();
        boolean isVoidMethod = ClassName.VOID.equals(spec.returnType);
        CodeBlock args = spec.parameters.stream().map(param -> CodeBlock.of("$N", param.name)).collect(CodeBlock.joining(", "));
        methodBuilder.addModifiers(Modifier.PUBLIC).addStatement("$L$N.$N($L)", isVoidMethod ? "" : "return ", DELEGATE, spec.name, args);
        loggerBuilder.addMethod(methodBuilder.build());
    }
    return JavaFile.builder(LOGGER_NAME.packageName(), loggerBuilder.build()).skipJavaLangImports(true).addFileComment(copyright(2021)).build();
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) Modifier(javax.lang.model.element.Modifier) MethodSpec(com.squareup.javapoet.MethodSpec) CompileTimeConstant(com.google.errorprone.annotations.CompileTimeConstant) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) JavaFile(com.squareup.javapoet.JavaFile) Objects(java.util.Objects) List(java.util.List) Safe(com.palantir.logsafe.Safe) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) Locale(java.util.Locale) Generated(javax.annotation.processing.Generated) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) TypeName(com.squareup.javapoet.TypeName) Arg(com.palantir.logsafe.Arg) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) CodeBlock(com.squareup.javapoet.CodeBlock) Nullable(javax.annotation.Nullable) Goethe(com.palantir.goethe.Goethe) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

Safe (com.palantir.logsafe.Safe)2 CodeBlock (com.squareup.javapoet.CodeBlock)2 List (java.util.List)2 Stream (java.util.stream.Stream)2 MoreElements (com.google.auto.common.MoreElements)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Iterables (com.google.common.collect.Iterables)1 CompileTimeConstant (com.google.errorprone.annotations.CompileTimeConstant)1 DefaultParamDecoder (com.palantir.conjure.java.undertow.annotations.DefaultParamDecoder)1 Handle (com.palantir.conjure.java.undertow.annotations.Handle)1 RequestContext (com.palantir.conjure.java.undertow.lib.RequestContext)1 ContainerType (com.palantir.conjure.java.undertow.processor.data.DefaultDecoderNames.ContainerType)1 SafeLoggingAnnotation (com.palantir.conjure.java.undertow.processor.data.ParameterType.SafeLoggingAnnotation)1 Goethe (com.palantir.goethe.Goethe)1 Arg (com.palantir.logsafe.Arg)1 SafeArg (com.palantir.logsafe.SafeArg)1 Unsafe (com.palantir.logsafe.Unsafe)1 SafeIllegalStateException (com.palantir.logsafe.exceptions.SafeIllegalStateException)1 AuthHeader (com.palantir.tokens.auth.AuthHeader)1 BearerToken (com.palantir.tokens.auth.BearerToken)1