Search in sources :

Example 1 with HttpPath

use of com.palantir.conjure.spec.HttpPath in project conjure-java by palantir.

the class Retrofit2ServiceGenerator method generateServiceMethod.

private MethodSpec generateServiceMethod(EndpointDefinition endpointDef, TypeMapper returnTypeMapper, TypeMapper argumentTypeMapper) {
    TypeName returnType = endpointDef.getReturns().map(returnTypeMapper::getClassName).orElse(ClassName.VOID);
    Set<ArgumentName> encodedPathArgs = extractEncodedPathArgs(endpointDef.getHttpPath());
    HttpPath endpointPathWithoutRegex = replaceEncodedPathArgs(endpointDef.getHttpPath());
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(endpointDef.getEndpointName().get()).addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).addAnnotation(AnnotationSpec.builder(httpMethodToClassName(endpointDef.getHttpMethod().get().name())).addMember("value", "$S", "." + endpointPathWithoutRegex).build()).addAnnotation(AnnotationSpec.builder(ClassName.get("retrofit2.http", "Headers")).addMember("value", "$S", "hr-path-template: " + endpointPathWithoutRegex).addMember("value", "$S", "Accept: " + getReturnMediaType(returnType)).build());
    if (returnType.equals(BINARY_RETURN_TYPE) || returnType.equals(OPTIONAL_BINARY_RETURN_TYPE)) {
        methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("retrofit2.http", "Streaming")).build());
    }
    endpointDef.getDeprecated().ifPresent(deprecatedDocsValue -> methodBuilder.addAnnotation(ClassName.get("java.lang", "Deprecated")));
    methodBuilder.addAnnotations(ConjureAnnotations.getClientEndpointAnnotations(endpointDef));
    ServiceGenerators.getJavaDoc(endpointDef).ifPresent(content -> methodBuilder.addJavadoc("$L", content));
    methodBuilder.returns(ParameterizedTypeName.get(LISTENABLE_FUTURE_TYPE, returnType.box()));
    methodBuilder.addParameters(createServiceMethodParameters(endpointDef, argumentTypeMapper, encodedPathArgs));
    return methodBuilder.build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) HttpPath(com.palantir.conjure.spec.HttpPath) MethodSpec(com.squareup.javapoet.MethodSpec) ArgumentName(com.palantir.conjure.spec.ArgumentName)

Example 2 with HttpPath

use of com.palantir.conjure.spec.HttpPath in project conjure-java by palantir.

the class Retrofit2ServiceGenerator method replaceEncodedPathArgs.

private HttpPath replaceEncodedPathArgs(HttpPath httpPath) {
    List<String> newSegments = new ArrayList<>();
    Pattern pattern = Pattern.compile("\\{([^:]+):(.*)}");
    Path path = Paths.get(httpPath.get());
    for (String segment : path.getSegments()) {
        Matcher matcher = pattern.matcher(segment);
        if (matcher.matches()) {
            newSegments.add("{" + matcher.group(1) + "}");
        } else {
            newSegments.add(segment);
        }
    }
    return HttpPath.of("/" + Joiner.on("/").join(newSegments));
}
Also used : HttpPath(com.palantir.conjure.spec.HttpPath) Path(com.palantir.util.syntacticpath.Path) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList)

Example 3 with HttpPath

use of com.palantir.conjure.spec.HttpPath in project conjure by palantir.

the class ConjureParserUtils method parseHttpPath.

private static HttpPath parseHttpPath(com.palantir.conjure.parser.services.EndpointDefinition def, PathString basePath) {
    HttpPath httpPath = HttpPath.of(basePath.resolve(def.http().path()).toString());
    HttpPathValidator.validate(httpPath);
    return httpPath;
}
Also used : HttpPath(com.palantir.conjure.spec.HttpPath)

Example 4 with HttpPath

use of com.palantir.conjure.spec.HttpPath in project conjure by palantir.

the class ConjureParserUtils method parseEndpoint.

private static EndpointDefinition parseEndpoint(String name, com.palantir.conjure.parser.services.EndpointDefinition def, PathString basePath, Optional<AuthType> defaultAuth, ReferenceTypeResolver typeResolver, DealiasingTypeVisitor dealiasingVisitor) {
    HttpPath httpPath = parseHttpPath(def, basePath);
    EndpointDefinition endpoint = EndpointDefinition.builder().endpointName(EndpointName.of(name)).httpMethod(HttpMethod.valueOf(def.http().method())).httpPath(httpPath).auth(def.auth().map(ConjureParserUtils::parseAuthType).orElse(defaultAuth)).args(parseArgs(def.args(), httpPath, typeResolver)).tags(def.tags().stream().peek(tag -> Preconditions.checkArgument(!tag.isEmpty(), "tag must not be empty")).collect(Collectors.toSet())).markers(parseMarkers(def.markers(), typeResolver)).returns(def.returns().map(t -> t.visit(new ConjureTypeParserVisitor(typeResolver)))).docs(def.docs().map(Documentation::of)).deprecated(def.deprecated().map(Documentation::of)).build();
    EndpointDefinitionValidator.validateAll(endpoint, dealiasingVisitor);
    return endpoint;
}
Also used : HeaderAuthType(com.palantir.conjure.spec.HeaderAuthType) PathString(com.palantir.conjure.parser.services.PathString) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) ConjureDefinition(com.palantir.conjure.spec.ConjureDefinition) ServiceDefinitionValidator(com.palantir.conjure.defs.validator.ServiceDefinitionValidator) ServiceDefinition(com.palantir.conjure.spec.ServiceDefinition) EnumValueDefinitionValidator(com.palantir.conjure.defs.validator.EnumValueDefinitionValidator) ConjureDefinitionValidator(com.palantir.conjure.defs.validator.ConjureDefinitionValidator) NamedTypesDefinition(com.palantir.conjure.parser.types.NamedTypesDefinition) Map(java.util.Map) ObjectDefinitionValidator(com.palantir.conjure.defs.validator.ObjectDefinitionValidator) ArgumentName(com.palantir.conjure.spec.ArgumentName) AnnotatedConjureSourceFile(com.palantir.conjure.parser.AnnotatedConjureSourceFile) ParameterId(com.palantir.conjure.spec.ParameterId) EndpointDefinitionValidator(com.palantir.conjure.defs.validator.EndpointDefinitionValidator) LogSafetyDefinition(com.palantir.conjure.parser.LogSafetyDefinition) ObjectDefinition(com.palantir.conjure.spec.ObjectDefinition) ConjureImports(com.palantir.conjure.parser.types.reference.ConjureImports) AuthType(com.palantir.conjure.spec.AuthType) Collection(java.util.Collection) SafeIllegalArgumentException(com.palantir.logsafe.exceptions.SafeIllegalArgumentException) Set(java.util.Set) BodyParameterType(com.palantir.conjure.spec.BodyParameterType) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) Collectors(java.util.stream.Collectors) FieldDefinitionValidator(com.palantir.conjure.defs.validator.FieldDefinitionValidator) ParameterType(com.palantir.conjure.spec.ParameterType) List(java.util.List) AliasDefinition(com.palantir.conjure.spec.AliasDefinition) UnsafeArg(com.palantir.logsafe.UnsafeArg) ReferenceTypeResolver(com.palantir.conjure.defs.ConjureTypeParserVisitor.ReferenceTypeResolver) Documentation(com.palantir.conjure.spec.Documentation) ConjureRuntimeException(com.palantir.conjure.exceptions.ConjureRuntimeException) Optional(java.util.Optional) HttpPathValidator(com.palantir.conjure.defs.validator.HttpPathValidator) PrimitiveType(com.palantir.conjure.spec.PrimitiveType) EndpointDefinition(com.palantir.conjure.spec.EndpointDefinition) HttpMethod(com.palantir.conjure.spec.HttpMethod) LogSafety(com.palantir.conjure.spec.LogSafety) EnumDefinitionValidator(com.palantir.conjure.defs.validator.EnumDefinitionValidator) FieldNameValidator(com.palantir.conjure.defs.validator.FieldNameValidator) ErrorDefinition(com.palantir.conjure.spec.ErrorDefinition) Type(com.palantir.conjure.spec.Type) PathParameterType(com.palantir.conjure.spec.PathParameterType) TypeDefinitionVisitor(com.palantir.conjure.visitor.TypeDefinitionVisitor) HashMap(java.util.HashMap) Namespace(com.palantir.conjure.parser.types.names.Namespace) HttpPath(com.palantir.conjure.spec.HttpPath) ConjureIllegalArgumentException(com.palantir.conjure.exceptions.ConjureIllegalArgumentException) Function(java.util.function.Function) ArrayList(java.util.ArrayList) UnionDefinition(com.palantir.conjure.spec.UnionDefinition) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) ErrorNamespace(com.palantir.conjure.spec.ErrorNamespace) TypeNameValidator(com.palantir.conjure.defs.validator.TypeNameValidator) PackageValidator(com.palantir.conjure.defs.validator.PackageValidator) TypeDefinition(com.palantir.conjure.spec.TypeDefinition) EnumDefinition(com.palantir.conjure.spec.EnumDefinition) CookieAuthType(com.palantir.conjure.spec.CookieAuthType) EnumValueDefinition(com.palantir.conjure.spec.EnumValueDefinition) ErrorDefinitionValidator(com.palantir.conjure.defs.validator.ErrorDefinitionValidator) ParameterName(com.palantir.conjure.parser.services.ParameterName) EndpointName(com.palantir.conjure.spec.EndpointName) QueryParameterType(com.palantir.conjure.spec.QueryParameterType) TypeName(com.palantir.conjure.spec.TypeName) FieldName(com.palantir.conjure.spec.FieldName) ConjureSourceFile(com.palantir.conjure.parser.ConjureSourceFile) DealiasingTypeVisitor(com.palantir.conjure.visitor.DealiasingTypeVisitor) ConjurePackage(com.palantir.conjure.parser.types.names.ConjurePackage) UnionDefinitionValidator(com.palantir.conjure.defs.validator.UnionDefinitionValidator) HeaderParameterType(com.palantir.conjure.spec.HeaderParameterType) Preconditions(com.palantir.logsafe.Preconditions) ArgumentDefinition(com.palantir.conjure.spec.ArgumentDefinition) HttpPath(com.palantir.conjure.spec.HttpPath) Documentation(com.palantir.conjure.spec.Documentation) EndpointDefinition(com.palantir.conjure.spec.EndpointDefinition)

Example 5 with HttpPath

use of com.palantir.conjure.spec.HttpPath in project conjure by palantir.

the class HttpPathValidator method validate.

/**
 * validates if a new instance has the correct syntax.
 */
public static void validate(HttpPath httpPath) {
    Path path = Paths.get(httpPath.get());
    Preconditions.checkArgument(path.isAbsolute(), "Conjure paths must be absolute, i.e., start with '/': %s", path);
    Preconditions.checkArgument(path.getSegments().isEmpty() || !path.isFolder(), "Conjure paths must not end with a '/': %s", path);
    for (String segment : path.getSegments()) {
        Preconditions.checkArgument(SEGMENT_PATTERN.matcher(segment).matches() || PARAM_SEGMENT_PATTERN.matcher(segment).matches() || PARAM_REGEX_SEGMENT_PATTERN.matcher(segment).matches(), "Segment %s of path %s did not match required segment patterns %s or parameter name " + "patterns %s or %s", segment, path, SEGMENT_PATTERN, PARAM_SEGMENT_PATTERN, PARAM_REGEX_SEGMENT_PATTERN);
    }
    // verify that path template variables are unique
    Set<String> templateVars = new HashSet<>();
    new UriTemplate(path.toString()).getTemplateVariables().forEach(var -> {
        Preconditions.checkState(!templateVars.contains(var), "Path parameter %s appears more than once in path %s", var, path);
        templateVars.add(var);
    });
    UriTemplateParser uriTemplateParser = new UriTemplateParser(path.toString());
    Map<String, Pattern> nameToPattern = uriTemplateParser.getNameToPattern();
    List<String> segments = Splitter.on('/').splitToList(uriTemplateParser.getNormalizedTemplate());
    for (int i = 0; i < segments.size(); i++) {
        String segment = segments.get(i);
        if (!(segment.startsWith("{") && segment.endsWith("}"))) {
            // path literal
            continue;
        }
        // variable
        Pattern varPattern = nameToPattern.get(segment.substring(1, segment.length() - 1));
        if (varPattern.equals(UriTemplateParser.TEMPLATE_VALUE_PATTERN)) {
            // no regular expression specified -- OK
            continue;
        }
        // if regular expression was specified, it must be ".+" or ".*" based on invariant previously enforced
        Preconditions.checkState(i == segments.size() - 1 || !varPattern.pattern().equals(".*"), "Path parameter %s in path %s specifies regular expression %s, but this regular " + "expression is only permitted if the path parameter is the last segment", segment, path, varPattern);
    }
}
Also used : HttpPath(com.palantir.conjure.spec.HttpPath) Path(com.palantir.util.syntacticpath.Path) Pattern(java.util.regex.Pattern) UriTemplate(org.glassfish.jersey.uri.UriTemplate) UriTemplateParser(org.glassfish.jersey.uri.internal.UriTemplateParser) HashSet(java.util.HashSet)

Aggregations

HttpPath (com.palantir.conjure.spec.HttpPath)6 ImmutableList (com.google.common.collect.ImmutableList)2 ArgumentName (com.palantir.conjure.spec.ArgumentName)2 AuthType (com.palantir.conjure.spec.AuthType)2 Documentation (com.palantir.conjure.spec.Documentation)2 HeaderParameterType (com.palantir.conjure.spec.HeaderParameterType)2 HttpMethod (com.palantir.conjure.spec.HttpMethod)2 ParameterId (com.palantir.conjure.spec.ParameterId)2 ParameterType (com.palantir.conjure.spec.ParameterType)2 Path (com.palantir.util.syntacticpath.Path)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Optional (java.util.Optional)2 Pattern (java.util.regex.Pattern)2 Collectors (java.util.stream.Collectors)2 Joiner (com.google.common.base.Joiner)1 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 ReferenceTypeResolver (com.palantir.conjure.defs.ConjureTypeParserVisitor.ReferenceTypeResolver)1 ConjureDefinitionValidator (com.palantir.conjure.defs.validator.ConjureDefinitionValidator)1