io.swagger.models.Path Java Examples

The following examples show how to use io.swagger.models.Path. 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: ExtendedSwaggerReader.java    From msf4j with Apache License 2.0 6 votes vote down vote up
protected Class<?> getSubResourceWithJaxRsSubresourceLocatorSpecs(Method method) {
    final Class<?> rawType = method.getReturnType();
    final Class<?> type;
    if (Class.class.equals(rawType)) {
        type = getClassArgument(method.getGenericReturnType());
        if (type == null) {
            return null;
        }
    } else {
        type = rawType;
    }

    if (method.getAnnotation(javax.ws.rs.Path.class) != null) {
        if (extractOperationMethod(null, method, null) == null) {
            return type;
        }
    }
    return null;
}
 
Example #3
Source File: SwaggerGeneratorTestIt.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
@org.junit.Test
public void testGenerateReadOnlyModule() {

    final Consumer<Path> onlyGetOperationExists = p -> {
        assertEquals(1, p.getOperations().size());
        assertNotNull(p.getGet());
    };

    //when
    swaggerFor("read-only.yang");

    //then
    // for read only operations only one get operation
    swagger.getPaths().entrySet().stream().filter(e -> e.getKey().contains("c2")).map(Map.Entry::getValue)
            .forEach(onlyGetOperationExists);
}
 
Example #4
Source File: MainApplication.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public void run(ApplicationConfiguration configuration, Environment environment) throws Exception {
  environment.jersey().register(new UriConnegFilter(new MediaTypeMappings(), Collections.<String, String>emptyMap()));
  Map<String, Object> props = new HashMap<>();
  props.put(MessageProperties.LEGACY_WORKERS_ORDERING, true);
  environment.jersey().getResourceConfig().addProperties(props);
  addWriters(environment.jersey());
  configureCors(environment);

  //TODO: This path should not be hard coded.
  configureSwagger(environment, "scigraph");
  environment.servlets().
          addFilter("Swagger Filter", factory.getInjector().getInstance(SwaggerFilter.class))
  .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/swagger.json", "/swagger");

  environment.servlets().addFilter("swaggerDocResolver", new SwaggerDocUrlFilter())
  .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");

  DynamicCypherResourceFactory cypherFactory = factory.getInjector().getInstance(DynamicCypherResourceFactory.class);
  for (Map.Entry<String,Path> config: configuration.getCypherResources().entrySet()) {
    environment.jersey().getResourceConfig().registerResources(cypherFactory.create(config.getKey(), config.getValue()).getBuilder().build());
  }
}
 
Example #5
Source File: RestControllerProcessorTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void test_3() throws Exception
{
    Swagger swagger = new Swagger();
    String restJavaPackage = "org.finra.herd.swaggergen.test.restControllerProcessor.case3";
    String tagPatternTemplate = "(?<tag>.+?)RestController";
    Class<?> modelErrorClass = null;
    new RestControllerProcessor(LOG, swagger, restJavaPackage, tagPatternTemplate, modelErrorClass);
    List<String> operationIds = new ArrayList<>();
    for (Path path : swagger.getPaths().values())
    {
        for (Operation operation : path.getOperations())
        {
            operationIds.add(operation.getOperationId());
        }
    }
    assertEquals(2, operationIds.size());
    assertTrue(operationIds.contains("Test3.duplicate"));
    assertTrue(operationIds.contains("Test3.duplicate1"));
}
 
Example #6
Source File: DocumentationDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
private void validatePaths(Map<String, Path> actualPaths, Map<String, Path> expectedPaths) {
    if (MapUtils.isNotEmpty(expectedPaths)) {
        softAssertions.assertThat(actualPaths).as("Checking Paths").isNotEmpty();
        if (MapUtils.isNotEmpty(actualPaths)) {
            softAssertions.assertThat(actualPaths.keySet()).as("Checking Paths").hasSameElementsAs(expectedPaths.keySet());
            for (Map.Entry<String, Path> actualPathEntry : actualPaths.entrySet()) {
                Path expectedPath = expectedPaths.get(actualPathEntry.getKey());
                Path actualPath = actualPathEntry.getValue();
                String pathName = actualPathEntry.getKey();
                validatePath(pathName, actualPath, expectedPath);
            }
        }
    } else {
        softAssertions.assertThat(actualPaths).as("Checking Paths").isNullOrEmpty();
    }
}
 
Example #7
Source File: ConsumerDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
private void validatePaths(Map<String, Path> actualPaths, Map<String, Path> expectedPaths) {
    if (MapUtils.isNotEmpty(expectedPaths)) {
        softAssertions.assertThat(actualPaths).as("Checking Paths").isNotEmpty();
        if (MapUtils.isNotEmpty(actualPaths)) {
            softAssertions.assertThat(actualPaths.keySet()).as("Checking Paths").containsAll(expectedPaths.keySet());
            for (Map.Entry<String, Path> actualPathEntry : actualPaths.entrySet()) {
                Path expectedPath = expectedPaths.get(actualPathEntry.getKey());
                Path actualPath = actualPathEntry.getValue();
                String pathName = actualPathEntry.getKey();
                validatePath(pathName, actualPath, expectedPath);
            }
        }
    } else {
        softAssertions.assertThat(actualPaths).as("Checking Paths").isNullOrEmpty();
    }
}
 
Example #8
Source File: ODLPathHandler.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void path(ListSchemaNode lN, PathSegment pathCtx) {
    final Path operationalPath = operationalOperations(lN, pathCtx);
    ODLRestconfPathPrinter operationalPathPrinter = new ODLRestconfPathPrinter(pathCtx, useModuleName);
    swagger.path(operational + operationalPathPrinter.path(), operationalPath);

    if (!pathCtx.isReadOnly()) {
        final Path configPath = operations(lN, pathCtx);
        ODLRestconfPathPrinter configPathPrinter = new ODLRestconfPathPrinter(pathCtx, useModuleName);
        swagger.path(data + configPathPrinter.path(), configPath);

        if(fullCrud) {
            //referencing list path
            final Path list = new Path();
            list.post(new PostOperationGenerator(pathCtx, dataObjectBuilder, true).execute(lN));


            ODLRestconfPathPrinter postPrinter = new ODLRestconfPathPrinter(pathCtx, useModuleName, true);
            swagger.path(data + postPrinter.path(), list);
        }
    }
}
 
Example #9
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param swagger
 * @return
 */
private List<InterfaceDiagram> processSwaggerPaths(Swagger swagger) {
	LOGGER.entering(LOGGER.getName(), "processSwaggerPaths");
	List<InterfaceDiagram> interfaceDiagrams = new ArrayList<InterfaceDiagram>();
	Map<String, Path> paths = swagger.getPaths();

	for (Map.Entry<String, Path> entry : paths.entrySet()) {
		Path pathObject = entry.getValue();

		LOGGER.info("Processing Path --> " + entry.getKey());

		List<Operation> operations = pathObject.getOperations();
		String uri = entry.getKey();

		for (Operation operation : operations) {
			interfaceDiagrams.add(getInterfaceDiagram(operation, uri));
		}
	}

	LOGGER.exiting(LOGGER.getName(), "processSwaggerPaths");
	return interfaceDiagrams;
}
 
Example #10
Source File: SwaggerOperations.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public SwaggerOperations(Swagger swagger) {
  this.swagger = swagger;
  Map<String, Path> paths = swagger.getPaths();
  if (paths == null) {
    return;
  }

  for (Entry<String, Path> pathEntry : paths.entrySet()) {
    for (Entry<HttpMethod, Operation> operationEntry : pathEntry.getValue().getOperationMap().entrySet()) {
      Operation operation = operationEntry.getValue();
      if (StringUtils.isEmpty(operation.getOperationId())) {
        throw new IllegalStateException(String
            .format("OperationId can not be empty, path=%s, httpMethod=%s.",
                pathEntry.getKey(), operationEntry.getKey()));
      }

      SwaggerOperation swaggerOperation = new SwaggerOperation(swagger, pathEntry.getKey(), operationEntry.getKey(),
          operation);
      if (operations.putIfAbsent(operation.getOperationId(), swaggerOperation) != null) {
        throw new IllegalStateException(
            "please make sure operationId is unique, duplicated operationId is " + operation.getOperationId());
      }
    }
  }
}
 
Example #11
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Provide a method to validate swagger. This method is now implemented to check common errors, and the logic
 * will be changed when necessary. For internal use only.
 */
public static void validateSwagger(Swagger swagger) {
  Map<String, Path> paths = swagger.getPaths();
  if (paths == null) {
    return;
  }

  for (Path path : paths.values()) {
    Operation operation = path.getPost();
    if (operation == null) {
      continue;
    }

    for (Parameter parameter : operation.getParameters()) {
      if (BodyParameter.class.isInstance(parameter) &&
          ((BodyParameter) parameter).getSchema() == null) {
        throw new ServiceCombException("swagger validator: body parameter schema is empty.");
      }
    }
  }
}
 
Example #12
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 #13
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 #14
Source File: PathsDocument.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a path operation depending on generation mode.
 *
 * @param operation operation
 */
private void buildOperation(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation, Swagger2MarkupConfig config) {
    if (config.isSeparatedOperationsEnabled()) {
        MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder);
        applyPathOperationComponent(pathDocBuilder, operation);
        java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation));
        pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
        if (logger.isDebugEnabled()) {
            logger.debug("Separate operation file produced : '{}'", operationFile);
        }
        buildOperationRef(markupDocBuilder, operation);

    } else {
        applyPathOperationComponent(markupDocBuilder, operation);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId()));
    }
}
 
Example #15
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private Path getNewWildCardPathObject(Path userDefinedWildCardPathObject) {
  Preconditions.checkNotNull(
      userDefinedWildCardPathObject, "userDefinedWildCardPathObject cannot be null");

  Path path = new Path();
  if (userDefinedWildCardPathObject.getGet() == null) {
    path.set("get", constructReservedOperation("Get"));
  }
  if (userDefinedWildCardPathObject.getDelete() == null) {
    path.set("delete", constructReservedOperation("Delete"));
  }
  if (userDefinedWildCardPathObject.getPatch() == null) {
    path.set("patch", constructReservedOperation("Patch"));
  }
  if (userDefinedWildCardPathObject.getPost() == null) {
    path.set("post", constructReservedOperation("Post"));
  }
  if (userDefinedWildCardPathObject.getPut() == null) {
    path.set("put", constructReservedOperation("Put"));
  }
  return path;
}
 
Example #16
Source File: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
private void mapRequestMapping(RequestMapping requestMapping, Method method, Map<String, Path> operationsMap, String controllerClassName,
							   String baseControllerPath) {
	List<HttpMethod> httpMethods = Arrays.stream(requestMapping.method())
										 .map(this::getSpringMethod)
										 .collect(toList());
	httpMethods.forEach(httpMethod -> {
		Operation operation = mapOperation(requestMapping.name(), httpMethod, method, requestMapping.produces(),
										   requestMapping.consumes(), controllerClassName);

		String path = ObjectUtils.defaultIfNull(getFirstFromArray(requestMapping.value()), getFirstFromArray(requestMapping.path()));
		updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap,
							pathItem -> setContentBasedOnHttpMethod(pathItem, httpMethod, operation)
		);
	});

}
 
Example #17
Source File: SwaggerInventory.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void process(Path path) {
    this.paths.add(path);
    Iterator var2;
    if(path.getParameters() != null) {
        var2 = path.getParameters().iterator();

        while(var2.hasNext()) {
            Parameter operation = (Parameter)var2.next();
            this.process(operation);
        }
    }

    if(path.getOperations() != null) {
        var2 = path.getOperations().iterator();

        while(var2.hasNext()) {
            Operation operation1 = (Operation)var2.next();
            this.process(operation1);
        }
    }

}
 
Example #18
Source File: AbstractContractValidatorTest.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnPathsPrefixedIfPrefixConfigured() {
    // given
    Swagger swagger = buildSwaggerFrom("/swagger.json");
    Properties properties = new Properties();
    String configuredPathPrefix = "/foo";
    properties.put("assertj.swagger.pathsPrependExpected", configuredPathPrefix);
    SwaggerAssertionConfig swaggerAssertionConfig = new SwaggerAssertionConfig(properties);
    // when
    Map<String, Path> paths = new DummyValidator().findExpectedPaths(swagger, swaggerAssertionConfig);
    // then configured prefix takes precedence over base path
    paths.entrySet().forEach(e -> {
        assertThat(e.getKey(), startsWith(configuredPathPrefix));
        assertThat(e.getKey(), not(containsString(swagger.getBasePath())));
    });
}
 
Example #19
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 #20
Source File: SwaggerGeneratorTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private void checkDuplicateOperations(Swagger actual) {
  Multimap<String, String> operationIds = HashMultimap.create();
  for (Entry<String, Path> pathEntry : actual.getPaths().entrySet()) {
    for (Entry<HttpMethod, Operation> opEntry : pathEntry.getValue().getOperationMap()
        .entrySet()) {
      operationIds
          .put(opEntry.getValue().getOperationId(), pathEntry.getKey() + "|" + opEntry.getKey());
    }
  }
  int duplicateOperationIdCount = 0;
  for (Entry<String, Collection<String>> entry : operationIds.asMap().entrySet()) {
    if (entry.getValue().size() > 1) {
      System.out.println("Duplicate operation id: " + entry);
      duplicateOperationIdCount++;
    }
  }
  assertThat(duplicateOperationIdCount).named("Duplicate operation ids").isEqualTo(0);
}
 
Example #21
Source File: SwaggerWorkflowReader.java    From mdw with Apache License 2.0 5 votes vote down vote up
private io.swagger.models.parameters.Parameter createParam(ParameterType paramType) {
    if (paramType == ParameterType.Path)
        return new PathParameter();
    else if (paramType == ParameterType.Query)
        return new QueryParameter();
    else if (paramType == ParameterType.Form)
        return new FormParameter();
    else if (paramType == ParameterType.Header)
        return new HeaderParameter();
    else if (paramType == ParameterType.Body)
        return new BodyParameter();
    return null;
}
 
Example #22
Source File: Utils.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static void sortSwagger(Swagger swagger) throws GenerateException {
    if (swagger == null || swagger.getPaths() == null) {
        return;
    }

    TreeMap<String, Path> sortedMap = new TreeMap<String, Path>();
    if (swagger.getPaths() == null) {
        return;
    }
    sortedMap.putAll(swagger.getPaths());
    swagger.paths(sortedMap);

    for (Path path : swagger.getPaths().values()) {
        String methods[] = {"Get", "Delete", "Post", "Put", "Options", "Patch"};
        for (String m : methods) {
            sortResponses(path, m);
        }
    }

    //reorder definitions
    if (swagger.getDefinitions() != null) {
        TreeMap<String, Model> defs = new TreeMap<String, Model>();
        defs.putAll(swagger.getDefinitions());
        swagger.setDefinitions(defs);
    }

    // order the tags
    if (swagger.getTags() != null) {
        Collections.sort(swagger.getTags(), new Comparator<Tag>() {
            public int compare(final Tag a, final Tag b) {
                return a.toString().toLowerCase().compareTo(b.toString().toLowerCase());
            }
        });
    }

}
 
Example #23
Source File: AbstractOktaJavaClientCodegen.java    From okta-sdk-java with Apache License 2.0 5 votes vote down vote up
public void addListModels(Swagger swagger) {

        Map<String, Model> listModels = new LinkedHashMap<>();

        // lists in paths
        for (Path path : swagger.getPaths().values()) {

            List<Property> properties = new ArrayList<>();
            properties.add(getArrayPropertyFromOperation(path.getGet()));
            properties.add(getArrayPropertyFromOperation(path.getPost()));
            properties.add(getArrayPropertyFromOperation(path.getPatch()));
            properties.add(getArrayPropertyFromOperation(path.getPut()));

            listModels.putAll(processListsFromProperties(properties, null, swagger));
        }

        swagger.getDefinitions()
                .entrySet().stream()
                .filter(entry -> topLevelResources.contains(entry.getKey()))
                .forEach(entry -> {
                    Model model = entry.getValue();
                    if (model != null && model.getProperties() != null) {
                        listModels.putAll(processListsFromProperties(model.getProperties().values(), model, swagger));
                    }
                });

        listModels.forEach(swagger::addDefinition);

    }
 
Example #24
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all parameters for the operation. Note: According to the spec, parameters defined
 * inside the operations overrides the parameters defined in the path scope which has the same
 * name and location values (example name : 'shelveId' and location : 'query').
 */
public static ImmutableList<Parameter> getAllResolvedParameters(
    Operation operation, Path parentPath, final DiagCollector diagCollector, Location location) {
  List<Parameter> allResolvedParameters = new ArrayList<>();
  // First populate all the parameters defined in the operation.
  if (operation.getParameters() != null) {
    ImmutableList<Parameter> resolvedParameters =
        getResolvedParameters(
            diagCollector, ImmutableList.copyOf(operation.getParameters()), location);
    allResolvedParameters.addAll(resolvedParameters);
  }
  FluentIterable<Parameter> fluentAllParameters = FluentIterable.from(allResolvedParameters);

  // Now populate shared parameters that were not overridden inside the operation.
  if (parentPath.getParameters() != null) {
    ImmutableList<Parameter> resolvedSharedParameters =
        getResolvedParameters(
            diagCollector, ImmutableList.copyOf(parentPath.getParameters()), location);
    for (final Parameter sharedParam : resolvedSharedParameters) {
      boolean overriddenInOperation =
          fluentAllParameters.anyMatch(
              new Predicate<Parameter>() {
                @Override
                public boolean apply(Parameter parameter) {
                  return parameter.getName().equals(sharedParam.getName())
                      && parameter.getIn().equals(sharedParam.getIn());
                }
              });
      if (!overriddenInOperation) {
        allResolvedParameters.add(sharedParam);
      }
    }
  }
  return ImmutableList.copyOf(allResolvedParameters);
}
 
Example #25
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) {
  Map<String, String> duplicateOperationIdLookup = Maps.newHashMap();
  TreeSet<String> urlPaths = Sets.newTreeSet(swagger.getPaths().keySet());
  for (String urlPath : urlPaths) {
    Path pathObj = swagger.getPath(urlPath);
    createServiceMethodsFromPath(serviceBuilder, urlPath, pathObj, duplicateOperationIdLookup);
  }

  if (isAllowAllMethodsConfigured(swagger, diagCollector)) {
    Path userDefinedWildCardPathObject = new Path();
    if (urlPaths.contains(OpenApiUtils.WILDCARD_URL_PATH)) {
      userDefinedWildCardPathObject = swagger.getPath(OpenApiUtils.WILDCARD_URL_PATH);
    }
    createServiceMethodsFromPath(
        serviceBuilder,
        OpenApiUtils.WILDCARD_URL_PATH,
        getNewWildCardPathObject(userDefinedWildCardPathObject),
        duplicateOperationIdLookup);
  }

  coreApiBuilder.setVersion(swagger.getInfo().getVersion());
  if (isDeprecated(swagger)) {
    coreApiBuilder.addOptions(
        createBoolOption(
            ServiceOptions.getDescriptor()
                .findFieldByNumber(ServiceOptions.DEPRECATED_FIELD_NUMBER)
                .getFullName(),
            true));
  }
  serviceBuilder.addApis(coreApiBuilder);
}
 
Example #26
Source File: DeserializationModule.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public DeserializationModule(boolean includePathDeserializer,
        boolean includeResponseDeserializer) {

    if (includePathDeserializer) {
        this.addDeserializer(Path.class, new PathDeserializer());
    }
    if (includeResponseDeserializer) {
        this.addDeserializer(Response.class, new ResponseDeserializer());
    }

    this.addDeserializer(Property.class, new PropertyDeserializer());
    this.addDeserializer(Model.class, new ModelDeserializer());
    this.addDeserializer(Parameter.class, new ParameterDeserializer());
    this.addDeserializer(SecuritySchemeDefinition.class, new SecurityDefinitionDeserializer());
}
 
Example #27
Source File: SwaggerOperation.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
public SwaggerOperation(final NormalisedPath pathString, final Path pathObject,
                        final HttpMethod method, final Operation operation) {

    this.pathString = requireNonNull(pathString, "A path string is required");
    this.pathObject = requireNonNull(pathObject, "A path object is required");
    this.method = requireNonNull(method, "A request method is required");
    this.operation = requireNonNull(operation, "A operation object is required");
}
 
Example #28
Source File: SwaggerGeneratorWithOdlPathHandlerTest.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
@org.junit.Test
public void testGenerateRCPModule() {
    //when
    swaggerFor("rpc-basic.yang", generator -> generator.pathHandler(new ODLPathHandlerBuilder().useModuleName()));

    //then
    Map<String, Path> paths = swagger.getPaths().entrySet().stream()
            .filter(entry -> entry.getKey().startsWith("/operations"))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    assertEquals(4, paths.keySet().size());
    paths.values().forEach(singlePostOperation.andThen(correctRPCOperationModels));
}
 
Example #29
Source File: AddSecurityDefinitions.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void accept(Swagger swagger) {
    swagger.securityDefinition(securityDefinitionName, securityDefinition);

    for(Path p : swagger.getPaths().values()) {
        for(Operation o : p.getOperations()) {
            o.addSecurity(securityDefinitionName, Collections.emptyList());
        }
    }
}
 
Example #30
Source File: OAS2ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas2" + File.separator + "oas2Resources.json";
    String oas2Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    SwaggerParser swaggerParser = new SwaggerParser();

    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas2Parser, oas2Resources);
    Swagger swaggerObj = swaggerParser.parse(definition);
    boolean isExtensionNotFound =
            swaggerObj.getVendorExtensions() == null || swaggerObj.getVendorExtensions().isEmpty();
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, swaggerObj.getPaths().size());

    Iterator<Map.Entry<String, Path>> itr = swaggerObj.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Path> pathEntry = itr.next();
        Path path = pathEntry.getValue();
        for (Map.Entry<HttpMethod, Operation> operationEntry : path.getOperationMap().entrySet()) {
            Operation operation = operationEntry.getValue();
            Assert.assertFalse(operation.getVendorExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }

    // check updated scopes in security definition
    Operation itemGet = swaggerObj.getPath("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));

    // check available scopes in security definition
    OAuth2Definition oAuth2Definition = (OAuth2Definition) swaggerObj.getSecurityDefinitions().get("default");
    Assert.assertTrue(oAuth2Definition.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", oAuth2Definition.getScopes().get("newScope"));

    Assert.assertTrue(oAuth2Definition.getVendorExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding = (Map<String, String>) oAuth2Definition.getVendorExtensions()
            .get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}