All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.openapi4j.parser.validation.v3.ServerValidator Maven / Gradle / Ivy

There is a newer version: 1.0.7
Show newest version
package org.openapi4j.parser.validation.v3;

import org.openapi4j.core.validation.ValidationResult;
import org.openapi4j.core.validation.ValidationResults;
import org.openapi4j.parser.model.v3.OpenApi3;
import org.openapi4j.parser.model.v3.Server;
import org.openapi4j.parser.validation.ValidationContext;
import org.openapi4j.parser.validation.Validator;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.openapi4j.core.validation.ValidationSeverity.ERROR;
import static org.openapi4j.parser.validation.v3.OAI3Keywords.*;

class ServerValidator extends Validator3Base {
  private static final ValidationResult VARIABLE_NOT_DEFINED = new ValidationResult(ERROR, 142, "Undefined variable '%s' for url '%s'");
  private static final ValidationResult VARIABLES_NOT_DEFINED = new ValidationResult(ERROR, 143, "Undefined variables for url '%s'");

  private static final Pattern PATTERN_VARIABLES = Pattern.compile("(\\{)(.*?)(})");

  private static final Validator INSTANCE = new ServerValidator();

  private ServerValidator() {
  }

  public static Validator instance() {
    return INSTANCE;
  }

  @Override
  public void validate(ValidationContext context, OpenApi3 api, Server server, ValidationResults results) {
    checkUrlWithVariables(api, server, results);
    validateMap(context, api, server.getVariables(), results, false, CRUMB_VARIABLES, Regexes.NAME_REGEX, ServerVariableValidator.instance());
    validateMap(context, api, server.getExtensions(), results, false, CRUMB_EXTENSIONS, Regexes.EXT_REGEX, null);
  }

  private void checkUrlWithVariables(OpenApi3 api, Server server, ValidationResults results) {
    String url = server.getUrl();

    validateUrl(api, url, results, true, true, CRUMB_URL);

    // Find variables
    Matcher matcher = PATTERN_VARIABLES.matcher(url);
    final List variables = new ArrayList<>();
    while (matcher.find()) {
      variables.add(matcher.group(2));
    }

    if (!variables.isEmpty() && server.getVariables() == null) {
      results.add(CRUMB_URL, VARIABLES_NOT_DEFINED, url);
    } else if (server.getVariables() != null) {
      // Validate defined variables
      for (String variable : variables) {
        if (!server.getVariables().containsKey(variable)) {
          results.add(CRUMB_URL, VARIABLE_NOT_DEFINED, variable, url);
        }
      }
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy