aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/com/vaadin/server/communication/PushRequestHandler.java
blob: ce3b39997339eda4a8a1a6549fce396a180f6b43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
 * Copyright 2000-2016 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.vaadin.server.communication;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.atmosphere.cache.UUIDBroadcasterCache;
import org.atmosphere.client.TrackMessageSizeInterceptor;
import org.atmosphere.cpr.ApplicationConfig;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereFramework.AtmosphereHandlerWrapper;
import org.atmosphere.cpr.AtmosphereHandler;
import org.atmosphere.cpr.AtmosphereInterceptor;
import org.atmosphere.cpr.AtmosphereRequestImpl;
import org.atmosphere.cpr.AtmosphereResponseImpl;
import org.atmosphere.interceptor.HeartbeatInterceptor;
import org.atmosphere.util.VoidAnnotationProcessor;

import com.vaadin.server.RequestHandler;
import com.vaadin.server.ServiceDestroyEvent;
import com.vaadin.server.ServiceException;
import com.vaadin.server.ServletPortletHelper;
import com.vaadin.server.SessionExpiredHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinServletRequest;
import com.vaadin.server.VaadinServletResponse;
import com.vaadin.server.VaadinServletService;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.communication.PushConstants;

/**
 * Handles requests to open a push (bidirectional) communication channel between
 * the client and the server. After the initial request, communication through
 * the push channel is managed by {@link PushAtmosphereHandler} and
 * {@link PushHandler}
 *
 * @author Vaadin Ltd
 * @since 7.1
 */
public class PushRequestHandler
        implements RequestHandler, SessionExpiredHandler {

    private AtmosphereFramework atmosphere;
    private PushHandler pushHandler;

    public PushRequestHandler(VaadinServletService service)
            throws ServiceException {

        service.addServiceDestroyListener((ServiceDestroyEvent event) -> {
            destroy();
        });

        final ServletConfig vaadinServletConfig = service.getServlet()
                .getServletConfig();

        pushHandler = createPushHandler(service);

        atmosphere = getPreInitializedAtmosphere(vaadinServletConfig);
        if (atmosphere == null) {
            // Not initialized by JSR356WebsocketInitializer
            getLogger().fine("Initializing Atmosphere for servlet "
                    + vaadinServletConfig.getServletName());
            try {
                atmosphere = initAtmosphere(vaadinServletConfig);
            } catch (Exception e) {
                getLogger().log(Level.WARNING,
                        "Failed to initialize Atmosphere for "
                                + service.getServlet().getServletName()
                                + ". Push will not work.",
                        e);
                return;
            }
        } else {
            getLogger().fine("Using pre-initialized Atmosphere for servlet "
                    + vaadinServletConfig.getServletName());
        }
        pushHandler.setLongPollingSuspendTimeout(
                atmosphere.getAtmosphereConfig().getInitParameter(
                        com.vaadin.server.Constants.SERVLET_PARAMETER_PUSH_SUSPEND_TIMEOUT_LONGPOLLING,
                        -1));
        for (AtmosphereHandlerWrapper handlerWrapper : atmosphere
                .getAtmosphereHandlers().values()) {
            AtmosphereHandler handler = handlerWrapper.atmosphereHandler;
            if (handler instanceof PushAtmosphereHandler) {
                // Map the (possibly pre-initialized) handler to the actual push
                // handler
                ((PushAtmosphereHandler) handler).setPushHandler(pushHandler);
            }

        }
    }

    /**
     * Creates a push handler for this request handler.
     * <p>
     * Create your own request handler and override this method if you want to
     * customize the {@link PushHandler}, e.g. to dynamically decide the suspend
     * timeout.
     *
     * @since 7.6
     * @param service
     *            the vaadin service
     * @return the push handler to use for this service
     */
    protected PushHandler createPushHandler(VaadinServletService service) {
        return new PushHandler(service);
    }

    private static final Logger getLogger() {
        return Logger.getLogger(PushRequestHandler.class.getName());
    }

    /**
     * Returns an AtmosphereFramework instance which was initialized in the
     * servlet context init phase by {@link JSR356WebsocketInitializer}, if such
     * exists
     */
    private AtmosphereFramework getPreInitializedAtmosphere(
            ServletConfig vaadinServletConfig) {
        String attributeName = JSR356WebsocketInitializer
                .getAttributeName(vaadinServletConfig.getServletName());
        Object framework = vaadinServletConfig.getServletContext()
                .getAttribute(attributeName);
        if (framework != null && framework instanceof AtmosphereFramework) {
            return (AtmosphereFramework) framework;
        }

        return null;
    }

    /**
     * Initializes Atmosphere for the given ServletConfiguration
     *
     * @since 7.5.0
     * @param vaadinServletConfig
     *            The servlet configuration for the servlet which should have
     *            Atmosphere support
     */
    static AtmosphereFramework initAtmosphere(
            final ServletConfig vaadinServletConfig) {
        AtmosphereFramework atmosphere = new AtmosphereFramework(false, false) {
            @Override
            protected void analytics() {
                // Overridden to disable version number check
            }

            @Override
            public AtmosphereFramework addInitParameter(String name,
                    String value) {
                if (vaadinServletConfig.getInitParameter(name) == null) {
                    super.addInitParameter(name, value);
                }
                return this;
            }
        };

        atmosphere.addAtmosphereHandler("/*", new PushAtmosphereHandler());
        atmosphere.addInitParameter(ApplicationConfig.BROADCASTER_CACHE,
                UUIDBroadcasterCache.class.getName());
        atmosphere.addInitParameter(ApplicationConfig.ANNOTATION_PROCESSOR,
                VoidAnnotationProcessor.class.getName());
        atmosphere.addInitParameter(ApplicationConfig.PROPERTY_SESSION_SUPPORT,
                "true");
        atmosphere.addInitParameter(ApplicationConfig.MESSAGE_DELIMITER,
                String.valueOf(PushConstants.MESSAGE_DELIMITER));
        atmosphere.addInitParameter(
                ApplicationConfig.DROP_ACCESS_CONTROL_ALLOW_ORIGIN_HEADER,
                "false");
        // Disable heartbeat (it does not emit correct events client side)
        // https://github.com/Atmosphere/atmosphere-javascript/issues/141
        atmosphere.addInitParameter(
                ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTORS,
                HeartbeatInterceptor.class.getName());

        final String bufferSize = String
                .valueOf(PushConstants.WEBSOCKET_BUFFER_SIZE);
        atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE,
                bufferSize);
        atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE,
                bufferSize);
        atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE,
                bufferSize);
        atmosphere.addInitParameter(
                ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL,
                "false");
        // This prevents Atmosphere from recreating a broadcaster after it has
        // already been destroyed when the servlet is being undeployed
        // (see #20026)
        atmosphere.addInitParameter(ApplicationConfig.RECOVER_DEAD_BROADCASTER,
                "false");
        // Disable Atmosphere's message about commercial support
        atmosphere.addInitParameter("org.atmosphere.cpr.showSupportMessage",
                "false");

        try {
            atmosphere.init(vaadinServletConfig);

            // Ensure the client-side knows how to split the message stream
            // into individual messages when using certain transports
            AtmosphereInterceptor trackMessageSize = new TrackMessageSizeInterceptor();
            trackMessageSize.configure(atmosphere.getAtmosphereConfig());
            atmosphere.interceptor(trackMessageSize);
        } catch (ServletException e) {
            throw new RuntimeException("Atmosphere init failed", e);
        }
        return atmosphere;
    }

    @Override
    public boolean handleRequest(VaadinSession session, VaadinRequest request,
            VaadinResponse response) throws IOException {

        if (!ServletPortletHelper.isPushRequest(request)) {
            return false;
        }

        if (request instanceof VaadinServletRequest) {
            if (atmosphere == null) {
                response.sendError(500,
                        "Atmosphere initialization failed. No push available.");
                return true;
            }
            try {
                atmosphere.doCometSupport(
                        AtmosphereRequestImpl
                                .wrap((VaadinServletRequest) request),
                        AtmosphereResponseImpl
                                .wrap((VaadinServletResponse) response));
            } catch (ServletException e) {
                // TODO PUSH decide how to handle
                throw new RuntimeException(e);
            }
        } else {
            throw new IllegalArgumentException(
                    "Portlets not currently supported");
        }

        return true;
    }

    public void destroy() {
        atmosphere.destroy();
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.vaadin.server.SessionExpiredHandler#handleSessionExpired(com.vaadin
     * .server.VaadinRequest, com.vaadin.server.VaadinResponse)
     */
    @Override
    public boolean handleSessionExpired(VaadinRequest request,
            VaadinResponse response) throws IOException {
        // Websockets request must be handled by accepting the websocket
        // connection and then sending session expired so we let
        // PushRequestHandler handle it
        return handleRequest(null, request, response);
    }
}