Java Code Examples for io.swagger.v3.oas.models.Operation#getExtensions()
The following examples show how to use
io.swagger.v3.oas.models.Operation#getExtensions() .
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: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 7 votes |
/** * Remove x-examples from all the paths from the OpenAPI definition. * * @param apiDefinition OpenAPI definition as String */ public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException { try { OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser(); SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null); if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) { log.debug("Errors found when parsing OAS definition"); } OpenAPI openAPI = parseAttemptForV3.getOpenAPI(); for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) { String path = entry.getKey(); List<Operation> operations = openAPI.getPaths().get(path).readOperations(); for (Operation operation : operations) { if (operation.getExtensions() != null && operation.getExtensions().keySet() .contains(APIConstants.SWAGGER_X_EXAMPLES)) { operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES); } } } return Yaml.pretty().writeValueAsString(openAPI); } catch (JsonProcessingException e) { throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES); } }
Example 2
Source File: OpenAPICodegenUtils.java From product-microgateway with Apache License 2.0 | 6 votes |
/** * get resource Endpoint configuration in the format of {@link MgwEndpointConfigDTO} to match the mustache * template. * * @param operation {@link Operation} object * @return {@link MgwEndpointConfigDTO} object */ public static MgwEndpointConfigDTO getResourceEpConfigForCodegen(Operation operation) throws CLICompileTimeException { Map<String, Object> extensions = operation.getExtensions(); EndpointListRouteDTO prodEndpointListDTO = extractEndpointFromOpenAPI( extensions != null ? operation.getExtensions().get(OpenAPIConstants.PRODUCTION_ENDPOINTS) : null, operation.getServers()); // if endpoint name is empty set operation id as the name if (prodEndpointListDTO != null && prodEndpointListDTO.getName() == null) { prodEndpointListDTO.setName(operation.getOperationId()); //Validate the endpointList and throw the exception as it is. prodEndpointListDTO.validateEndpoints(); } EndpointListRouteDTO sandEndpointListDTO = extractEndpointFromOpenAPI( extensions != null ? operation.getExtensions().get(OpenAPIConstants.SANDBOX_ENDPOINTS) : null, null); if (sandEndpointListDTO != null && sandEndpointListDTO.getName() == null) { sandEndpointListDTO.setName(operation.getOperationId()); sandEndpointListDTO.validateEndpoints(); } return RouteUtils.convertToMgwServiceMap(prodEndpointListDTO, sandEndpointListDTO); }
Example 3
Source File: PhpZendExpressivePathHandlerServerCodegen.java From openapi-generator with Apache License 2.0 | 5 votes |
protected void addInternalExtensionToOperation(Operation operation, String name, Object value) { //Add internal extension directly, because addExtension filters extension names if (operation.getExtensions() == null) { operation.setExtensions(new HashMap<>()); } operation.getExtensions().put(name, value); }
Example 4
Source File: OpenAPICodegenUtils.java From product-microgateway with Apache License 2.0 | 5 votes |
/** * Validate Resource level extensions for Single Resource. * * @param operation {@link Operation} object * @param pathItem path name * @param operationName operation name * @param openAPIFilePath file path to openAPI definition */ private static void validateSingleResourceExtensions(Operation operation, String pathItem, String operationName, String openAPIFilePath) { if (operation == null || operation.getExtensions() == null) { return; } //todo: validate policy validateInterceptors(operation.getExtensions(), pathItem, operationName, openAPIFilePath); }
Example 5
Source File: PathItemTransformer.java From swagger-brake with Apache License 2.0 | 5 votes |
private boolean getBetaApiValue(Operation operation) { Map<String, Object> extensions = operation.getExtensions(); if (extensions != null) { Object betaApiAttribute = extensions.get(checkerOptionsProvider.get().getBetaApiExtensionName()); if (betaApiAttribute != null) { return BooleanUtils.toBoolean(betaApiAttribute.toString()); } } return false; }
Example 6
Source File: DefaultSpecFilter.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Override public Optional<Operation> filterOperation(Operation operation, ApiDescription api, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { if(operation.getExtensions() != null && operation.getExtensions().containsKey(Constants.X_INFLECTOR_HIDDEN)) { return Optional.empty(); } return Optional.of(operation); }
Example 7
Source File: VendorSpecFilter.java From swagger-inflector with Apache License 2.0 | 5 votes |
@Override public Operation filterOperation(OpenAPISpecFilter filter, Operation op, String path, String key , Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { final Operation operation = super.filterOperation(filter, op, path, key, params, cookies, headers); if(operation != null) { if (operation.getExtensions() != null) { filterVendorExtensions(operation.getExtensions()); } } return operation; }
Example 8
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Get scope of operation * * @param operation * @return */ private List<String> getScopeOfOperationsFromExtensions(Operation operation) { Map<String, Object> extensions = operation.getExtensions(); if (extensions != null && extensions.containsKey(APIConstants.SWAGGER_X_SCOPE)) { String scopeKey = (String) extensions.get(APIConstants.SWAGGER_X_SCOPE); return Stream.of(scopeKey.split(",")).collect(Collectors.toList()); } return Collections.emptyList(); }
Example 9
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Remove legacy scope information from swagger operation. * * @param resource Given Resource in the input * @param operation Operation in APIDefinition */ private void updateLegacyScopesFromOperation(SwaggerData.Resource resource, Operation operation) { Map<String, Object> extensions = operation.getExtensions(); if (extensions != null && extensions.containsKey(APIConstants.SWAGGER_X_SCOPE)) { extensions.remove(APIConstants.SWAGGER_X_SCOPE); } }
Example 10
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Update OAS operations for Store * * @param openAPI OpenAPI to be updated */ private void updateOperations(OpenAPI openAPI) { for (String pathKey : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathKey); for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) { Operation operation = entry.getValue(); Map<String, Object> extensions = operation.getExtensions(); 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<SecurityRequirement> security = operation.getSecurity(); if (security == null) { security = new ArrayList<>(); operation.setSecurity(security); } for (Map<String, List<String>> requirement : security) { if (requirement.get(OPENAPI_SECURITY_SCHEMA_KEY) == null || !requirement .get(OPENAPI_SECURITY_SCHEMA_KEY).contains(scope)) { requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.singletonList(scope)); } } } } } } }
Example 11
Source File: ScalaGatlingCodegen.java From openapi-generator with Apache License 2.0 | 4 votes |
/** * Modifies the openapi doc to make mustache easier to use * * @param openAPI input openapi document */ @Override public void preprocessOpenAPI(OpenAPI openAPI) { for (String pathname : openAPI.getPaths().keySet()) { PathItem path = openAPI.getPaths().get(pathname); if (path.readOperations() == null) { continue; } for (Operation operation : path.readOperations()) { if (operation.getExtensions() == null) { operation.setExtensions(new HashMap()); } if (!operation.getExtensions().keySet().contains("x-gatling-path")) { if (pathname.contains("{")) { String gatlingPath = pathname.replaceAll("\\{", "\\$\\{"); operation.addExtension("x-gatling-path", gatlingPath); } else { operation.addExtension("x-gatling-path", pathname); } } Set<Parameter> headerParameters = new HashSet<>(); Set<Parameter> formParameters = new HashSet<>(); Set<Parameter> queryParameters = new HashSet<>(); Set<Parameter> pathParameters = new HashSet<>(); if (operation.getParameters() != null) { for (Parameter parameter : operation.getParameters()) { if (parameter.getIn().equalsIgnoreCase("header")) { headerParameters.add(parameter); } /* need to revise below as form parameter is no longer in the parameter list if (parameter.getIn().equalsIgnoreCase("formData")) { formParameters.add(parameter); } */ if (parameter.getIn().equalsIgnoreCase("query")) { queryParameters.add(parameter); } if (parameter.getIn().equalsIgnoreCase("path")) { pathParameters.add(parameter); } /* TODO need to revise below as body is no longer in the parameter if (parameter.getIn().equalsIgnoreCase("body")) { BodyParameter bodyParameter = (BodyParameter) parameter; Model model = bodyParameter.getSchema(); if (model instanceof RefModel) { String[] refArray = model.getReference().split("\\/"); operation.setVendorExtension("x-gatling-body-object", refArray[refArray.length - 1] + ".toStringBody"); Set<String> bodyFeederParams = new HashSet<>(); Set<String> sessionBodyVars = new HashSet<>(); for (Map.Entry<String, Model> modelEntry : swagger.getDefinitions().entrySet()) { if (refArray[refArray.length - 1].equalsIgnoreCase(modelEntry.getKey())) { for (Map.Entry<String, Property> propertyEntry : modelEntry.getValue().getProperties().entrySet()) { bodyFeederParams.add(propertyEntry.getKey()); sessionBodyVars.add("\"${" + propertyEntry.getKey() + "}\""); } } } operation.setVendorExtension("x-gatling-body-feeder", operation.getOperationId() + "BodyFeeder"); operation.setVendorExtension("x-gatling-body-feeder-params", StringUtils.join(sessionBodyVars, ",")); try { FileUtils.writeStringToFile( new File(outputFolder + File.separator + dataFolder + File.separator + operation.getOperationId() + "-" + "bodyParams.csv"), StringUtils.join(bodyFeederParams, ","), StandardCharsets.UTF_8 ); } catch (IOException ioe) { LOGGER.error("Could not create feeder file for operationId" + operation.getOperationId(), ioe); } } else if (model instanceof ArrayModel) { operation.setVendorExtension("x-gatling-body-object", "StringBody(\"[]\")"); } else { operation.setVendorExtension("x-gatling-body-object", "StringBody(\"{}\")"); } } */ } } prepareGatlingData(operation, headerParameters, "header"); prepareGatlingData(operation, formParameters, "form"); prepareGatlingData(operation, queryParameters, "query"); prepareGatlingData(operation, pathParameters, "path"); } } }
Example 12
Source File: NodeJSExpressServerCodegen.java From openapi-generator with Apache License 2.0 | 4 votes |
@Override public void preprocessOpenAPI(OpenAPI openAPI) { URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); String host = URLPathUtils.getProtocolAndHost(url); String port = URLPathUtils.getPort(url, defaultServerPort); String basePath = url.getPath(); if (additionalProperties.containsKey(SERVER_PORT)) { port = additionalProperties.get(SERVER_PORT).toString(); } this.additionalProperties.put(SERVER_PORT, port); if (openAPI.getInfo() != null) { Info info = openAPI.getInfo(); if (info.getTitle() != null) { // when info.title is defined, use it for projectName // used in package.json projectName = info.getTitle() .replaceAll("[^a-zA-Z0-9]", "-") .replaceAll("^[-]*", "") .replaceAll("[-]*$", "") .replaceAll("[-]{2,}", "-") .toLowerCase(Locale.ROOT); this.additionalProperties.put("projectName", projectName); } } // need vendor extensions Paths paths = openAPI.getPaths(); if (paths != null) { for (String pathname : paths.keySet()) { PathItem path = paths.get(pathname); Map<HttpMethod, Operation> operationMap = path.readOperationsMap(); if (operationMap != null) { for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); String tag = "default"; if (operation.getTags() != null && operation.getTags().size() > 0) { tag = toApiName(operation.getTags().get(0)); } if (operation.getOperationId() == null) { operation.setOperationId(getOrGenerateOperationId(operation, pathname, method.toString())); } // add x-openapi-router-controller // if (operation.getExtensions() == null || // operation.getExtensions().get("x-openapi-router-controller") == null) { // operation.addExtension("x-openapi-router-controller", sanitizeTag(tag) + "Controller"); // } // // add x-openapi-router-service // if (operation.getExtensions() == null || // operation.getExtensions().get("x-openapi-router-service") == null) { // operation.addExtension("x-openapi-router-service", sanitizeTag(tag) + "Service"); // } if (operation.getExtensions() == null || operation.getExtensions().get("x-eov-operation-handler") == null) { operation.addExtension("x-eov-operation-handler", "controllers/" + sanitizeTag(tag) + "Controller"); } } } } } }
Example 13
Source File: BallerinaOperation.java From product-microgateway with Apache License 2.0 | 4 votes |
@Override public BallerinaOperation buildContext(Operation operation, ExtendedAPI api) throws BallerinaServiceGenException, CLICompileTimeException { if (operation == null) { return getDefaultValue(); } // OperationId with spaces with special characters will cause errors in ballerina code. // Replacing it with uuid so that we can identify there was a ' ' when doing bal -> swagger operation.setOperationId(UUID.randomUUID().toString().replaceAll("-", "")); this.operationId = operation.getOperationId(); this.tags = operation.getTags(); this.summary = operation.getSummary(); this.description = operation.getDescription(); this.externalDocs = operation.getExternalDocs(); this.parameters = new ArrayList<>(); //to provide resource level security in dev-first approach ApplicationSecurity appSecurity = OpenAPICodegenUtils.populateApplicationSecurity(api.getName(), api.getVersion(), operation.getExtensions(), api.getMutualSSL()); this.authProviders = OpenAPICodegenUtils.getMgwResourceSecurity(operation, appSecurity); this.apiKeys = OpenAPICodegenUtils.generateAPIKeysFromSecurity(operation.getSecurity(), this.authProviders.contains(OpenAPIConstants.APISecurity.apikey.name())); ApplicationSecurity apiAppSecurity = api.getApplicationSecurity(); if (appSecurity != null && appSecurity.isOptional() != null) { // if app security is made optional at resource this.applicationSecurityOptional = appSecurity.isOptional(); } else if (apiAppSecurity != null && apiAppSecurity.isOptional() != null) { // if app security made optional at API level this.applicationSecurityOptional = apiAppSecurity.isOptional(); } //to set resource level scopes in dev-first approach this.scope = OpenAPICodegenUtils.getMgwResourceScope(operation); //set resource level endpoint configuration setEpConfigDTO(operation); Map<String, Object> exts = operation.getExtensions(); if (exts != null) { // set interceptor details Object reqExt = exts.get(OpenAPIConstants.REQUEST_INTERCEPTOR); Object resExt = exts.get(OpenAPIConstants.RESPONSE_INTERCEPTOR); if (reqExt != null) { reqInterceptorContext = new BallerinaInterceptor(reqExt.toString()); requestInterceptor = reqInterceptorContext.getInvokeStatement(); isJavaRequestInterceptor = BallerinaInterceptor.Type.JAVA == reqInterceptorContext.getType(); } if (resExt != null) { resInterceptorContext = new BallerinaInterceptor(resExt.toString()); responseInterceptor = resInterceptorContext.getInvokeStatement(); isJavaResponseInterceptor = BallerinaInterceptor.Type.JAVA == resInterceptorContext.getType(); } Optional<Object> scopes = Optional.ofNullable(exts.get(X_SCOPE)); scopes.ifPresent(value -> this.scope = "\"" + value.toString() + "\""); Optional<Object> authType = Optional.ofNullable(exts.get(X_AUTH_TYPE)); authType.ifPresent(value -> { if (AUTH_TYPE_NONE.equals(value)) { this.isSecured = false; } }); Optional<Object> resourceTier = Optional.ofNullable(exts.get(X_THROTTLING_TIER)); resourceTier.ifPresent(value -> this.resourceTier = value.toString()); //set dev-first resource level throttle policy if (this.resourceTier == null) { Optional<Object> extResourceTier = Optional.ofNullable(exts.get(OpenAPIConstants.THROTTLING_TIER)); extResourceTier.ifPresent(value -> this.resourceTier = value.toString()); } if (api.getApiLevelPolicy() != null && this.resourceTier != null) { //if api level policy exists then we are neglecting the resource level policies String message = "[WARN] : Resource level policy: " + this.resourceTier + " will be neglected due to the presence of API level policy: " + api.getApiLevelPolicy() + " for the API : " + api.getName() + "\n"; CmdUtils.appendMessagesToConsole(message); this.resourceTier = null; } Optional<Object> extDisableSecurity = Optional.ofNullable(exts.get(OpenAPIConstants.DISABLE_SECURITY)); extDisableSecurity.ifPresent(value -> { try { this.isSecured = !(Boolean) value; this.isSecuredAssignedFromOperation = true; } catch (ClassCastException e) { throw new CLIRuntimeException("The property '" + OpenAPIConstants.DISABLE_SECURITY + "' should be a boolean value. But provided '" + value.toString() + "'."); } }); } if (operation.getParameters() != null) { for (Parameter parameter : operation.getParameters()) { this.parameters.add(new BallerinaParameter().buildContext(parameter, api)); } } return this; }
Example 14
Source File: OASMergeUtil.java From crnk-framework with Apache License 2.0 | 4 votes |
public static Operation mergeOperations(Operation thisOperation, Operation thatOperation) { if (thatOperation == null) { return thisOperation; } if (thatOperation.getTags() != null) { thisOperation.setTags( mergeTags(thisOperation.getTags(), thatOperation.getTags()) ); } if (thatOperation.getExternalDocs() != null) { thisOperation.setExternalDocs( mergeExternalDocumentation(thisOperation.getExternalDocs(), thatOperation.getExternalDocs()) ); } if (thatOperation.getParameters() != null) { thisOperation.setParameters( mergeParameters(thisOperation.getParameters(), thatOperation.getParameters()) ); } if (thatOperation.getRequestBody() != null) { thisOperation.setRequestBody(thatOperation.getRequestBody()); } if (thatOperation.getResponses() != null) { thisOperation.setResponses(thatOperation.getResponses()); } if (thatOperation.getCallbacks() != null) { thisOperation.setCallbacks(thatOperation.getCallbacks()); } if (thatOperation.getDeprecated() != null) { thisOperation.setDeprecated(thatOperation.getDeprecated()); } if (thatOperation.getSecurity() != null) { thisOperation.setSecurity(thatOperation.getSecurity()); } if (thatOperation.getServers() != null) { thisOperation.setServers(thatOperation.getServers()); } if (thatOperation.getExtensions() != null) { thisOperation.setExtensions(thatOperation.getExtensions()); } if (thatOperation.getOperationId() != null) { thisOperation.setOperationId(thatOperation.getOperationId()); } if (thatOperation.getSummary() != null) { thisOperation.setSummary(thatOperation.getSummary()); } if (thatOperation.getDescription() != null) { thisOperation.setDescription(thatOperation.getDescription()); } if (thatOperation.getExtensions() != null) { thisOperation.setExtensions(thatOperation.getExtensions()); } return thisOperation; }
Example 15
Source File: ReflectionUtils.java From swagger-inflector with Apache License 2.0 | 4 votes |
public String getControllerName(Operation operation) { String name = null; if (operation.getExtensions() != null){ name = (String) operation.getExtensions().get(Constants.X_SWAGGER_ROUTER_CONTROLLER); } if (name != null) { name = name.replaceAll("^\"|\"$", ""); if (name.indexOf(".") == -1 && config.getControllerPackage() != null) { name = config.getControllerPackage() + "." + name; } if( classNameValidator.isValidClassname( name )) { return name; } } if (operation.getTags() != null && operation.getTags().size() > 0) { for( String tag : operation.getTags()){ name = StringUtils.capitalize(sanitizeToJava(tag)); if (config.getControllerPackage() != null) { name = config.getControllerPackage() + "." + name; } if( classNameValidator.isValidClassname( name )){ return name; } else if( classNameValidator.isValidClassname( name + "Controller" )){ return name + "Controller"; } else if( classNameValidator.isValidClassname( sanitizeToJava("default"))) { return sanitizeToJava("default"); } else if( classNameValidator.isValidClassname( sanitizeToJava("default"))) { return sanitizeToJava("default") + "Controller"; } } } String controllerClass = config.getControllerClass(); if( StringUtils.isEmpty( controllerClass )){ controllerClass = StringUtils.capitalize(sanitizeToJava("default")); } return config.getControllerPackage() + "." + controllerClass; }
Example 16
Source File: OAS3Parser.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * 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 { OpenAPI openAPI = getOpenAPI(resourceConfigsJSON); Set<URITemplate> urlTemplates = new LinkedHashSet<>(); Set<Scope> scopes = getScopes(resourceConfigsJSON); for (String pathKey : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathKey); for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) { Operation operation = entry.getValue(); URITemplate template = new URITemplate(); if (APIConstants.SUPPORTED_METHODS.contains(entry.getKey().name().toLowerCase())) { template.setHTTPVerb(entry.getKey().name().toUpperCase()); template.setHttpVerbs(entry.getKey().name().toUpperCase()); template.setUriTemplate(pathKey); List<String> opScopes = getScopeOfOperations(OPENAPI_SECURITY_SCHEMA_KEY, 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> extensios = operation.getExtensions(); if (extensios != null) { if (extensios.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) { String scopeKey = (String) extensios.get(APIConstants.SWAGGER_X_AUTH_TYPE); template.setAuthType(scopeKey); template.setAuthTypes(scopeKey); } else { template.setAuthType("Any"); template.setAuthTypes("Any"); } if (extensios.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) { String throttlingTier = (String) extensios.get(APIConstants.SWAGGER_X_THROTTLING_TIER); template.setThrottlingTier(throttlingTier); template.setThrottlingTiers(throttlingTier); } if (extensios.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) { String mediationScript = (String) extensios.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT); template.setMediationScript(mediationScript); template.setMediationScripts(template.getHTTPVerb(), mediationScript); } } urlTemplates.add(template); } } } return urlTemplates; }