static void doSetCacheTime(VaadinResponse response, long milliseconds) { if (milliseconds <= 0) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); } else { response.setHeader("Cache-Control", "max-age=" + milliseconds / 1000); response.setDateHeader("Expires", System.currentTimeMillis() + milliseconds); // Required to apply caching in some Tomcats response.setHeader("Pragma", "cache"); } }
private void writeBootstrapPage(VaadinResponse response, String html) throws IOException { response.setContentType( ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(response.getOutputStream(), UTF_8))) { writer.append(html); } }
protected void writeError(VaadinResponse response, Throwable e) throws IOException { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage()); }
/** * Commit the JSON response. We can't write immediately to the output stream * as we want to write only a critical notification if something goes wrong * during the response handling. * * @param request * The request that resulted in this response * @param response * The response to write to * @param json * The JSON to write * @return true if the JSON was written successfully, false otherwise * @throws IOException * If there was an exception while writing to the output */ static boolean commitJsonResponse(VaadinRequest request, VaadinResponse response, String json) throws IOException { // The response was produced without errors so write it to the client response.setContentType(JsonConstants.JSON_CONTENT_TYPE); // Response might contain sensitive information, so prevent all forms of // caching response.setNoCacheHeaders(); byte[] b = json.getBytes(UTF_8); response.setContentLength(b.length); OutputStream outputStream = response.getOutputStream(); outputStream.write(b); // NOTE GateIn requires the buffers to be flushed to work outputStream.flush(); return true; }
if (StringUtils.isNotEmpty(errorMessage)) { log.warn(errorMessage); response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage); return false; response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); log.warn(msg); return false; response.setContentType(mimeType != null ? mimeType : FileTypesHelper.DEFAULT_MIME_TYPE); ? "max-age=" + String.valueOf(resourceCacheTime) : "public, max-age=0, no-cache, no-store, must-revalidate"; response.setHeader("Cache-Control", cacheControl); response.setDateHeader("Expires", expires); response.setDateHeader("Last-Modified", lastModifiedTime); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; copy(inputStream, response.getOutputStream());
throws IOException { if (getParameter("Location") != null) { response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", getParameter("Location")); return; response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; try { response.setContentType(getContentType()); response.setCacheTime(getCacheTime()); while (i.hasNext()) { final String param = i.next(); response.setHeader(param, getParameter(param)); response.setHeader(CONTENT_DISPOSITION, contentDisposition); int bytesRead = 0; out = response.getOutputStream();
ApplicationConstants.PUBLISHED_FILE_PATH.length() + 2); final String mimetype = response.getService().getMimeType(fileName); .warning("Published file request starting with / rejected: " + fileName); response.sendError(HttpServletResponse.SC_NOT_FOUND, fileName); return true; "Rejecting published file request for file that has not been published: " + fileName); response.sendError(HttpServletResponse.SC_NOT_FOUND, fileName); return true; + context.getPackage().getName().replace('.', '/') + '/' + fileName + " is available on the classpath."); response.sendError(HttpServletResponse.SC_NOT_FOUND, fileName); return true; cacheControl = "max-age=" + String.valueOf(resourceCacheTime); response.setHeader("Cache-Control", cacheControl); response.setContentType(mimetype); out = response.getOutputStream();
/** * Commit the JSON response. We can't write immediately to the output stream * as we want to write only a critical notification if something goes wrong * during the response handling. * * @param response * The response to write to * @param json * The JSON to write * @throws IOException * If there was an exception while writing to the output */ public static void commitJsonResponse(VaadinResponse response, String json) throws IOException { response.setContentType(JsonConstants.JSON_CONTENT_TYPE); // Ensure that the browser does not cache UIDL responses. // iOS 6 Safari requires this (#9732) response.setHeader("Cache-Control", "no-cache"); byte[] b = json.getBytes("UTF-8"); response.setContentLength(b.length); OutputStream outputStream = response.getOutputStream(); outputStream.write(b); // NOTE GateIn requires the buffers to be flushed to work outputStream.flush(); } }
.flatMap(session.getResourceRegistry()::getResource); if (!resource.isPresent()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource is not found for path=" + pathInfo); return true; ServletContext context = ((VaadinServletRequest) request) .getServletContext(); response.setContentType(streamResource.getContentTypeResolver() .apply(streamResource, context)); response.setCacheTime(streamResource.getCacheTime()); writer = streamResource.getWriter(); if (writer == null) { session.unlock(); try (OutputStream outputStream = response.getOutputStream()) { writer.accept(outputStream, session);
/** * Handles a heartbeat request for the given session. Reads the GET * parameter named {@link UIConstants#UI_ID_PARAMETER} to identify the UI. * If the UI is found in the session, sets it * {@link UI#getLastHeartbeatTimestamp() heartbeat timestamp} to the current * time. Otherwise, writes a HTTP Not Found error to the response. */ @Override public boolean synchronizedHandleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { UI ui = session.getService().findUI(request); if (ui != null) { ui.setLastHeartbeatTimestamp(System.currentTimeMillis()); // Ensure that the browser does not cache heartbeat responses. // iOS 6 Safari requires this (#10370) response.setHeader("Cache-Control", "no-cache"); // If Content-Type is not set, browsers assume text/html and may // complain about the empty response body (#12182) response.setHeader("Content-Type", "text/plain"); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "UI not found"); } return true; }
@Override public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { String requestPath = request.getPathInfo(); // redirect to base URL if we have unparsable path tail if (!Objects.equals("/", requestPath)) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", request.getContextPath()); return true; } return super.handleRequest(session, request, response); } }
/** * Sets all conceivable headers that might prevent a response from being * stored in any caches. * * @since 8.3.2 */ public default void setNoCacheHeaders() { // no-store to disallow storing even if cache would be revalidated // must-revalidate to not use stored value even if someone asks for it setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // Also set legacy values in case of old proxies in between setHeader("Pragma", "no-cache"); setHeader("Expires", "0"); }
try (Writer page = response.getWriter()) { WebBrowser b = VaadinSession.getCurrent().getBrowser();
VaadinResponse response = VaadinService.getCurrentResponse(); if (response != null) { response.setStatus(404);
@Override protected void writeBrowserTooOldPage(VaadinRequest request, VaadinResponse response) throws IOException { try (BufferedWriter page = new BufferedWriter(new OutputStreamWriter( response.getOutputStream(), StandardCharsets.UTF_8))) { Locale locale = request.getLocale(); ParamsMap paramsMap = ParamsMap.of() .pair("captionMessage", messages.getMainMessage("unsupportedPage.captionMessage", locale)) .pair("descriptionMessage", messages.getMainMessage("unsupportedPage.descriptionMessage", locale)) .pair("browserListCaption", messages.getMainMessage("unsupportedPage.browserListCaption", locale)) .pair("chromeMessage", messages.getMainMessage("unsupportedPage.chromeMessage", locale)) .pair("firefoxMessage", messages.getMainMessage("unsupportedPage.firefoxMessage", locale)) .pair("safariMessage", messages.getMainMessage("unsupportedPage.safariMessage", locale)) .pair("operaMessage", messages.getMainMessage("unsupportedPage.operaMessage", locale)) .pair("edgeMessage", messages.getMainMessage("unsupportedPage.edgeMessage", locale)) .pair("explorerMessage", messages.getMainMessage("unsupportedPage.explorerMessage", locale)); String template = resources.getResourceAsString(webConfig.getUnsupportedPagePath()); String pageContent = TemplateHelper.processTemplate(template, paramsMap.create()); page.write(pageContent); } } }
/** * Handles a heartbeat request for the given session. Reads the GET * parameter named {@link ApplicationConstants#UI_ID_PARAMETER} to identify * the UI. If the UI is found in the session, sets it * {@link UIInternals#getLastHeartbeatTimestamp() heartbeat timestamp} to * the current time. Otherwise, writes a HTTP Not Found error to the * response. */ @Override public boolean synchronizedHandleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { UI ui = session.getService().findUI(request); if (ui != null) { ui.getInternals() .setLastHeartbeatTimestamp(System.currentTimeMillis()); // Ensure that the browser does not cache heartbeat responses. // iOS 6 Safari requires this (#10370) response.setHeader("Cache-Control", "no-cache"); // If Content-Type is not set, browsers assume text/html and may // complain about the empty response body (#12182) response.setHeader("Content-Type", "text/plain"); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "UI not found"); } return true; }
@Test public void testContentDispositionHeaderIsSetCorrectly() throws Exception { // GIVEN String encodedFileName = EncodeUtil.rfc5987Encode(fileName); action = new DownloadBinaryAction<DownloadBinaryActionDefinition>(definition, item); DownloadStreamResource downloadStreamResource = action.getStreamResource(inputStream, fileName); String expectedContentDispositionHeaderValue = String.format("attachment;filename=\"%s\"; filename*=utf-8''%<s", encodedFileName); VaadinRequest vaadinRequest = mock(VaadinRequest.class); VaadinResponse vaadinResponse = mock(VaadinResponse.class); // WHEN downloadStreamResource.getStream().writeResponse(vaadinRequest, vaadinResponse); // THEN // At least as of 7.6 Vaadin may set content-disposition header twice with the same value verify(vaadinResponse, atLeastOnce()).setHeader("Content-Disposition", expectedContentDispositionHeaderValue); }
Writer page = response.getWriter(); WebBrowser b = VaadinSession.getCurrent().getBrowser();
/** * Sends the upload response. * * @param request * @param response * @throws IOException */ protected void sendUploadResponse(VaadinRequest request, VaadinResponse response) throws IOException { response.setContentType( ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8); try (OutputStream out = response.getOutputStream()) { final PrintWriter outWriter = new PrintWriter( new BufferedWriter(new OutputStreamWriter(out, UTF_8))); outWriter.print("<html><body>download handled</body></html>"); outWriter.flush(); } }
private void sendBootstrapHeaders(VaadinResponse response, Map<String, Object> headers) { Set<Entry<String, Object>> entrySet = headers.entrySet(); for (Entry<String, Object> header : entrySet) { Object value = header.getValue(); if (value instanceof String) { response.setHeader(header.getKey(), (String) value); } else if (value instanceof Long) { response.setDateHeader(header.getKey(), ((Long) value).longValue()); } else { throw new RuntimeException( "Unsupported header value: " + value); } } }