io.swagger.jaxrs.ext.SwaggerExtension Java Examples

The following examples show how to use io.swagger.jaxrs.ext.SwaggerExtension. 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: VendorExtensionWithoutReader.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void decorateOperation(final Operation operation, final Method method, final Iterator<SwaggerExtension> chain) {

    final TestVendorAnnotation annotation = method.getAnnotation(TestVendorAnnotation.class);
    if (annotation != null) {

        Map<String, Response> map = new HashMap<String, Response>(operation.getResponses());
        final Response value = new Response();
        value.setDescription(RESPONSE_DESCRIPTION);
        map.put(RESPONSE_STATUS_501, value);
        operation.setResponses(map);
    }

    if (chain.hasNext()) {
        chain.next().decorateOperation(operation, method, chain);
    }
}
 
Example #2
Source File: SpringSwaggerExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) {
    if (this.shouldIgnoreType(type, typesToSkip)) {
        return new ArrayList<Parameter>();
    }

    if (annotations.isEmpty()) {
        // Method arguments are not required to have any annotations
        annotations = Lists.newArrayList((Annotation) null);
    }

    Map<Class<?>, Annotation> annotationMap = toMap(annotations);

    List<Parameter> parameters = new ArrayList<Parameter>();
    parameters.addAll(extractParametersFromModelAttributeAnnotation(type, annotationMap));
    parameters.addAll(extractParametersFromAnnotation(type, annotationMap));

    if (!parameters.isEmpty()) {
        return parameters;
    }
    return super.extractParameters(annotations, type, typesToSkip, chain);
}
 
Example #3
Source File: TestVendorExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void decorateOperation(final Operation operation, final Method method, final Iterator<SwaggerExtension> chain) {

    final TestVendorAnnotation annotation = method.getAnnotation(TestVendorAnnotation.class);
    if (annotation != null) {

        Map<String, Response> map = new HashMap<String, Response>(operation.getResponses());
        final Response value = new Response();
        value.setDescription(RESPONSE_DESCRIPTION);
        map.put(RESPONSE_STATUS_401, value);
        operation.setResponses(map);
    }

    if (chain.hasNext()) {
        chain.next().decorateOperation(operation, method, chain);
    }
}
 
Example #4
Source File: JaxrsParameterExtensionTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testParameterDefaultValue() {
    List<Parameter> parameters = new JaxrsParameterExtension().extractParameters(
            Lists.newArrayList(
                    getTestAnnotation("getWithDefault", QueryParam.class),
                    getTestAnnotation("getWithDefault", DefaultValue.class)
            ),
            String.class,
            Sets.<Type>newHashSet(),
            Lists.<SwaggerExtension>newArrayList().iterator());

    assertFalse(parameters.isEmpty());
    assertEquals(parameters.size(), 1);

    Parameter extracted = parameters.get(0);
    assertEquals(((AbstractSerializableParameter)extracted).getDefaultValue(), "en-US");
}
 
Example #5
Source File: BeanParamInjectParamExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) {
    Class<?> cls = TypeUtils.getRawType(type, type);

    if (shouldIgnoreClass(cls) || typesToSkip.contains(type)) {
        // stop the processing chain
        typesToSkip.add(type);
        return Lists.newArrayList();
    }
    for (Annotation annotation : annotations) {
        if (annotation instanceof BeanParam || annotation instanceof InjectParam) {
            return reader.extractTypes(cls, typesToSkip, Lists.newArrayList());
        }
    }
    return super.extractParameters(annotations, type, typesToSkip, chain);
}
 
Example #6
Source File: JaxrsParameterExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) {
    if (this.shouldIgnoreType(type, typesToSkip)) {
        return new ArrayList<Parameter>();
    }

    ClassToInstanceMap<Annotation> annotationMap = toMap(annotations);

    List<Parameter> parameters = new ArrayList<Parameter>();
    parameters.addAll(extractParametersFromAnnotation(type, annotationMap));

    if (!parameters.isEmpty()) {
        return parameters;
    }
    return super.extractParameters(annotations, type, typesToSkip, chain);
}
 
Example #7
Source File: SwaggerMavenPluginTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
           FileUtils.forceDelete(docOutput);
       } catch(Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example #8
Source File: SpringMvcSkipInheritedTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
           FileUtils.forceDelete(docOutput);
       } catch (Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config-springmvc-skip-inherited.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example #9
Source File: SpringMvcTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
           FileUtils.forceDelete(docOutput);
       } catch (Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config-springmvc.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example #10
Source File: JaxrsEnhancedOperationIdTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
       } catch(Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config-enhanced-operation-id.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example #11
Source File: VendorExtensionsJaxrsReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
public VendorExtensionsJaxrsReader(Swagger swagger, Log LOG) {
    super(swagger, LOG);

    List<SwaggerExtension> extensions = new LinkedList<SwaggerExtension>(SwaggerExtensions.getExtensions());
    extensions.add(new TestVendorExtension());
    SwaggerExtensions.setExtensions(extensions);
}
 
Example #12
Source File: VendorExtensionsSpringMvcReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
public VendorExtensionsSpringMvcReader(Swagger swagger, Log log) {
    super(swagger, log);

    List<SwaggerExtension> extensions = new LinkedList<SwaggerExtension>(SwaggerExtensions.getExtensions());
    extensions.add(new TestVendorExtension());
    SwaggerExtensions.setExtensions(extensions);
}
 
Example #13
Source File: JaxrsParameterExtensionTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractParametersReturnsRetrievedParameters() {
    List<Parameter> parameters = new JaxrsParameterExtension().extractParameters(
            Lists.newArrayList(getTestAnnotation("get", QueryParam.class)),
            String.class,
            Sets.<Type>newHashSet(),
            Lists.<SwaggerExtension>newArrayList().iterator());

    assertFalse(parameters.isEmpty());
    assertEquals(parameters.size(), 1);
}
 
Example #14
Source File: SpringSwaggerExtensionTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractParametersNoModelAttributeAnnotation() {
    List<Parameter> parameters = new SpringSwaggerExtension(new SystemStreamLog()).extractParameters(
            Lists.newArrayList(),
            PaginationHelper.class,
            Sets.<Type>newHashSet(),
            Lists.<SwaggerExtension>newArrayList().iterator());

    assertEquals(parameters.size(), 2);
}
 
Example #15
Source File: SpringSwaggerExtensionTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractParametersReturnsRetrievedParameters() {
    List<Parameter> parameters = new SpringSwaggerExtension(new SystemStreamLog()).extractParameters(
            Lists.newArrayList(getTestAnnotation()),
            PaginationHelper.class,
            Sets.<Type>newHashSet(),
            Lists.<SwaggerExtension>newArrayList().iterator());

    assertEquals(parameters.size(), 2);
}
 
Example #16
Source File: SpringMvcEnhancedOperationIdTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
       } catch (Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config-springmvc-enhanced-operation-id.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example #17
Source File: StringWrapperModelTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
       } catch (Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config-springmvc-string-wrapper-model.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example #18
Source File: ServerParameterExtension.java    From proteus with Apache License 2.0 5 votes vote down vote up
@Override
public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain)
{
    if (type.getTypeName().contains("java.nio.ByteBuffer") || type.getTypeName().contains("java.nio.file.Path"))
    {
        type = java.io.File.class;
    }

    return super.extractParameters(annotations, type, typesToSkip, chain);
}
 
Example #19
Source File: AbstractDocumentSource.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * The reader may modify the extensions list, therefore add the additional swagger extensions
 * after the instantiation of the reader
 */
private void loadSwaggerExtensions(ApiSource apiSource) throws GenerateException {
    if (apiSource.getSwaggerExtensions() != null) {
        List<SwaggerExtension> extensions = SwaggerExtensions.getExtensions();
        extensions.addAll(resolveSwaggerExtensions());
    }
}
 
Example #20
Source File: AbstractReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
void processOperationDecorator(Operation operation, Method method) {
    final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
    if (chain.hasNext()) {
        SwaggerExtension extension = chain.next();
        extension.decorateOperation(operation, method, chain);
    }
}
 
Example #21
Source File: AbstractReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected List<Parameter> getParameters(Type type, List<Annotation> annotations, Set<Type> typesToSkip) {
    if (!hasValidAnnotations(annotations) || isApiParamHidden(annotations)) {
        return Collections.emptyList();
    }

    Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
    List<Parameter> parameters = new ArrayList<>();
    Class<?> cls = TypeUtils.getRawType(type, type);
    LOG.debug("Looking for path/query/header/form/cookie params in " + cls);

    if (chain.hasNext()) {
        SwaggerExtension extension = chain.next();
        LOG.debug("trying extension " + extension);
        parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
    }

    if (!parameters.isEmpty()) {
        for (Parameter parameter : parameters) {
            ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations);
        }
    } else {
        LOG.debug("Looking for body params in " + cls);
        // parameters is guaranteed to be empty at this point, replace it with a mutable collection
        parameters = Lists.newArrayList();
        if (!typesToSkip.contains(type)) {
            Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
            if (param != null) {
                parameters.add(param);
            }
        }
    }
    return parameters;
}
 
Example #22
Source File: JaxrsReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void updateExtensionChain() {
    List<SwaggerExtension> extensions = new ArrayList<>();
    extensions.add(new BeanParamInjectParamExtension(this));
    extensions.add(new SwaggerJerseyJaxrs());
    extensions.add(new JaxrsParameterExtension());
    SwaggerExtensions.setExtensions(extensions);
}
 
Example #23
Source File: ExtendedSwaggerReader.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private List<Parameter> getParameters(Type type, List<Annotation> annotations) {
    final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
    if (!chain.hasNext()) {
        return Collections.emptyList();
    }
    LOGGER.debug("getParameters for " + type);
    Set<Type> typesToSkip = new HashSet<>();
    final SwaggerExtension extension = chain.next();
    LOGGER.debug("trying extension " + extension);

    final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
    if (parameters.size() > 0) {
        final List<Parameter> processed = new ArrayList<>(parameters.size());
        processed.addAll(parameters.stream().filter(parameter -> ParameterProcessor
                                                                         .applyAnnotations(swagger, parameter, type,
                                                                                           annotations) != null)
                                   .collect(Collectors.toList()));
        return processed;
    } else {
        LOGGER.debug("no parameter found, looking at body params");
        final List<Parameter> body = new ArrayList<>();
        if (!typesToSkip.contains(type)) {
            Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
            if (param != null) {
                body.add(param);
            }
        }
        return body;
    }
}
 
Example #24
Source File: Reader.java    From proteus with Apache License 2.0 5 votes vote down vote up
private void processOperationDecorator(Operation operation, Method method) {
    final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
    if (chain.hasNext()) {
        SwaggerExtension extension = chain.next();
      //  LOGGER.debug("trying to decorate operation: {}", extension);
        extension.decorateOperation(operation, method, chain);
    }
}
 
Example #25
Source File: SpringMvcApiReader.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected void updateExtensionChain() {
	List<SwaggerExtension> extensions = new ArrayList<SwaggerExtension>();
	extensions.add(new SpringSwaggerExtension(LOG));
	SwaggerExtensions.setExtensions(extensions);
}
 
Example #26
Source File: IncludedSwaggerExtensionTest.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Test
/**
 * This tests acts more like an integration test than a real unit test. It tests whether the extensions return
 * generally correct values.
 */
public void testExtractParametersReturnsEmptyList() {
    for (AbstractSwaggerExtension swaggerExtension : SWAGGER_EXTENSIONS) {
        Set<Type> typesToSkip = Collections.emptySet();
        List<Annotation> annotations = Lists.newArrayList(AnnotationBearer.class.getAnnotation(Deprecated.class));
        AbstractSwaggerExtension extension = mock(AbstractSwaggerExtension.class, CALLS_REAL_METHODS);
        doReturn(new ArrayList<Parameter>()).when(extension).extractParameters(any(), any(), any(), any());

        Iterator<SwaggerExtension> iterator = Lists.<SwaggerExtension>newArrayList(extension).iterator();

        // Not possible to add any parameters for the extensions, since no annotation / field is given to the extensions
        // only the previously created mock AbstractSwaggerExtension is in the chain
        // This allows to test if first the chain is called, and only then empty, modifiable lists are returned as last resort
        List<Parameter> parameters = swaggerExtension.extractParameters(
                annotations,
                Void.class,
                typesToSkip,
                iterator);
        // Has to return a collection we can later modify.
        try {
            parameters.add(null);
        } catch (Exception e) {
            throw new IllegalStateException("Extension "+ swaggerExtension.getClass().getName() + " did not return a modifiable list.", e);
        }

        // Test if the next extension in the chain was called
        try {
            verify(extension).extractParameters(
                    anyListOf(Annotation.class),
                    any(Type.class),
                    anySetOf(Type.class),
                    eq(iterator)
            );
        } catch (Throwable t) {
            // Catch everything here.
            // We need to output the currently tested extension here
            // so that the reason why the test failed can be easier recognized later on
            // Still need to rethrow the exception though, to make the test fail

            // TODO: Is there any better wrapper exception type?
            throw new IllegalStateException("Extension "+ swaggerExtension.getClass().getName() + " failed this Test.", t);
        }
    }
}
 
Example #27
Source File: Reader.java    From proteus with Apache License 2.0 4 votes vote down vote up
private List<Parameter> getParameters(Type type, List<Annotation> annotations, java.lang.reflect.Parameter methodParameter, List<String> pathParamNames) {
      final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
      
       
      if (!chain.hasNext()) {
          return Collections.emptyList();
      }
 
      
   //   LOGGER.debug("getParameters for {}", type);
      Set<Type> typesToSkip = new HashSet<>();
      typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerRequest.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpServerExchange.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerResponse.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpHandler.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(io.undertow.server.session.Session.class));

      final SwaggerExtension extension = chain.next();
            
      if (typesToSkip.contains(type)) {
          return Collections.emptyList();
      }
 
 
      annotations = new ArrayList<>(annotations);

       
      if(! annotations.stream().filter( a -> a instanceof ApiParam ).findFirst().isPresent() )
      {
      	annotations.add( AnnotationHelper.createApiParam( methodParameter ) ) ; 
      }
      

if(type.getTypeName().contains("java.nio.file.Path") || type.getTypeName().contains("java.nio.ByteBuffer")  || type.getTypeName().contains("java.io.File"))
      { 
	  if(type.getTypeName().contains("java.nio.file.Path") || type.getTypeName().contains("java.nio.ByteBuffer"))
      {
      	type = java.io.File.class;
      }
	
	  annotations.add(AnnotationHelper.createFormParam(methodParameter));
	  
      }

      if(annotations.size() == 1)
      {
      	if( annotations.get(0) instanceof ApiParam)
      	{ 
      	    // If there is only one ApiParam and the parameter type is a member of the java.lang and the name of that parameter is in the path operation's path make the assumption that this is a path param
      		if(methodParameter.getType().getName().indexOf("java.lang") > -1 && pathParamNames.contains(methodParameter.getName()))
      		{
      			annotations.add(AnnotationHelper.createPathParam(methodParameter));

      		}
      	    // If there is only one ApiParam and the parameter type is a member of the java.lang or java.util package we make the assumption that this is a query param
      		else if( methodParameter.getType().getName().indexOf("java.lang") > -1 || methodParameter.getType().getName().indexOf("java.util") > -1 )
      		{
      			annotations.add(AnnotationHelper.createQueryParam(methodParameter));
      		}
      	}
      }
      
      final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
      if (!parameters.isEmpty()) {
          final List<Parameter> processed = new ArrayList<Parameter>(parameters.size());
          for (Parameter parameter : parameters) {
          	
            //  LOGGER.debug("getParameters for {}", type);

              if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) {
              	
                  processed.add(parameter);
              }
          }
          return processed;
      } else {
        //  LOGGER.debug("no parameter found, looking at body params");
          final List<Parameter> body = new ArrayList<Parameter>();
          if (!typesToSkip.contains(type)) {
          	
              Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
              if (param != null) {
              	 
                  body.add(param);
              }
          }
          return body;
      }
  }