You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VaadinServletService.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. * Copyright 2000-2021 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.net.MalformedURLException;
  21. import java.net.URL;
  22. import java.util.List;
  23. import java.util.logging.Level;
  24. import java.util.logging.Logger;
  25. import javax.servlet.http.HttpServletRequest;
  26. import com.vaadin.server.communication.PushRequestHandler;
  27. import com.vaadin.server.communication.ServletBootstrapHandler;
  28. import com.vaadin.server.communication.ServletUIInitHandler;
  29. import com.vaadin.ui.UI;
  30. public class VaadinServletService extends VaadinService {
  31. /**
  32. * Should never be used directly, always use {@link #getServlet()}
  33. */
  34. private final VaadinServlet servlet;
  35. public VaadinServletService(VaadinServlet servlet,
  36. DeploymentConfiguration deploymentConfiguration)
  37. throws ServiceException {
  38. super(deploymentConfiguration);
  39. this.servlet = servlet;
  40. }
  41. /**
  42. * Creates a servlet service. This method is for use by dependency injection
  43. * frameworks etc. {@link #getServlet()} should be overridden (or otherwise
  44. * intercepted) so it does not return <code>null</code>.
  45. *
  46. * @since 8.2
  47. */
  48. protected VaadinServletService() {
  49. servlet = null;
  50. }
  51. @Override
  52. protected List<RequestHandler> createRequestHandlers()
  53. throws ServiceException {
  54. List<RequestHandler> handlers = super.createRequestHandlers();
  55. handlers.add(0, new ServletBootstrapHandler());
  56. handlers.add(new ServletUIInitHandler());
  57. if (isAtmosphereAvailable()) {
  58. try {
  59. handlers.add(new PushRequestHandler(this));
  60. } catch (ServiceException e) {
  61. // Atmosphere init failed. Push won't work but we don't throw a
  62. // service exception as we don't want to prevent non-push
  63. // applications from working
  64. getLogger().log(Level.WARNING,
  65. "Error initializing Atmosphere. Push will not work.",
  66. e);
  67. }
  68. }
  69. return handlers;
  70. }
  71. /**
  72. * Retrieves a reference to the servlet associated with this service. Should
  73. * be overridden (or otherwise intercepted) if the no-arg constructor is
  74. * used to prevent NPEs.
  75. *
  76. * @return A reference to the VaadinServlet this service is using
  77. */
  78. public VaadinServlet getServlet() {
  79. return servlet;
  80. }
  81. @Override
  82. public String getStaticFileLocation(VaadinRequest request) {
  83. VaadinServletRequest servletRequest = (VaadinServletRequest) request;
  84. String staticFileLocation;
  85. // if property is defined in configurations, use that
  86. staticFileLocation = getDeploymentConfiguration().getResourcesPath();
  87. if (staticFileLocation != null) {
  88. return staticFileLocation;
  89. }
  90. // the last (but most common) option is to generate default location
  91. // from request by finding how many "../" should be added to the
  92. // requested path before we get to the context root
  93. String requestedPath = servletRequest.getServletPath();
  94. String pathInfo = servletRequest.getPathInfo();
  95. if (pathInfo != null) {
  96. requestedPath += pathInfo;
  97. }
  98. return getCancelingRelativePath(requestedPath);
  99. }
  100. /**
  101. * Gets a relative path that cancels the provided path. This essentially
  102. * adds one .. for each part of the path to cancel.
  103. *
  104. * @param pathToCancel
  105. * the path that should be canceled
  106. * @return a relative path that cancels out the provided path segment
  107. */
  108. public static String getCancelingRelativePath(String pathToCancel) {
  109. StringBuilder sb = new StringBuilder(".");
  110. // Start from i = 1 to ignore first slash
  111. for (int i = 1; i < pathToCancel.length(); i++) {
  112. if (pathToCancel.charAt(i) == '/') {
  113. sb.append("/..");
  114. }
  115. }
  116. return sb.toString();
  117. }
  118. /**
  119. * Gets a relative path you can use to refer to the context root.
  120. *
  121. * @param request
  122. * the request for which the location should be determined
  123. * @return A relative path to the context root. Never ends with a slash (/).
  124. *
  125. * @since 8.0.3
  126. */
  127. public static String getContextRootRelativePath(VaadinRequest request) {
  128. VaadinServletRequest servletRequest = (VaadinServletRequest) request;
  129. // Generate location from the request by finding how many "../" should
  130. // be added to the servlet path before we get to the context root
  131. String servletPath = servletRequest.getServletPath();
  132. if (servletPath == null) {
  133. // Not allowed by the spec but servers are servers...
  134. servletPath = "";
  135. }
  136. String pathInfo = servletRequest.getPathInfo();
  137. if (pathInfo != null && !pathInfo.isEmpty()) {
  138. servletPath += pathInfo;
  139. }
  140. return getCancelingRelativePath(servletPath);
  141. }
  142. @Override
  143. public String getConfiguredWidgetset(VaadinRequest request) {
  144. return getDeploymentConfiguration()
  145. .getWidgetset(VaadinServlet.DEFAULT_WIDGETSET);
  146. }
  147. @Override
  148. public String getConfiguredTheme(VaadinRequest request) {
  149. // Use the default
  150. return VaadinServlet.getDefaultTheme();
  151. }
  152. @Override
  153. public boolean isStandalone(VaadinRequest request) {
  154. return true;
  155. }
  156. @Override
  157. public String getMimeType(String resourceName) {
  158. return getServlet().getServletContext().getMimeType(resourceName);
  159. }
  160. @Override
  161. public File getBaseDirectory() {
  162. final String realPath = VaadinServlet
  163. .getResourcePath(getServlet().getServletContext(), "/");
  164. if (realPath == null) {
  165. return null;
  166. }
  167. return new File(realPath);
  168. }
  169. @Override
  170. protected boolean requestCanCreateSession(VaadinRequest request) {
  171. if (ServletUIInitHandler.isUIInitRequest(request)) {
  172. // This is the first request if you are embedding by writing the
  173. // embedding code yourself
  174. return true;
  175. } else if (isOtherRequest(request)) {
  176. /*
  177. * I.e URIs that are not RPC calls or static (theme) files.
  178. */
  179. return true;
  180. }
  181. return false;
  182. }
  183. private boolean isOtherRequest(VaadinRequest request) {
  184. // TODO This should be refactored in some way. It should not be
  185. // necessary to check all these types.
  186. return (!ServletPortletHelper.isAppRequest(request)
  187. && !ServletUIInitHandler.isUIInitRequest(request)
  188. && !ServletPortletHelper.isFileUploadRequest(request)
  189. && !ServletPortletHelper.isHeartbeatRequest(request)
  190. && !ServletPortletHelper.isPublishedFileRequest(request)
  191. && !ServletPortletHelper.isUIDLRequest(request)
  192. && !ServletPortletHelper.isPushRequest(request));
  193. }
  194. @Override
  195. protected URL getApplicationUrl(VaadinRequest request)
  196. throws MalformedURLException {
  197. return getServlet().getApplicationUrl((VaadinServletRequest) request);
  198. }
  199. public static HttpServletRequest getCurrentServletRequest() {
  200. return VaadinServletRequest.getCurrent();
  201. }
  202. public static VaadinServletResponse getCurrentResponse() {
  203. return VaadinServletResponse.getCurrent();
  204. }
  205. @Override
  206. public String getServiceName() {
  207. return getServlet().getServletName();
  208. }
  209. @Override
  210. public InputStream getThemeResourceAsStream(UI uI, String themeName,
  211. String resource) throws IOException {
  212. String filename = "/" + VaadinServlet.THEME_DIR_PATH + '/' + themeName
  213. + "/" + resource;
  214. URL resourceUrl = getServlet().findResourceURL(filename);
  215. if (resourceUrl != null) {
  216. // security check: do not permit navigation out of the VAADIN
  217. // directory
  218. if (!getServlet().isAllowedVAADINResourceUrl(null, resourceUrl)) {
  219. throw new IOException(
  220. String.format(
  221. "Requested resource [%s] is a directory, "
  222. + "is not within the VAADIN directory, "
  223. + "or access to it is forbidden.",
  224. filename));
  225. }
  226. return resourceUrl.openStream();
  227. } else {
  228. return null;
  229. }
  230. }
  231. @Override
  232. public String getMainDivId(VaadinSession session, VaadinRequest request,
  233. Class<? extends UI> uiClass) {
  234. String appId = null;
  235. try {
  236. URL appUrl = getServlet()
  237. .getApplicationUrl((VaadinServletRequest) request);
  238. appId = appUrl.getPath();
  239. } catch (MalformedURLException e) {
  240. // Just ignore problem here
  241. }
  242. if (appId == null || appId.isEmpty() || "/".equals(appId)) {
  243. appId = "ROOT";
  244. }
  245. appId = appId.replaceAll("[^a-zA-Z0-9]", "");
  246. // Add hashCode to the end, so that it is still (sort of)
  247. // predictable, but indicates that it should not be used in CSS
  248. // and
  249. // such:
  250. int hashCode = appId.hashCode();
  251. if (hashCode < 0) {
  252. hashCode = -hashCode;
  253. }
  254. appId = appId + "-" + hashCode;
  255. return appId;
  256. }
  257. private static final Logger getLogger() {
  258. return Logger.getLogger(VaadinServletService.class.getName());
  259. }
  260. }