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

The following examples show how to use io.swagger.models.Swagger#setPaths() . 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: ApiDocV2Service.java    From api-layer with Eclipse Public License 2.0 8 votes vote down vote up
/**
 * Updates BasePath and Paths in Swagger
 *
 * @param swagger    the API doc
 * @param serviceId  the unique service id
 * @param apiDocInfo the service information
 * @param hidden     do not set Paths for automatically generated API doc
 */
protected void updatePaths(Swagger swagger, String serviceId, ApiDocInfo apiDocInfo, boolean hidden) {
    ApiDocPath<Path> apiDocPath = new ApiDocPath<>();
    String basePath = swagger.getBasePath();

    if (swagger.getPaths() != null && !swagger.getPaths().isEmpty()) {
        swagger.getPaths()
            .forEach((originalEndpoint, path)
                -> preparePath(path, apiDocPath, apiDocInfo, basePath, originalEndpoint, serviceId));
    }

    Map<String, Path> updatedPaths;
    if (apiDocPath.getPrefixes().size() == 1) {
        swagger.setBasePath(OpenApiUtil.SEPARATOR + apiDocPath.getPrefixes().iterator().next() + OpenApiUtil.SEPARATOR + serviceId);
        updatedPaths = apiDocPath.getShortPaths();
    } else {
        swagger.setBasePath("");
        updatedPaths = apiDocPath.getLongPaths();
    }

    if (!hidden) {
        swagger.setPaths(updatedPaths);
    }
}
 
Example 2
Source File: SwaggerHandlerImplTest.java    From spring-cloud-huawei with Apache License 2.0 6 votes vote down vote up
private void init() {
  mockMap.put("xxxx", apiListing);
  mockDoc = new Documentation("xx", "/xx", null, mockMap,
      null, Collections.emptySet(), Collections.emptySet(), null, Collections.emptySet(), Collections.emptyList());
  mockSwagger = new Swagger();
  mockSwagger.setInfo(new Info());
  Map<String, Model> defMap = new HashMap<>();
  defMap.put("xx", new ModelImpl());
  mockSwagger.setDefinitions(defMap);
  Map<String, Path> pathMap = new HashMap<>();
  pathMap.put("xx", new Path());
  mockSwagger.setPaths(pathMap);
  new Expectations() {
    {
      documentationCache.documentationByGroup(anyString);
      result = mockDoc;

      DefinitionCache.getClassNameBySchema(anyString);
      result = "app";

      mapper.mapDocumentation((Documentation) any);
      result = mockSwagger;
    }
  };
}
 
Example 3
Source File: SwaggerService.java    From heimdall with Apache License 2.0 6 votes vote down vote up
public Swagger exportApiToSwaggerJSON(Api api) {
    Swagger swagger = new Swagger();

    swagger.setSwagger("2.0");
    swagger.setBasePath(api.getBasePath());

    swagger.setInfo(getInfoByApi(api));
    Optional<Environment> optionalEnvironment = api.getEnvironments().stream().findFirst();
    optionalEnvironment.ifPresent(environment -> swagger.setHost(environment.getInboundURL()));
    swagger.setTags(getTagsByApi(api));
    swagger.setPaths(getPathsByApi(api));
    swagger.setDefinitions(new HashMap<>());
    swagger.setConsumes(new ArrayList<>());

    return swagger;
}
 
Example 4
Source File: Hello.java    From hasor with Apache License 2.0 6 votes vote down vote up
@Any
public void execute(HttpServletResponse response) throws IOException {
    Swagger swagger = new Swagger();
    swagger.setBasePath("/127.0.0.1");
    //
    Operation operation = new Operation();
    Path apiPath = new Path();
    apiPath.setPost(operation);
    //        apiPath.setPost();
    swagger.setPaths(new LinkedHashMap<String, Path>() {{
        put("/aaa", apiPath);
    }});
    //
    //
    String asString = Json.pretty().writeValueAsString(swagger);
    PrintWriter writer = response.getWriter();
    writer.write(asString);
    writer.flush();
}
 
Example 5
Source File: SwaggerFilter.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
private byte[] writeDynamicResource(InputStream is) throws IOException {
  String str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
  Swagger swagger = new SwaggerParser().parse(str);
  // set the resource listing tag
  Tag dynamic = new Tag();
  dynamic.setName("dynamic");
  dynamic.setDescription("Dynamic Cypher resources");
  swagger.addTag(dynamic);
  // add resources to the path
  Map<String,Path> paths = swagger.getPaths();
  paths.putAll(configuration.getCypherResources());
  Map<String,Path> sorted = new LinkedHashMap<>();
  List<String> keys = new ArrayList<>();
  keys.addAll(paths.keySet());
  Collections.sort(keys);
  for (String key : keys) {
    sorted.put(key, paths.get(key));
  }
  swagger.setPaths(sorted);
  // return updated swagger JSON
  return Json.pretty(swagger).getBytes();
}
 
Example 6
Source File: AbstractDocumentSourceTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void removeBasePathFromEndpoints() {
    // arrange
    Swagger swagger = new Swagger();
    Map<String, Path> pathMap = new HashMap<String, Path>();
    pathMap.put("/a/b/c", new Path());
    swagger.setPaths(pathMap);
    swagger.setBasePath("/a/b");

    // act
    Swagger result = source.removeBasePathFromEndpoints(swagger, true);

    // assert
    assertThat(result.getPath("/c"), notNullValue());
    assertThat(result.getPath("/a/b/c"), nullValue());
}
 
Example 7
Source File: OpenAPIV2Generator.java    From spring-openapi with MIT License 5 votes vote down vote up
public Swagger generate(OpenApiV2GeneratorConfig config) {
	logger.info("Starting OpenAPI v2 generation");
	environment = config.getEnvironment();
	Swagger openAPI = new Swagger();
	openAPI.setDefinitions(createDefinitions());
	openAPI.setPaths(createPaths(config));
	openAPI.setInfo(info);
	openAPI.setBasePath(config.getBasePath());
	openAPI.setHost(config.getHost());
	logger.info("OpenAPI v2 generation done!");
	return openAPI;
}
 
Example 8
Source File: UpdateManager.java    From cellery-distribution with Apache License 2.0 5 votes vote down vote up
/**
 * Creates Swagger file for the API given by controller
 *
 * @param api API sent by controller
 */
private static void createSwagger(API api) {
    Swagger swagger = new Swagger();
    swagger.setInfo(createSwaggerInfo(api));
    swagger.basePath("/" + api.getContext());
    swagger.setPaths(createAPIResources(api));
    String swaggerString = Json.pretty(swagger);
    writeSwagger(swaggerString, removeSpecialChars(api.getBackend() + api.getContext()));
}
 
Example 9
Source File: MySwaggerModelExtension.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
public void apply(Swagger swagger) {
    swagger.setHost("newHostName"); //<1>
    swagger.basePath("newBasePath");

    Map<String, Path> paths = swagger.getPaths(); //<2>
    paths.remove("/remove");
    swagger.setPaths(paths);
}
 
Example 10
Source File: SwaggerUtils.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Create a swagger definition from data-service resource details.
 *
 * @param axisResourceMap AxisResourceMap containing resource details.
 * @param dataServiceName Name of the data service.
 * @param transports      Transports supported from the data-service.
 * @param serverConfig    Server config details.
 * @param isJSON          result format JSON or YAML.
 * @return Swagger definition as string.
 * @throws AxisFault Error occurred while fetching the host address.
 */
private static String createSwaggerFromDefinition(AxisResourceMap axisResourceMap, String dataServiceName,
                                                  List<String> transports, MIServerConfig serverConfig,
                                                  boolean isJSON)
        throws AxisFault {

    Swagger swaggerDoc = new Swagger();
    addSwaggerInfoSection(dataServiceName, transports, serverConfig, swaggerDoc);

    Map<String, Path> paths = new HashMap<>();

    for (Map.Entry<String, AxisResource> entry : axisResourceMap.getResources().entrySet()) {
        Path path = new Path();
        for (String method : entry.getValue().getMethods()) {
            Operation operation = new Operation();
            List<AxisResourceParameter> parameterList = entry.getValue().getResourceParameterList(method);
            generatePathAndQueryParameters(method, operation, parameterList);
            // Adding a sample request payload for methods except GET.
            generateSampleRequestPayload(method, operation, parameterList);
            Response response = new Response();
            response.description("this is the default response");
            operation.addResponse("default", response);
            switch (method) {
                case "GET":
                    path.get(operation);
                    break;
                case "POST":
                    path.post(operation);
                    break;
                case "DELETE":
                    path.delete(operation);
                    break;
                case "PUT":
                    path.put(operation);
                    break;
                default:
                    throw new AxisFault("Invalid method \"" + method + "\" detected in the data-service");
            }
        }
        String contextPath = entry.getKey().startsWith("/") ? entry.getKey() : "/" + entry.getKey();
        paths.put(contextPath, path);
    }
    swaggerDoc.setPaths(paths);
    if (isJSON) return Json.pretty(swaggerDoc);
    try {
        return Yaml.pretty().writeValueAsString(swaggerDoc);
    } catch (JsonProcessingException e) {
        logger.error("Error occurred while creating the YAML configuration", e);
        return null;
    }
}
 
Example 11
Source File: SwaggerGenMojo.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a new Swagger metadata.
 *
 * @return the Swagger metadata.
 * @throws MojoExecutionException if any problems were encountered.
 */
private Swagger getSwagger() throws MojoExecutionException
{
    getLog().debug("Creating Swagger Metadata");
    // Set up initial Swagger metadata.
    Swagger swagger = new Swagger();
    swagger.setInfo(new Info().title(title).version(version));
    swagger.setBasePath(basePath);

    // Set the schemes.
    if (!CollectionUtils.isEmpty(schemeParameters))
    {
        List<Scheme> schemes = new ArrayList<>();
        for (String schemeParameter : schemeParameters)
        {
            Scheme scheme = Scheme.forValue(schemeParameter);
            if (scheme == null)
            {
                throw new MojoExecutionException("Invalid scheme specified: " + schemeParameter);
            }
            schemes.add(scheme);
        }
        swagger.setSchemes(schemes);
    }

    // Add authorization support if specified.
    if (authType != null)
    {
        // Find the definition for the user specified type.
        SecuritySchemeDefinition securitySchemeDefinition = null;
        for (SecuritySchemeDefinition possibleDefinition : SECURITY_SCHEME_DEFINITIONS)
        {
            if (possibleDefinition.getType().equalsIgnoreCase(authType))
            {
                securitySchemeDefinition = possibleDefinition;
                break;
            }
        }

        // If we found a match, set it on the swagger object.
        if (securitySchemeDefinition != null)
        {
            // Come up with an authentication name for easy identification (e.g. basicAuthentication, etc.).
            String securityName = securitySchemeDefinition.getType() + "Authentication";

            // Add the security definition.
            swagger.addSecurityDefinition(securityName, securitySchemeDefinition);

            // Add the security for everything based on the name of the definition.
            SecurityRequirement securityRequirement = new SecurityRequirement();
            securityRequirement.requirement(securityName);
            swagger.addSecurity(securityRequirement);
        }
    }

    // Use default paths and definitions.
    swagger.setPaths(new TreeMap<>());
    swagger.setDefinitions(new TreeMap<>());
    return swagger;
}
 
Example 12
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(Swagger version 2)
 *
 * @param swagger Swagger
 * @return Swagger
 * @throws APIManagementException
 */
private Swagger injectOtherResourceScopesToDefaultScheme(Swagger swagger) throws APIManagementException {
    List<String> schemes = getOtherSchemes();

    Map<String, Path> paths = swagger.getPaths();
    for (String pathKey : paths.keySet()) {
        Path pathItem = paths.get(pathKey);
        Map<HttpMethod, Operation> operationsMap = pathItem.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationsMap.entrySet()) {
            HttpMethod httpMethod = entry.getKey();
            Operation operation = entry.getValue();
            Map<String, List<String>> updatedDefaultSecurityRequirement = new HashMap<>();
            List<Map<String, List<String>>> securityRequirements = operation.getSecurity();
            if (securityRequirements == null) {
                securityRequirements = new ArrayList<>();
            }
            if (APIConstants.SUPPORTED_METHODS.contains(httpMethod.name().toLowerCase())) {
                List<String> opScopesDefault = new ArrayList<>();
                List<String> opScopesDefaultInstance = getScopeOfOperations(SWAGGER_SECURITY_SCHEMA_KEY, operation);
                if (opScopesDefaultInstance != null) {
                    opScopesDefault.addAll(opScopesDefaultInstance);
                }
                updatedDefaultSecurityRequirement.put(SWAGGER_SECURITY_SCHEMA_KEY, opScopesDefault);
                for (Map<String, List<String>> input : securityRequirements) {
                    for (String scheme : schemes) {
                        if (!SWAGGER_SECURITY_SCHEMA_KEY.equals(scheme)) {
                            List<String> opScopesOthers = getScopeOfOperations(scheme, operation);
                            if (opScopesOthers != null) {
                                for (String scope : opScopesOthers) {
                                    if (!opScopesDefault.contains(scope)) {
                                        opScopesDefault.add(scope);
                                    }
                                }
                            }
                        }
                        updatedDefaultSecurityRequirement.put(SWAGGER_SECURITY_SCHEMA_KEY, opScopesDefault);
                    }
                }
                securityRequirements.add(updatedDefaultSecurityRequirement);
            }
            operation.setSecurity(securityRequirements);
            entry.setValue(operation);
            operationsMap.put(httpMethod, operation);
        }
        paths.put(pathKey, pathItem);
    }
    swagger.setPaths(paths);
    return swagger;
}
 
Example 13
Source File: SwaggerGenerator.java    From yang2swagger with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Run Swagger generation for configured modules. Write result to target. The file format
 * depends on configured {@link SwaggerGenerator.Format}
 * @param target writer
 * @throws IOException when problem with writing
 */
public void generate(Writer target) throws IOException {
    if(target == null) throw new NullPointerException();

    Swagger result = generate();

    new SortComplexModels().accept(result);

    result.setDefinitions(SwaggerUtils.sortMap(result.getDefinitions()));
    result.setPaths(SwaggerUtils.sortMap(result.getPaths()));

    mapper.writeValue(target, result);
}