Search in sources :

Example 56 with RefProperty

use of io.swagger.models.properties.RefProperty in project endpoints-java by cloudendpoints.

the class SwaggerGenerator method writeApiMethod.

private void writeApiMethod(ApiMethodConfig methodConfig, ApiConfig apiConfig, Swagger swagger, GenerationContext genCtx) throws ApiConfigException {
    Path path = getOrCreatePath(swagger, methodConfig);
    Operation operation = new Operation();
    operation.setOperationId(getOperationId(apiConfig, methodConfig));
    operation.setDescription(methodConfig.getDescription());
    Collection<String> pathParameters = methodConfig.getPathParameters();
    for (ApiParameterConfig parameterConfig : methodConfig.getParameterConfigs()) {
        switch(parameterConfig.getClassification()) {
            case API_PARAMETER:
                boolean isPathParameter = pathParameters.contains(parameterConfig.getName());
                SerializableParameter parameter = isPathParameter ? new PathParameter() : new QueryParameter();
                parameter.setName(parameterConfig.getName());
                parameter.setDescription(parameterConfig.getDescription());
                boolean required = isPathParameter || (!parameterConfig.getNullable() && parameterConfig.getDefaultValue() == null);
                if (parameterConfig.isRepeated()) {
                    TypeToken<?> t = parameterConfig.getRepeatedItemSerializedType();
                    parameter.setType("array");
                    Property p = getSwaggerArrayProperty(t);
                    if (parameterConfig.isEnum()) {
                        // TODO: Not sure if this is the right check
                        ((StringProperty) p).setEnum(getEnumValues(t));
                    }
                    parameter.setItems(p);
                } else if (parameterConfig.isEnum()) {
                    parameter.setType("string");
                    parameter.setEnum(getEnumValues(parameterConfig.getType()));
                    parameter.setRequired(required);
                } else {
                    parameter.setType(TYPE_TO_STRING_MAP.get(parameterConfig.getSchemaBaseType().getType()));
                    parameter.setFormat(TYPE_TO_FORMAT_MAP.get(parameterConfig.getSchemaBaseType().getType()));
                    parameter.setRequired(required);
                }
                operation.parameter(parameter);
                break;
            case RESOURCE:
                TypeToken<?> requestType = parameterConfig.getSchemaBaseType();
                Schema schema = genCtx.schemata.getOrAdd(requestType, apiConfig);
                BodyParameter bodyParameter = new BodyParameter();
                bodyParameter.setName("body");
                bodyParameter.setSchema(new RefModel(schema.name()));
                operation.addParameter(bodyParameter);
                break;
            case UNKNOWN:
                throw new IllegalArgumentException("Unclassifiable parameter type found.");
            case INJECTED:
                // Do nothing, these are synthetic and created by the framework.
                break;
        }
    }
    Response response = new Response().description("A successful response");
    if (methodConfig.hasResourceInResponse()) {
        TypeToken<?> returnType = ApiAnnotationIntrospector.getSchemaType(methodConfig.getReturnType(), apiConfig);
        Schema schema = genCtx.schemata.getOrAdd(returnType, apiConfig);
        response.setSchema(new RefProperty(schema.name()));
    }
    operation.response(200, response);
    writeAuthConfig(swagger, methodConfig, operation);
    if (methodConfig.isApiKeyRequired()) {
        List<Map<String, List<String>>> security = operation.getSecurity();
        // security requirements, add a new one for just the API key.
        if (security != null) {
            for (Map<String, List<String>> securityEntry : security) {
                securityEntry.put(API_KEY, ImmutableList.<String>of());
            }
        } else {
            operation.addSecurity(API_KEY, ImmutableList.<String>of());
        }
        Map<String, SecuritySchemeDefinition> definitions = swagger.getSecurityDefinitions();
        if (definitions == null || !definitions.containsKey(API_KEY)) {
            swagger.securityDefinition(API_KEY, new ApiKeyAuthDefinition(API_KEY_PARAM, In.QUERY));
        }
    }
    path.set(methodConfig.getHttpMethod().toLowerCase(), operation);
    addDefinedMetricCosts(genCtx.limitMetrics, operation, methodConfig.getMetricCosts());
}
Also used : SerializableParameter(io.swagger.models.parameters.SerializableParameter) QueryParameter(io.swagger.models.parameters.QueryParameter) RefModel(io.swagger.models.RefModel) Schema(com.google.api.server.spi.config.model.Schema) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) RefProperty(io.swagger.models.properties.RefProperty) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) LongProperty(io.swagger.models.properties.LongProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) DateTimeProperty(io.swagger.models.properties.DateTimeProperty) ByteArrayProperty(io.swagger.models.properties.ByteArrayProperty) RefProperty(io.swagger.models.properties.RefProperty) FloatProperty(io.swagger.models.properties.FloatProperty) DateProperty(io.swagger.models.properties.DateProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty) Path(io.swagger.models.Path) ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Response(io.swagger.models.Response) ApiKeyAuthDefinition(io.swagger.models.auth.ApiKeyAuthDefinition) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 57 with RefProperty

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

the class ModelPropertyConverterTest method convertRefArrayModelProperty.

@Test
public void convertRefArrayModelProperty() throws Exception {
    ModelProperty property = new ModelProperty();
    property.setType("array");
    Items items = new Items();
    items.setRef("Pet");
    property.setItems(items);
    Property converted = converter.convertProperty(property);
    assertEquals(converted.getClass(), ArrayProperty.class);
    ArrayProperty prop = (ArrayProperty) converted;
    Property innerType = prop.getItems();
    RefProperty ref = (RefProperty) innerType;
    assertEquals(ref.getSimpleRef(), "Pet");
}
Also used : ArrayProperty(io.swagger.models.properties.ArrayProperty) ModelProperty(io.swagger.models.apideclaration.ModelProperty) Items(io.swagger.models.apideclaration.Items) DoubleProperty(io.swagger.models.properties.DoubleProperty) FloatProperty(io.swagger.models.properties.FloatProperty) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) DateTimeProperty(io.swagger.models.properties.DateTimeProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) ModelProperty(io.swagger.models.apideclaration.ModelProperty) LongProperty(io.swagger.models.properties.LongProperty) RefProperty(io.swagger.models.properties.RefProperty) Property(io.swagger.models.properties.Property) RefProperty(io.swagger.models.properties.RefProperty) Test(org.testng.annotations.Test)

Example 58 with RefProperty

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

the class ResolverCache method updateLocalRefs.

protected <T> void updateLocalRefs(String file, Property schema) {
    if (schema instanceof RefProperty) {
        RefProperty ref = (RefProperty) schema;
        String updatedLocation = merge(file, ref.get$ref());
        ref.set$ref(updatedLocation);
    }
}
Also used : RefProperty(io.swagger.models.properties.RefProperty)

Example 59 with RefProperty

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

the class ExternalRefProcessor method processRefToExternalDefinition.

public String processRefToExternalDefinition(String $ref, RefFormat refFormat) {
    String renamedRef = cache.getRenamedRef($ref);
    if (renamedRef != null) {
        return renamedRef;
    }
    final Model model = cache.loadRef($ref, refFormat, Model.class);
    if (model == null) {
        // stop!  There's a problem.  retain the original ref
        LOGGER.warn("unable to load model reference from `" + $ref + "`.  It may not be available " + "or the reference isn't a valid model schema");
        return $ref;
    }
    String newRef;
    Map<String, Model> definitions = swagger.getDefinitions();
    if (definitions == null) {
        definitions = new LinkedHashMap<>();
    }
    final String possiblyConflictingDefinitionName = computeDefinitionName($ref);
    String tryName = null;
    Model existingModel = definitions.get(possiblyConflictingDefinitionName);
    if (existingModel != null) {
        LOGGER.debug("A model for " + existingModel + " already exists");
        if (existingModel instanceof RefModel) {
            // use the new model
            existingModel = null;
        } else {
            // We add a number at the end of the definition name
            int i = 2;
            for (String name : definitions.keySet()) {
                if (name.equals(possiblyConflictingDefinitionName)) {
                    tryName = possiblyConflictingDefinitionName + "_" + i;
                    existingModel = definitions.get(tryName);
                    i++;
                }
            }
        }
    }
    if (StringUtils.isNotBlank(tryName)) {
        newRef = tryName;
    } else {
        newRef = possiblyConflictingDefinitionName;
    }
    cache.putRenamedRef($ref, newRef);
    if (existingModel == null) {
        // don't overwrite existing model reference
        swagger.addDefinition(newRef, model);
        cache.addReferencedKey(newRef);
        String file = $ref.split("#/")[0];
        if (model instanceof RefModel) {
            RefModel refModel = (RefModel) model;
            if (isAnExternalRefFormat(refModel.getRefFormat())) {
                refModel.set$ref(processRefToExternalDefinition(refModel.get$ref(), refModel.getRefFormat()));
            } else {
                processRefToExternalDefinition(file + refModel.get$ref(), RefFormat.RELATIVE);
            }
        }
        if (model instanceof ComposedModel) {
            ComposedModel composedModel = (ComposedModel) model;
            List<Model> listOfAllOF = composedModel.getAllOf();
            for (Model allOfModel : listOfAllOF) {
                if (allOfModel instanceof RefModel) {
                    RefModel refModel = (RefModel) allOfModel;
                    if (isAnExternalRefFormat(refModel.getRefFormat())) {
                        String joinedRef = join(file, refModel.get$ref());
                        refModel.set$ref(processRefToExternalDefinition(joinedRef, refModel.getRefFormat()));
                    } else {
                        processRefToExternalDefinition(file + refModel.get$ref(), RefFormat.RELATIVE);
                    }
                } else if (allOfModel instanceof ModelImpl) {
                    // Loop through additional properties of allOf and recursively call this method;
                    processProperties(allOfModel.getProperties(), file);
                }
            }
        }
        // Loop the properties and recursively call this method;
        processProperties(model.getProperties(), file);
        if (model instanceof ModelImpl) {
            ModelImpl modelImpl = (ModelImpl) model;
            Property additionalProperties = modelImpl.getAdditionalProperties();
            if (additionalProperties != null) {
                if (additionalProperties instanceof RefProperty) {
                    processRefProperty(((RefProperty) additionalProperties), file);
                } else if (additionalProperties instanceof ArrayProperty) {
                    ArrayProperty arrayProp = (ArrayProperty) additionalProperties;
                    if (arrayProp.getItems() instanceof RefProperty) {
                        processRefProperty((RefProperty) arrayProp.getItems(), file);
                    }
                } else if (additionalProperties instanceof MapProperty) {
                    MapProperty mapProp = (MapProperty) additionalProperties;
                    if (mapProp.getAdditionalProperties() instanceof RefProperty) {
                        processRefProperty((RefProperty) mapProp.getAdditionalProperties(), file);
                    } else if (mapProp.getAdditionalProperties() instanceof ArrayProperty && ((ArrayProperty) mapProp.getAdditionalProperties()).getItems() instanceof RefProperty) {
                        processRefProperty((RefProperty) ((ArrayProperty) mapProp.getAdditionalProperties()).getItems(), file);
                    }
                }
            }
        }
        if (model instanceof ArrayModel && ((ArrayModel) model).getItems() instanceof RefProperty) {
            processRefProperty((RefProperty) ((ArrayModel) model).getItems(), file);
        }
    }
    return newRef;
}
Also used : ArrayProperty(io.swagger.models.properties.ArrayProperty) MapProperty(io.swagger.models.properties.MapProperty) RefProperty(io.swagger.models.properties.RefProperty) MapProperty(io.swagger.models.properties.MapProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) RefProperty(io.swagger.models.properties.RefProperty) Property(io.swagger.models.properties.Property)

Example 60 with RefProperty

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

the class LocalReferenceTests method testAuth.

@Test
public void testAuth() throws Exception {
    new Expectations() {

        {
            remoteUrl.urlToString("https://remote-server.com/issue-454.yaml", null);
            result = issue_454_yaml;
            remoteUrl.urlToString("https://remote-components.com/issue-454-components", null);
            result = issue_454_components_yaml;
        }
    };
    Swagger swagger = new SwaggerParser().read("https://remote-server.com/issue-454.yaml", null, true);
    assertNotNull(swagger.getDefinitions().get("ErrorModel"));
    assertNotNull(swagger.getDefinitions().get("ModelWithNestedProperties"));
    ModelImpl model = (ModelImpl) swagger.getDefinitions().get("ModelWithNestedProperties");
    Property property = model.getProperties().get("remoteProperty");
    assertNotNull(property);
    assertTrue(property instanceof RefProperty);
    RefProperty ref = (RefProperty) property;
    assertEquals(ref.get$ref(), "#/definitions/RemoteComponent");
    assertNotNull(swagger.getDefinitions().get("NestedProperty"));
    ModelImpl nestedModel = (ModelImpl) swagger.getDefinitions().get("NestedProperty");
    assertNotNull(nestedModel);
    assertNotNull(nestedModel.getProperties().get("name"));
    assertTrue(nestedModel.getProperties().get("name") instanceof StringProperty);
}
Also used : Expectations(mockit.Expectations) Swagger(io.swagger.models.Swagger) StringProperty(io.swagger.models.properties.StringProperty) ModelImpl(io.swagger.models.ModelImpl) StringProperty(io.swagger.models.properties.StringProperty) RefProperty(io.swagger.models.properties.RefProperty) Property(io.swagger.models.properties.Property) RefProperty(io.swagger.models.properties.RefProperty) Test(org.testng.annotations.Test)

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