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.objectfactory.Components;
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.HashMap;
51  
52  import javax.inject.Inject;
53  import javax.inject.Named;
54  import javax.servlet.ServletConfig;
55  import javax.servlet.ServletException;
56  import javax.servlet.http.HttpServletRequest;
57  import javax.servlet.http.HttpServletResponse;
58  
59  import io.swagger.jaxrs.config.DefaultJaxrsConfig;
60  import io.swagger.jaxrs.listing.ApiListingResource;
61  
62  /**
63   * API-aware dispatcher of the rest requests to the dynamically registered endpoints.
64   *
65   * Additional providers needed for the API documentation are loaded in {@link info.magnolia.rest.RestDispatcherServlet}.
66   * More providers can be loaded by adding them to the configuration of {@link info.magnolia.rest.RestIntegrationModule}.
67   */
68  public class SwaggerRestDispatcherServlet extends RestDispatcherServlet {
69  
70      private final static String PARAMETER_API_VERSION = "api.version";
71      private final static String PARAMETER_API_BASEPATH = "swagger.api.basepath";
72      private static final String ENDPOINT_NAME = "api-listing-resource-json";
73      /**
74       * Key of object in servlet context where swagger caches data.
75       */
76      static final String SWAGGER = "swagger";
77  
78      private final RestToolsModule restToolsModule;
79      private DefaultJaxrsConfig config;
80      /**
81       * Indicates that endpoint definitions have changed. Swagger caches some information in the servlet context
82       * (see {@link ApiListingResource}), which we can only access (and flush) during a request. However, since notifications
83       * about changed endpoint definitions arrive independently of requests, we use this flag to keep track of 'staleness'
84       * and flush on the next request we encounter.
85       */
86      private boolean swaggerCacheIsStale = false;
87  
88      @Inject
89      public SwaggerRestDispatcherServlet(final RestIntegrationModule restIntegrationModule, final EndpointDefinitionRegistry endpointDefinitionRegistry, @Named(SystemEventBus.NAME) EventBus systemEventBus, final RestToolsModule restToolsModule, ComponentProvider componentProvider, ServerConfiguration serverConfiguration) {
90          super(restIntegrationModule, endpointDefinitionRegistry, systemEventBus, componentProvider, serverConfiguration);
91          this.restToolsModule = restToolsModule;
92      }
93  
94      /**
95       * @deprecated since 2.0 – use {@link SwaggerRestDispatcherServlet#SwaggerRestDispatcherServlet(RestIntegrationModule, EndpointDefinitionRegistry, EventBus, RestToolsModule, ComponentProvider)} instead.
96       */
97      @Deprecated
98      public SwaggerRestDispatcherServlet(final RestIntegrationModule restIntegrationModule, final EndpointDefinitionRegistry endpointDefinitionRegistry, @Named(SystemEventBus.NAME) EventBus systemEventBus, final RestToolsModule restToolsModule) {
99          this(restIntegrationModule, endpointDefinitionRegistry, systemEventBus, restToolsModule, Components.getComponentProvider(), Components.getComponent(ServerConfiguration.class));
100     }
101 
102     @Override
103     public void init(ServletConfig servletConfig) throws ServletException {
104         super.init(servletConfig);
105 
106         initApiListing();
107 
108         config = new DefaultJaxrsConfig();
109         HashMap<String, String> initParameters = new HashMap<String, String>();
110         initParameters.put(PARAMETER_API_VERSION, restToolsModule.getApiVersion());
111         initParameters.put(PARAMETER_API_BASEPATH, restToolsModule.getApiBasepath());
112         config.init(new CustomServletConfig("DefaultJaxrsConfig", super.getServletContext(), initParameters));
113     }
114 
115     private void initApiListing() {
116         // Register API listing resource
117         ConfiguredEndpointDefinition endpointDefinition = new ConfiguredEndpointDefinition();
118         endpointDefinition.setImplementationClass(ApiListingResource.class);
119         endpointDefinition.setName(ENDPOINT_NAME);
120         super.registerEndpoint(endpointDefinition);
121     }
122 
123     /**
124      * Refresh doc listings after changes in endpoint config.
125      * In particular, un- and re-register the doc endpoint to create new instances in order to get rid of internal cachings,
126      * like in {@link ApiListingResource}. Then set a flag to flush additional cached data in servlet context on next opportunity.
127      */
128     private void refreshApiListing() {
129         unregisterEndpoint(ENDPOINT_NAME);
130         initApiListing();
131         swaggerCacheIsStale = true;
132     }
133 
134     @Override
135     protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
136         // Swagger caches data in context -> hack it away. Sometimes you gotta turn your swag off.
137         if (swaggerCacheIsStale) {
138             MgnlContext.getWebContext().getServletContext().removeAttribute(SWAGGER);
139             swaggerCacheIsStale = false;
140         }
141 
142         super.service(httpServletRequest, httpServletResponse);
143     }
144 
145     @Override
146     public void destroy() {
147         unregisterEndpoint(ENDPOINT_NAME);
148         super.destroy();
149         if (config != null) {
150             config.destroy();
151         }
152     }
153 
154     @Override
155     public void onEndpointRegistered(EndpointDefinitionRegistryEvent event) {
156         super.onEndpointRegistered(event);
157         refreshApiListing();
158     }
159 
160     @Override
161     public void onEndpointReregistered(EndpointDefinitionRegistryEvent event) {
162         super.onEndpointReregistered(event);
163         refreshApiListing();
164     }
165 
166     @Override
167     public void onEndpointUnregistered(EndpointDefinitionRegistryEvent event) {
168         super.onEndpointUnregistered(event);
169         refreshApiListing();
170     }
171 }