Java Code Examples for io.swagger.models.Swagger#getPath()

The following examples show how to use io.swagger.models.Swagger#getPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractJavaCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    if (swagger == null || swagger.getPaths() == null){
        return;
    }
    for (String pathname : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathname);
        if (path.getOperations() == null){
            continue;
        }
        for (Operation operation : path.getOperations()) {
            boolean hasFormParameters = false;
            boolean hasBodyParameters = false;
            for (Parameter parameter : operation.getParameters()) {
                if (parameter instanceof FormParameter) {
                    hasFormParameters = true;
                }
                if (parameter instanceof BodyParameter) {
                    hasBodyParameters = true;
                }
            }
            if (hasBodyParameters || hasFormParameters){
                String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
                String contentType =  operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0);
                operation.setVendorExtension("x-contentType", contentType);
            }
            String accepts = getAccept(operation);
            operation.setVendorExtension("x-accepts", accepts);
        }
    }
}
 
Example 2
Source File: JMeterCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
  if (swagger != null && swagger.getPaths() != null) {
    for (String pathname : swagger.getPaths().keySet()) {
      Path path = swagger.getPath(pathname);
      if (path.getOperations() != null) {
        for (Operation operation : path.getOperations()) {
          String pathWithDollars = pathname.replaceAll("\\{", "\\$\\{");
          operation.setVendorExtension("x-path", pathWithDollars);
        }
      }
    }
  }
}
 
Example 3
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) {
  Map<String, String> duplicateOperationIdLookup = Maps.newHashMap();
  TreeSet<String> urlPaths = Sets.newTreeSet(swagger.getPaths().keySet());
  for (String urlPath : urlPaths) {
    Path pathObj = swagger.getPath(urlPath);
    createServiceMethodsFromPath(serviceBuilder, urlPath, pathObj, duplicateOperationIdLookup);
  }

  if (isAllowAllMethodsConfigured(swagger, diagCollector)) {
    Path userDefinedWildCardPathObject = new Path();
    if (urlPaths.contains(OpenApiUtils.WILDCARD_URL_PATH)) {
      userDefinedWildCardPathObject = swagger.getPath(OpenApiUtils.WILDCARD_URL_PATH);
    }
    createServiceMethodsFromPath(
        serviceBuilder,
        OpenApiUtils.WILDCARD_URL_PATH,
        getNewWildCardPathObject(userDefinedWildCardPathObject),
        duplicateOperationIdLookup);
  }

  coreApiBuilder.setVersion(swagger.getInfo().getVersion());
  if (isDeprecated(swagger)) {
    coreApiBuilder.addOptions(
        createBoolOption(
            ServiceOptions.getDescriptor()
                .findFieldByNumber(ServiceOptions.DEPRECATED_FIELD_NUMBER)
                .getFullName(),
            true));
  }
  serviceBuilder.addApis(coreApiBuilder);
}
 
Example 4
Source File: SwaggerValidator.java    From mdw with Apache License 2.0 5 votes vote down vote up
public SwaggerValidator(HttpMethod method, String path) throws ValidationException {
    this.method = method;
    this.path = path.startsWith("/") ? path : "/" + path;
    Swagger swagger = MdwSwaggerCache.getSwagger(this.path);
    if (swagger == null)
        throw new ValidationException(Status.NOT_FOUND.getCode(), "Swagger not found for path: " + this.path);
    io.swagger.models.Path swaggerPath = swagger.getPath(this.path);
    if (swaggerPath == null)
        throw new ValidationException(Status.NOT_FOUND.getCode(), "Swagger path not found: " + this.path);
    Operation swaggerOp = swaggerPath.getOperationMap().get(this.method);
    if (swaggerOp == null)
        throw new ValidationException(Status.NOT_FOUND.getCode(), "Swagger operation not found: " + method + " " + this.path);
    validator = new SwaggerModelValidator(method.toString(), this.path, swagger);
}
 
Example 5
Source File: SwaggerInventory.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public SwaggerInventory process(Swagger swagger) {
    Iterator var2;
    if(swagger.getTags() != null) {
        var2 = swagger.getTags().iterator();

        while(var2.hasNext()) {
            Tag key = (Tag)var2.next();
            this.process(key);
        }
    }

    String key1;
    if(swagger.getPaths() != null) {
        var2 = swagger.getPaths().keySet().iterator();

        while(var2.hasNext()) {
            key1 = (String)var2.next();
            Path model = swagger.getPath(key1);
            this.process(model);
        }
    }

    if(swagger.getDefinitions() != null) {
        var2 = swagger.getDefinitions().keySet().iterator();

        while(var2.hasNext()) {
            key1 = (String)var2.next();
            Model model1 = (Model)swagger.getDefinitions().get(key1);
            this.process(model1);
        }
    }

    return this;
}
 
Example 6
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Remove MG related information
 *
 * @param swagger Swagger
 */
private void removePublisherSpecificInfo(Swagger swagger) {
    Map<String, Object> extensions = swagger.getVendorExtensions();
    OASParserUtil.removePublisherSpecificInfo(extensions);
    for (String pathKey : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathKey);
        Map<HttpMethod, Operation> operationMap = path.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
            Operation operation = entry.getValue();
            OASParserUtil.removePublisherSpecificInfofromOperation(operation.getVendorExtensions());
        }
    }
}
 
Example 7
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Update OAS operations for Store
 *
 * @param swagger Swagger to be updated
 */
private void updateOperations(Swagger swagger) {
    for (String pathKey : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathKey);
        Map<HttpMethod, Operation> operationMap = path.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
            Operation operation = entry.getValue();
            Map<String, Object> extensions = operation.getVendorExtensions();
            if (extensions != null) {
                // remove mediation extension
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    extensions.remove(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                }
                // set x-scope value to security definition if it not there.
                if (extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SCOPES)) {
                    String scope = (String) extensions.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
                    List<Map<String, List<String>>> security = operation.getSecurity();
                    if (security == null) {
                        security = new ArrayList<>();
                        operation.setSecurity(security);
                    }
                    for (Map<String, List<String>> requirement : security) {
                        if (requirement.get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY) == null || !requirement
                                .get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).contains(scope)) {
                            requirement
                                    .put(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY, Collections.singletonList(scope));
                        }
                    }
                }
            }
        }
    }
}
 
Example 8
Source File: SwaggerValidatorActivity.java    From mdw with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(ActivityRuntimeContext runtimeContext) throws ActivityException {
    ServiceValuesAccess serviceValues = runtimeContext.getServiceValues();
    Map<String,String> requestHeaders = serviceValues.getRequestHeaders();
    if (requestHeaders == null)
        throw new ActivityException("Missing request headers: " + serviceValues.getRequestHeadersVariableName());

    String httpMethod = serviceValues.getHttpMethod();
    String requestPath = getRequestPath(runtimeContext);
    if (requestPath == null)
        throw new ActivityException("Request path not found");

    String lookupPath = requestPath.replaceAll("\\{.*}", "");
    while (lookupPath.endsWith(("/")))
        lookupPath = lookupPath.substring(0, lookupPath.length() - 1);
    logDebug("Swagger validation for lookupPath=" + lookupPath + " and requestPath=" + requestPath);

    Object request = null;
    if (!"GET".equalsIgnoreCase(httpMethod)) {
        request = serviceValues.getRequest();
    }

    try {
        Swagger swagger = MdwSwaggerCache.getSwagger(lookupPath);
        Path swaggerPath = swagger.getPath(requestPath);
        if (swaggerPath == null)
            throw new ValidationException(Status.NOT_FOUND.getCode(), "No swagger found: " + requestPath);
        Operation swaggerOp = swaggerPath.getOperationMap().get(HttpMethod.valueOf(httpMethod));
        if (swaggerOp == null)
            throw new ValidationException(Status.NOT_FOUND.getCode(), "No swagger found: " + httpMethod + " " + requestPath);
        SwaggerModelValidator validator = new SwaggerModelValidator(httpMethod, requestPath, swagger);
        Result result = new Result();
        if (isValidate(ParameterType.Path))
            result.also(validator.validatePath(requestPath, isStrict()));
        if (isValidate(ParameterType.Query))
            result.also(validator.validateQuery(serviceValues.getQuery(), isStrict()));
        if (isValidate(ParameterType.Header))
            result.also(validator.validateHeaders(requestHeaders, isStrict()));
        if (isValidate(ParameterType.Body)) {
            if (request == null) {
                result.also(Status.BAD_REQUEST, "Missing request: " + serviceValues.getRequestVariableName());
            }
            else {
                JSONObject requestJson = getRequestJson(request, runtimeContext);
                result.also(validator.validateBody(requestJson, isStrict()));
            }
        }
        return handleResult(result);
    }
    catch (ValidationException ex) {
        logger.debug(ex.getMessage(), ex);
        return handleResult(ex.getResult());
    }
}
 
Example 9
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns URI templates according to the given swagger file
 *
 * @param resourceConfigsJSON swaggerJSON
 * @return URI Templates
 * @throws APIManagementException
 */
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
    Swagger swagger = getSwagger(resourceConfigsJSON);
    Set<URITemplate> urlTemplates = new LinkedHashSet<>();
    Set<Scope> scopes = getScopes(resourceConfigsJSON);
    String oauth2SchemeKey = getOAuth2SecuritySchemeKey(swagger);

    for (String pathString : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathString);
        Map<HttpMethod, Operation> operationMap = path.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
            Operation operation = entry.getValue();
            URITemplate template = new URITemplate();
            template.setHTTPVerb(entry.getKey().name().toUpperCase());
            template.setHttpVerbs(entry.getKey().name().toUpperCase());
            template.setUriTemplate(pathString);
            List<String> opScopes = getScopeOfOperations(oauth2SchemeKey, operation);
            if (!opScopes.isEmpty()) {
                if (opScopes.size() == 1) {
                    String firstScope = opScopes.get(0);
                    Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
                    if (scope == null) {
                        throw new APIManagementException("Scope '" + firstScope + "' not found.");
                    }
                    template.setScope(scope);
                    template.setScopes(scope);
                } else {
                    template = OASParserUtil.setScopesToTemplate(template, opScopes, scopes);
                }
            }
            Map<String, Object> extensions = operation.getVendorExtensions();
            if (extensions != null) {
                if (extensions.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) {
                    String authType = (String) extensions.get(APIConstants.SWAGGER_X_AUTH_TYPE);
                    template.setAuthType(authType);
                    template.setAuthTypes(authType);
                } else {
                    template.setAuthType("Any");
                    template.setAuthTypes("Any");
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) {
                    String throttlingTier = (String) extensions.get(APIConstants.SWAGGER_X_THROTTLING_TIER);
                    template.setThrottlingTier(throttlingTier);
                    template.setThrottlingTiers(throttlingTier);
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    String mediationScript = (String) extensions.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                    template.setMediationScript(mediationScript);
                    template.setMediationScripts(template.getHTTPVerb(), mediationScript);
                }
            }
            urlTemplates.add(template);
        }
    }
    return urlTemplates;
}
 
Example 10
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Update OAS definition for API Publisher
 *
 * @param api           API
 * @param oasDefinition
 * @return OAS definition
 * @throws APIManagementException throws if an error occurred
 */
@Override
public String getOASDefinitionForPublisher(API api, String oasDefinition) throws APIManagementException {
    Swagger swagger = getSwagger(oasDefinition);
    if (api.getAuthorizationHeader() != null) {
        swagger.setVendorExtension(APIConstants.X_WSO2_AUTH_HEADER, api.getAuthorizationHeader());
    }
    if (api.getApiLevelPolicy() != null) {
        swagger.setVendorExtension(APIConstants.X_THROTTLING_TIER, api.getApiLevelPolicy());
    }
    swagger.setVendorExtension(APIConstants.X_WSO2_CORS, api.getCorsConfiguration());
    Object prodEndpointObj = OASParserUtil.generateOASConfigForEndpoints(api, true);
    if (prodEndpointObj != null) {
        swagger.setVendorExtension(APIConstants.X_WSO2_PRODUCTION_ENDPOINTS, prodEndpointObj);
    }
    Object sandEndpointObj = OASParserUtil.generateOASConfigForEndpoints(api, false);
    if (sandEndpointObj != null) {
        swagger.setVendorExtension(APIConstants.X_WSO2_SANDBOX_ENDPOINTS, sandEndpointObj);
    }
    swagger.setVendorExtension(APIConstants.X_WSO2_BASEPATH, api.getContext());
    if (api.getTransports() != null) {
        swagger.setVendorExtension(APIConstants.X_WSO2_TRANSPORTS, api.getTransports().split(","));
    }
    String apiSecurity = api.getApiSecurity();
    // set mutual ssl extension if enabled
    if (apiSecurity != null) {
        List<String> securityList = Arrays.asList(apiSecurity.split(","));
        if (securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL)) {
            String mutualSSLOptional = !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY) ?
                    APIConstants.OPTIONAL : APIConstants.MANDATORY;
            swagger.setVendorExtension(APIConstants.X_WSO2_MUTUAL_SSL, mutualSSLOptional);
        }
    }
    // This app security is should given in resource level,
    // otherwise the default oauth2 scheme defined at each resouce level will override application securities
    JsonNode appSecurityExtension = OASParserUtil.getAppSecurity(apiSecurity);
    for (String pathKey : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathKey);
        Map<HttpMethod, Operation> operationMap = path.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
            Operation operation = entry.getValue();
            operation.setVendorExtension(APIConstants.X_WSO2_APP_SECURITY, appSecurityExtension);
        }
    }
    swagger.setVendorExtension(APIConstants.X_WSO2_APP_SECURITY, appSecurityExtension);
    swagger.setVendorExtension(APIConstants.X_WSO2_RESPONSE_CACHE,
            OASParserUtil.getResponseCacheConfig(api.getResponseCache(), api.getCacheTimeout()));

    return getSwaggerJsonString(swagger);
}