Search in sources :

Example 1 with HttpMethod

use of com.palantir.conjure.spec.HttpMethod 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 2 with HttpMethod

use of com.palantir.conjure.spec.HttpMethod in project conjure-python by palantir.

the class PythonEndpointDefinition method emit.

@SuppressWarnings({ "CyclomaticComplexity", "MethodLength" })
@Override
default void emit(PythonPoetWriter poetWriter) {
    poetWriter.maintainingIndent(() -> {
        // if auth type is header, insert it as a fake param
        boolean isHeaderType = auth().isPresent() && auth().get().accept(AuthTypeVisitor.IS_HEADER);
        List<PythonEndpointParam> paramsWithHeader = isHeaderType ? ImmutableList.<PythonEndpointParam>builder().add(PythonEndpointParam.builder().paramName("authHeader").pythonParamName("auth_header").myPyType("str").isOptional(false).paramType(ParameterType.header(HeaderParameterType.of(ParameterId.of("Authorization")))).build()).addAll(params()).build() : params();
        poetWriter.writeIndentedLine("def %s(self, %s) -> %s:", pythonMethodName(), Joiner.on(", ").join(paramsWithHeader.stream().sorted(new PythonEndpointParamComparator()).map(param -> {
            String typedParam = String.format("%s: %s", param.pythonParamName(), param.myPyType());
            if (param.isOptional()) {
                return String.format("%s = None", typedParam);
            }
            return typedParam;
        }).collect(Collectors.toList())), myPyReturnType().orElse("None"));
        poetWriter.increaseIndent();
        docs().ifPresent(docs -> {
            poetWriter.writeIndentedLine("\"\"\"");
            poetWriter.writeIndentedLine(docs.get().trim());
            poetWriter.writeIndentedLine("\"\"\"");
        });
        // header
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_headers: Dict[str, Any] = {");
        poetWriter.increaseIndent();
        poetWriter.writeIndentedLine("'Accept': '%s',", isResponseBinary() ? MediaType.APPLICATION_OCTET_STREAM : MediaType.APPLICATION_JSON);
        // body
        Optional<PythonEndpointParam> bodyParam = paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_BODY)).findAny();
        if (bodyParam.isPresent()) {
            poetWriter.writeIndentedLine("'Content-Type': '%s',", isRequestBinary() ? MediaType.APPLICATION_OCTET_STREAM : MediaType.APPLICATION_JSON);
        }
        paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_HEADER)).forEach(param -> {
            poetWriter.writeIndentedLine("'%s': %s,", param.paramType().accept(ParameterTypeVisitor.HEADER).getParamId().get(), param.pythonParamName());
        });
        poetWriter.decreaseIndent();
        poetWriter.writeIndentedLine("}");
        // params
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_params: Dict[str, Any] = {");
        poetWriter.increaseIndent();
        paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_QUERY)).forEach(param -> {
            poetWriter.writeIndentedLine("'%s': %s,", param.paramType().accept(ParameterTypeVisitor.QUERY).getParamId().get(), param.pythonParamName());
        });
        poetWriter.decreaseIndent();
        poetWriter.writeIndentedLine("}");
        // path params
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_path_params: Dict[str, Any] = {");
        poetWriter.increaseIndent();
        // TODO(qchen): no need for param name twice?
        paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_PATH)).forEach(param -> {
            poetWriter.writeIndentedLine("'%s': %s,", param.paramName(), param.pythonParamName());
        });
        poetWriter.decreaseIndent();
        poetWriter.writeIndentedLine("}");
        if (bodyParam.isPresent()) {
            if (!isRequestBinary()) {
                poetWriter.writeLine();
                poetWriter.writeIndentedLine("_json: Any = ConjureEncoder().default(%s)", bodyParam.get().pythonParamName());
            } else {
                poetWriter.writeLine();
                poetWriter.writeIndentedLine("_data: Any = %s", bodyParam.get().pythonParamName());
            }
        } else {
            poetWriter.writeLine();
            poetWriter.writeIndentedLine("_json: Any = None");
        }
        // fix the path, add path params
        poetWriter.writeLine();
        HttpPath fullPath = httpPath();
        String fixedPath = fullPath.toString().replaceAll("\\{(.*):[^}]*}", "{$1}");
        poetWriter.writeIndentedLine("_path = '%s'", fixedPath);
        poetWriter.writeIndentedLine("_path = _path.format(**_path_params)");
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_response: Response = self._request(");
        poetWriter.increaseIndent();
        poetWriter.writeIndentedLine("'%s',", httpMethod());
        poetWriter.writeIndentedLine("self._uri + _path,");
        poetWriter.writeIndentedLine("params=_params,");
        poetWriter.writeIndentedLine("headers=_headers,");
        if (isResponseBinary()) {
            poetWriter.writeIndentedLine("stream=True,");
        }
        if (!isRequestBinary()) {
            poetWriter.writeIndentedLine("json=_json)");
        } else {
            poetWriter.writeIndentedLine("data=_data)");
        }
        poetWriter.decreaseIndent();
        poetWriter.writeLine();
        if (isResponseBinary()) {
            poetWriter.writeIndentedLine("_raw = _response.raw");
            poetWriter.writeIndentedLine("_raw.decode_content = True");
            poetWriter.writeIndentedLine("return _raw");
        } else if (pythonReturnType().isPresent()) {
            poetWriter.writeIndentedLine("_decoder = ConjureDecoder()");
            if (isOptionalReturnType()) {
                poetWriter.writeIndentedLine("return None if _response.status_code == 204 else _decoder.decode(_response.json(), %s)", pythonReturnType().get());
            } else {
                poetWriter.writeIndentedLine("return _decoder.decode(_response.json(), %s)", pythonReturnType().get());
            }
        } else {
            poetWriter.writeIndentedLine("return");
        }
        poetWriter.decreaseIndent();
    });
}
Also used : HttpMethod(com.palantir.conjure.spec.HttpMethod) AuthType(com.palantir.conjure.spec.AuthType) AuthTypeVisitor(com.palantir.conjure.visitor.AuthTypeVisitor) HttpPath(com.palantir.conjure.spec.HttpPath) Collectors(java.util.stream.Collectors) ParameterTypeVisitor(com.palantir.conjure.visitor.ParameterTypeVisitor) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ParameterType(com.palantir.conjure.spec.ParameterType) List(java.util.List) MediaType(javax.ws.rs.core.MediaType) ImmutableList(com.google.common.collect.ImmutableList) Value(org.immutables.value.Value) Documentation(com.palantir.conjure.spec.Documentation) Optional(java.util.Optional) Comparator(java.util.Comparator) HeaderParameterType(com.palantir.conjure.spec.HeaderParameterType) Joiner(com.google.common.base.Joiner) ParameterId(com.palantir.conjure.spec.ParameterId) HttpPath(com.palantir.conjure.spec.HttpPath)

Aggregations

ImmutableList (com.google.common.collect.ImmutableList)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 HttpPath (com.palantir.conjure.spec.HttpPath)2 ParameterId (com.palantir.conjure.spec.ParameterId)2 ParameterType (com.palantir.conjure.spec.ParameterType)2 List (java.util.List)2 Optional (java.util.Optional)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 EndpointDefinitionValidator (com.palantir.conjure.defs.validator.EndpointDefinitionValidator)1 EnumDefinitionValidator (com.palantir.conjure.defs.validator.EnumDefinitionValidator)1 EnumValueDefinitionValidator (com.palantir.conjure.defs.validator.EnumValueDefinitionValidator)1 ErrorDefinitionValidator (com.palantir.conjure.defs.validator.ErrorDefinitionValidator)1 FieldDefinitionValidator (com.palantir.conjure.defs.validator.FieldDefinitionValidator)1