Search in sources :

Example 26 with RefProperty

use of io.swagger.models.properties.RefProperty in project swagger-parser by swagger-api.

the class SwaggerCompatConverter method convertOperation.

public Operation convertOperation(String tag, io.swagger.models.apideclaration.Operation operation, ApiDeclaration apiDeclaration) {
    Method method;
    if (operation.getMethod() == null) {
        JsonNode node = (JsonNode) operation.getExtraFields().get("httpMethod");
        method = Method.forValue(node.asText());
        operation.setMethod(method);
    }
    Operation output = new Operation().summary(operation.getSummary()).description(operation.getNotes()).operationId(operation.getNickname());
    if (tag != null) {
        output.tag(tag);
    }
    for (io.swagger.models.apideclaration.Parameter parameter : operation.getParameters()) {
        output.parameter(convertParameter(parameter));
    }
    if (operation.getConsumes() != null && !operation.getConsumes().isEmpty()) {
        for (String consumes : operation.getConsumes()) {
            output.consumes(consumes);
        }
    } else if (apiDeclaration.getConsumes() != null) {
        for (String consumes : apiDeclaration.getConsumes()) {
            output.consumes(consumes);
        }
    }
    if (operation.getProduces() != null && !operation.getProduces().isEmpty()) {
        for (String produces : operation.getProduces()) {
            output.produces(produces);
        }
    } else if (apiDeclaration.getProduces() != null) {
        for (String produces : apiDeclaration.getProduces()) {
            output.produces(produces);
        }
    }
    for (ResponseMessage message : operation.getResponseMessages()) {
        Response response = new Response().description(message.getMessage());
        Model responseModel = null;
        if (message.getResponseModel() != null) {
            response.schema(new RefProperty(message.getResponseModel()));
        }
        output.response(message.getCode(), response);
    }
    // default response type
    Property responseProperty = propertyFromTypedObject(operation);
    Response response = new Response().description("success").schema(responseProperty);
    if (output.getResponses() == null) {
        output.defaultResponse(response);
    } else if (responseProperty != null) {
        output.response(200, response);
    }
    Map<String, List<AuthorizationScope>> auths = operation.getAuthorizations();
    for (String securityName : auths.keySet()) {
        List<AuthorizationScope> scopes = auths.get(securityName);
        List<String> updatedScopes = new ArrayList<String>();
        for (AuthorizationScope s : scopes) {
            updatedScopes.add(s.getScope());
        }
        output.addSecurity(securityName, updatedScopes);
    }
    return output;
}
Also used : ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) Method(io.swagger.models.Method) Operation(io.swagger.models.Operation) ResponseMessage(io.swagger.models.apideclaration.ResponseMessage) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) ArrayModel(io.swagger.models.ArrayModel) List(java.util.List) ArrayList(java.util.ArrayList) AuthorizationScope(io.swagger.models.AuthorizationScope) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) ModelProperty(io.swagger.models.apideclaration.ModelProperty) RefProperty(io.swagger.models.properties.RefProperty) UntypedProperty(io.swagger.models.properties.UntypedProperty)

Example 27 with RefProperty

use of io.swagger.models.properties.RefProperty in project candlepin by candlepin.

the class CandlepinSwaggerModelConverter method resolveProperty.

public Property resolveProperty(Type type, ModelConverterContext context, Annotation[] annotations, Iterator<ModelConverter> next) {
    JavaType propType = null;
    /**
     * See java doc of NestedComplexType. This unwrapping makes sure that a
     * real type of field is passed to _mapper
     */
    if (type instanceof NestedComplexType) {
        propType = pMapper.constructType(((NestedComplexType) type).getOriginalType());
    } else {
        propType = pMapper.constructType(type);
    }
    log.debug("resolveProperty {}", propType);
    Property property = null;
    if (propType.isContainerType()) {
        JavaType keyType = propType.getKeyType();
        JavaType valueType = propType.getContentType();
        if (keyType != null && valueType != null) {
            property = new MapProperty().additionalProperties(context.resolveProperty(valueType, new Annotation[] {}));
        } else if (valueType != null) {
            ArrayProperty arrayProperty = new ArrayProperty().items(context.resolveProperty(valueType, new Annotation[] {}));
            if (pIsSetType(propType.getRawClass())) {
                arrayProperty.setUniqueItems(true);
            }
            property = arrayProperty;
        }
    } else {
        property = PrimitiveType.createProperty(propType);
    }
    if (property == null) {
        if (propType.isEnumType()) {
            property = new StringProperty();
            pAddEnumProps(propType.getRawClass(), property);
        } else if (pIsOptionalType(propType)) {
            property = context.resolveProperty(propType.containedType(0), null);
        } else {
            // complex type
            Model innerModel = context.resolve(type);
            if (innerModel instanceof ModelImpl) {
                ModelImpl mi = (ModelImpl) innerModel;
                property = new RefProperty(StringUtils.isNotEmpty(mi.getReference()) ? mi.getReference() : mi.getName());
            }
        }
    }
    return property;
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) ArrayProperty(io.swagger.models.properties.ArrayProperty) MapProperty(io.swagger.models.properties.MapProperty) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) ComposedModel(io.swagger.models.ComposedModel) ApiModel(io.swagger.annotations.ApiModel) StringProperty(io.swagger.models.properties.StringProperty) ModelImpl(io.swagger.models.ModelImpl) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) UUIDProperty(io.swagger.models.properties.UUIDProperty) ApiModelProperty(io.swagger.annotations.ApiModelProperty) AbstractNumericProperty(io.swagger.models.properties.AbstractNumericProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) RefProperty(io.swagger.models.properties.RefProperty)

Example 28 with RefProperty

use of io.swagger.models.properties.RefProperty in project candlepin by candlepin.

the class CandlepinSwaggerModelConverter method parseProperty.

private void parseProperty(ModelConverterContext context, boolean isNested, final BeanDescription beanDesc, Set<String> propertiesToIgnore, List<Property> props, BeanPropertyDefinition propDef) {
    Property property = null;
    String propName = propDef.getName();
    Annotation[] annotations = null;
    propName = getPropName(propDef, propName);
    PropertyMetadata md = propDef.getMetadata();
    boolean hasSetter = false, hasGetter = false;
    if (propDef.getSetter() == null) {
        hasSetter = false;
    } else {
        hasSetter = true;
    }
    if (propDef.getGetter() != null) {
        JsonProperty pd = propDef.getGetter().getAnnotation(JsonProperty.class);
        if (pd != null) {
            hasGetter = true;
        }
    }
    Boolean isReadOnly = null;
    if (!hasSetter & hasGetter) {
        isReadOnly = Boolean.TRUE;
    } else {
        isReadOnly = Boolean.FALSE;
    }
    final AnnotatedMember member = propDef.getPrimaryMember();
    if (member != null && !propertiesToIgnore.contains(propName) && /**
     * If the owning type is nested than we should include only those
     * fields that have the Hateoas annotation.
     */
    !(isNested && !member.hasAnnotation(HateoasInclude.class))) {
        List<Annotation> annotationList = new ArrayList<>();
        for (Annotation a : member.annotations()) {
            annotationList.add(a);
        }
        annotations = annotationList.toArray(new Annotation[annotationList.size()]);
        ApiModelProperty mp = member.getAnnotation(ApiModelProperty.class);
        if (mp != null && mp.readOnly()) {
            isReadOnly = mp.readOnly();
        }
        Type nested = null;
        JavaType propType = member.getType(beanDesc.bindingsForBeanType());
        JsonFilter jsonFilter = propType.getRawClass().getAnnotation(JsonFilter.class);
        /**
         * At this point the propType is a type of some nested field of the
         * type that is being processed. The condition checks if this
         * particular type should have Hateoas serialization enabled. In
         * other words, if we should create a new Nested* model.
         */
        if (jsonFilter != null && (jsonFilter.value().equals("ConsumerFilter") || jsonFilter.value().equals("EntitlementFilter") || jsonFilter.value().equals("OwnerFilter") || jsonFilter.value().equals("GuestFilter"))) {
            if (!nestedJavaTypes.containsKey(propType)) {
                nestedJavaTypes.put(propType, new NestedComplexType(propType));
            }
            nested = nestedJavaTypes.get(propType);
        } else {
            nested = propType;
        }
        // allow override of name from annotation
        if (mp != null && !mp.name().isEmpty()) {
            propName = mp.name();
        }
        if (mp != null && !mp.dataType().isEmpty()) {
            property = resolveApiAnnotated(context, property, annotations, mp, propType);
        }
        // no property from override, construct from propType
        if (property == null) {
            if (mp != null && StringUtils.isNotEmpty(mp.reference())) {
                property = new RefProperty(mp.reference());
            } else if (member.getAnnotation(JsonIdentityInfo.class) != null) {
                property = GeneratorWrapper.processJsonIdentity(propType, context, pMapper, member.getAnnotation(JsonIdentityInfo.class), member.getAnnotation(JsonIdentityReference.class));
            }
            if (property == null) {
                property = context.resolveProperty(nested, annotations);
            }
        }
        if (property != null) {
            addMetadataToProperty(property, propName, md, isReadOnly, member, mp);
            applyBeanValidatorAnnotations(property, annotations);
            props.add(property);
        }
    }
}
Also used : ApiModelProperty(io.swagger.annotations.ApiModelProperty) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) JsonIdentityReference(com.fasterxml.jackson.annotation.JsonIdentityReference) AnnotatedMember(com.fasterxml.jackson.databind.introspect.AnnotatedMember) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) RefProperty(io.swagger.models.properties.RefProperty) NamedType(com.fasterxml.jackson.databind.jsontype.NamedType) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) PrimitiveType(io.swagger.util.PrimitiveType) JavaType(com.fasterxml.jackson.databind.JavaType) JsonIdentityInfo(com.fasterxml.jackson.annotation.JsonIdentityInfo) JsonFilter(com.fasterxml.jackson.annotation.JsonFilter) PropertyMetadata(com.fasterxml.jackson.databind.PropertyMetadata) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) UUIDProperty(io.swagger.models.properties.UUIDProperty) ApiModelProperty(io.swagger.annotations.ApiModelProperty) AbstractNumericProperty(io.swagger.models.properties.AbstractNumericProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) HateoasInclude(org.candlepin.common.jackson.HateoasInclude)

Example 29 with RefProperty

use of io.swagger.models.properties.RefProperty in project okta-sdk-java by okta.

the class AbstractOktaJavaClientCodegen method processListsFromProperties.

private Map<String, Model> processListsFromProperties(Collection<Property> properties, Model baseModel, Swagger swagger) {
    Map<String, Model> result = new LinkedHashMap<>();
    for (Property p : properties) {
        if (p != null && "array".equals(p.getType())) {
            ArrayProperty arrayProperty = (ArrayProperty) p;
            if (arrayProperty.getItems() instanceof RefProperty) {
                RefProperty ref = (RefProperty) arrayProperty.getItems();
                String baseName = ref.getSimpleRef();
                // Do not generate List wrappers for primitives (or strings)
                if (!languageSpecificPrimitives.contains(baseName) && topLevelResources.contains(baseName)) {
                    String modelName = baseName + "List";
                    ModelImpl model = new ModelImpl();
                    model.setName(modelName);
                    model.setAllowEmptyValue(false);
                    model.setDescription("Collection List for " + baseName);
                    if (baseModel == null) {
                        baseModel = swagger.getDefinitions().get(baseName);
                    }
                    // only add the tags from the base model
                    if (baseModel.getVendorExtensions().containsKey("x-okta-tags")) {
                        model.setVendorExtension("x-okta-tags", baseModel.getVendorExtensions().get("x-okta-tags"));
                    }
                    model.setVendorExtension("x-isResourceList", true);
                    model.setVendorExtension("x-baseType", baseName);
                    model.setType(modelName);
                    result.put(modelName, model);
                }
            }
        }
    }
    return result;
}
Also used : ArrayProperty(io.swagger.models.properties.ArrayProperty) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) CodegenModel(io.swagger.codegen.CodegenModel) ModelImpl(io.swagger.models.ModelImpl) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) CodegenProperty(io.swagger.codegen.CodegenProperty) RefProperty(io.swagger.models.properties.RefProperty) LinkedHashMap(java.util.LinkedHashMap) RefProperty(io.swagger.models.properties.RefProperty)

Example 30 with RefProperty

use of io.swagger.models.properties.RefProperty in project okta-sdk-java by okta.

the class AbstractOktaJavaClientCodegen method buildTopLevelResourceList.

/**
 * Figure out which models are top level models (directly returned from a endpoint).
 * @param swagger The instance of swagger.
 */
protected void buildTopLevelResourceList(Swagger swagger) {
    Set<String> resources = new HashSet<>();
    // Loop through all of the operations looking for the models that are used as the response and body params
    swagger.getPaths().forEach((pathName, path) -> path.getOperations().forEach(operation -> {
        // find all body params
        operation.getParameters().forEach(parameter -> {
            if (parameter instanceof BodyParameter) {
                resources.add(((RefModel) ((BodyParameter) parameter).getSchema()).getSimpleRef());
            }
        });
        // response objects are a more complicated, start with filter for only the 200 responses
        operation.getResponses().entrySet().stream().filter(entry -> "200".equals(entry.getKey())).forEach(entry -> {
            // this schema could be a ref or an array property containing a ref (or null)
            Property rawSchema = entry.getValue().getSchema();
            if (rawSchema != null) {
                RefProperty refProperty;
                // detect array properties
                if (rawSchema instanceof ArrayProperty) {
                    Property innerProp = ((ArrayProperty) rawSchema).getItems();
                    if (innerProp instanceof RefProperty) {
                        refProperty = (RefProperty) innerProp;
                    } else {
                        // invalid swagger config file
                        throw new SwaggerException("Expected 'schema.items.$ref' to exist.");
                    }
                } else if (rawSchema instanceof RefProperty) {
                    // non array, standard ref property typically in the format of '#/Definitions/MyModel'
                    refProperty = (RefProperty) rawSchema;
                } else {
                    throw new SwaggerException("Expected 'schema' to be of type 'ArrayProperty' or 'RefProperty'.");
                }
                // get the simple name 'MyModel' instead of '#/Definitions/MyModel'
                resources.add(refProperty.getSimpleRef());
            }
        });
    }));
    // find any children of these resources
    swagger.getDefinitions().forEach((name, model) -> {
        String parent = (String) model.getVendorExtensions().get("x-okta-parent");
        if (parent != null) {
            parent = parent.replaceAll(".*/", "");
            if (resources.contains(parent)) {
                resources.add(parent);
            }
        }
    });
    // mark each model with a 'top-level' vendorExtension
    resources.stream().map(resourceName -> swagger.getDefinitions().get(resourceName)).forEach(model -> {
        model.getVendorExtensions().put("top-level", true);
    });
    this.topLevelResources = resources;
}
Also used : SortedSet(java.util.SortedSet) LoggerFactory(org.slf4j.LoggerFactory) ModelImpl(io.swagger.models.ModelImpl) ArrayProperty(io.swagger.models.properties.ArrayProperty) StringUtils(org.apache.commons.lang3.StringUtils) Model(io.swagger.models.Model) Path(io.swagger.models.Path) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Operation(io.swagger.models.Operation) Property(io.swagger.models.properties.Property) RefModel(io.swagger.models.RefModel) Collection(java.util.Collection) Set(java.util.Set) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Response(io.swagger.models.Response) List(java.util.List) Optional(java.util.Optional) CodegenParameter(io.swagger.codegen.CodegenParameter) AbstractJavaCodegen(io.swagger.codegen.languages.AbstractJavaCodegen) Swagger(io.swagger.models.Swagger) BooleanUtils(org.apache.commons.lang3.BooleanUtils) HashMap(java.util.HashMap) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) TreeSet(java.util.TreeSet) Yaml(org.yaml.snakeyaml.Yaml) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) CodegenProperty(io.swagger.codegen.CodegenProperty) RefProperty(io.swagger.models.properties.RefProperty) Logger(org.slf4j.Logger) CodegenOperation(io.swagger.codegen.CodegenOperation) BodyParameter(io.swagger.models.parameters.BodyParameter) Iterator(java.util.Iterator) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CodegenType(io.swagger.codegen.CodegenType) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) File(java.io.File) SwaggerException(io.swagger.parser.SwaggerException) CodegenModel(io.swagger.codegen.CodegenModel) HttpMethod(io.swagger.models.HttpMethod) Collections(java.util.Collections) SwaggerException(io.swagger.parser.SwaggerException) ArrayProperty(io.swagger.models.properties.ArrayProperty) RefModel(io.swagger.models.RefModel) BodyParameter(io.swagger.models.parameters.BodyParameter) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) CodegenProperty(io.swagger.codegen.CodegenProperty) RefProperty(io.swagger.models.properties.RefProperty) HashSet(java.util.HashSet) RefProperty(io.swagger.models.properties.RefProperty)

Aggregations

RefProperty (io.swagger.models.properties.RefProperty)74 Property (io.swagger.models.properties.Property)50 ArrayProperty (io.swagger.models.properties.ArrayProperty)46 StringProperty (io.swagger.models.properties.StringProperty)35 Test (org.testng.annotations.Test)35 Model (io.swagger.models.Model)23 MapProperty (io.swagger.models.properties.MapProperty)20 ModelImpl (io.swagger.models.ModelImpl)18 Response (io.swagger.models.Response)18 IntegerProperty (io.swagger.models.properties.IntegerProperty)18 Operation (io.swagger.models.Operation)17 RefModel (io.swagger.models.RefModel)17 LongProperty (io.swagger.models.properties.LongProperty)14 Path (io.swagger.models.Path)12 Swagger (io.swagger.models.Swagger)12 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)12 ArrayModel (io.swagger.models.ArrayModel)11 BodyParameter (io.swagger.models.parameters.BodyParameter)11 Map (java.util.Map)11