Java Code Examples for io.swagger.v3.oas.models.Operation#getTags()

The following examples show how to use io.swagger.v3.oas.models.Operation#getTags() . 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: OperationTagsReferenceValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location,
  Operation oasObject) {

  List<String> tags = oasObject.getTags();
  if (CollectionUtils.isEmpty(tags)) {
    return emptyList();
  }

  List<OasViolation> violations = new ArrayList<>();

  Set<String> globalTagNames = getGlobalTagNames(context.getOpenAPI());
  for (int i = 0; i < tags.size(); i++) {
    String tagName = tags.get(i);
    if (!globalTagNames.contains(tagName)) {
      violations.add(
        new OasViolation(location.property("tags[" + i + "]"), ERROR));
    }
  }

  return violations;
}
 
Example 2
Source File: OperationTagsSizeEqValidator.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location,
  Operation oasObject) {

  List<String> tags = oasObject.getTags();
  if (CollectionUtils.size(tags) != expectedSize) {
    return singletonList(new OasViolation(location.property("tags"), ERROR + expectedSize));
  }
  return emptyList();
}
 
Example 3
Source File: TagMustBeReferencedValidator.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private Set<String> getAllOperationsTags(OasValidationContext context) {

    Set<String> allTags = context.getAttribute(CACHE_KEY);
    if (allTags != null) {
      return allTags;
    }

    allTags = new HashSet<>();

    OpenAPI openAPI = context.getOpenAPI();
    Paths paths = openAPI.getPaths();
    if (paths == null) {
      return emptySet();
    }

    for (Map.Entry<String, PathItem> entry : paths.entrySet()) {
      PathItem pathItem = entry.getValue();
      List<Operation> operations = pathItem.readOperations();
      for (Operation operation : operations) {
        List<String> tags = operation.getTags();
        if (CollectionUtils.isEmpty(tags)) {
          continue;
        }
        allTags.addAll(tags);
      }
    }

    context.setAttribute(CACHE_KEY, allTags);
    return allTags;
  }
 
Example 4
Source File: ActuatorOperationCustomizer.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Operation customize(Operation operation, HandlerMethod handlerMethod) {
	if (operation.getTags() != null && operation.getTags().contains(actuatorProvider.getTag().getName())) {
		operation.setSummary(handlerMethod.toString());
		operation.setOperationId(operation.getOperationId() + "_" + methodCount++);
	}
	return operation;
}
 
Example 5
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private void validateOperationTags(String path, String httpMethod,
        Operation operation) {
    List<String> operationTags = operation.getTags();
    if (operationTags == null || operationTags.isEmpty()) {
        getLogger().warn(
                "The '{}' operation with path '{}' does not have any tag. The generated method will be included in 'Default' Endpoint.",
                httpMethod, path);
    } else if (operationTags.size() > 1) {
        String fileList = String.join(", ", operationTags);
        getLogger().warn(
                "The '{}' operation with path '{}' contains multiple tags. The generated method will be included in classes: '{}'.",
                httpMethod, path, fileList);
    }
}
 
Example 6
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private OperationValue(HttpMethod method, String path, Operation operationModel, PathItem pathModel) {
  this.method = method;
  this.path = path;
  this.pathModel = pathModel;
  this.operationModel = operationModel;
  this.tags = operationModel.getTags();
  // Merge parameters
  List<Parameter> opParams = operationModel.getParameters()==null ? new ArrayList<>() : operationModel.getParameters();
  List<Parameter> parentParams = pathModel.getParameters() == null ? new ArrayList<>() : pathModel.getParameters();
  this.parameters = OpenApi3Utils.mergeParameters(opParams, parentParams);
  this.userHandlers = new ArrayList<>();
  this.userFailureHandlers = new ArrayList<>();
}
 
Example 7
Source File: NodeJSExpressServerCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@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 8
Source File: BallerinaOperation.java    From product-microgateway with Apache License 2.0 4 votes vote down vote up
@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 9
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
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 10
Source File: ReflectionUtils.java    From swagger-inflector with Apache License 2.0 4 votes vote down vote up
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;
}