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.

ApplicationRunnerServlet.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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.launcher;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.io.Serializable;
  20. import java.lang.reflect.InvocationHandler;
  21. import java.lang.reflect.Method;
  22. import java.lang.reflect.Proxy;
  23. import java.net.MalformedURLException;
  24. import java.net.URI;
  25. import java.net.URISyntaxException;
  26. import java.net.URL;
  27. import java.util.Arrays;
  28. import java.util.Collections;
  29. import java.util.LinkedHashSet;
  30. import java.util.LinkedList;
  31. import java.util.Map;
  32. import java.util.Properties;
  33. import java.util.logging.Level;
  34. import java.util.logging.Logger;
  35. import javax.servlet.ServletConfig;
  36. import javax.servlet.ServletException;
  37. import javax.servlet.http.HttpServletRequest;
  38. import javax.servlet.http.HttpServletResponse;
  39. import javax.servlet.http.HttpSession;
  40. import com.vaadin.launcher.CustomDeploymentConfiguration.Conf;
  41. import com.vaadin.server.DefaultDeploymentConfiguration;
  42. import com.vaadin.server.DeploymentConfiguration;
  43. import com.vaadin.server.LegacyApplication;
  44. import com.vaadin.server.LegacyVaadinServlet;
  45. import com.vaadin.server.ServiceException;
  46. import com.vaadin.server.SystemMessages;
  47. import com.vaadin.server.SystemMessagesProvider;
  48. import com.vaadin.server.UIClassSelectionEvent;
  49. import com.vaadin.server.UICreateEvent;
  50. import com.vaadin.server.UIProvider;
  51. import com.vaadin.server.VaadinRequest;
  52. import com.vaadin.server.VaadinService;
  53. import com.vaadin.server.VaadinServlet;
  54. import com.vaadin.server.VaadinServletRequest;
  55. import com.vaadin.server.VaadinServletService;
  56. import com.vaadin.server.VaadinSession;
  57. import com.vaadin.shared.ApplicationConstants;
  58. import com.vaadin.tests.components.TestBase;
  59. import com.vaadin.ui.UI;
  60. import com.vaadin.util.CurrentInstance;
  61. @SuppressWarnings("serial")
  62. public class ApplicationRunnerServlet extends LegacyVaadinServlet {
  63. private static class ApplicationRunnerRedirectException
  64. extends RuntimeException {
  65. private final String target;
  66. public ApplicationRunnerRedirectException(String target) {
  67. this.target = target;
  68. }
  69. public String getTarget() {
  70. return target;
  71. }
  72. public static String extractRedirectTarget(ServletException e) {
  73. Throwable cause = e.getCause();
  74. if (cause instanceof ServiceException) {
  75. ServiceException se = (ServiceException) cause;
  76. Throwable serviceCause = se.getCause();
  77. if (serviceCause instanceof ApplicationRunnerRedirectException) {
  78. ApplicationRunnerRedirectException redirect = (ApplicationRunnerRedirectException) serviceCause;
  79. return redirect.getTarget();
  80. }
  81. }
  82. return null;
  83. }
  84. }
  85. public static String CUSTOM_SYSTEM_MESSAGES_PROPERTY = "custom-"
  86. + SystemMessages.class.getName();
  87. /**
  88. * The name of the application class currently used. Only valid within one
  89. * request.
  90. */
  91. private LinkedHashSet<String> defaultPackages = new LinkedHashSet<>();
  92. private transient final ThreadLocal<HttpServletRequest> request = new ThreadLocal<>();
  93. @Override
  94. public void init(ServletConfig servletConfig) throws ServletException {
  95. super.init(servletConfig);
  96. String initParameter = servletConfig
  97. .getInitParameter("defaultPackages");
  98. if (initParameter != null) {
  99. Collections.addAll(defaultPackages, initParameter.split(","));
  100. }
  101. String str = TestBase.class.getName().replace('.', '/') + ".class";
  102. URL url = getService().getClassLoader().getResource(str);
  103. if ("file".equals(url.getProtocol())) {
  104. String path = url.getPath();
  105. try {
  106. path = new URI(path).getPath();
  107. } catch (URISyntaxException e) {
  108. getLogger().log(Level.FINE, "Failed to decode url", e);
  109. }
  110. File comVaadinTests = new File(path).getParentFile()
  111. .getParentFile();
  112. addDirectories(comVaadinTests, defaultPackages, "com.vaadin.tests");
  113. }
  114. }
  115. @Override
  116. protected void servletInitialized() throws ServletException {
  117. super.servletInitialized();
  118. getService().addSessionInitListener(
  119. event -> onVaadinSessionStarted(event.getRequest(), event.getSession()));
  120. }
  121. private void addDirectories(File parent, LinkedHashSet<String> packages,
  122. String parentPackage) {
  123. packages.add(parentPackage);
  124. for (File f : parent.listFiles()) {
  125. if (f.isDirectory()) {
  126. String newPackage = parentPackage + "." + f.getName();
  127. addDirectories(f, packages, newPackage);
  128. }
  129. }
  130. }
  131. @Override
  132. protected void service(HttpServletRequest request,
  133. HttpServletResponse response) throws ServletException, IOException {
  134. this.request.set(request);
  135. try {
  136. super.service(request, response);
  137. } catch (ServletException e) {
  138. String redirectTarget = ApplicationRunnerRedirectException
  139. .extractRedirectTarget(e);
  140. if (redirectTarget != null) {
  141. response.sendRedirect(redirectTarget + "?restartApplication");
  142. } else {
  143. // Not the exception we were looking for, just rethrow
  144. throw e;
  145. }
  146. } finally {
  147. this.request.set(null);
  148. }
  149. }
  150. @Override
  151. protected URL getApplicationUrl(HttpServletRequest request)
  152. throws MalformedURLException {
  153. URL url = super.getApplicationUrl(request);
  154. String path = url.toString();
  155. path += getApplicationRunnerApplicationClassName(request);
  156. path += "/";
  157. return new URL(path);
  158. }
  159. @Override
  160. protected Class<? extends LegacyApplication> getApplicationClass()
  161. throws ClassNotFoundException {
  162. return getClassToRun().asSubclass(LegacyApplication.class);
  163. }
  164. @Override
  165. protected boolean shouldCreateApplication(HttpServletRequest request)
  166. throws ServletException {
  167. try {
  168. return LegacyApplication.class.isAssignableFrom(getClassToRun());
  169. } catch (ClassNotFoundException e) {
  170. throw new ServletException(e);
  171. }
  172. }
  173. protected void onVaadinSessionStarted(VaadinRequest request,
  174. VaadinSession session) throws ServiceException {
  175. try {
  176. final Class<?> classToRun = getClassToRun();
  177. if (UI.class.isAssignableFrom(classToRun)) {
  178. session.addUIProvider(
  179. new ApplicationRunnerUIProvider(classToRun));
  180. } else if (LegacyApplication.class.isAssignableFrom(classToRun)) {
  181. // Avoid using own UIProvider for legacy Application
  182. } else if (UIProvider.class.isAssignableFrom(classToRun)) {
  183. session.addUIProvider((UIProvider) classToRun.newInstance());
  184. } else {
  185. throw new ServiceException(classToRun.getCanonicalName()
  186. + " is neither an Application nor a UI");
  187. }
  188. } catch (final IllegalAccessException e) {
  189. throw new ServiceException(e);
  190. } catch (final InstantiationException e) {
  191. throw new ServiceException(e);
  192. } catch (final ClassNotFoundException e) {
  193. throw new ServiceException(new InstantiationException(
  194. "Failed to load application class: "
  195. + getApplicationRunnerApplicationClassName(
  196. (VaadinServletRequest) request)));
  197. }
  198. }
  199. private String getApplicationRunnerApplicationClassName(
  200. HttpServletRequest request) {
  201. return getApplicationRunnerURIs(request).applicationClassname;
  202. }
  203. private static final class ProxyDeploymentConfiguration
  204. implements InvocationHandler, Serializable {
  205. private final DeploymentConfiguration originalConfiguration;
  206. private ProxyDeploymentConfiguration(
  207. DeploymentConfiguration originalConfiguration) {
  208. this.originalConfiguration = originalConfiguration;
  209. }
  210. @Override
  211. public Object invoke(Object proxy, Method method, Object[] args)
  212. throws Throwable {
  213. if (method.getDeclaringClass() == DeploymentConfiguration.class) {
  214. // Find the configuration instance to delegate to
  215. DeploymentConfiguration configuration = findDeploymentConfiguration(
  216. originalConfiguration);
  217. return method.invoke(configuration, args);
  218. } else {
  219. return method.invoke(proxy, args);
  220. }
  221. }
  222. }
  223. private static final class ApplicationRunnerUIProvider extends UIProvider {
  224. private final Class<?> classToRun;
  225. private ApplicationRunnerUIProvider(Class<?> classToRun) {
  226. this.classToRun = classToRun;
  227. }
  228. @Override
  229. public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
  230. return (Class<? extends UI>) classToRun;
  231. }
  232. @Override
  233. public UI createInstance(UICreateEvent event) {
  234. event.getRequest().setAttribute(ApplicationConstants.UI_ROOT_PATH,
  235. "/" + event.getUIClass().getName());
  236. return super.createInstance(event);
  237. }
  238. }
  239. // TODO Don't need to use a data object now that there's only one field
  240. private static class URIS {
  241. // String staticFilesPath;
  242. // String applicationURI;
  243. // String context;
  244. // String runner;
  245. String applicationClassname;
  246. }
  247. /**
  248. * Parses application runner URIs.
  249. *
  250. * If request URL is e.g.
  251. * http://localhost:8080/vaadin/run/com.vaadin.demo.Calc then
  252. * <ul>
  253. * <li>context=vaadin</li>
  254. * <li>Runner servlet=run</li>
  255. * <li>Vaadin application=com.vaadin.demo.Calc</li>
  256. * </ul>
  257. *
  258. * @param request
  259. * @return string array containing widgetset URI, application URI and
  260. * context, runner, application classname
  261. */
  262. private static URIS getApplicationRunnerURIs(HttpServletRequest request) {
  263. final String[] urlParts = request.getRequestURI().split("\\/");
  264. // String runner = null;
  265. URIS uris = new URIS();
  266. String applicationClassname = null;
  267. String contextPath = request.getContextPath();
  268. if (urlParts[1].equals(contextPath.replaceAll("\\/", ""))) {
  269. // class name comes after web context and runner application
  270. // runner = urlParts[2];
  271. if (urlParts.length == 3) {
  272. throw new ApplicationRunnerRedirectException(
  273. findLastModifiedApplication());
  274. } else {
  275. applicationClassname = urlParts[3];
  276. }
  277. // uris.applicationURI = "/" + context + "/" + runner + "/"
  278. // + applicationClassname;
  279. // uris.context = context;
  280. // uris.runner = runner;
  281. uris.applicationClassname = applicationClassname;
  282. } else {
  283. // no context
  284. // runner = urlParts[1];
  285. if (urlParts.length == 2) {
  286. throw new ApplicationRunnerRedirectException(
  287. findLastModifiedApplication());
  288. } else {
  289. applicationClassname = urlParts[2];
  290. }
  291. // uris.applicationURI = "/" + runner + "/" + applicationClassname;
  292. // uris.context = context;
  293. // uris.runner = runner;
  294. uris.applicationClassname = applicationClassname;
  295. }
  296. return uris;
  297. }
  298. private static String findLastModifiedApplication() {
  299. String lastModifiedClassName = null;
  300. File uitestDir = new File("src/main/java");
  301. if (uitestDir.isDirectory()) {
  302. LinkedList<File> stack = new LinkedList<>();
  303. stack.add(uitestDir);
  304. long lastModifiedTimestamp = Long.MIN_VALUE;
  305. while (!stack.isEmpty()) {
  306. File file = stack.pop();
  307. if (file.isDirectory()) {
  308. stack.addAll(Arrays.asList(file.listFiles()));
  309. } else if (file.getName().endsWith(".java")) {
  310. if (lastModifiedTimestamp < file.lastModified()) {
  311. String className = file.getPath()
  312. .substring(uitestDir.getPath().length() + 1)
  313. .replace(File.separatorChar, '.');
  314. className = className.substring(0,
  315. className.length() - ".java".length());
  316. if (isSupportedClass(className)) {
  317. lastModifiedTimestamp = file.lastModified();
  318. lastModifiedClassName = className;
  319. }
  320. }
  321. }
  322. }
  323. }
  324. if (lastModifiedClassName == null) {
  325. throw new IllegalArgumentException("No application specified");
  326. } else {
  327. return lastModifiedClassName;
  328. }
  329. }
  330. private static boolean isSupportedClass(String className) {
  331. try {
  332. Class<?> type = Class.forName(className, false,
  333. ApplicationRunnerServlet.class.getClassLoader());
  334. if (UI.class.isAssignableFrom(type)) {
  335. return true;
  336. } else if (LegacyApplication.class.isAssignableFrom(type)) {
  337. return true;
  338. } else if (UIProvider.class.isAssignableFrom(type)) {
  339. return true;
  340. }
  341. return false;
  342. } catch (Exception e) {
  343. return false;
  344. }
  345. }
  346. private Class<?> getClassToRun() throws ClassNotFoundException {
  347. // TODO use getClassLoader() ?
  348. Class<?> appClass = null;
  349. String baseName = getApplicationRunnerApplicationClassName(
  350. request.get());
  351. try {
  352. appClass = getClass().getClassLoader().loadClass(baseName);
  353. return appClass;
  354. } catch (Exception e) {
  355. //
  356. for (String pkg : defaultPackages) {
  357. try {
  358. appClass = getClass().getClassLoader()
  359. .loadClass(pkg + "." + baseName);
  360. } catch (ClassNotFoundException ee) {
  361. // Ignore as this is expected for many packages
  362. } catch (Exception e2) {
  363. // TODO: handle exception
  364. getLogger().log(Level.FINE,
  365. "Failed to find application class " + pkg + "."
  366. + baseName,
  367. e2);
  368. }
  369. if (appClass != null) {
  370. return appClass;
  371. }
  372. }
  373. }
  374. throw new ClassNotFoundException(baseName);
  375. }
  376. private Logger getLogger() {
  377. return Logger.getLogger(ApplicationRunnerServlet.class.getName());
  378. }
  379. @Override
  380. protected DeploymentConfiguration createDeploymentConfiguration(
  381. Properties initParameters) {
  382. // Get the original configuration from the super class
  383. final DeploymentConfiguration originalConfiguration = super.createDeploymentConfiguration(
  384. initParameters);
  385. // And then create a proxy instance that delegates to the original
  386. // configuration or a customized version
  387. return (DeploymentConfiguration) Proxy.newProxyInstance(
  388. DeploymentConfiguration.class.getClassLoader(),
  389. new Class[] { DeploymentConfiguration.class },
  390. new ProxyDeploymentConfiguration(originalConfiguration));
  391. }
  392. @Override
  393. protected VaadinServletService createServletService(
  394. DeploymentConfiguration deploymentConfiguration)
  395. throws ServiceException {
  396. VaadinServletService service = super.createServletService(
  397. deploymentConfiguration);
  398. final SystemMessagesProvider provider = service
  399. .getSystemMessagesProvider();
  400. service.setSystemMessagesProvider(systemMessagesInfo -> {
  401. if (systemMessagesInfo.getRequest() == null) {
  402. return provider.getSystemMessages(systemMessagesInfo);
  403. }
  404. Object messages = systemMessagesInfo.getRequest()
  405. .getAttribute(CUSTOM_SYSTEM_MESSAGES_PROPERTY);
  406. if (messages instanceof SystemMessages) {
  407. return (SystemMessages) messages;
  408. }
  409. return provider.getSystemMessages(systemMessagesInfo);
  410. });
  411. return service;
  412. }
  413. private static DeploymentConfiguration findDeploymentConfiguration(
  414. DeploymentConfiguration originalConfiguration) throws Exception {
  415. // First level of cache
  416. DeploymentConfiguration configuration = CurrentInstance
  417. .get(DeploymentConfiguration.class);
  418. if (configuration == null) {
  419. // Not in cache, try to find a VaadinSession to get it from
  420. VaadinSession session = VaadinSession.getCurrent();
  421. if (session == null) {
  422. /*
  423. * There's no current session, request or response when serving
  424. * static resources, but there's still the current request
  425. * maintained by AppliationRunnerServlet, and there's most
  426. * likely also a HttpSession containing a VaadinSession for that
  427. * request.
  428. */
  429. HttpServletRequest currentRequest = VaadinServletService
  430. .getCurrentServletRequest();
  431. if (currentRequest != null) {
  432. HttpSession httpSession = currentRequest.getSession(false);
  433. if (httpSession != null) {
  434. Map<Class<?>, CurrentInstance> oldCurrent = CurrentInstance
  435. .setCurrent((VaadinSession) null);
  436. try {
  437. VaadinServletService service = (VaadinServletService) VaadinService
  438. .getCurrent();
  439. session = service.findVaadinSession(
  440. new VaadinServletRequest(currentRequest,
  441. service));
  442. } finally {
  443. /*
  444. * Clear some state set by findVaadinSession to
  445. * avoid accidentally depending on it when coding on
  446. * e.g. static request handling.
  447. */
  448. CurrentInstance.restoreInstances(oldCurrent);
  449. currentRequest.removeAttribute(
  450. VaadinSession.class.getName());
  451. }
  452. }
  453. }
  454. }
  455. if (session != null) {
  456. String name = ApplicationRunnerServlet.class.getName()
  457. + ".deploymentConfiguration";
  458. try {
  459. session.lock();
  460. configuration = (DeploymentConfiguration) session
  461. .getAttribute(name);
  462. if (configuration == null) {
  463. ApplicationRunnerServlet servlet = (ApplicationRunnerServlet) VaadinServlet
  464. .getCurrent();
  465. Class<?> classToRun;
  466. try {
  467. classToRun = servlet.getClassToRun();
  468. } catch (ClassNotFoundException e) {
  469. /*
  470. * This happens e.g. if the UI class defined in the
  471. * URL is not found or if this servlet just serves
  472. * static resources while there's some other servlet
  473. * that serves the UI (e.g. when using /run-push/).
  474. */
  475. return originalConfiguration;
  476. }
  477. CustomDeploymentConfiguration customDeploymentConfiguration = classToRun
  478. .getAnnotation(
  479. CustomDeploymentConfiguration.class);
  480. if (customDeploymentConfiguration != null) {
  481. Properties initParameters = new Properties(
  482. originalConfiguration.getInitParameters());
  483. for (Conf entry : customDeploymentConfiguration
  484. .value()) {
  485. initParameters.put(entry.name(), entry.value());
  486. }
  487. configuration = new DefaultDeploymentConfiguration(
  488. servlet.getClass(), initParameters);
  489. } else {
  490. configuration = originalConfiguration;
  491. }
  492. session.setAttribute(name, configuration);
  493. }
  494. } finally {
  495. session.unlock();
  496. }
  497. CurrentInstance.set(DeploymentConfiguration.class,
  498. configuration);
  499. } else {
  500. configuration = originalConfiguration;
  501. }
  502. }
  503. return configuration;
  504. }
  505. }