无法使用dropwizard应用程序与swagger-ui一起工作

时间:2015-05-10 19:21:39

标签: dropwizard swagger-ui

我很难让Swagger UI与我的dropwizard应用程序一起工作。带注释的dropwizard应用程序似乎生成了正确的json文档,但是swagger UI无法正确导航它。 主要API页面,生成于http://localhost:8080/v1/TimeService/api-docs

{"apiVersion":"0.0","swaggerVersion":"1.2","apis":[{"path":"/times"}]}

Swagger正确显示该页面。 在http://localhost:8080/v1/TimeService/api-docs/times生成的时间资源的详细信息:

{"apiVersion":"0.0","swaggerVersion":"1.2","basePath":"/v1/TimeService/*","resourcePath":"/times","produces":["application/json"],"apis":[{"path":"/times/","operations":[{"method":"GET","summary":"Retrieves time for given","notes":"timezone parameter is optional, defaults to GMT","type":"array","items":{"$ref":"Time"},"nickname":"getTime","parameters":[{"name":"timezone","description":"timezone","required":false,"items":{"type":"string"},"paramType":"query","allowMultiple":false}]}]}],"models":{"Time":{"id":"Time","properties":{"time":{"type":"string"}}}}}

这对我来说很好看。但无论何时,在虚张声势的用户界面中,我都会点击任何"次"超链接显示详细信息,没有任何反应。看起来swagger ui无法正确解析链接。

我的注释资源,TimeResource.java:

package com.cgi.saas.bluprint;

import com.google.common.base.Optional;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@Path("/times")
@Produces(MediaType.APPLICATION_JSON)
@Api("/times")
public class TimeResource {
    private final String defaultTimezone;

    public TimeResource(String defaultTimezone) {
        this.defaultTimezone = defaultTimezone;
    }

    @GET
    @ApiOperation(value = "Retrieves time for given",
    notes = "timezone parameter is optional, defaults to GMT",
    response = Time.class,
    responseContainer = "List")
    @Path("/")
    public Time getTime(@ApiParam(value="timezone") @QueryParam("timezone") Optional<String> timezone) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone timeZone = TimeZone.getTimeZone(timezone.or(defaultTimezone));
        formatter.setTimeZone(timeZone);
        String formatted = formatter.format(new Date());
        return new Time(formatted);
    }
}

主服务类TimeService.java:

package com.cgi.saas.bluprint;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration.Dynamic;

import org.eclipse.jetty.servlets.CrossOriginFilter;

import com.wordnik.swagger.config.ConfigFactory;
import com.wordnik.swagger.config.ScannerFactory;
import com.wordnik.swagger.config.SwaggerConfig;
import com.wordnik.swagger.jaxrs.config.DefaultJaxrsScanner;
import com.wordnik.swagger.jaxrs.listing.ApiDeclarationProvider;
import com.wordnik.swagger.jaxrs.listing.ApiListingResourceJSON;
import com.wordnik.swagger.jaxrs.listing.ResourceListingProvider;
import com.wordnik.swagger.jaxrs.reader.DefaultJaxrsApiReader;
import com.wordnik.swagger.reader.ClassReaders;

import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.server.DefaultServerFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;



public class TimeService extends Application<TimezoneConfiguration> {

    private void configureCors(Environment environment) {
        final Dynamic filter = environment.servlets().addFilter("CORS",
                CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        filter.setInitParameter("allowedHeaders",
        "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filter.setInitParameter("allowCredentials", "true");
    }

    public static void main(String[] args) throws Exception {
        new TimeService().run(args);
    }


    public void initialize(Bootstrap<TimezoneConfiguration> timezoneConfigurationBootstrap) {
        timezoneConfigurationBootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
        timezoneConfigurationBootstrap.addBundle(new AssetsBundle("/assets/swagger", "/swagger", "index.html", "swagger"));
    }

    @Override
    public void run(TimezoneConfiguration appConfig, Environment environment) throws Exception {

        DefaultServerFactory sf = (DefaultServerFactory) appConfig.getServerFactory();
        String rootPath = "/v1/" + appConfig.getDeployName() + "/*";
        sf.setJerseyRootPath(rootPath);

        configureCors(environment);     

        String defaultTimezone = appConfig.getDefaultTimezone();
        TimeResource timeResource = new TimeResource(defaultTimezone);

        environment.jersey().register(timeResource);
        // Swagger Resource
        environment.jersey().register(new ApiListingResourceJSON());

        // Swagger providers
        environment.jersey().register(new ApiDeclarationProvider());
        environment.jersey().register(new ResourceListingProvider());

        // Swagger Scanner, which finds all the resources for @Api Annotations
        ScannerFactory.setScanner(new DefaultJaxrsScanner());

        // Add the reader, which scans the resources and extracts the resource information
        ClassReaders.setReader(new DefaultJaxrsApiReader());

        // Set the swaggeonfigurationBootstrap
        final SwaggerConfig swConfig = ConfigFactory.config();

        swConfig.setBasePath(rootPath);
    }
}

我的pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cgi.saas.bluprint</groupId>
    <artifactId>Application2</artifactId>
    <version>1.0</version>

    <repositories>
        <repository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus Snapshots</name>
            <url>http://oss.sonatype.org/content/repositories/snapshots</url>
        </repository>
    </repositories>

    <properties>
        <dropwizard.version>0.9.0-SNAPSHOT</dropwizard.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-core</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-assets</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-jersey</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>


        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-jaxrs_2.10</artifactId>
            <version>1.3.10</version>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.module</groupId>
                    <artifactId>jackson-module-scala_2.10</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.3.10</version>
        </dependency>               
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.cgi.saas.bluprint.TimeService</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

1 个答案:

答案 0 :(得分:0)

重写如下:

  1. https://github.com/swagger-api/swagger-ui.git

  2. 克隆了最新最好的swagger-ui版本
  3. 在src / main / resources / swagger / assets下复制dist

  4. 更新了pom.xml:

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>
    <dependency>
        <groupId>io.federecio</groupId>
        <artifactId>dropwizard-swagger</artifactId>
        <version>0.6</version>
    </dependency>               
    
  5. 更新了TimeService.java:

     import java.util.EnumSet;
    
     import javax.servlet.DispatcherType;
    
     import javax.servlet.FilterRegistration.Dynamic;
    
     import org.eclipse.jetty.servlets.CrossOriginFilter;
    
     import io.dropwizard.Application;
    
     import io.dropwizard.server.DefaultServerFactory;
    
     import io.dropwizard.setup.Bootstrap;
    
     import io.dropwizard.setup.Environment;
    
     import io.federecio.dropwizard.swagger.SwaggerDropwizard;
    
    
    
    
    public class TimeService extends Application<TimezoneConfiguration> {
    
    
    private final SwaggerDropwizard swaggerDropwizard = new SwaggerDropwizard();
    
    private void configureCors(Environment environment) {
        final Dynamic filter = environment.servlets().addFilter("CORS",
                CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        filter.setInitParameter("allowedHeaders",
                "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filter.setInitParameter("allowCredentials", "true");
    }
    
    public static void main(String[] args) throws Exception {
        new TimeService().run(args);
    }
    
    
    public void initialize(Bootstrap<TimezoneConfiguration> timezoneConfigurationBootstrap) {
        swaggerDropwizard.onInitialize(timezoneConfigurationBootstrap);
    }
    
    @Override
    public void run(TimezoneConfiguration appConfig, Environment environment) throws Exception {
    
        DefaultServerFactory sf = (DefaultServerFactory) appConfig.getServerFactory();
        String rootPath = "/v1/" + appConfig.getDeployName() + "/*";
        sf.setJerseyRootPath(rootPath);
    
        configureCors(environment);     
    
        String defaultTimezone = appConfig.getDefaultTimezone();
        TimeResource timeResource = new TimeResource(defaultTimezone);        
        environment.jersey().register(timeResource);
    
        swaggerDropwizard.onRun(appConfig, environment, "localhost");
    }
    

    }

    1. swagger ui可在http://localhost:8080/v1/TimeService/swagger
    2. 获得