Java Code Examples for io.swagger.models.Operation#setVendorExtension()

The following examples show how to use io.swagger.models.Operation#setVendorExtension() . 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: SwaggerGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private void addDefinedMetricCosts(Map<String, ApiLimitMetricConfig> limitMetrics,
    Operation operation, List<ApiMetricCostConfig> metricCosts) throws ApiConfigException {
  if (!metricCosts.isEmpty()) {
    Map<String, Integer> costs = new HashMap<>();
    for (ApiMetricCostConfig cost : metricCosts) {
      if (!limitMetrics.containsKey(cost.name())) {
        throw new ApiConfigException(String.format(
            "Could not add a metric cost for metric '%s'. The limit metric must be "
                + "defined at the API level.", cost.name()));
      }
      costs.put(cost.name(), cost.cost());
    }
    operation.setVendorExtension("x-google-quota", ImmutableMap.of("metricCosts", costs));
  }
}
 
Example 4
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@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);
    }

}
 
Example 5
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method  generates Sample/Mock payloads for Swagger (2.0) definitions
 *
 * @param swaggerDef Swagger Definition
 * @return Swagger Json
 */
@Override
public Map<String, Object> generateExample(String swaggerDef) {
    // create APIResourceMediationPolicy List = policyList
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
    Swagger swagger = parseAttemptForV2.getSwagger();
    //return map
    Map<String, Object> returnMap = new HashMap<>();
    //List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
        int responseCode = 0;
        int minResponseCode = 0;
        String path = entry.getKey();
        //initializing apiResourceMediationPolicyObject
        APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
        //setting path for apiResourceMediationPolicyObject
        apiResourceMediationPolicyObject.setPath(path);
        Map<String, Model> definitions = swagger.getDefinitions();
        //operation map to get verb
        Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
        List<Operation> operations = swagger.getPaths().get(path).getOperations();
        for (Operation op : operations) {
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            //for each HTTP method get the verb
            for (Map.Entry<HttpMethod, Operation> HTTPMethodMap : operationMap.entrySet()) {
                //add verb to apiResourceMediationPolicyObject
                apiResourceMediationPolicyObject.setVerb(String.valueOf(HTTPMethodMap.getKey()));
            }
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            //for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                if (op.getResponses().get(responseEntry).getExamples() != null) {
                    Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
                    Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        String jsonExample = Json.pretty(applicationJson);
                        genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                        respCodeInitialized = true;
                        hasJsonPayload = true;
                    }
                    if (applicationXml != null) {
                        String xmlExample = applicationXml.toString();
                        genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                        hasXmlPayload = true;
                    }
                } else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
                    Model model = op.getResponses().get(responseEntry).getResponseSchema();
                    String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
                    genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
                    hasJsonPayload = true;
                } else if (op.getResponses().get(responseEntry).getExamples() == null
                        && op.getResponses().get(responseEntry).getResponseSchema() == null) {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            //inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            //gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
            //sets script to each resource in the swagger
            op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
        }
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
 
Example 6
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);
}
 
Example 7
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Updates managed info of a provided operation such as auth type and throttling
 *
 * @param resource  API resource data
 * @param operation swagger operation
 */
private void updateOperationManagedInfo(SwaggerData.Resource resource, Operation operation) {
    String authType = resource.getAuthType();
    if (APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.equals(authType)) {
        authType = APIConstants.OASResourceAuthTypes.APPLICATION_OR_APPLICATION_USER;
    }
    if (APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN.equals(authType)) {
        authType = APIConstants.OASResourceAuthTypes.APPLICATION_USER;
    }
    if (APIConstants.AUTH_APPLICATION_LEVEL_TOKEN.equals(authType)) {
        authType = APIConstants.OASResourceAuthTypes.APPLICATION;
    }
    operation.setVendorExtension(APIConstants.SWAGGER_X_AUTH_TYPE, authType);
    operation.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, resource.getPolicy());
    // AWS Lambda: set arn & timeout to swagger
    if (resource.getAmznResourceName() != null) {
        operation.setVendorExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME, resource.getAmznResourceName());
    }
    if (resource.getAmznResourceTimeout() != 0) {
        operation.setVendorExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT, resource.getAmznResourceTimeout());
    }
    updateLegacyScopesFromOperation(resource, operation);
    String oauth2SchemeKey = APIConstants.SWAGGER_APIM_DEFAULT_SECURITY;
    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(oauth2SchemeKey) != null) {
            if (resource.getScopes().isEmpty()) {
                requirement.put(oauth2SchemeKey, Collections.EMPTY_LIST);
            } else {
                 requirement.put(oauth2SchemeKey, resource.getScopes().stream().map(Scope::getKey).collect(
                        Collectors.toList()));
            }
            return;
        }
    }
    // if oauth2SchemeKey not present, add a new
    Map<String, List<String>> defaultRequirement = new HashMap<>();
    if (resource.getScopes().isEmpty()) {
        defaultRequirement.put(oauth2SchemeKey, Collections.EMPTY_LIST);
    } else {
        defaultRequirement.put(oauth2SchemeKey, resource.getScopes().stream().map(Scope::getKey).collect(
                Collectors.toList()));
    }
    security.add(defaultRequirement);
}
 
Example 8
Source File: UpdateManager.java    From cellery-distribution with Apache License 2.0 2 votes vote down vote up
/**
 * Adds X-auth to swagger to disable Micro-GW authentication
 *
 * @param operation Swagger operation
 */
private static void disableMicroGWAuth(Operation operation) {
    operation.setVendorExtension(Constants.JsonParamNames.X_AUTH_TYPE, Constants.JsonParamNames.NONE);
}