Redirecting to swagger-ui from JAX-RS, v2


@Path("/swagger")
public class SwaggerResource {

    @GET
    @Path("/json")
    @Produces({MediaType.APPLICATION_JSON})
    public Response readJson() throws IOException {
        try (InputStream resource
                = getClass().getResourceAsStream("/swagger.json");
             final JsonReader reader = Json.createReader(resource)) {
            final JsonObject object = reader.readObject();
            final JsonObjectBuilder builder = Json.createObjectBuilder();
            object.entrySet().stream()
                    .filter(e -> !e.getKey().equals("host")
                                 && !e.getKey().equals("basePath")
                                 && !e.getKey().equals("schemes"))
                    .forEach(e -> builder.add(e.getKey(), e.getValue()));
            builder.add("host", uriInfo.getBaseUri().getAuthority());
            builder.add("basePath", servletContext.getContextPath()
                                    + Application_.APPLICATION_PATH);
            builder.add("schemes", Json.createArrayBuilder()
                        .add(uriInfo.getBaseUri().getScheme()));
            return Response.ok((StreamingOutput) output -> {
                try (JsonWriter writer = Json.createWriter(output)) {
                    writer.writeObject(builder.build());
                }
            }).build();
        }
    }

    @GET
    @Path("/ui")
    public Response readUi() throws IOException {
        final URI json
                = uriInfo.getBaseUriBuilder()
                .path("swagger")
                .path("json")
                .build();
        final URI swaggerUi
                = UriBuilder.fromUri(servletContext.getContextPath())
                .path("swagger-ui")
                .path("index.html")
                .queryParam("url", json).build();
        return Response.seeOther(swaggerUi).build();
    }

    @Context
    private UriInfo uriInfo;

    @Context
    private ServletContext servletContext;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s