-
Notifications
You must be signed in to change notification settings - Fork 160
/
JavaScriptBootstrapHandler.java
328 lines (285 loc) · 12.3 KB
/
JavaScriptBootstrapHandler.java
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
* Copyright 2000-2023 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.flow.server.communication;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.HttpURLConnection;
import java.util.Optional;
import java.util.function.Function;
import com.vaadin.flow.component.PushConfiguration;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.function.DeploymentConfiguration;
import com.vaadin.flow.internal.BootstrapHandlerHelper;
import com.vaadin.flow.internal.DevModeHandler;
import com.vaadin.flow.internal.DevModeHandlerManager;
import com.vaadin.flow.internal.UsageStatistics;
import com.vaadin.flow.router.InvalidLocationException;
import com.vaadin.flow.router.Location;
import com.vaadin.flow.router.LocationUtil;
import com.vaadin.flow.router.QueryParameters;
import com.vaadin.flow.server.AppShellRegistry;
import com.vaadin.flow.server.BootstrapHandler;
import com.vaadin.flow.server.HandlerHelper;
import com.vaadin.flow.server.Mode;
import com.vaadin.flow.server.HandlerHelper.RequestType;
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.VaadinResponse;
import com.vaadin.flow.server.VaadinService;
import com.vaadin.flow.server.VaadinServletRequest;
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.shared.ApplicationConstants;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
import elemental.json.impl.JsonUtil;
import static com.vaadin.flow.component.UI.SERVER_ROUTING;
/**
* Processes a 'start' request type from the client to initialize server session
* and UI. It returns a JSON response with everything needed to bootstrap flow
* views.
* <p>
* The handler is for client driven projects where `index.html` does not contain
* bootstrap data. Bootstrapping is the responsibility of the `@vaadin/flow`
* client that is able to ask the server side to create the vaadin session and
* do the bootstrapping lazily.
* <p>
* For internal use only. May be renamed or removed in a future release.
*
*/
public class JavaScriptBootstrapHandler extends BootstrapHandler {
/**
* Custom BootstrapContext for {@link JavaScriptBootstrapHandler}.
*/
public static class JavaScriptBootstrapContext extends BootstrapContext {
/**
* Creates a new context instance using the given parameters.
*
* @param request
* the request object
* @param response
* the response object
* @param ui
* the UI object
* @param callback
* a callback that is invoked to resolve the context root
* from the request
*/
public JavaScriptBootstrapContext(VaadinRequest request,
VaadinResponse response, UI ui,
Function<VaadinRequest, String> callback) {
super(request, response, ui.getInternals().getSession(), ui,
callback, JavaScriptBootstrapContext::initRoute);
}
private static Location initRoute(VaadinRequest request) {
// This can be called in two ways:
// 1. From the JS during the second phase of a two phase init. In
// this case, the
// location is included in the REQUEST_LOCATION_PARAMETER and the
// request always
// goes to the servlet path
// 2. During the first request if eagerServerLoad is enabled. In
// this case, the
// location comes from the pathinfo + query parameters in the
// request
String path = request.getParameter(
ApplicationConstants.REQUEST_LOCATION_PARAMETER);
String params = request
.getParameter(ApplicationConstants.REQUEST_QUERY_PARAMETER);
if (path != null) {
return new Location(path, QueryParameters.fromString(params));
}
// Case 2, use the request
if (request instanceof VaadinServletRequest) {
return new Location(request.getPathInfo(),
QueryParameters
.fromString(((VaadinServletRequest) request)
.getQueryString()));
} else {
return new Location(request.getPathInfo(),
QueryParameters.empty());
}
}
}
/**
* Creates a new bootstrap handler with default page builder.
*/
public JavaScriptBootstrapHandler() {
super(context -> null);
}
@Override
protected boolean canHandleRequest(VaadinRequest request) {
return HandlerHelper.isRequestType(request, RequestType.INIT)
&& isServletRootRequest(request);
}
private boolean isServletRootRequest(VaadinRequest request) {
String pathInfo = request.getPathInfo();
return pathInfo == null || "".equals(pathInfo) || "/".equals(pathInfo);
}
protected String getRequestUrl(VaadinRequest request) {
return ((VaadinServletRequest) request).getRequestURL().toString();
}
@Override
protected BootstrapContext createAndInitUI(Class<? extends UI> uiClass,
VaadinRequest request, VaadinResponse response,
VaadinSession session) {
BootstrapContext context = super.createAndInitUI(UI.class, request,
response, session);
JsonObject config = context.getApplicationParameters();
String requestURL = getRequestUrl(request);
PushConfiguration pushConfiguration = context.getUI()
.getPushConfiguration();
pushConfiguration.setPushServletMapping(
BootstrapHandlerHelper.determinePushServletMapping(session));
AppShellRegistry registry = AppShellRegistry
.getInstance(session.getService().getContext());
registry.modifyPushConfiguration(pushConfiguration);
config.put("requestURL", requestURL);
addLinkTagForTheme(session);
return context;
}
@Override
protected void initializeUIWithRouter(BootstrapContext context, UI ui) {
if (context.getRequest().getParameter("serverSideRouting") != null) {
// App is using classic server-routing, set a session attribute
// to know that in future navigation calls
ui.getSession().setAttribute(SERVER_ROUTING, Boolean.TRUE);
ui.getInternals().getRouter().initializeUI(ui, context.getRoute());
}
}
@Override
protected BootstrapContext createBootstrapContext(VaadinRequest request,
VaadinResponse response, UI ui,
Function<VaadinRequest, String> callback) {
return new JavaScriptBootstrapContext(request, response, ui, callback);
}
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
VaadinRequest request, VaadinResponse response) throws IOException {
try {
// #9443 Use error code 400 for bad location and don't create UI
// Normally caught by IndexHtmlRequestHandler, but checking here too
// for handcrafted requests
String pathAndParams = request.getParameter(
ApplicationConstants.REQUEST_LOCATION_PARAMETER);
if (pathAndParams == null) {
throw new InvalidLocationException(
"Location parameter missing from bootstrap request to server.");
}
LocationUtil.parsePathToSegments(pathAndParams, false);
} catch (InvalidLocationException invalidLocationException) {
response.sendError(400, "Invalid location: "
+ invalidLocationException.getMessage());
return true;
}
HandlerHelper.setResponseNoCacheHeaders(response::setHeader,
response::setDateHeader);
writeResponse(response, getInitialJson(request, response, session));
return true;
}
/**
* Gets the service URL as a URL relative to the request URI.
*
* @param vaadinRequest
* the request
* @return the relative service URL
*/
protected static String getServiceUrl(VaadinRequest vaadinRequest) {
return BootstrapHandlerHelper.getServiceUrl(vaadinRequest);
}
private JsonObject getStats() {
JsonObject stats = Json.createObject();
UsageStatistics.getEntries().forEach(entry -> {
String name = entry.getName();
String version = entry.getVersion();
JsonObject json = Json.createObject();
json.put("is", name);
json.put("version", version);
String escapedName = Json.create(name).toJson();
stats.put(escapedName, json);
});
return stats;
}
private JsonValue getErrors(VaadinService service) {
JsonObject errors = Json.createObject();
Optional<DevModeHandler> devModeHandler = DevModeHandlerManager
.getDevModeHandler(service);
if (devModeHandler.isPresent()) {
String errorMsg = devModeHandler.get().getFailedOutput();
if (errorMsg != null) {
errors.put("webpack-dev-server", errorMsg);
}
}
return errors.keys().length > 0 ? errors : Json.createNull();
}
private void writeResponse(VaadinResponse response, JsonObject json)
throws IOException {
response.setContentType("application/json");
response.setStatus(HttpURLConnection.HTTP_OK);
response.getOutputStream()
.write(JsonUtil.stringify(json).getBytes("UTF-8"));
}
/**
* Returns the JSON object with the application config and UIDL info that
* can be used in the bootstrapper to embed that info in the initial page.
*
* @param request
* the vaadin request.
* @param response
* the response.
* @param session
* the vaadin session.
* @return the initial application JSON.
*/
protected JsonObject getInitialJson(VaadinRequest request,
VaadinResponse response, VaadinSession session) {
BootstrapContext context = createAndInitUI(UI.class, request, response,
session);
JsonObject initial = Json.createObject();
boolean productionMode = context.getSession().getConfiguration()
.isProductionMode();
JsonObject appConfig = context.getApplicationParameters();
appConfig.put("productionMode", Json.create(productionMode));
appConfig.put("appId", context.getAppId());
appConfig.put("uidl", getInitialUidl(context.getUI()));
initial.put("appConfig", appConfig);
if (context.getPushMode().isEnabled()) {
initial.put("pushScript", getPushScript(context));
}
if (!session.getConfiguration().isProductionMode()) {
initial.put("stats", getStats());
}
initial.put("errors", getErrors(request.getService()));
return initial;
}
private static void addLinkTagForTheme(VaadinSession session) {
DeploymentConfiguration deploymentConfiguration = session
.getConfiguration();
if (deploymentConfiguration.getMode() == Mode.DEVELOPMENT_BUNDLE) {
try {
BootstrapHandler
.getStylesheetLinks(deploymentConfiguration,
"styles.css")
.forEach(link -> UI.getCurrent().getPage().executeJs(
BootstrapHandler.SCRIPT_TEMPLATE_FOR_STYLESHEET_LINK_TAG,
link));
} catch (IOException e) {
throw new UncheckedIOException(
"Failed to add a link tag for 'styles.css' to the document",
e);
}
}
}
}