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

The following examples show how to use io.swagger.models.Swagger#setBasePath() . 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: 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 3
Source File: ReaderTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testRead() {
    Map<Class<?>, Object> interfaceMapRef = new HashMap<>();
    interfaceMapRef.put(TestSwaggerService.class, new TestSwaggerServiceImpl());
    Swagger swagger = new Swagger();
    swagger.setBasePath("/rest/");
    Reader.read(swagger, interfaceMapRef, "");

    Assert.assertEquals("2.0", swagger.getSwagger());
    Assert.assertEquals("/rest/", swagger.getBasePath());
    Map<String, Path> paths = swagger.getPaths();
    Assert.assertEquals(TestSwaggerService.class.getMethods().length, paths.size());
    Assert.assertTrue(paths.containsKey(COMPLEX));
    List<Parameter> parameters = paths.get(COMPLEX).getPost().getParameters();
    Assert.assertTrue(CommonUtils.isNotEmpty(parameters));
    Parameter parameter = parameters.get(0);
    Assert.assertTrue(parameter instanceof BodyParameter);
    Model schema = ((BodyParameter) parameter).getSchema();
    Assert.assertTrue(schema instanceof RefModel);
    String ref = ((RefModel) schema).get$ref();
    Assert.assertEquals("#/definitions/ComplexPojo", ref);

}
 
Example 4
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 5
Source File: Java2SwaggerMojo.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void configureSwagger() {
    swagger = new Swagger();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    Info info = new Info();
    Contact swaggerContact = new Contact();
    License swaggerLicense = new License();
    swaggerLicense.name(this.license)
        .url(this.licenseUrl);
    swaggerContact.name(this.contact);
    info.version(this.version)
        .description(this.description)
        .contact(swaggerContact)
        .license(swaggerLicense)
        .title(this.title);
    swagger.setInfo(info);
    if (this.schemes != null) {
        for (String scheme : this.schemes) {
            swagger.scheme(Scheme.forValue(scheme));
        }
    }
    swagger.setHost(this.host);
    swagger.setBasePath(this.basePath);
}
 
Example 6
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Update OAS definition with GW endpoints and API information
 *
 * @param swagger        Swagger
 * @param basePath       API context
 * @param transports     transports types
 * @param hostsWithSchemes GW hosts with protocol mapping
 */
private void updateEndpoints(Swagger swagger, String basePath, String transports,
                             Map<String, String> hostsWithSchemes) {

    String host = StringUtils.EMPTY;
    String[] apiTransports = transports.split(",");
    List<Scheme> schemes = new ArrayList<>();
    if (ArrayUtils.contains(apiTransports, APIConstants.HTTPS_PROTOCOL)
            && hostsWithSchemes.get(APIConstants.HTTPS_PROTOCOL) != null) {
        schemes.add(Scheme.HTTPS);
        host = hostsWithSchemes.get(APIConstants.HTTPS_PROTOCOL).trim()
                .replace(APIConstants.HTTPS_PROTOCOL_URL_PREFIX, "");
    }
    if (ArrayUtils.contains(apiTransports, APIConstants.HTTP_PROTOCOL)
            && hostsWithSchemes.get(APIConstants.HTTP_PROTOCOL) != null) {
        schemes.add(Scheme.HTTP);
        if (StringUtils.isEmpty(host)) {
            host = hostsWithSchemes.get(APIConstants.HTTP_PROTOCOL).trim()
                    .replace(APIConstants.HTTP_PROTOCOL_URL_PREFIX, "");
        }
    }
    swagger.setSchemes(schemes);
    swagger.setBasePath(basePath);
    swagger.setHost(host);
}
 
Example 7
Source File: InspectorImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void correctBasePathForOnlineTest() {
  Transport restTransport = scbEngine.getTransportManager().findTransport(Const.RESTFUL);
  if (restTransport == null ||
      !restTransport.getClass().getName()
          .equals("org.apache.servicecomb.transport.rest.servlet.ServletRestTransport")) {
    return;
  }

  String urlPrefix = ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX);
  if (StringUtils.isEmpty(urlPrefix)) {
    return;
  }

  for (Entry<String, String> entry : schemas.entrySet()) {
    Swagger swagger = SwaggerUtils.parseSwagger(entry.getValue());
    if (swagger.getBasePath().startsWith(urlPrefix)) {
      continue;
    }

    swagger.setBasePath(urlPrefix + swagger.getBasePath());

    entry.setValue(SwaggerUtils.swaggerToString(swagger));
  }
}
 
Example 8
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 9
Source File: EntrypointsSwaggerV2Transformer.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Override
public void transform(SwaggerV2Descriptor descriptor) {
    if (asBoolean(SwaggerProperties.ENTRYPOINTS_AS_SERVERS) && entrypoints != null && ! entrypoints.isEmpty()) {
        Swagger swagger = descriptor.getSpecification();

        // Swagger vs2 supports only a single server
        ApiEntrypointEntity first = entrypoints.iterator().next();
        URI target = URI.create(first.getTarget());
        swagger.setSchemes(Collections.singletonList(Scheme.forValue(target.getScheme())));
        swagger.setHost(target.getHost());

        if (getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH) == null
                || getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH).isEmpty()
                || asBoolean(SwaggerProperties.ENTRYPOINT_AS_BASEPATH)) {
            swagger.setBasePath(target.getPath());
        }
    }
}
 
Example 10
Source File: ProducerProviderManager.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void registerUrlPrefixToSwagger(Swagger swagger) {
  String urlPrefix = ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX);
  if (!StringUtils.isEmpty(urlPrefix) && !swagger.getBasePath().startsWith(urlPrefix)
      && DynamicPropertyFactory.getInstance()
      .getBooleanProperty(DefinitionConst.REGISTER_URL_PREFIX, false).get()) {
    LOGGER.info("Add swagger base path prefix for {} with {}", swagger.getBasePath(), urlPrefix);
    swagger.setBasePath(urlPrefix + swagger.getBasePath());
  }
}
 
Example 11
Source File: AbstractDocumentSource.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
public AbstractDocumentSource(Log log, ApiSource apiSource, String encoding) throws MojoFailureException {
    LOG = log;
    this.outputPath = apiSource.getOutputPath();
    this.templatePath = apiSource.getTemplatePath();
    this.swaggerPath = apiSource.getSwaggerDirectory();
    this.modelSubstitute = apiSource.getModelSubstitute();
    this.jsonExampleValues = apiSource.isJsonExampleValues();

    swagger = new Swagger();
    if (apiSource.getSchemes() != null) {
        for (String scheme : apiSource.getSchemes()) {
            swagger.scheme(Scheme.forValue(scheme));
        }
    }

    // read description from file
    if (apiSource.getDescriptionFile() != null) {
        InputStream is = null;
        try {
            is = new FileInputStream(apiSource.getDescriptionFile());
            apiSource.getInfo().setDescription(IOUtils.toString(is));
        } catch (IOException e) {
            throw new MojoFailureException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    swagger.setHost(apiSource.getHost());
    swagger.setInfo(apiSource.getInfo());
    swagger.setBasePath(apiSource.getBasePath());
    swagger.setExternalDocs(apiSource.getExternalDocs());

    this.apiSource = apiSource;
    if (encoding != null) {
        this.encoding = encoding;
    }
}
 
Example 12
Source File: MSF4JBeanConfig.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public void scanAndRead() {
    Swagger swagger = reader.read(classes());
    if (StringUtils.isNotBlank(getHost())) {
        swagger.setHost(getHost());
    }

    if (StringUtils.isNotBlank(getBasePath())) {
        swagger.setBasePath(getBasePath());
    }

    updateInfoFromConfig();
}
 
Example 13
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 14
Source File: RestControllerClassAnnotationProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(SwaggerGenerator swaggerGenerator, RestController restController) {
  Swagger swagger = swaggerGenerator.getSwagger();
  if (StringUtils.isEmpty(swagger.getBasePath())) {
    swagger.setBasePath("/");
  }
}
 
Example 15
Source File: JbootSwaggerManager.java    From jboot with Apache License 2.0 5 votes vote down vote up
public void init() {
    if (!config.isConfigOk()) {
        return;
    }

    swagger = new Swagger();
    swagger.setHost(config.getHost());
    swagger.setBasePath("/");
    swagger.addScheme(HTTP);
    swagger.addScheme(HTTPS);


    Info swaggerInfo = new Info();
    swaggerInfo.setDescription(config.getDescription());
    swaggerInfo.setVersion(config.getVersion());
    swaggerInfo.setTitle(config.getTitle());
    swaggerInfo.setTermsOfService(config.getTermsOfService());

    Contact contact = new Contact();
    contact.setName(config.getContactName());
    contact.setEmail(config.getContactEmail());
    contact.setUrl(config.getContactUrl());
    swaggerInfo.setContact(contact);

    License license = new License();
    license.setName(config.getLicenseName());
    license.setUrl(config.getLicenseUrl());
    swaggerInfo.setLicense(license);


    swagger.setInfo(swaggerInfo);

    List<Class> classes = ClassScanner.scanClassByAnnotation(RequestMapping.class, false);

    Reader.read(swagger, classes);

}
 
Example 16
Source File: GenerateService.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public String generate(String protocol) {
    if (protocol == null) {
        protocol = defaultProtocol;
    }
    Swagger swagger = new Swagger();

    swagger.setInfo(getInfo());
    swagger.setBasePath(basePath);

    Map<Class<?>, Object> interfaceMapRef = new HashMap<>();
    List<ProviderBootstrap> providerBootstraps = RpcRuntimeContext.getProviderConfigs();
    for (ProviderBootstrap providerBootstrap : providerBootstraps) {
        ProviderConfig providerConfig = providerBootstrap.getProviderConfig();
        List<ServerConfig> server = providerConfig.getServer();
        for (ServerConfig serverConfig : server) {
            if (serverConfig.getProtocol().equals(protocol)) {
                interfaceMapRef.put(providerConfig.getProxyClass(), providerConfig.getRef());
                break;
            }
        }
    }

    Reader.read(swagger, interfaceMapRef, "");
    String result = null;
    try {
        result = Json.mapper().writeValueAsString(swagger);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    return result;
}
 
Example 17
Source File: BashClientCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
/**
 * Preprocess original properties from the Swagger definition where necessary.
 *
 * @param swagger [description]
 */
@Override
public void preprocessSwagger(Swagger swagger) {
    super.preprocessSwagger(swagger);

    if ("/".equals(swagger.getBasePath())) {
        swagger.setBasePath("");
    }

    if(swagger.getInfo() != null
       && swagger.getInfo().getVendorExtensions()!=null) {
      String bash_codegen_app_description
        = (String)swagger.getInfo().getVendorExtensions()
                                          .get("x-bash-codegen-description");

      if(bash_codegen_app_description != null) {

        bash_codegen_app_description
          = escapeText(bash_codegen_app_description);

        additionalProperties.put("x-bash-codegen-app-description",
          bash_codegen_app_description);

      }
    }

}
 
Example 18
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 19
Source File: RestApiResourceScanner.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public Swagger configure(Swagger swagger) {
    swagger.setBasePath("/v1");
    return swagger;
}
 
Example 20
Source File: DubboPropertyConfig.java    From swagger-dubbo with Apache License 2.0 4 votes vote down vote up
private void setBashPath(Swagger swagger) {
	if (StringUtils.isEmpty(swagger.getBasePath())){
		swagger.setBasePath(StringUtils.isEmpty(servletContext.getContextPath()) ? "/" : servletContext.getContextPath());
	}
}