View Javadoc
1   /**
2    * This file Copyright (c) 2013-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.rest.tools;
35  
36  import info.magnolia.cms.beans.config.ServerConfiguration;
37  import info.magnolia.cms.util.CustomServletConfig;
38  import info.magnolia.context.MgnlContext;
39  import info.magnolia.event.EventBus;
40  import info.magnolia.event.SystemEventBus;
41  import info.magnolia.objectfactory.ComponentProvider;
42  import info.magnolia.rest.EndpointDefinition;
43  import info.magnolia.rest.RestDispatcherServlet;
44  import info.magnolia.rest.RestIntegrationModule;
45  import info.magnolia.rest.registry.ConfiguredEndpointDefinition;
46  import info.magnolia.rest.registry.EndpointDefinitionRegistry;
47  import info.magnolia.rest.registry.EndpointDefinitionRegistryEvent;
48  
49  import java.io.IOException;
50  import java.util.ArrayList;
51  import java.util.HashMap;
52  import java.util.List;
53  
54  import javax.inject.Inject;
55  import javax.inject.Named;
56  import javax.servlet.ServletConfig;
57  import javax.servlet.ServletException;
58  import javax.servlet.http.HttpServletRequest;
59  import javax.servlet.http.HttpServletResponse;
60  
61  import io.swagger.v3.jaxrs2.integration.OpenApiServlet;
62  import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource;
63  import io.swagger.v3.oas.integration.SwaggerConfiguration;
64  import io.swagger.v3.oas.models.OpenAPI;
65  import io.swagger.v3.oas.models.servers.Server;
66  
67  /**
68   * API-aware dispatcher of the rest requests to the dynamically registered endpoints.
69   *
70   * Additional providers needed for the API documentation are loaded in {@link info.magnolia.rest.RestDispatcherServlet}.
71   * More providers can be loaded by adding them to the configuration of {@link info.magnolia.rest.RestIntegrationModule}.
72   */
73  public class SwaggerRestDispatcherServlet extends RestDispatcherServlet {
74      
75      private static final String ENDPOINT_NAME = "openapi";
76      /**
77       * Key of object in servlet context where swagger caches data.
78       */
79      static final String SWAGGER = "swagger";
80  
81      private final RestToolsModule restToolsModule;
82      private OpenApiServlet swaggerServlet;
83      /**
84       * Indicates that endpoint definitions have changed. Swagger caches some information in the servlet context
85       * (see {@link OpenApiResource}), which we can only access (and flush) during a request. However, since notifications
86       * about changed endpoint definitions arrive independently of requests, we use this flag to keep track of 'staleness'
87       * and flush on the next request we encounter.
88       */
89      private boolean swaggerCacheIsStale = false;
90  
91      @Inject
92      public SwaggerRestDispatcherServlet(final RestIntegrationModule restIntegrationModule, final EndpointDefinitionRegistry endpointDefinitionRegistry, @Named(SystemEventBus.NAME) EventBus systemEventBus, final RestToolsModule restToolsModule, ComponentProvider componentProvider, ServerConfiguration serverConfiguration) {
93          super(restIntegrationModule, endpointDefinitionRegistry, systemEventBus, componentProvider, serverConfiguration);
94          this.restToolsModule = restToolsModule;
95      }
96  
97      @Override
98      public void init(ServletConfig servletConfig) throws ServletException {
99          super.init(servletConfig);
100 
101         initApiListing();
102 
103         swaggerServlet = new OpenApiServlet();
104         swaggerServlet.init(new CustomServletConfig("DefaultJaxrsConfig", super.getServletContext(), new HashMap<>()));
105     }
106 
107     private void initApiListing() {
108         // Register API listing resource
109         ConfiguredEndpointDefinition endpointDefinition = new ConfiguredEndpointDefinition();
110         endpointDefinition.setImplementationClass(OpenApiResource.class);
111         endpointDefinition.setName(ENDPOINT_NAME);
112         super.registerEndpoint(endpointDefinition);
113     }
114 
115     @Override
116     protected Object instantiateEndpoint(EndpointDefinition endpointDefinition) {
117         Object endpoint = super.instantiateEndpoint(endpointDefinition);
118         if (ENDPOINT_NAME.equalsIgnoreCase(endpointDefinition.getName()) && endpoint instanceof OpenApiResource) {
119             OpenAPI oas = new OpenAPI();
120             List<Server> servers = new ArrayList<>();
121             // Have to re set up again for servers url for open api
122             servers.add(new Server().url(restToolsModule.getApiBasepath()));
123             oas.servers(servers);
124             SwaggerConfiguration oasConfig = new SwaggerConfiguration()
125                     .openAPI(oas)
126                     .prettyPrint(false);
127             ((OpenApiResource) endpoint).setOpenApiConfiguration(oasConfig);
128         }
129 
130         return endpoint;
131     }
132 
133     /**
134      * Refresh doc listings after changes in endpoint config.
135      * In particular, un- and re-register the doc endpoint to create new instances in order to get rid of internal cachings,
136      * like in {@link OpenApiResource}. Then set a flag to flush additional cached data in servlet context on next opportunity.
137      */
138     private void refreshApiListing() {
139         unregisterEndpoint(ENDPOINT_NAME);
140         initApiListing();
141         swaggerCacheIsStale = true;
142     }
143 
144     @Override
145     protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
146         // Swagger caches data in context -> hack it away. Sometimes you gotta turn your swag off.
147         if (swaggerCacheIsStale) {
148             MgnlContext.getWebContext().getServletContext().removeAttribute(SWAGGER);
149             swaggerCacheIsStale = false;
150         }
151 
152         super.service(httpServletRequest, httpServletResponse);
153     }
154 
155     @Override
156     public void destroy() {
157         unregisterEndpoint(ENDPOINT_NAME);
158         super.destroy();
159         if (swaggerServlet != null) {
160             swaggerServlet.destroy();
161         }
162     }
163 
164     @Override
165     public void onEndpointRegistered(EndpointDefinitionRegistryEvent event) {
166         super.onEndpointRegistered(event);
167         refreshApiListing();
168     }
169 
170     @Override
171     public void onEndpointReregistered(EndpointDefinitionRegistryEvent event) {
172         super.onEndpointReregistered(event);
173         refreshApiListing();
174     }
175 
176     @Override
177     public void onEndpointUnregistered(EndpointDefinitionRegistryEvent event) {
178         super.onEndpointUnregistered(event);
179         refreshApiListing();
180     }
181 }