Search in sources :

Example 26 with SwaggerDeserializationResult

use of io.swagger.parser.util.SwaggerDeserializationResult in project swagger-parser by swagger-api.

the class SwaggerResolverTest method testSettingsAddParametersToEachOperationDisabled.

@Test
public void testSettingsAddParametersToEachOperationDisabled() {
    String yaml = "---\n" + "swagger: '2.0'\n" + "info:\n" + "  title: test spec\n" + "  version: '1.0'\n" + "paths:\n" + "  \"/test/{id}\":\n" + "    parameters:\n" + "    - name: id\n" + "      in: path\n" + "      type: string\n" + "      required: true\n" + "    get:\n" + "      description: test get\n" + "      parameters:\n" + "      - name: page\n" + "        in: query\n" + "        type: string\n" + "      responses:\n" + "        default:\n" + "          description: test response\n";
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult result = parser.readWithInfo(yaml);
    Swagger swagger = result.getSwagger();
    final Swagger resolved = new SwaggerResolver(swagger, null, null, new SwaggerResolver.Settings().addParametersToEachOperation(false)).resolve();
    assertEquals(resolved.getPaths().get("/test/{id}").getParameters().size(), 1);
    PathParameter pp = (PathParameter) resolved.getPaths().get("/test/{id}").getParameters().get(0);
    assertEquals(pp.getName(), "id");
    assertEquals(resolved.getPaths().get("/test/{id}").getGet().getParameters().size(), 1);
    QueryParameter qp = (QueryParameter) resolved.getPaths().get("/test/{id}").getGet().getParameters().get(0);
    assertEquals(qp.getName(), "page");
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) PathParameter(io.swagger.models.parameters.PathParameter) Test(org.testng.annotations.Test)

Example 27 with SwaggerDeserializationResult

use of io.swagger.parser.util.SwaggerDeserializationResult in project swagger-parser by swagger-api.

the class SwaggerResolverTest method testIssue291.

@Test
public void testIssue291() {
    String json = "{\n" + "  \"swagger\": \"2.0\",\n" + "  \"info\": {\n" + "    \"title\": \"test spec\",\n" + "    \"version\": \"1.0\"\n" + "  },\n" + "  \"parameters\": {\n" + "    \"testParam\": {\n" + "      \"collectionFormat\": \"csv\",\n" + "      \"name\": \"test\",\n" + "      \"in\": \"query\",\n" + "      \"type\": \"array\",\n" + "      \"items\": {\n" + "        \"type\": \"string\"\n" + "      }\n" + "    }\n" + "  },\n" + "  \"paths\": {\n" + "    \"/test\": {\n" + "      \"get\": {\n" + "        \"description\": \"test get\",\n" + "        \"parameters\": [\n" + "          {\n" + "            \"$ref\": \"#/parameters/testParam\"\n" + "          }\n" + "        ],\n" + "        \"responses\": {\n" + "          \"default\": {\n" + "             \"description\": \"test response\"\n" + "          }\n" + "        }\n" + "      }\n" + "    }\n" + "  }\n" + "}";
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult result = parser.readWithInfo(json);
    Swagger swagger = result.getSwagger();
    final Swagger resolved = new SwaggerResolver(swagger, null).resolve();
    Parameter param = resolved.getPaths().get("/test").getGet().getParameters().get(0);
    QueryParameter qp = (QueryParameter) param;
    assertEquals(qp.getCollectionFormat(), "csv");
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) RefParameter(io.swagger.models.parameters.RefParameter) Test(org.testng.annotations.Test)

Example 28 with SwaggerDeserializationResult

use of io.swagger.parser.util.SwaggerDeserializationResult in project carbon-apimgt by wso2.

the class OAS2Parser method getOASDefinitionWithTierContentAwareProperty.

@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    Swagger swagger = parseAttemptForV2.getSwagger();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).getOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList.contains(op.getVendorExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug("API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Swagger(io.swagger.models.Swagger) Operation(io.swagger.models.Operation) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 29 with SwaggerDeserializationResult

use of io.swagger.parser.util.SwaggerDeserializationResult in project carbon-apimgt by wso2.

the class OAS2Parser method getSwagger.

/**
 * Get parsed Swagger object
 *
 * @param oasDefinition OAS definition
 * @return Swagger
 * @throws APIManagementException
 */
Swagger getSwagger(String oasDefinition) {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    if (CollectionUtils.isNotEmpty(parseAttemptForV2.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    return parseAttemptForV2.getSwagger();
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult)

Example 30 with SwaggerDeserializationResult

use of io.swagger.parser.util.SwaggerDeserializationResult in project carbon-apimgt by wso2.

the class OAS2Parser method validateAPIDefinition.

/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(apiDefinition);
    boolean swaggerErrorFound = false;
    for (String message : parseAttemptForV2.getMessages()) {
        OASParserUtil.addErrorToValidationResponse(validationResponse, message);
        if (message.contains(APIConstants.SWAGGER_IS_MISSING_MSG)) {
            ErrorItem errorItem = new ErrorItem();
            errorItem.setErrorCode(ExceptionCodes.INVALID_OAS2_FOUND.getErrorCode());
            errorItem.setMessage(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
            errorItem.setDescription(ExceptionCodes.INVALID_OAS2_FOUND.getErrorMessage());
            validationResponse.getErrorItems().add(errorItem);
            swaggerErrorFound = true;
        }
    }
    if (parseAttemptForV2.getSwagger() == null || swaggerErrorFound) {
        validationResponse.setValid(false);
    } else {
        Swagger swagger = parseAttemptForV2.getSwagger();
        Info info = swagger.getInfo();
        OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, swagger.getSwagger(), info.getTitle(), info.getVersion(), swagger.getBasePath(), info.getDescription(), (swagger.getHost() == null || swagger.getHost().isEmpty()) ? null : new ArrayList<String>(Arrays.asList(swagger.getHost())));
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) {
                // not a json (it is yaml)
                try {
                    JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition, new SwaggerDeserializationResult());
                    validationResponse.setJsonContent(jsonNode.toString());
                } catch (IOException e) {
                    throw new APIManagementException("Error while reading API definition yaml", e);
                }
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerDeserializationResult(io.swagger.parser.util.SwaggerDeserializationResult) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) Info(io.swagger.models.Info) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Aggregations

SwaggerDeserializationResult (io.swagger.parser.util.SwaggerDeserializationResult)56 Test (org.testng.annotations.Test)44 Swagger (io.swagger.models.Swagger)21 AuthorizationValue (io.swagger.models.auth.AuthorizationValue)10 SwaggerParser (io.swagger.parser.SwaggerParser)8 Expectations (mockit.Expectations)8 Parameter (io.swagger.models.parameters.Parameter)7 PathParameter (io.swagger.models.parameters.PathParameter)7 QueryParameter (io.swagger.models.parameters.QueryParameter)7 RefProperty (io.swagger.models.properties.RefProperty)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 ArrayModel (io.swagger.models.ArrayModel)5 Model (io.swagger.models.Model)5 RefModel (io.swagger.models.RefModel)5 BodyParameter (io.swagger.models.parameters.BodyParameter)5 ComposedModel (io.swagger.models.ComposedModel)4 Path (io.swagger.models.Path)4 ArrayProperty (io.swagger.models.properties.ArrayProperty)4 Property (io.swagger.models.properties.Property)4 IOException (java.io.IOException)4