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

The following examples show how to use io.swagger.models.Swagger#getBasePath() . 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: AbstractAdaCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
    objs.put("orderedModels", orderedModels);
    Swagger swagger = (Swagger)objs.get("swagger");
    if(swagger != null) {
        String host = swagger.getBasePath();
        try {
            swagger.setHost("SWAGGER_HOST");
            objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n"));
        } catch (JsonProcessingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        swagger.setHost(host);
    }

    /**
     * Collect the scopes to generate unique identifiers for each of them.
     */
    List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
    postProcessAuthMethod(authMethods);

    return super.postProcessSupportingFileData(objs);
}
 
Example 3
Source File: ProducerBootListener.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void saveBasePaths(MicroserviceMeta microserviceMeta) {
  if (!DynamicPropertyFactory.getInstance().getBooleanProperty(DefinitionConst.REGISTER_SERVICE_PATH, false).get()) {
    return;
  }

  String urlPrefix = ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX);
  Map<String, BasePath> basePaths = new LinkedHashMap<>();
  for (SchemaMeta schemaMeta : microserviceMeta.getSchemaMetas().values()) {
    Swagger swagger = schemaMeta.getSwagger();

    String basePath = swagger.getBasePath();
    if (StringUtils.isNotEmpty(urlPrefix) && !basePath.startsWith(urlPrefix)) {
      basePath = urlPrefix + basePath;
    }
    if (StringUtils.isNotEmpty(basePath)) {
      BasePath basePathObj = new BasePath();
      basePathObj.setPath(basePath);
      basePaths.put(basePath, basePathObj);
    }
  }

  RegistrationManager.INSTANCE.addBasePath(basePaths.values());
}
 
Example 4
Source File: SpringBootWrapper.java    From funcatron with Apache License 2.0 6 votes vote down vote up
public String dumpSwagger() {
    try {
        String groupName = Docket.DEFAULT_GROUP_NAME;
        Documentation documentation = documentationCache.documentationByGroup(groupName);
        if (documentation == null) {
            if (documentationCache.all().isEmpty()) return "{}";
            documentation = documentationCache.all().values().stream().findFirst().get();
        }
        Swagger swagger = mapper.mapDocumentation(documentation);

        basePath = swagger.getBasePath();

        return jsonSerializer.toJson(swagger).value();
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new RuntimeException("Failed to dump the Swagger", e);
    }
}
 
Example 5
Source File: AbstractContractValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the expected paths considering both {@code pathsPrependExpected} in the config and {@code basePath} in the Swagger model. The configured value
 * takes precedence regardless of whether it happens to be the same value as the base path or not. If no prefix is configured the Swagger base path is added
 * to each actual path.
 *
 * @param expected        Swagger model
 * @param assertionConfig assertion configuration
 * @return expected paths
 */
protected Map<String, Path> findExpectedPaths(Swagger expected, SwaggerAssertionConfig assertionConfig) {
    String pathsPrependExpected = assertionConfig.getPathsPrependExpected();
    String basePath = expected.getBasePath();
    if (StringUtils.isBlank(pathsPrependExpected) && isBlankOrSlash(basePath)) {
        return expected.getPaths();   // no path prefix configured and no basePath set, nothing to do
    }

    String pathPrefix = null;
    if (StringUtils.isNotBlank(pathsPrependExpected)) {
        pathPrefix = pathsPrependExpected;
    } else if (!isBlankOrSlash(basePath)) {
        pathPrefix = basePath;
    }

    final String finalPathPrefix = pathPrefix;
    return finalPathPrefix == null ?
            expected.getPaths() :
            getPathsWithPrefix(expected, finalPathPrefix);
}
 
Example 6
Source File: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void swaggerToStringException(@Mocked Swagger swagger) {
  new Expectations() {
    {
      swagger.getBasePath();
      result = new RuntimeExceptionWithoutStackTrace();
    }
  };
  expectedException.expect(ServiceCombException.class);
  expectedException.expectMessage("Convert swagger to string failed, ");

  SwaggerUtils.swaggerToString(swagger);
}
 
Example 7
Source File: OpenApiConversionResources.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
public static OpenApiConversionResources create(
    Swagger swagger, String filename, String methodNamespace, String typeNamespace) {
  OpenApiImporterDiagCollector diagCollector = new OpenApiImporterDiagCollector(filename);
  TypeBuilder typeBuilder = new TypeBuilder(swagger, typeNamespace, diagCollector);
  HttpRuleGenerator httpRuleGenerator =
      new HttpRuleGenerator(methodNamespace, swagger.getBasePath(), diagCollector);
  AuthRuleGenerator authRuleGenerator = new AuthRuleGenerator(methodNamespace, diagCollector);
  AuthBuilder authBuilder = new AuthBuilder(methodNamespace, diagCollector, authRuleGenerator);
  MetricRuleGenerator metricRuleGenerator =
      new MetricRuleGenerator(methodNamespace, diagCollector);
  QuotaBuilder quotaBuilder = new QuotaBuilder(diagCollector);
  EndpointBuilder endpointBuilder = new EndpointBuilder(diagCollector);
  AuthzBuilder authzBuilder = new AuthzBuilder(diagCollector);
  BackendBuilder backendBuilder = new BackendBuilder(methodNamespace, diagCollector);
  ProtoApiFromOpenApi apiBuilder =
      new ProtoApiFromOpenApi(
          diagCollector,
          typeBuilder,
          filename,
          methodNamespace,
          httpRuleGenerator,
          authRuleGenerator,
          metricRuleGenerator,
          authBuilder);
  final List<AspectBuilder> aspectBuilders = Lists.newArrayList(
      typeBuilder, authBuilder, backendBuilder, endpointBuilder, quotaBuilder, authzBuilder);
  return new AutoValue_OpenApiConversionResources(aspectBuilders, apiBuilder, diagCollector);
}
 
Example 8
Source File: AbstractContractValidator.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the paths from the actual Swagger model. Each path is prefixed with the base path configured in the model.
 *
 * @param actual Swagger model
 * @return paths including base path
 */
protected Map<String, Path> getPathsIncludingBasePath(Swagger actual) {
    String basePath = actual.getBasePath();
    return isBlankOrSlash(basePath) ?
            actual.getPaths() :
            getPathsWithPrefix(actual, basePath);
}
 
Example 9
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 4 votes vote down vote up
private static String getBasePath(Swagger swagger) {
    String result = swagger.getBasePath();
    if (result == null)
        result = "";
    return result;
}
 
Example 10
Source File: SwaggerV2ToAPIConverter.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public SwaggerApiEntity visit(Swagger swagger) {
    final SwaggerApiEntity apiEntity = new SwaggerApiEntity();
    apiEntity.setName(swagger.getInfo().getTitle());

    if (swagger.getBasePath() != null && !swagger.getBasePath().isEmpty()) {
        apiEntity.setContextPath(swagger.getBasePath());
    } else {
        apiEntity.setContextPath(apiEntity.getName().replaceAll("\\s+", "").toLowerCase());
    }

    apiEntity.setDescription(swagger.getInfo().getDescription() == null ? "Description of " + apiEntity.getName() :
            swagger.getInfo().getDescription());
    apiEntity.setVersion(swagger.getInfo().getVersion());

    String scheme = (swagger.getSchemes() == null || swagger.getSchemes().isEmpty()) ? defaultScheme :
            swagger.getSchemes().iterator().next().toValue();

    apiEntity.setEndpoint(Collections.singletonList(scheme + "://" + swagger.getHost() + swagger.getBasePath()));
    apiEntity.setPaths(swagger.getPaths().entrySet().stream()
            .map(entry -> {
                final io.gravitee.definition.model.Path path = new Path();
                path.setPath(entry.getKey().replaceAll("\\{(.[^/]*)\\}", ":$1"));
                List<Rule> rules = new ArrayList<>();

                entry.getValue().getOperationMap().forEach(new BiConsumer<io.swagger.models.HttpMethod, io.swagger.models.Operation>() {

                    @Override
                    public void accept(io.swagger.models.HttpMethod httpMethod, io.swagger.models.Operation operation) {
                        visitors.forEach(new Consumer<SwaggerOperationVisitor>() {
                            @Override
                            public void accept(SwaggerOperationVisitor operationVisitor) {
                                // Consider only policy visitor for now
                                Optional<Policy> policy = (Optional<Policy>) operationVisitor.visit(swagger, operation);

                                if (policy.isPresent()) {
                                    final Rule rule = new Rule();
                                    rule.setEnabled(true);
                                    rule.setDescription(operation.getSummary() == null ?
                                            (operation.getOperationId() == null ? operation.getDescription() : operation.getOperationId()) :
                                            operation.getSummary());
                                    rule.setMethods(singleton(HttpMethod.valueOf(httpMethod.name())));

                                    io.gravitee.definition.model.Policy defPolicy = new io.gravitee.definition.model.Policy();
                                    defPolicy.setName(policy.get().getName());
                                    defPolicy.setConfiguration(policy.get().getConfiguration());
                                    rule.setPolicy(defPolicy);
                                    rules.add(rule);
                                }
                            }
                        });
                    }
                });

                path.setRules(rules);

                return path;
            })
            .collect(toMap(Path::getPath, path -> path)));

    if (apiEntity.getPaths() != null) {
        apiEntity.setPathMappings(apiEntity.getPaths().keySet());
    }

    return apiEntity;
}
 
Example 11
Source File: ImportController.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
private void swaggerToRFConverter(String projectId, String name, MultipartFile file) throws IOException {
// MultipartFile file
File tempFile = File.createTempFile("RF_SWAGGER_IMPORT", "JSON");
file.transferTo(tempFile);
Swagger swagger = new SwaggerParser().read(tempFile.getAbsolutePath());

String host = swagger.getHost();
String basePath = swagger.getBasePath();

Info info = swagger.getInfo();
String title = info.getTitle();
String description = info.getDescription();

NodeDTO folderNode = createFolder(projectId, title);
folderNode.setDescription(description);

ConversationDTO conversationDTO;

Map<String, Path> paths = swagger.getPaths();
Set<String> keySet = paths.keySet();
for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {
    String pathKey = iterator.next();
    Path path = paths.get(pathKey);

    Map<HttpMethod, Operation> operationMap = path.getOperationMap();
    Set<HttpMethod> operationsKeySet = operationMap.keySet();
    for (Iterator<HttpMethod> operIterator = operationsKeySet.iterator(); operIterator.hasNext();) {
	HttpMethod httpMethod = operIterator.next();
	Operation operation = operationMap.get(httpMethod);

	conversationDTO = new ConversationDTO();
	RfRequestDTO rfRequestDTO = new RfRequestDTO();
	rfRequestDTO.setApiUrl("http://" + host + basePath + pathKey);
	rfRequestDTO.setMethodType(httpMethod.name());
	operation.getParameters();
	conversationDTO.setRfRequestDTO(rfRequestDTO);
	ConversationDTO createdConversation = conversationController.create(conversationDTO);
	conversationDTO.setId(createdConversation.getId());

	String operationId = operation.getOperationId();
	String summary = operation.getSummary();
	// Request Node
	NodeDTO childNode = new NodeDTO();
	childNode.setName(operationId);
	childNode.setDescription(summary);
	childNode.setProjectId(projectId);
	childNode.setConversationDTO(conversationDTO);
	NodeDTO createdChildNode = nodeController.create(folderNode.getId(), childNode);
	System.out.println("created node : " + createdChildNode.getName());
    }
}
   }