Ошибка 404 при попытке доступа к {API} /swagger.json - джерси 1.x swagger-core 1.5.8 - PullRequest
2 голосов
/ 23 января 2020

Я пытаюсь интегрировать Swagger (версия 1.5.8) в существующий REST API, который использует Джерси 1.19. Я следовал документации для реализации swagger в приложении jersey 1.x, но, что бы я ни пытался, конечная точка (localhost: 8080 / swagger. json) всегда возвращает 404.

(Отказ от ответственности: части этого кода были анонимны)

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>my.namespace</groupId>
  <artifactId>loremipsum</artifactId>
  <version>1.0.0</version>
  <packaging>war</packaging>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <version.servlet>3.1.0</version.servlet>
    <version.commons.codec>1.11</version.commons.codec>
    <version.log4j>1.2.17</version.log4j>
    <version.jersey>1.19.4</version.jersey>
    <version.openjpa>2.4.2</version.openjpa>
    <version.commons-dbcp>1.4</version.commons-dbcp>
    <version.postgresql>42.1.4.jre7</version.postgresql>
    <version.mysql>5.1.45</version.mysql>
    <version.httpclient>4.5.4</version.httpclient>
    <version.commons.net>3.6</version.commons.net>
  </properties>

  <dependencies>
    <!-- Java API -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${version.servlet}</version>
      <scope>provided</scope>
    </dependency>

    <!-- Database -->
    <dependency>
      <groupId>org.apache.openjpa</groupId>
      <artifactId>openjpa</artifactId>
      <version>${version.openjpa}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>${version.commons-dbcp}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>${version.postgresql}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${version.mysql}</version>
      <scope>runtime</scope>
    </dependency>

    <!-- Logging -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${version.log4j}</version>
      <scope>compile</scope>
    </dependency>

    <!-- Rest -->
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-servlet</artifactId>
      <version>${version.jersey}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-json</artifactId>
      <version>${version.jersey}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-server</artifactId>
      <version>${version.jersey}</version>
      <scope>compile</scope>
    </dependency>

    <!-- Util -->
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>${version.commons.codec}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>${version.httpclient}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>${version.commons.net}</version>
    </dependency>

    <!-- Swagger -->
    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-jersey-jaxrs</artifactId>
      <version>1.5.8</version>
    </dependency>

  </dependencies>

  <build>
    <sourceDirectory>${basedir}/src</sourceDirectory>
    <resources>
      <resource>
        <directory>${basedir}/config</directory>
        <excludes>
          <exclude>app.conf.default</exclude>
        </excludes>
      </resource>
      <resource>
        <directory>${basedir}/resources</directory>
      </resource>
      <resource>
        <directory>${basedir}/resources</directory>
        <includes>
          <include>version.properties</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>${maven.compiler.source}</source>
          <target>${maven.compiler.target}</target>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.openjpa</groupId>
        <artifactId>openjpa-maven-plugin</artifactId>
        <version>${version.openjpa}</version>
        <configuration>
          <includes>**/entities/*.class</includes>
          <excludes>**/entities/XML*.class</excludes>
          <addDefaultConstructor>true</addDefaultConstructor>
          <enforcePropertyRestrictions>true</enforcePropertyRestrictions>
        </configuration>
        <executions>
          <execution>
            <id>enhancer</id>
            <phase>process-classes</phase>
            <goals>
              <goal>enhance</goal>
            </goals>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>${version.openjpa}</version>
          </dependency>
        </dependencies>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warSourceDirectory>${basedir}/WebContent</warSourceDirectory>
          <attachClasses>true</attachClasses>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>tomcat-maven-plugin</artifactId>
        <version>1.1</version>
        <configuration>
          <warSourceDirectory>${basedir}/WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>

    <pluginManagement>
      <plugins>
        <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
        <plugin>
          <groupId>org.eclipse.m2e</groupId>
          <artifactId>lifecycle-mapping</artifactId>
          <version>1.0.0</version>
          <configuration>
            <lifecycleMappingMetadata>
              <pluginExecutions>
                <pluginExecution>
                  <pluginExecutionFilter>
                    <groupId>
                          org.apache.openjpa
                        </groupId>
                    <artifactId>
                          openjpa-maven-plugin
                        </artifactId>
                    <versionRange>
                          [${version.openjpa},)
                        </versionRange>
                    <goals>
                      <goal>enhance</goal>
                    </goals>
                  </pluginExecutionFilter>
                  <action>
                    <execute />
                  </action>
                </pluginExecution>
              </pluginExecutions>
            </lifecycleMappingMetadata>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

web. xml:

<?xml version="1.0" encoding="UTF-8" ?>
<web-app metadata-complete="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <display-name>my.namespace</display-name>

    <servlet>
        <servlet-name>jersey</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>
                io.swagger.jaxrs.json,
                io.swagger.jaxrs.listing,
                my.namespace.webservice,
            </param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>Jersey2Config</servlet-name>
        <servlet-class>io.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class>
        <init-param>
            <param-name>api.version</param-name>
            <param-value>1.0.0</param-value>
        </init-param>
        <init-param>
            <param-name>swagger.api.basepath</param-name>
            <param-value>http://localhost:8080/</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <!-- Filter to add Server header -->
    <filter>
        <filter-name>loremipsum - ServerInfoFilter</filter-name>
        <filter-class>my.namespace.ServerInfoFilter</filter-class>
    </filter>
    <!-- Filter to add "Server" header ("loremipsum/x.y.z") to responses -->
    <filter-mapping>
        <filter-name>loremipsum - ServerInfoFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Filter to add header for Cross-origin resource sharing -->
    <filter>
        <filter-name>loremipsum - CorsResponseFilter</filter-name>
        <filter-class>my.namespace.CorsResponseFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loremipsum - CorsResponseFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>loremipsum</filter-name>
        <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>my.namespace</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/jsp</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|webjar)/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <!-- Allows to convert POST requests to other methods via header "X-HTTP-Method-Override" 
            or parameter "_method" -->
        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
            <param-value>com.sun.jersey.api.container.filter.PostReplaceFilter</param-value>
        </init-param>
    </filter>
    <listener>
        <listener-class>my.namespace.Initializer</listener-class>
    </listener>
    <filter-mapping>
        <filter-name>loremipsum</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Ресурс класс с аннотациями:

package my.namespace.webservice;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "/example", description = "lorem ipsum")
@Path("/example")
public class ExampleResource {

  /**
   * Retrieves data
   */
  @Path("{idString}")
  @GET
  @Produces({"application/xml,application/json"})
  @ApiOperation(value = "gets some value by id")
  public Response dataResponse(@Context HttpServletRequest req,
          @PathParam("idString") String idString,
          @QueryParam("_format") String format,
          @QueryParam("_pretty") String pretty) {

     // some code
  }


...

}

Приложение работает в контейнере docker, который регистрирует, что подразумевается наличие ресурсов во время выполнения

23-Jan-2020 15:38:11.606 INFO [http-nio-8080-exec-1] com.sun.jersey.api.core.ScanningResourceConfig.logClasses Root resource classes found:
  class my.namespace.webservice.ExampleResource
23-Jan-2020 15:38:11.608 INFO [http-nio-8080-exec-1] com.sun.jersey.api.core.ScanningResourceConfig.logClasses Provider classes found:
  class io.swagger.jaxrs.listing.SwaggerSerializers
  class my.namespace.webservice.TokenMessageBodyWriter
23-Jan-2020 15:38:11.624 INFO [http-nio-8080-exec-1] com.sun.jersey.server.impl.application.WebApplicationImpl._initiate Initiating Jersey application, version 'Jersey: 1.19.4 05/24/2017 03:20 PM'

Ресурсы находятся в my.namespace.webservice . Также нигде не определен @ApplicationPath, поэтому, если я правильно понимаю, я смогу получить чванство. json, вызвав localhost: 8080 / swagger. json.

Любые указатели в правильном направлении были бы очень полезны!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...