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.

VaadinServlet.java 54KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  1. /*
  2. * Copyright 2000-2016 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.BufferedWriter;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileNotFoundException;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  25. import java.io.OutputStreamWriter;
  26. import java.io.PrintWriter;
  27. import java.io.Serializable;
  28. import java.lang.reflect.Method;
  29. import java.net.MalformedURLException;
  30. import java.net.URISyntaxException;
  31. import java.net.URL;
  32. import java.net.URLConnection;
  33. import java.nio.charset.Charset;
  34. import java.nio.charset.StandardCharsets;
  35. import java.util.ArrayList;
  36. import java.util.Arrays;
  37. import java.util.Collection;
  38. import java.util.Enumeration;
  39. import java.util.HashMap;
  40. import java.util.HashSet;
  41. import java.util.List;
  42. import java.util.Map;
  43. import java.util.Properties;
  44. import java.util.logging.Level;
  45. import java.util.logging.Logger;
  46. import javax.servlet.ServletContext;
  47. import javax.servlet.ServletException;
  48. import javax.servlet.http.HttpServlet;
  49. import javax.servlet.http.HttpServletRequest;
  50. import javax.servlet.http.HttpServletResponse;
  51. import com.vaadin.annotations.VaadinServletConfiguration;
  52. import com.vaadin.annotations.VaadinServletConfiguration.InitParameterName;
  53. import com.vaadin.sass.internal.ScssStylesheet;
  54. import com.vaadin.server.communication.ServletUIInitHandler;
  55. import com.vaadin.shared.ApplicationConstants;
  56. import com.vaadin.shared.JsonConstants;
  57. import com.vaadin.shared.Version;
  58. import com.vaadin.ui.UI;
  59. import com.vaadin.util.CurrentInstance;
  60. import elemental.json.Json;
  61. import elemental.json.JsonArray;
  62. import elemental.json.JsonObject;
  63. @SuppressWarnings("serial")
  64. public class VaadinServlet extends HttpServlet implements Constants {
  65. private class ScssCacheEntry implements Serializable {
  66. private final String css;
  67. private final List<String> sourceUris;
  68. private final long timestamp;
  69. private final String scssFileName;
  70. public ScssCacheEntry(String scssFileName, String css,
  71. List<String> sourceUris) {
  72. this.scssFileName = scssFileName;
  73. this.css = css;
  74. this.sourceUris = sourceUris;
  75. timestamp = getLastModified();
  76. }
  77. public ScssCacheEntry(JsonObject json) {
  78. css = json.getString("css");
  79. timestamp = Long.parseLong(json.getString("timestamp"));
  80. sourceUris = new ArrayList<>();
  81. JsonArray uris = json.getArray("uris");
  82. for (int i = 0; i < uris.length(); i++) {
  83. sourceUris.add(uris.getString(i));
  84. }
  85. // Not set for cache entries read from disk
  86. scssFileName = null;
  87. }
  88. public String asJson() {
  89. JsonArray uris = Json.createArray();
  90. for (String uri : sourceUris) {
  91. uris.set(uris.length(), uri);
  92. }
  93. JsonObject object = Json.createObject();
  94. object.put("version", Version.getFullVersion());
  95. object.put("timestamp", Long.toString(timestamp));
  96. object.put("uris", uris);
  97. object.put("css", css);
  98. return object.toJson();
  99. }
  100. public String getCss() {
  101. return css;
  102. }
  103. private long getLastModified() {
  104. long newest = 0;
  105. for (String uri : sourceUris) {
  106. File file = new File(uri);
  107. URL resource = getService().getClassLoader().getResource(uri);
  108. long lastModified = -1L;
  109. if (file.exists()) {
  110. lastModified = file.lastModified();
  111. } else if (resource != null
  112. && resource.getProtocol().equals("file")) {
  113. try {
  114. file = new File(resource.toURI());
  115. if (file.exists()) {
  116. lastModified = file.lastModified();
  117. }
  118. } catch (URISyntaxException e) {
  119. getLogger().log(Level.WARNING,
  120. "Could not resolve timestamp for " + resource,
  121. e);
  122. }
  123. }
  124. if (lastModified == -1L && resource == null) {
  125. /*
  126. * Ignore missing files found in the classpath, report
  127. * problem and abort for other files.
  128. */
  129. getLogger().log(Level.WARNING,
  130. "Could not resolve timestamp for {0}, Scss on the fly caching will be disabled",
  131. uri);
  132. // -1 means this cache entry will never be valid
  133. return -1;
  134. }
  135. newest = Math.max(newest, lastModified);
  136. }
  137. return newest;
  138. }
  139. public boolean isStillValid() {
  140. if (timestamp == -1) {
  141. /*
  142. * Don't ever bother checking anything if files used during the
  143. * compilation were gone before the cache entry was created.
  144. */
  145. return false;
  146. } else if (timestamp != getLastModified()) {
  147. /*
  148. * Would in theory still be valid if the last modification is
  149. * before the recorded timestamp, but that would still mean that
  150. * something has changed since we last checked, so let's
  151. * invalidate in that case as well to be on the safe side.
  152. */
  153. return false;
  154. } else {
  155. return true;
  156. }
  157. }
  158. public String getScssFileName() {
  159. return scssFileName;
  160. }
  161. }
  162. private VaadinServletService servletService;
  163. /**
  164. * Called by the servlet container to indicate to a servlet that the servlet
  165. * is being placed into service.
  166. *
  167. * @param servletConfig
  168. * the object containing the servlet's configuration and
  169. * initialization parameters
  170. * @throws ServletException
  171. * if an exception has occurred that interferes with the
  172. * servlet's normal operation.
  173. */
  174. @Override
  175. public void init(javax.servlet.ServletConfig servletConfig)
  176. throws ServletException {
  177. CurrentInstance.clearAll();
  178. super.init(servletConfig);
  179. Properties initParameters = new Properties();
  180. readUiFromEnclosingClass(initParameters);
  181. readConfigurationAnnotation(initParameters);
  182. // Read default parameters from server.xml
  183. final ServletContext context = servletConfig.getServletContext();
  184. for (final Enumeration<String> e = context.getInitParameterNames(); e
  185. .hasMoreElements();) {
  186. final String name = e.nextElement();
  187. initParameters.setProperty(name, context.getInitParameter(name));
  188. }
  189. // Override with application config from web.xml
  190. for (final Enumeration<String> e = servletConfig
  191. .getInitParameterNames(); e.hasMoreElements();) {
  192. final String name = e.nextElement();
  193. initParameters.setProperty(name,
  194. servletConfig.getInitParameter(name));
  195. }
  196. DeploymentConfiguration deploymentConfiguration = createDeploymentConfiguration(
  197. initParameters);
  198. try {
  199. servletService = createServletService(deploymentConfiguration);
  200. } catch (ServiceException e) {
  201. throw new ServletException("Could not initialize VaadinServlet", e);
  202. }
  203. // Sets current service even though there are no request and response
  204. servletService.setCurrentInstances(null, null);
  205. servletInitialized();
  206. CurrentInstance.clearAll();
  207. }
  208. private void readUiFromEnclosingClass(Properties initParameters) {
  209. Class<?> enclosingClass = getClass().getEnclosingClass();
  210. if (enclosingClass != null
  211. && UI.class.isAssignableFrom(enclosingClass)) {
  212. initParameters.put(VaadinSession.UI_PARAMETER,
  213. enclosingClass.getName());
  214. }
  215. }
  216. private void readConfigurationAnnotation(Properties initParameters)
  217. throws ServletException {
  218. VaadinServletConfiguration configAnnotation = UIProvider
  219. .getAnnotationFor(getClass(), VaadinServletConfiguration.class);
  220. if (configAnnotation != null) {
  221. Method[] methods = VaadinServletConfiguration.class
  222. .getDeclaredMethods();
  223. for (Method method : methods) {
  224. InitParameterName name = method
  225. .getAnnotation(InitParameterName.class);
  226. assert name != null : "All methods declared in VaadinServletConfiguration should have a @InitParameterName annotation";
  227. try {
  228. Object value = method.invoke(configAnnotation);
  229. String stringValue;
  230. if (value instanceof Class<?>) {
  231. stringValue = ((Class<?>) value).getName();
  232. } else {
  233. stringValue = value.toString();
  234. }
  235. if (VaadinServlet.PARAMETER_WIDGETSET.equals(name.value())
  236. && method.getDefaultValue().equals(stringValue)) {
  237. // Do not set the widgetset to anything so that the
  238. // framework can fallback to the default. Setting
  239. // anything to the init parameter will force that into
  240. // use and e.g. AppWidgetset will not be used even
  241. // though it is found.
  242. continue;
  243. }
  244. initParameters.setProperty(name.value(), stringValue);
  245. } catch (Exception e) {
  246. // This should never happen
  247. throw new ServletException(
  248. "Could not read @VaadinServletConfiguration value "
  249. + method.getName(),
  250. e);
  251. }
  252. }
  253. }
  254. }
  255. protected void servletInitialized() throws ServletException {
  256. // Empty by default
  257. }
  258. /**
  259. * Gets the currently used Vaadin servlet. The current servlet is
  260. * automatically defined when initializing the servlet and when processing
  261. * requests to the server (see {@link ThreadLocal}) and in
  262. * {@link VaadinSession#access(Runnable)} and {@link UI#access(Runnable)}.
  263. * In other cases, (e.g. from background threads), the current servlet is
  264. * not automatically defined.
  265. * <p>
  266. * The current servlet is derived from the current service using
  267. * {@link VaadinService#getCurrent()}
  268. *
  269. * @return the current Vaadin servlet instance if available, otherwise
  270. * <code>null</code>
  271. *
  272. * @since 7.0
  273. */
  274. public static VaadinServlet getCurrent() {
  275. VaadinService vaadinService = CurrentInstance.get(VaadinService.class);
  276. if (vaadinService instanceof VaadinServletService) {
  277. VaadinServletService vss = (VaadinServletService) vaadinService;
  278. return vss.getServlet();
  279. } else {
  280. return null;
  281. }
  282. }
  283. protected DeploymentConfiguration createDeploymentConfiguration(
  284. Properties initParameters) {
  285. return new DefaultDeploymentConfiguration(getClass(), initParameters);
  286. }
  287. protected VaadinServletService createServletService(
  288. DeploymentConfiguration deploymentConfiguration)
  289. throws ServiceException {
  290. VaadinServletService service = new VaadinServletService(this,
  291. deploymentConfiguration);
  292. service.init();
  293. return service;
  294. }
  295. /**
  296. * Receives standard HTTP requests from the public service method and
  297. * dispatches them.
  298. *
  299. * @param request
  300. * the object that contains the request the client made of the
  301. * servlet.
  302. * @param response
  303. * the object that contains the response the servlet returns to
  304. * the client.
  305. * @throws ServletException
  306. * if an input or output error occurs while the servlet is
  307. * handling the TRACE request.
  308. * @throws IOException
  309. * if the request for the TRACE cannot be handled.
  310. */
  311. @Override
  312. protected void service(HttpServletRequest request,
  313. HttpServletResponse response) throws ServletException, IOException {
  314. // Handle context root request without trailing slash, see #9921
  315. if (handleContextRootWithoutSlash(request, response)) {
  316. return;
  317. }
  318. CurrentInstance.clearAll();
  319. VaadinServletRequest vaadinRequest = createVaadinRequest(request);
  320. VaadinServletResponse vaadinResponse = createVaadinResponse(response);
  321. if (!ensureCookiesEnabled(vaadinRequest, vaadinResponse)) {
  322. return;
  323. }
  324. if (isStaticResourceRequest(vaadinRequest)) {
  325. // Define current servlet and service, but no request and response
  326. getService().setCurrentInstances(null, null);
  327. try {
  328. serveStaticResources(vaadinRequest, vaadinResponse);
  329. return;
  330. } finally {
  331. CurrentInstance.clearAll();
  332. }
  333. }
  334. try {
  335. getService().handleRequest(vaadinRequest, vaadinResponse);
  336. } catch (ServiceException e) {
  337. throw new ServletException(e);
  338. }
  339. }
  340. /**
  341. * Invoked for every request to this servlet to potentially send a redirect
  342. * to avoid problems with requests to the context root with no trailing
  343. * slash.
  344. *
  345. * @param request
  346. * the processed request
  347. * @param response
  348. * the processed response
  349. * @return <code>true</code> if a redirect has been sent and the request
  350. * should not be processed further; <code>false</code> if the
  351. * request should be processed as usual
  352. * @throws IOException
  353. * If an input or output exception occurs
  354. */
  355. protected boolean handleContextRootWithoutSlash(HttpServletRequest request,
  356. HttpServletResponse response) throws IOException {
  357. // Query parameters like "?a=b" are handled by the servlet container but
  358. // path parameter (e.g. ;jsessionid=) needs to be handled here
  359. String location = request.getRequestURI();
  360. String lastPathParameter = getLastPathParameter(location);
  361. location = location.substring(0,
  362. location.length() - lastPathParameter.length());
  363. if ((request.getPathInfo() == null || "/".equals(request.getPathInfo()))
  364. && "".equals(request.getServletPath())
  365. && !location.endsWith("/")) {
  366. /*
  367. * Path info is for the root but request URI doesn't end with a
  368. * slash -> redirect to the same URI but with an ending slash.
  369. */
  370. location = location + "/" + lastPathParameter;
  371. String queryString = request.getQueryString();
  372. if (queryString != null) {
  373. // Prevent HTTP Response splitting in case the server doesn't
  374. queryString = queryString.replaceAll("[\\r\\n]", "");
  375. location += '?' + queryString;
  376. }
  377. response.sendRedirect(location);
  378. return true;
  379. } else {
  380. return false;
  381. }
  382. }
  383. /**
  384. * Finds any path parameter added to the last part of the uri. A path
  385. * parameter is any string separated by ";" from the path and ends in / or
  386. * at the end of the string.
  387. * <p>
  388. * For example the uri http://myhost.com/foo;a=1/bar;b=1 contains two path
  389. * parameters, {@literal a=1} related to {@literal /foo} and {@literal b=1}
  390. * related to /bar.
  391. * <p>
  392. * For http://myhost.com/foo;a=1/bar;b=1 this method will return ;b=1
  393. *
  394. * @since 7.2
  395. * @param uri
  396. * a URI
  397. * @return the last path parameter of the uri including the semicolon or an
  398. * empty string. Never null.
  399. */
  400. protected static String getLastPathParameter(String uri) {
  401. int lastPathStart = uri.lastIndexOf('/');
  402. if (lastPathStart == -1) {
  403. return "";
  404. }
  405. int semicolonPos = uri.indexOf(';', lastPathStart);
  406. if (semicolonPos < 0) {
  407. // No path parameter for the last part
  408. return "";
  409. } else {
  410. // This includes the semicolon.
  411. String semicolonString = uri.substring(semicolonPos);
  412. return semicolonString;
  413. }
  414. }
  415. private VaadinServletResponse createVaadinResponse(
  416. HttpServletResponse response) {
  417. return new VaadinServletResponse(response, getService());
  418. }
  419. /**
  420. * Create a Vaadin request for a http servlet request. This method can be
  421. * overridden if the Vaadin request should have special properties.
  422. *
  423. * @param request
  424. * the original http servlet request
  425. * @return a Vaadin request for the original request
  426. */
  427. protected VaadinServletRequest createVaadinRequest(
  428. HttpServletRequest request) {
  429. return new VaadinServletRequest(request, getService());
  430. }
  431. /**
  432. * Gets a the vaadin service for this servlet.
  433. *
  434. * @return the vaadin service
  435. */
  436. protected VaadinServletService getService() {
  437. return servletService;
  438. }
  439. /**
  440. * Check that cookie support is enabled in the browser. Only checks UIDL
  441. * requests.
  442. *
  443. * @param request
  444. * The request from the browser
  445. * @param response
  446. * The response to which an error can be written
  447. * @return false if cookies are disabled, true otherwise
  448. * @throws IOException
  449. */
  450. private boolean ensureCookiesEnabled(VaadinServletRequest request,
  451. VaadinServletResponse response) throws IOException {
  452. if (ServletPortletHelper.isUIDLRequest(request)) {
  453. // In all other but the first UIDL request a cookie should be
  454. // returned by the browser.
  455. // This can be removed if cookieless mode (#3228) is supported
  456. if (request.getRequestedSessionId() == null) {
  457. // User has cookies disabled
  458. SystemMessages systemMessages = getService().getSystemMessages(
  459. ServletPortletHelper.findLocale(null, null, request),
  460. request);
  461. getService().writeStringResponse(response,
  462. JsonConstants.JSON_CONTENT_TYPE,
  463. VaadinService.createCriticalNotificationJSON(
  464. systemMessages.getCookiesDisabledCaption(),
  465. systemMessages.getCookiesDisabledMessage(),
  466. null, systemMessages.getCookiesDisabledURL()));
  467. return false;
  468. }
  469. }
  470. return true;
  471. }
  472. /**
  473. * Send a notification to client-side widgetset. Used to notify client of
  474. * critical errors, session expiration and more. Server has no knowledge of
  475. * what UI client refers to.
  476. *
  477. * @param request
  478. * the HTTP request instance.
  479. * @param response
  480. * the HTTP response to write to.
  481. * @param caption
  482. * the notification caption
  483. * @param message
  484. * to notification body
  485. * @param details
  486. * a detail message to show in addition to the message. Currently
  487. * shown directly below the message but could be hidden behind a
  488. * details drop down in the future. Mainly used to give
  489. * additional information not necessarily useful to the end user.
  490. * @param url
  491. * url to load when the message is dismissed. Null will reload
  492. * the current page.
  493. * @throws IOException
  494. * if the writing failed due to input/output error.
  495. *
  496. * @deprecated As of 7.0. This method is retained only for backwards
  497. * compatibility and for GAEVaadinServlet.
  498. */
  499. @Deprecated
  500. protected void criticalNotification(VaadinServletRequest request,
  501. VaadinServletResponse response, String caption, String message,
  502. String details, String url) throws IOException {
  503. if (ServletPortletHelper.isUIDLRequest(request)) {
  504. String output = VaadinService.createCriticalNotificationJSON(
  505. caption, message, details, url);
  506. getService().writeStringResponse(response,
  507. JsonConstants.JSON_CONTENT_TYPE, output);
  508. } else {
  509. // Create an HTML reponse with the error
  510. String output = "";
  511. if (url != null) {
  512. output += "<a href=\"" + url + "\">";
  513. }
  514. if (caption != null) {
  515. output += "<b>" + caption + "</b><br/>";
  516. }
  517. if (message != null) {
  518. output += message;
  519. output += "<br/><br/>";
  520. }
  521. if (details != null) {
  522. output += details;
  523. output += "<br/><br/>";
  524. }
  525. if (url != null) {
  526. output += "</a>";
  527. }
  528. getService().writeStringResponse(response,
  529. ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8, output);
  530. }
  531. }
  532. /**
  533. * Writes the response in {@code output} using the contentType given in
  534. * {@code contentType} to the provided {@link HttpServletResponse}
  535. *
  536. * @param response
  537. * @param contentType
  538. * @param output
  539. * Output to write (UTF-8 encoded)
  540. * @throws IOException
  541. */
  542. private void writeResponse(HttpServletResponse response, String contentType,
  543. String output) throws IOException {
  544. response.setContentType(contentType);
  545. final OutputStream out = response.getOutputStream();
  546. try ( // Set the response type
  547. PrintWriter outWriter = new PrintWriter(new BufferedWriter(
  548. new OutputStreamWriter(out, "UTF-8")))) {
  549. outWriter.print(output);
  550. outWriter.flush();
  551. }
  552. }
  553. /**
  554. * Gets resource path using different implementations. Required to
  555. * supporting different servlet container implementations (application
  556. * servers).
  557. *
  558. * @param servletContext
  559. * @param path
  560. * the resource path.
  561. * @return the resource path.
  562. *
  563. * @deprecated As of 7.0. Will likely change or be removed in a future
  564. * version
  565. */
  566. @Deprecated
  567. protected static String getResourcePath(ServletContext servletContext,
  568. String path) {
  569. String resultPath = null;
  570. resultPath = servletContext.getRealPath(path);
  571. if (resultPath != null) {
  572. return resultPath;
  573. } else {
  574. try {
  575. final URL url = servletContext.getResource(path);
  576. resultPath = url.getFile();
  577. } catch (final Exception e) {
  578. // FIXME: Handle exception
  579. getLogger().log(Level.INFO,
  580. "Could not find resource path " + path, e);
  581. }
  582. }
  583. return resultPath;
  584. }
  585. /**
  586. * A helper method to strip away characters that might somehow be used for
  587. * XSS attacks. Leaves at least alphanumeric characters intact. Also removes
  588. * e.g. '(' and ')', so values should be safe in javascript too.
  589. *
  590. * @param themeName
  591. * @return
  592. *
  593. * @deprecated As of 7.0. Will likely change or be removed in a future
  594. * version
  595. */
  596. @Deprecated
  597. public static String stripSpecialChars(String themeName) {
  598. StringBuilder sb = new StringBuilder();
  599. char[] charArray = themeName.toCharArray();
  600. for (char c : charArray) {
  601. if (!CHAR_BLACKLIST.contains(c)) {
  602. sb.append(c);
  603. }
  604. }
  605. return sb.toString();
  606. }
  607. private static final Collection<Character> CHAR_BLACKLIST = new HashSet<>(
  608. Arrays.asList(new Character[] { '&', '"', '\'', '<', '>', '(', ')',
  609. ';' }));
  610. /**
  611. * Mutex for preventing to scss compilations to take place simultaneously.
  612. * This is a workaround needed as the scss compiler currently is not thread
  613. * safe (#10292).
  614. * <p>
  615. * In addition, this is also used to protect the cached compilation results.
  616. */
  617. private static final Object SCSS_MUTEX = new Object();
  618. /**
  619. * Global cache of scss compilation results. This map is protected from
  620. * concurrent access by {@link #SCSS_MUTEX}.
  621. */
  622. private final Map<String, ScssCacheEntry> scssCache = new HashMap<>();
  623. /**
  624. * Keeps track of whether a warning about not being able to persist cache
  625. * files has already been printed. The flag is protected from concurrent
  626. * access by {@link #SCSS_MUTEX}.
  627. */
  628. private static boolean scssCompileWarWarningEmitted = false;
  629. /**
  630. * Returns the default theme. Must never return null.
  631. *
  632. * @return
  633. */
  634. public static String getDefaultTheme() {
  635. return DEFAULT_THEME_NAME;
  636. }
  637. /**
  638. * Check if this is a request for a static resource and, if it is, serve the
  639. * resource to the client.
  640. *
  641. * @param request
  642. * @param response
  643. * @return true if a file was served and the request has been handled, false
  644. * otherwise.
  645. * @throws IOException
  646. * @throws ServletException
  647. */
  648. private boolean serveStaticResources(HttpServletRequest request,
  649. HttpServletResponse response) throws IOException, ServletException {
  650. String filePath = getStaticFilePath(request);
  651. if (filePath != null) {
  652. serveStaticResourcesInVAADIN(filePath, request, response);
  653. return true;
  654. }
  655. return false;
  656. }
  657. /**
  658. * Serve resources from VAADIN directory.
  659. *
  660. * @param filename
  661. * The filename to serve. Should always start with /VAADIN/.
  662. * @param request
  663. * @param response
  664. * @throws IOException
  665. * @throws ServletException
  666. */
  667. private void serveStaticResourcesInVAADIN(String filename,
  668. HttpServletRequest request, HttpServletResponse response)
  669. throws IOException, ServletException {
  670. final ServletContext sc = getServletContext();
  671. URL resourceUrl = findResourceURL(filename);
  672. if (resourceUrl == null) {
  673. // File not found, if this was a css request we still look for a
  674. // scss file with the same name
  675. if (serveOnTheFlyCompiledScss(filename, request, response, sc)) {
  676. return;
  677. } else {
  678. // cannot serve requested file
  679. getLogger().log(Level.INFO,
  680. "Requested resource [{0}] not found from filesystem or through class loader."
  681. + " Add widgetset and/or theme JAR to your classpath or add files to WebContent/VAADIN folder.",
  682. filename);
  683. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  684. }
  685. return;
  686. }
  687. // security check: do not permit navigation out of the VAADIN
  688. // directory
  689. if (!isAllowedVAADINResourceUrl(request, resourceUrl)) {
  690. getLogger().log(Level.INFO,
  691. "Requested resource [{0}] not accessible in the VAADIN directory or access to it is forbidden.",
  692. filename);
  693. response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  694. return;
  695. }
  696. String cacheControl = "public, max-age=0, must-revalidate";
  697. int resourceCacheTime = getCacheTime(filename);
  698. if (resourceCacheTime > 0) {
  699. cacheControl = "max-age=" + String.valueOf(resourceCacheTime);
  700. }
  701. response.setHeader("Cache-Control", cacheControl);
  702. response.setDateHeader("Expires",
  703. System.currentTimeMillis() + resourceCacheTime * 1000);
  704. // Find the modification timestamp
  705. long lastModifiedTime = 0;
  706. URLConnection connection = null;
  707. try {
  708. connection = resourceUrl.openConnection();
  709. lastModifiedTime = connection.getLastModified();
  710. // Remove milliseconds to avoid comparison problems (milliseconds
  711. // are not returned by the browser in the "If-Modified-Since"
  712. // header).
  713. lastModifiedTime -= lastModifiedTime % 1000;
  714. response.setDateHeader("Last-Modified", lastModifiedTime);
  715. if (browserHasNewestVersion(request, lastModifiedTime)) {
  716. response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
  717. return;
  718. }
  719. } catch (Exception e) {
  720. // Failed to find out last modified timestamp. Continue without it.
  721. getLogger().log(Level.FINEST,
  722. "Failed to find out last modified timestamp. Continuing without it.",
  723. e);
  724. } finally {
  725. try {
  726. // Explicitly close the input stream to prevent it
  727. // from remaining hanging
  728. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4257700
  729. InputStream is = connection.getInputStream();
  730. if (is != null) {
  731. is.close();
  732. }
  733. } catch (FileNotFoundException e) {
  734. // Not logging when the file does not exist.
  735. } catch (IOException e) {
  736. getLogger().log(Level.INFO,
  737. "Error closing URLConnection input stream", e);
  738. }
  739. }
  740. // Set type mime type if we can determine it based on the filename
  741. final String mimetype = sc.getMimeType(filename);
  742. if (mimetype != null) {
  743. response.setContentType(mimetype);
  744. }
  745. writeStaticResourceResponse(request, response, resourceUrl);
  746. }
  747. /**
  748. * Calculates the cache lifetime for the given filename in seconds. By
  749. * default filenames containing ".nocache." return 0, filenames containing
  750. * ".cache." return one year, all other return the value defined in the
  751. * web.xml using resourceCacheTime (defaults to 1 hour).
  752. *
  753. * @param filename
  754. * @return cache lifetime for the given filename in seconds
  755. */
  756. protected int getCacheTime(String filename) {
  757. /*
  758. * GWT conventions:
  759. *
  760. * - files containing .nocache. will not be cached.
  761. *
  762. * - files containing .cache. will be cached for one year.
  763. *
  764. * https://developers.google.com/web-toolkit/doc/latest/
  765. * DevGuideCompilingAndDebugging#perfect_caching
  766. */
  767. if (filename.contains(".nocache.")) {
  768. return 0;
  769. }
  770. if (filename.contains(".cache.")) {
  771. return 60 * 60 * 24 * 365;
  772. }
  773. /*
  774. * For all other files, the browser is allowed to cache for 1 hour
  775. * without checking if the file has changed. This forces browsers to
  776. * fetch a new version when the Vaadin version is updated. This will
  777. * cause more requests to the servlet than without this but for high
  778. * volume sites the static files should never be served through the
  779. * servlet.
  780. */
  781. return getService().getDeploymentConfiguration().getResourceCacheTime();
  782. }
  783. /**
  784. * Writes the contents of the given resourceUrl in the response. Can be
  785. * overridden to add/modify response headers and similar.
  786. *
  787. * @param request
  788. * The request for the resource
  789. * @param response
  790. * The response
  791. * @param resourceUrl
  792. * The url to send
  793. * @throws IOException
  794. */
  795. protected void writeStaticResourceResponse(HttpServletRequest request,
  796. HttpServletResponse response, URL resourceUrl) throws IOException {
  797. URLConnection connection = null;
  798. InputStream is = null;
  799. String urlStr = resourceUrl.toExternalForm();
  800. if (allowServePrecompressedResource(request, urlStr)) {
  801. // try to serve a precompressed version if available
  802. try {
  803. connection = new URL(urlStr + ".gz").openConnection();
  804. is = connection.getInputStream();
  805. // set gzip headers
  806. response.setHeader("Content-Encoding", "gzip");
  807. } catch (IOException e) {
  808. // NOP: will be still tried with non gzipped version
  809. } catch (Exception e) {
  810. getLogger().log(Level.FINE,
  811. "Unexpected exception looking for gzipped version of resource "
  812. + urlStr,
  813. e);
  814. }
  815. }
  816. if (is == null) {
  817. // precompressed resource not available, get non compressed
  818. connection = resourceUrl.openConnection();
  819. try {
  820. is = connection.getInputStream();
  821. } catch (FileNotFoundException e) {
  822. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  823. return;
  824. }
  825. }
  826. try {
  827. int length = connection.getContentLength();
  828. if (length >= 0) {
  829. response.setContentLength(length);
  830. }
  831. } catch (Throwable e) {
  832. // This can be ignored, content length header is not required.
  833. // Need to close the input stream because of
  834. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4257700 to
  835. // prevent it from hanging, but that is done below.
  836. }
  837. try {
  838. streamContent(response, is);
  839. } finally {
  840. is.close();
  841. }
  842. }
  843. /**
  844. * Returns whether this servlet should attempt to serve a precompressed
  845. * version of the given static resource. If this method returns true, the
  846. * suffix {@code .gz} is appended to the URL and the corresponding resource
  847. * is served if it exists. It is assumed that the compression method used is
  848. * gzip. If this method returns false or a compressed version is not found,
  849. * the original URL is used.
  850. *
  851. * The base implementation of this method returns true if and only if the
  852. * request indicates that the client accepts gzip compressed responses and
  853. * the filename extension of the requested resource is .js, .css, or .html.
  854. *
  855. * @since 7.5.0
  856. *
  857. * @param request
  858. * the request for the resource
  859. * @param url
  860. * the URL of the requested resource
  861. * @return true if the servlet should attempt to serve a precompressed
  862. * version of the resource, false otherwise
  863. */
  864. protected boolean allowServePrecompressedResource(
  865. HttpServletRequest request, String url) {
  866. String accept = request.getHeader("Accept-Encoding");
  867. return accept != null && accept.contains("gzip") && (url.endsWith(".js")
  868. || url.endsWith(".css") || url.endsWith(".html"));
  869. }
  870. private void streamContent(HttpServletResponse response, InputStream is)
  871. throws IOException {
  872. final OutputStream os = response.getOutputStream();
  873. final byte buffer[] = new byte[DEFAULT_BUFFER_SIZE];
  874. int bytes;
  875. while ((bytes = is.read(buffer)) >= 0) {
  876. os.write(buffer, 0, bytes);
  877. }
  878. }
  879. /**
  880. * Finds the given resource from the web content folder or using the class
  881. * loader.
  882. *
  883. * @since 7.7
  884. * @param filename
  885. * The file to find, starting with a "/"
  886. * @return The URL to the given file, or null if the file was not found
  887. * @throws IOException
  888. * if there was a problem while locating the file
  889. */
  890. protected URL findResourceURL(String filename) throws IOException {
  891. URL resourceUrl = getServletContext().getResource(filename);
  892. if (resourceUrl == null) {
  893. // try if requested file is found from class loader
  894. // strip leading "/" otherwise stream from JAR wont work
  895. if (filename.startsWith("/")) {
  896. filename = filename.substring(1);
  897. }
  898. resourceUrl = getService().getClassLoader().getResource(filename);
  899. }
  900. return resourceUrl;
  901. }
  902. private boolean serveOnTheFlyCompiledScss(String filename,
  903. HttpServletRequest request, HttpServletResponse response,
  904. ServletContext sc) throws IOException {
  905. if (!filename.endsWith(".css")) {
  906. return false;
  907. }
  908. String scssFilename = filename.substring(0, filename.length() - 4)
  909. + ".scss";
  910. URL scssUrl = findResourceURL(scssFilename);
  911. if (scssUrl == null) {
  912. // Is a css request but no scss file was found
  913. return false;
  914. }
  915. // security check: do not permit navigation out of the VAADIN
  916. // directory
  917. if (!isAllowedVAADINResourceUrl(request, scssUrl)) {
  918. getLogger().log(Level.INFO,
  919. "Requested resource [{0}] not accessible in the VAADIN directory or access to it is forbidden.",
  920. filename);
  921. response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  922. // Handled, return true so no further processing is done
  923. return true;
  924. }
  925. if (getService().getDeploymentConfiguration().isProductionMode()) {
  926. // This is not meant for production mode.
  927. getLogger().log(Level.INFO,
  928. "Request for {0} not handled by sass compiler while in production mode",
  929. filename);
  930. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  931. // Handled, return true so no further processing is done
  932. return true;
  933. }
  934. synchronized (SCSS_MUTEX) {
  935. ScssCacheEntry cacheEntry = scssCache.get(scssFilename);
  936. if (cacheEntry == null) {
  937. try {
  938. cacheEntry = loadPersistedScssCache(scssFilename, sc);
  939. } catch (Exception e) {
  940. getLogger().log(Level.WARNING,
  941. "Could not read persisted scss cache", e);
  942. }
  943. }
  944. if (cacheEntry == null || !cacheEntry.isStillValid()) {
  945. cacheEntry = compileScssOnTheFly(filename, scssFilename, sc);
  946. persistCacheEntry(cacheEntry);
  947. }
  948. scssCache.put(scssFilename, cacheEntry);
  949. if (cacheEntry == null) {
  950. // compilation did not produce any result, but logged a message
  951. return false;
  952. }
  953. // This is for development mode only so instruct the browser to
  954. // never cache it
  955. response.setHeader("Cache-Control", "no-cache");
  956. final String mimetype = getService().getMimeType(filename);
  957. writeResponse(response, mimetype, cacheEntry.getCss());
  958. return true;
  959. }
  960. }
  961. private ScssCacheEntry loadPersistedScssCache(String scssFilename,
  962. ServletContext sc) throws IOException {
  963. String realFilename = sc.getRealPath(scssFilename);
  964. File scssCacheFile = getScssCacheFile(new File(realFilename));
  965. if (!scssCacheFile.exists()) {
  966. return null;
  967. }
  968. String jsonString = readFile(scssCacheFile, StandardCharsets.UTF_8);
  969. JsonObject entryJson = Json.parse(jsonString);
  970. String cacheVersion = entryJson.getString("version");
  971. if (!Version.getFullVersion().equals(cacheVersion)) {
  972. // Compiled for some other Vaadin version, discard cache
  973. scssCacheFile.delete();
  974. return null;
  975. }
  976. return new ScssCacheEntry(entryJson);
  977. }
  978. private ScssCacheEntry compileScssOnTheFly(String filename,
  979. String scssFilename, ServletContext sc) throws IOException {
  980. String realFilename = sc.getRealPath(scssFilename);
  981. ScssStylesheet scss = ScssStylesheet.get(realFilename);
  982. if (scss == null) {
  983. // Not a file in the file system (WebContent directory). Use the
  984. // identifier directly (VAADIN/themes/.../styles.css) so
  985. // ScssStylesheet will try using the class loader.
  986. if (scssFilename.startsWith("/")) {
  987. scssFilename = scssFilename.substring(1);
  988. }
  989. scss = ScssStylesheet.get(scssFilename);
  990. }
  991. if (scss == null) {
  992. getLogger().log(Level.WARNING,
  993. "Scss file {0} exists but ScssStylesheet was not able to find it",
  994. scssFilename);
  995. return null;
  996. }
  997. try {
  998. getLogger().log(Level.FINE, "Compiling {0} for request to {1}",
  999. new Object[] { realFilename, filename });
  1000. scss.compile();
  1001. } catch (Exception e) {
  1002. getLogger().log(Level.WARNING, "Scss compilation failed", e);
  1003. return null;
  1004. }
  1005. return new ScssCacheEntry(realFilename, scss.printState(),
  1006. scss.getSourceUris());
  1007. }
  1008. /**
  1009. * Check whether a URL obtained from a classloader refers to a valid static
  1010. * resource in the directory VAADIN.
  1011. *
  1012. * Warning: Overriding of this method is not recommended, but is possible to
  1013. * support non-default classloaders or servers that may produce URLs
  1014. * different from the normal ones. The method prototype may change in the
  1015. * future. Care should be taken not to expose class files or other resources
  1016. * outside the VAADIN directory if the method is overridden.
  1017. *
  1018. * @param request
  1019. * @param resourceUrl
  1020. * @return
  1021. *
  1022. * @since 6.6.7
  1023. *
  1024. * @deprecated As of 7.0. Will likely change or be removed in a future
  1025. * version
  1026. */
  1027. @Deprecated
  1028. protected boolean isAllowedVAADINResourceUrl(HttpServletRequest request,
  1029. URL resourceUrl) {
  1030. String resourcePath = resourceUrl.getPath();
  1031. if ("jar".equals(resourceUrl.getProtocol())) {
  1032. // This branch is used for accessing resources directly from the
  1033. // Vaadin JAR in development environments and in similar cases.
  1034. // Inside a JAR, a ".." would mean a real directory named ".." so
  1035. // using it in paths should just result in the file not being found.
  1036. // However, performing a check in case some servers or class loaders
  1037. // try to normalize the path by collapsing ".." before the class
  1038. // loader sees it.
  1039. if (!resourcePath.contains("!/VAADIN/")
  1040. && !resourcePath.contains("!/META-INF/resources/VAADIN/")) {
  1041. getLogger().log(Level.INFO,
  1042. "Blocked attempt to access a JAR entry not starting with /VAADIN/: {0}",
  1043. resourceUrl);
  1044. return false;
  1045. }
  1046. getLogger().log(Level.FINE,
  1047. "Accepted access to a JAR entry using a class loader: {0}",
  1048. resourceUrl);
  1049. return true;
  1050. } else {
  1051. // Some servers such as GlassFish extract files from JARs (file:)
  1052. // and e.g. JBoss 5+ use protocols vsf: and vfsfile: .
  1053. // Check that the URL is in a VAADIN directory and does not contain
  1054. // "/../"
  1055. if (!resourcePath.contains("/VAADIN/")
  1056. || resourcePath.contains("/../")) {
  1057. getLogger().log(Level.INFO,
  1058. "Blocked attempt to access file: {0}", resourceUrl);
  1059. return false;
  1060. }
  1061. getLogger().log(Level.FINE,
  1062. "Accepted access to a file using a class loader: {0}",
  1063. resourceUrl);
  1064. return true;
  1065. }
  1066. }
  1067. /**
  1068. * Checks if the browser has an up to date cached version of requested
  1069. * resource. Currently the check is performed using the "If-Modified-Since"
  1070. * header. Could be expanded if needed.
  1071. *
  1072. * @param request
  1073. * The HttpServletRequest from the browser.
  1074. * @param resourceLastModifiedTimestamp
  1075. * The timestamp when the resource was last modified. 0 if the
  1076. * last modification time is unknown.
  1077. * @return true if the If-Modified-Since header tells the cached version in
  1078. * the browser is up to date, false otherwise
  1079. */
  1080. private boolean browserHasNewestVersion(HttpServletRequest request,
  1081. long resourceLastModifiedTimestamp) {
  1082. if (resourceLastModifiedTimestamp < 1) {
  1083. // We do not know when it was modified so the browser cannot have an
  1084. // up-to-date version
  1085. return false;
  1086. }
  1087. /*
  1088. * The browser can request the resource conditionally using an
  1089. * If-Modified-Since header. Check this against the last modification
  1090. * time.
  1091. */
  1092. try {
  1093. // If-Modified-Since represents the timestamp of the version cached
  1094. // in the browser
  1095. long headerIfModifiedSince = request
  1096. .getDateHeader("If-Modified-Since");
  1097. if (headerIfModifiedSince >= resourceLastModifiedTimestamp) {
  1098. // Browser has this an up-to-date version of the resource
  1099. return true;
  1100. }
  1101. } catch (Exception e) {
  1102. // Failed to parse header. Fail silently - the browser does not have
  1103. // an up-to-date version in its cache.
  1104. }
  1105. return false;
  1106. }
  1107. /**
  1108. *
  1109. * @author Vaadin Ltd
  1110. * @since 7.0
  1111. *
  1112. * @deprecated As of 7.0. This is no longer used and only provided for
  1113. * backwards compatibility. Each {@link RequestHandler} can
  1114. * individually decide whether it wants to handle a request or
  1115. * not.
  1116. */
  1117. @Deprecated
  1118. protected enum RequestType {
  1119. FILE_UPLOAD, BROWSER_DETAILS, UIDL, OTHER, STATIC_FILE, APP, PUBLISHED_FILE, HEARTBEAT;
  1120. }
  1121. /**
  1122. * @param request
  1123. * @return
  1124. *
  1125. * @deprecated As of 7.0. This is no longer used and only provided for
  1126. * backwards compatibility. Each {@link RequestHandler} can
  1127. * individually decide whether it wants to handle a request or
  1128. * not.
  1129. */
  1130. @Deprecated
  1131. protected RequestType getRequestType(VaadinServletRequest request) {
  1132. if (ServletPortletHelper.isFileUploadRequest(request)) {
  1133. return RequestType.FILE_UPLOAD;
  1134. } else if (ServletPortletHelper.isPublishedFileRequest(request)) {
  1135. return RequestType.PUBLISHED_FILE;
  1136. } else if (ServletUIInitHandler.isUIInitRequest(request)) {
  1137. return RequestType.BROWSER_DETAILS;
  1138. } else if (ServletPortletHelper.isUIDLRequest(request)) {
  1139. return RequestType.UIDL;
  1140. } else if (isStaticResourceRequest(request)) {
  1141. return RequestType.STATIC_FILE;
  1142. } else if (ServletPortletHelper.isAppRequest(request)) {
  1143. return RequestType.APP;
  1144. } else if (ServletPortletHelper.isHeartbeatRequest(request)) {
  1145. return RequestType.HEARTBEAT;
  1146. }
  1147. return RequestType.OTHER;
  1148. }
  1149. protected boolean isStaticResourceRequest(HttpServletRequest request) {
  1150. return getStaticFilePath(request) != null;
  1151. }
  1152. /**
  1153. * Returns the relative path at which static files are served for a request
  1154. * (if any).
  1155. *
  1156. * @param request
  1157. * HTTP request
  1158. * @return relative servlet path or null if the request path does not
  1159. * contain "/VAADIN/" or the request has no path info
  1160. * @since 8.0
  1161. */
  1162. protected String getStaticFilePath(HttpServletRequest request) {
  1163. String pathInfo = request.getPathInfo();
  1164. if (pathInfo == null) {
  1165. return null;
  1166. }
  1167. // Servlet mapped as /* serves at /VAADIN
  1168. // Servlet mapped as /foo/bar/* serves at /foo/bar/VAADIN
  1169. if (pathInfo.startsWith("/VAADIN/")) {
  1170. return pathInfo;
  1171. }
  1172. String servletPrefixedPath = request.getServletPath() + pathInfo;
  1173. // Servlet mapped as /VAADIN/*
  1174. if (servletPrefixedPath.startsWith("/VAADIN/")) {
  1175. return servletPrefixedPath;
  1176. }
  1177. return null;
  1178. }
  1179. /**
  1180. * Remove any heading or trailing "what" from the "string".
  1181. *
  1182. * @param string
  1183. * @param what
  1184. * @return
  1185. */
  1186. static String removeHeadingOrTrailing(String string, String what) {
  1187. while (string.startsWith(what)) {
  1188. string = string.substring(1);
  1189. }
  1190. while (string.endsWith(what)) {
  1191. string = string.substring(0, string.length() - 1);
  1192. }
  1193. return string;
  1194. }
  1195. /**
  1196. * Gets the current application URL from request.
  1197. *
  1198. * @param request
  1199. * the HTTP request.
  1200. * @throws MalformedURLException
  1201. * if the application is denied access to the persistent data
  1202. * store represented by the given URL.
  1203. *
  1204. * @deprecated As of 7.0. Will likely change or be removed in a future
  1205. * version
  1206. */
  1207. @Deprecated
  1208. protected URL getApplicationUrl(HttpServletRequest request)
  1209. throws MalformedURLException {
  1210. final URL reqURL = new URL((request.isSecure() ? "https://" : "http://")
  1211. + request.getServerName()
  1212. + (request.isSecure() && request.getServerPort() == 443
  1213. || !request.isSecure() && request.getServerPort() == 80
  1214. ? "" : ":" + request.getServerPort())
  1215. + request.getRequestURI());
  1216. String servletPath = "";
  1217. if (request
  1218. .getAttribute("javax.servlet.include.servlet_path") != null) {
  1219. // this is an include request
  1220. servletPath = request
  1221. .getAttribute("javax.servlet.include.context_path")
  1222. .toString()
  1223. + request
  1224. .getAttribute("javax.servlet.include.servlet_path");
  1225. } else {
  1226. servletPath = request.getContextPath() + request.getServletPath();
  1227. }
  1228. if (servletPath.length() == 0
  1229. || servletPath.charAt(servletPath.length() - 1) != '/') {
  1230. servletPath += "/";
  1231. }
  1232. URL u = new URL(reqURL, servletPath);
  1233. return u;
  1234. }
  1235. /*
  1236. * (non-Javadoc)
  1237. *
  1238. * @see javax.servlet.GenericServlet#destroy()
  1239. */
  1240. @Override
  1241. public void destroy() {
  1242. super.destroy();
  1243. getService().destroy();
  1244. }
  1245. private static void persistCacheEntry(ScssCacheEntry cacheEntry) {
  1246. String scssFileName = cacheEntry.getScssFileName();
  1247. if (scssFileName == null) {
  1248. if (!scssCompileWarWarningEmitted) {
  1249. getLogger().warning(
  1250. "Could not persist scss cache because no real file was found for the compiled scss file. "
  1251. + "This might happen e.g. if serving the scss file directly from a .war file.");
  1252. scssCompileWarWarningEmitted = true;
  1253. }
  1254. return;
  1255. }
  1256. File scssFile = new File(scssFileName);
  1257. File cacheFile = getScssCacheFile(scssFile);
  1258. String cacheEntryJsonString = cacheEntry.asJson();
  1259. try {
  1260. writeFile(cacheEntryJsonString, cacheFile, StandardCharsets.UTF_8);
  1261. } catch (IOException e) {
  1262. getLogger().log(Level.WARNING,
  1263. "Error persisting scss cache " + cacheFile, e);
  1264. }
  1265. }
  1266. private static String readFile(File file, Charset charset)
  1267. throws IOException {
  1268. try (InputStream in = new FileInputStream(file)) {
  1269. // no point in reading files over 2GB to a String
  1270. byte[] b = new byte[(int) file.length()];
  1271. int len = b.length;
  1272. int total = 0;
  1273. while (total < len) {
  1274. int result = in.read(b, total, len - total);
  1275. if (result == -1) {
  1276. break;
  1277. }
  1278. total += result;
  1279. }
  1280. return new String(b, charset);
  1281. }
  1282. }
  1283. private static void writeFile(String content, File file, Charset charset)
  1284. throws IOException {
  1285. try (FileOutputStream fos = new FileOutputStream(file)) {
  1286. fos.write(content.getBytes(charset));
  1287. }
  1288. }
  1289. private static File getScssCacheFile(File scssFile) {
  1290. return new File(scssFile.getParentFile(),
  1291. scssFile.getName() + ".cache");
  1292. }
  1293. /**
  1294. * Escapes characters to html entities. An exception is made for some "safe
  1295. * characters" to keep the text somewhat readable.
  1296. *
  1297. * @param unsafe
  1298. * @return a safe string to be added inside an html tag
  1299. *
  1300. * @deprecated As of 7.0. Will likely change or be removed in a future
  1301. * version
  1302. */
  1303. @Deprecated
  1304. public static final String safeEscapeForHtml(String unsafe) {
  1305. if (null == unsafe) {
  1306. return null;
  1307. }
  1308. StringBuilder safe = new StringBuilder();
  1309. char[] charArray = unsafe.toCharArray();
  1310. for (char c : charArray) {
  1311. if (isSafe(c)) {
  1312. safe.append(c);
  1313. } else {
  1314. safe.append("&#");
  1315. safe.append((int) c);
  1316. safe.append(";");
  1317. }
  1318. }
  1319. return safe.toString();
  1320. }
  1321. private static boolean isSafe(char c) {
  1322. return //
  1323. c > 47 && c < 58 || // alphanum
  1324. c > 64 && c < 91 || // A-Z
  1325. c > 96 && c < 123 // a-z
  1326. ;
  1327. }
  1328. private static final Logger getLogger() {
  1329. return Logger.getLogger(VaadinServlet.class.getName());
  1330. }
  1331. }