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.

ApplicationServlet.java 56KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. /* *************************************************************************
  2. IT Mill Toolkit
  3. Development of Browser User Intarfaces Made Easy
  4. Copyright (C) 2000-2006 IT Mill Ltd
  5. *************************************************************************
  6. This product is distributed under commercial license that can be found
  7. from the product package on license/license.txt. Use of this product might
  8. require purchasing a commercial license from IT Mill Ltd. For guidelines
  9. on usage, see license/licensing-guidelines.html
  10. *************************************************************************
  11. For more information, contact:
  12. IT Mill Ltd phone: +358 2 4802 7180
  13. Ruukinkatu 2-4 fax: +358 2 4802 7181
  14. 20540, Turku email: info@itmill.com
  15. Finland company www: www.itmill.com
  16. Primary source for information and releases: www.itmill.com
  17. ********************************************************************** */
  18. package com.itmill.toolkit.terminal.web;
  19. import java.io.BufferedReader;
  20. import java.io.BufferedWriter;
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.InputStreamReader;
  26. import java.io.OutputStream;
  27. import java.io.OutputStreamWriter;
  28. import java.io.PrintWriter;
  29. import java.net.MalformedURLException;
  30. import java.net.URL;
  31. import java.util.Arrays;
  32. import java.util.Collection;
  33. import java.util.Date;
  34. import java.util.Enumeration;
  35. import java.util.HashMap;
  36. import java.util.HashSet;
  37. import java.util.Iterator;
  38. import java.util.LinkedList;
  39. import java.util.List;
  40. import java.util.Map;
  41. import java.util.Properties;
  42. import java.util.Set;
  43. import java.util.StringTokenizer;
  44. import java.util.Vector;
  45. import java.util.WeakHashMap;
  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 javax.servlet.http.HttpSession;
  52. import javax.servlet.http.HttpSessionBindingEvent;
  53. import javax.servlet.http.HttpSessionBindingListener;
  54. import org.xml.sax.SAXException;
  55. import com.itmill.toolkit.Application;
  56. import com.itmill.toolkit.Application.WindowAttachEvent;
  57. import com.itmill.toolkit.Application.WindowDetachEvent;
  58. import com.itmill.toolkit.service.FileTypeResolver;
  59. import com.itmill.toolkit.service.License;
  60. import com.itmill.toolkit.service.License.InvalidLicenseFile;
  61. import com.itmill.toolkit.service.License.LicenseFileHasAlreadyBeenRead;
  62. import com.itmill.toolkit.service.License.LicenseFileHasNotBeenRead;
  63. import com.itmill.toolkit.service.License.LicenseSignatureIsInvalid;
  64. import com.itmill.toolkit.service.License.LicenseViolation;
  65. import com.itmill.toolkit.terminal.DownloadStream;
  66. import com.itmill.toolkit.terminal.Paintable;
  67. import com.itmill.toolkit.terminal.ParameterHandler;
  68. import com.itmill.toolkit.terminal.ThemeResource;
  69. import com.itmill.toolkit.terminal.URIHandler;
  70. import com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent;
  71. import com.itmill.toolkit.terminal.web.ThemeSource.ThemeException;
  72. import com.itmill.toolkit.ui.Window;
  73. /**
  74. * This servlet connects IT Mill Toolkit Application to Web. This servlet
  75. * replaces both WebAdapterServlet and AjaxAdapterServlet.
  76. *
  77. * @author IT Mill Ltd.
  78. * @version
  79. * @VERSION@
  80. * @since 4.0
  81. */
  82. public class ApplicationServlet extends HttpServlet implements
  83. Application.WindowAttachListener, Application.WindowDetachListener,
  84. Paintable.RepaintRequestListener {
  85. private static final long serialVersionUID = -4937882979845826574L;
  86. /** Version number of this release. For example "4.0.0" */
  87. public static final String VERSION;
  88. /** Major version number. For example 4 in 4.1.0. */
  89. public static final int VERSION_MAJOR;
  90. /** Minor version number. For example 1 in 4.1.0. */
  91. public static final int VERSION_MINOR;
  92. /** Build number. For example 0-beta1 in 4.0.0-beta1. */
  93. public static final String VERSION_BUILD;
  94. /* Initialize version numbers from string replaced by build-script. */
  95. static {
  96. if ("@VERSION@".equals("@" + "VERSION" + "@"))
  97. VERSION = "4.0.0-INTERNAL-NONVERSIONED-DEBUG-BUILD";
  98. else
  99. VERSION = "@VERSION@";
  100. String[] digits = VERSION.split("\\.");
  101. VERSION_MAJOR = Integer.parseInt(digits[0]);
  102. VERSION_MINOR = Integer.parseInt(digits[1]);
  103. VERSION_BUILD = digits[2];
  104. }
  105. // Configurable parameter names
  106. private static final String PARAMETER_DEBUG = "Debug";
  107. private static final String PARAMETER_DEFAULT_THEME_JAR = "DefaultThemeJar";
  108. private static final String PARAMETER_THEMESOURCE = "ThemeSource";
  109. private static final String PARAMETER_THEME_CACHETIME = "ThemeCacheTime";
  110. private static final String PARAMETER_MAX_TRANSFORMERS = "MaxTransformers";
  111. private static final String PARAMETER_TRANSFORMER_CACHETIME = "TransformerCacheTime";
  112. private static final int DEFAULT_THEME_CACHETIME = 1000 * 60 * 60 * 24;
  113. private static final int DEFAULT_BUFFER_SIZE = 32 * 1024;
  114. private static final int DEFAULT_MAX_TRANSFORMERS = 1;
  115. private static final int MAX_BUFFER_SIZE = 64 * 1024;
  116. private static final String SESSION_ATTR_VARMAP = "itmill-toolkit-varmap";
  117. private static final String SESSION_ATTR_CONTEXT = "itmill-toolkit-context";
  118. protected static final String SESSION_ATTR_APPS = "itmill-toolkit-apps";
  119. private static final String SESSION_BINDING_LISTENER = "itmill-toolkit-bindinglistener";
  120. // TODO Should default or base theme be the default?
  121. protected static final String DEFAULT_THEME = "base";
  122. private static final String RESOURCE_URI = "/RES/";
  123. private static final String AJAX_UIDL_URI = "/UIDL/";
  124. private static final String THEME_DIRECTORY_PATH = "WEB-INF/lib/themes/";
  125. private static final String THEME_LISTING_FILE = THEME_DIRECTORY_PATH
  126. + "themes.txt";
  127. private static final String DEFAULT_THEME_JAR_PREFIX = "itmill-toolkit-themes";
  128. private static final String DEFAULT_THEME_JAR = "WEB-INF/lib/"
  129. + DEFAULT_THEME_JAR_PREFIX + "-" + VERSION + ".jar";
  130. private static final String DEFAULT_THEME_TEMP_FILE_PREFIX = "ITMILL_TMP_";
  131. private static final String SERVER_COMMAND_PARAM = "SERVER_COMMANDS";
  132. private static final int SERVER_COMMAND_STREAM_MAINTAIN_PERIOD = 15000;
  133. private static final int SERVER_COMMAND_HEADER_PADDING = 2000;
  134. // Maximum delay between request for an user to be considered active (in ms)
  135. private static final long ACTIVE_USER_REQUEST_INTERVAL = 1000 * 45;
  136. // Private fields
  137. private Class applicationClass;
  138. private Properties applicationProperties;
  139. private UIDLTransformerFactory transformerFactory;
  140. private CollectionThemeSource themeSource;
  141. private String resourcePath = null;
  142. private String debugMode = "";
  143. private int maxConcurrentTransformers;
  144. private long transformerCacheTime;
  145. private long themeCacheTime;
  146. private WeakHashMap applicationToDirtyWindowSetMap = new WeakHashMap();
  147. private WeakHashMap applicationToServerCommandStreamLock = new WeakHashMap();
  148. private static WeakHashMap applicationToLastRequestDate = new WeakHashMap();
  149. private List allWindows = new LinkedList();
  150. private WeakHashMap applicationToAjaxAppMgrMap = new WeakHashMap();
  151. private HashMap licenseForApplicationClass = new HashMap();
  152. private static HashSet licensePrintedForApplicationClass = new HashSet();
  153. /**
  154. * Called by the servlet container to indicate to a servlet that the servlet
  155. * is being placed into service.
  156. *
  157. * @param servletConfig
  158. * object containing the servlet's configuration and
  159. * initialization parameters
  160. * @throws ServletException
  161. * if an exception has occurred that interferes with the
  162. * servlet's normal operation.
  163. */
  164. public void init(javax.servlet.ServletConfig servletConfig)
  165. throws javax.servlet.ServletException {
  166. super.init(servletConfig);
  167. // Get the application class name
  168. String applicationClassName = servletConfig
  169. .getInitParameter("application");
  170. if (applicationClassName == null) {
  171. Log.error("Application not specified in servlet parameters");
  172. }
  173. // Store the application parameters into Properties object
  174. this.applicationProperties = new Properties();
  175. for (Enumeration e = servletConfig.getInitParameterNames(); e
  176. .hasMoreElements();) {
  177. String name = (String) e.nextElement();
  178. this.applicationProperties.setProperty(name, servletConfig
  179. .getInitParameter(name));
  180. }
  181. // Override with server.xml parameters
  182. ServletContext context = servletConfig.getServletContext();
  183. for (Enumeration e = context.getInitParameterNames(); e
  184. .hasMoreElements();) {
  185. String name = (String) e.nextElement();
  186. this.applicationProperties.setProperty(name, context
  187. .getInitParameter(name));
  188. }
  189. // Get the debug window parameter
  190. String debug = getApplicationOrSystemProperty(PARAMETER_DEBUG, "")
  191. .toLowerCase();
  192. // Enable application specific debug
  193. if (!"".equals(debug) && !"true".equals(debug)
  194. && !"false".equals(debug))
  195. throw new ServletException(
  196. "If debug parameter is given for an application, it must be 'true' or 'false'");
  197. this.debugMode = debug;
  198. // Get the maximum number of simultaneous transformers
  199. this.maxConcurrentTransformers = Integer
  200. .parseInt(getApplicationOrSystemProperty(
  201. PARAMETER_MAX_TRANSFORMERS, "-1"));
  202. if (this.maxConcurrentTransformers < 1)
  203. this.maxConcurrentTransformers = DEFAULT_MAX_TRANSFORMERS;
  204. // Get cache time for transformers
  205. this.transformerCacheTime = Integer
  206. .parseInt(getApplicationOrSystemProperty(
  207. PARAMETER_TRANSFORMER_CACHETIME, "-1")) * 1000;
  208. // Get cache time for theme resources
  209. this.themeCacheTime = Integer.parseInt(getApplicationOrSystemProperty(
  210. PARAMETER_THEME_CACHETIME, "-1")) * 1000;
  211. if (this.themeCacheTime < 0) {
  212. this.themeCacheTime = DEFAULT_THEME_CACHETIME;
  213. }
  214. // Add all specified theme sources
  215. this.themeSource = new CollectionThemeSource();
  216. List directorySources = getThemeSources();
  217. for (Iterator i = directorySources.iterator(); i.hasNext();) {
  218. this.themeSource.add((ThemeSource) i.next());
  219. }
  220. // Add the default theme source
  221. String[] defaultThemeFiles = new String[] { getApplicationOrSystemProperty(
  222. PARAMETER_DEFAULT_THEME_JAR, DEFAULT_THEME_JAR) };
  223. File f = findDefaultThemeJar(defaultThemeFiles);
  224. try {
  225. // Add themes.jar if exists
  226. if (f != null && f.exists())
  227. this.themeSource.add(new JarThemeSource(f, this, ""));
  228. else {
  229. Log.warn("Default theme JAR not found in: "
  230. + Arrays.asList(defaultThemeFiles));
  231. }
  232. } catch (Exception e) {
  233. throw new ServletException("Failed to load default theme from "
  234. + Arrays.asList(defaultThemeFiles), e);
  235. }
  236. // Check that at least one themesource was loaded
  237. if (this.themeSource.getThemes().size() <= 0) {
  238. throw new ServletException(
  239. "No themes found in specified themesources.");
  240. }
  241. // Initialize the transformer factory, if not initialized
  242. if (this.transformerFactory == null) {
  243. this.transformerFactory = new UIDLTransformerFactory(
  244. this.themeSource, this, this.maxConcurrentTransformers,
  245. this.transformerCacheTime);
  246. }
  247. // Load the application class using the same class loader
  248. // as the servlet itself
  249. ClassLoader loader = this.getClass().getClassLoader();
  250. try {
  251. this.applicationClass = loader.loadClass(applicationClassName);
  252. } catch (ClassNotFoundException e) {
  253. throw new ServletException("Failed to load application class: "
  254. + applicationClassName);
  255. }
  256. }
  257. /**
  258. * Get an application or system property value.
  259. *
  260. * @param parameterName
  261. * Name or the parameter
  262. * @param defaultValue
  263. * Default to be used
  264. * @return String value or default if not found
  265. */
  266. private String getApplicationOrSystemProperty(String parameterName,
  267. String defaultValue) {
  268. // Try application properties
  269. String val = this.applicationProperties.getProperty(parameterName);
  270. if (val != null) {
  271. return val;
  272. }
  273. // Try lowercased application properties for backward compability with
  274. // 3.0.2 and earlier
  275. val = this.applicationProperties.getProperty(parameterName
  276. .toLowerCase());
  277. if (val != null) {
  278. return val;
  279. }
  280. // Try system properties
  281. String pkgName;
  282. Package pkg = this.getClass().getPackage();
  283. if (pkg != null) {
  284. pkgName = pkg.getName();
  285. } else {
  286. String clazzName = this.getClass().getName();
  287. pkgName = new String(clazzName.toCharArray(), 0, clazzName
  288. .lastIndexOf('.'));
  289. }
  290. val = System.getProperty(pkgName + "." + parameterName);
  291. if (val != null) {
  292. return val;
  293. }
  294. // Try lowercased system properties
  295. val = System.getProperty(pkgName + "." + parameterName.toLowerCase());
  296. if (val != null) {
  297. return val;
  298. }
  299. return defaultValue;
  300. }
  301. /**
  302. * Get ThemeSources from given path. Construct the list of avalable themes
  303. * in path using the following sources: 1. content of THEME_PATH directory
  304. * (if available) 2. The themes listed in THEME_LIST_FILE 3. "themesource"
  305. * application parameter - "org. millstone.webadapter. themesource" system
  306. * property
  307. *
  308. * @param THEME_DIRECTORY_PATH
  309. * @return List
  310. */
  311. private List getThemeSources() throws ServletException {
  312. List returnValue = new LinkedList();
  313. // Check the list file in theme directory
  314. List sourcePaths = new LinkedList();
  315. try {
  316. BufferedReader reader = new BufferedReader(new InputStreamReader(
  317. this.getServletContext().getResourceAsStream(
  318. THEME_LISTING_FILE)));
  319. String line = null;
  320. while ((line = reader.readLine()) != null) {
  321. sourcePaths.add(THEME_DIRECTORY_PATH + line.trim());
  322. }
  323. if (this.isDebugMode(null)) {
  324. Log.debug("Listed " + sourcePaths.size() + " themes in "
  325. + THEME_LISTING_FILE + ". Loading " + sourcePaths);
  326. }
  327. } catch (Exception ignored) {
  328. // If the file reading fails, just skip to next method
  329. }
  330. // If no file was found or it was empty,
  331. // try to add themes filesystem directory if it is accessible
  332. if (sourcePaths.size() <= 0) {
  333. if (this.isDebugMode(null)) {
  334. Log.debug("No themes listed in " + THEME_LISTING_FILE
  335. + ". Trying to read the content of directory "
  336. + THEME_DIRECTORY_PATH);
  337. }
  338. try {
  339. String path = this.getServletContext().getRealPath(
  340. THEME_DIRECTORY_PATH);
  341. if (path != null) {
  342. File f = new File(path);
  343. if (f != null && f.exists())
  344. returnValue.add(new DirectoryThemeSource(f, this));
  345. }
  346. } catch (java.io.IOException je) {
  347. Log.info("Theme directory " + THEME_DIRECTORY_PATH
  348. + " not available. Skipped.");
  349. } catch (ThemeException e) {
  350. throw new ServletException("Failed to load themes from "
  351. + THEME_DIRECTORY_PATH, e);
  352. }
  353. }
  354. // Add the theme sources from application properties
  355. String paramValue = getApplicationOrSystemProperty(
  356. PARAMETER_THEMESOURCE, null);
  357. if (paramValue != null) {
  358. StringTokenizer st = new StringTokenizer(paramValue, ";");
  359. while (st.hasMoreTokens()) {
  360. sourcePaths.add(st.nextToken());
  361. }
  362. }
  363. // Construct appropriate theme source instances for each path
  364. for (Iterator i = sourcePaths.iterator(); i.hasNext();) {
  365. String source = (String) i.next();
  366. File sourceFile = new File(source);
  367. try {
  368. // Relative files are treated as streams (to support
  369. // resource inside WAR files)
  370. if (!sourceFile.isAbsolute()) {
  371. returnValue.add(new ServletThemeSource(this
  372. .getServletContext(), this, source));
  373. } else if (sourceFile.isDirectory()) {
  374. // Absolute directories are read from filesystem
  375. returnValue.add(new DirectoryThemeSource(sourceFile, this));
  376. } else {
  377. // Absolute JAR-files are read from filesystem
  378. returnValue.add(new JarThemeSource(sourceFile, this, ""));
  379. }
  380. } catch (Exception e) {
  381. // Any exception breaks the the init
  382. throw new ServletException("Invalid theme source: " + source, e);
  383. }
  384. }
  385. // Return the constructed list of theme sources
  386. return returnValue;
  387. }
  388. /**
  389. * Receives standard HTTP requests from the public service method and
  390. * dispatches them.
  391. *
  392. * @param request
  393. * object that contains the request the client made of the
  394. * servlet
  395. * @param response
  396. * object that contains the response the servlet returns to the
  397. * client
  398. * @throws ServletException
  399. * if an input or output error occurs while the servlet is
  400. * handling the TRACE request
  401. * @throws IOException
  402. * if the request for the TRACE cannot be handled
  403. */
  404. protected void service(HttpServletRequest request,
  405. HttpServletResponse response) throws ServletException, IOException {
  406. // Transformer and output stream for the result
  407. UIDLTransformer transformer = null;
  408. HttpVariableMap variableMap = null;
  409. OutputStream out = response.getOutputStream();
  410. HashSet currentlyDirtyWindowsForThisApplication = new HashSet();
  411. Application application = null;
  412. try {
  413. // Handle resource requests
  414. if (handleResourceRequest(request, response))
  415. return;
  416. // Handle server commands
  417. if (handleServerCommands(request, response))
  418. return;
  419. // Get the application
  420. application = getApplication(request);
  421. // Create application if it doesn't exist
  422. if (application == null)
  423. application = createApplication(request);
  424. // Set the last application request date
  425. applicationToLastRequestDate.put(application, new Date());
  426. // Invoke context transaction listeners
  427. ((WebApplicationContext) application.getContext())
  428. .startTransaction(application, request);
  429. // Is this a download request from application
  430. DownloadStream download = null;
  431. // The rest of the process is synchronized with the application
  432. // in order to guarantee that no parallel variable handling is
  433. // made
  434. synchronized (application) {
  435. // Handle UIDL requests?
  436. String resourceId = request.getPathInfo();
  437. if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) {
  438. getApplicationManager(application).handleUidlRequest(
  439. request, response);
  440. return;
  441. }
  442. // Get the variable map
  443. variableMap = getVariableMap(application, request);
  444. if (variableMap == null)
  445. return;
  446. // Change all variables based on request parameters
  447. Map unhandledParameters = variableMap.handleVariables(request,
  448. application);
  449. // Check/handle client side feature checks
  450. WebBrowserProbe
  451. .handleProbeRequest(request, unhandledParameters);
  452. // Handle the URI if the application is still running
  453. if (application.isRunning())
  454. download = handleURI(application, request, response);
  455. // If this is not a download request
  456. if (download == null) {
  457. // Window renders are not cacheable
  458. response.setHeader("Cache-Control", "no-cache");
  459. response.setHeader("Pragma", "no-cache");
  460. response.setDateHeader("Expires", 0);
  461. // Find the window within the application
  462. Window window = null;
  463. if (application.isRunning())
  464. window = getApplicationWindow(request, application,
  465. unhandledParameters);
  466. // Handle the unhandled parameters if the application is
  467. // still running
  468. if (window != null && unhandledParameters != null
  469. && !unhandledParameters.isEmpty()) {
  470. try {
  471. window.handleParameters(unhandledParameters);
  472. } catch (Throwable t) {
  473. application
  474. .terminalError(new ParameterHandlerErrorImpl(
  475. window, t));
  476. }
  477. }
  478. // Remove application if it has stopped
  479. if (!application.isRunning()) {
  480. endApplication(request, response, application);
  481. return;
  482. }
  483. // Return blank page, if no window found
  484. if (window == null) {
  485. response.setContentType("text/html");
  486. BufferedWriter page = new BufferedWriter(
  487. new OutputStreamWriter(out));
  488. page.write("<html><head><script>");
  489. page
  490. .write(ThemeFunctionLibrary
  491. .generateWindowScript(
  492. null,
  493. application,
  494. this,
  495. WebBrowserProbe
  496. .getTerminalType(request
  497. .getSession())));
  498. page.write("</script></head><body>");
  499. page
  500. .write("The requested window has been removed from application.");
  501. page.write("</body></html>");
  502. page.close();
  503. return;
  504. }
  505. // Get the terminal type for the window
  506. WebBrowser terminalType = (WebBrowser) window.getTerminal();
  507. // Set terminal type for the window, if not already set
  508. if (terminalType == null) {
  509. terminalType = WebBrowserProbe.getTerminalType(request
  510. .getSession());
  511. window.setTerminal(terminalType);
  512. }
  513. // Find theme
  514. Theme theme = themeSource
  515. .getThemeByName(window.getTheme() != null ? window
  516. .getTheme() : DEFAULT_THEME);
  517. if (theme == null)
  518. throw new ServletException("Default theme (named '"
  519. + DEFAULT_THEME + "') can not be found");
  520. // If UIDL rendering mode is preferred, a page for it is
  521. // rendered
  522. String renderingMode = theme.getPreferredMode(terminalType,
  523. themeSource);
  524. if (unhandledParameters.get("renderingMode") != null)
  525. renderingMode = (String) ((Object[]) unhandledParameters
  526. .get("renderingMode"))[0];
  527. if (Theme.MODE_UIDL.equals(renderingMode)
  528. && !(window instanceof DebugWindow)) {
  529. response.setContentType("text/html");
  530. BufferedWriter page = new BufferedWriter(
  531. new OutputStreamWriter(out));
  532. page
  533. .write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
  534. + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
  535. page.write("<html><head>\n<title>"
  536. + window.getCaption() + "</title>\n");
  537. Theme t = theme;
  538. Vector themes = new Vector();
  539. themes.add(t);
  540. while (t.getParent() != null) {
  541. String parentName = t.getParent();
  542. t = themeSource.getThemeByName(parentName);
  543. themes.add(t);
  544. }
  545. for (int k = themes.size() - 1; k >= 0; k--) {
  546. t = (Theme) themes.get(k);
  547. Collection files = t.getFileNames(terminalType,
  548. Theme.MODE_UIDL);
  549. for (Iterator i = files.iterator(); i.hasNext();) {
  550. String file = (String) i.next();
  551. if (file.endsWith(".css"))
  552. page
  553. .write("<link rel=\"stylesheet\" href=\""
  554. + getResourceLocation(t
  555. .getName(),
  556. new ThemeResource(
  557. file))
  558. + "\" type=\"text/css\" />\n");
  559. else if (file.endsWith(".js"))
  560. page
  561. .write("<script src=\""
  562. + getResourceLocation(t
  563. .getName(),
  564. new ThemeResource(
  565. file))
  566. + "\" type=\"text/javascript\"></script>\n");
  567. }
  568. }
  569. page.write("</head><body>\n");
  570. page
  571. .write("<div id=\"ajax-wait\"><div>Loading...</div></div>\n");
  572. page.write("<div id=\"ajax-window\"></div>\n");
  573. page.write("<script language=\"JavaScript\">\n");
  574. String appUrl = getApplicationUrl(request).toString();
  575. page
  576. .write("var client = new ITMillToolkitClient("
  577. + "document.getElementById('ajax-window'),"
  578. + "\""
  579. + appUrl
  580. + (appUrl.endsWith("/") ? "" : "/")
  581. + "UIDL/"
  582. + "\",\""
  583. + resourcePath
  584. + ((Theme) themes
  585. .get(themes.size() - 1))
  586. .getName()
  587. + "/"
  588. + "client/\",document.getElementById('ajax-wait'));\n");
  589. for (int k = themes.size() - 1; k >= 0; k--) {
  590. t = (Theme) themes.get(k);
  591. String themeObjName = t.getName() + "Theme";
  592. themeObjName = themeObjName.substring(0, 1)
  593. .toUpperCase()
  594. + themeObjName.substring(1);
  595. page.write(" (new " + themeObjName + "(\""
  596. + resourcePath
  597. + ((Theme) themes.get(k)).getName()
  598. + "/\")).registerTo(client);\n");
  599. }
  600. if (isDebugMode(unhandledParameters))
  601. page.write("client.debugEnabled =true;\n");
  602. page.write("client.start();\n");
  603. page.write("</script>\n");
  604. page.write("</body></html>\n");
  605. page.close();
  606. return;
  607. }
  608. // If other than XSLT or UIDL mode is requested
  609. if (!Theme.MODE_XSLT.equals(renderingMode)
  610. && !(window instanceof DebugWindow)) {
  611. // TODO More informal message should be given is browser
  612. // is not supported
  613. response.setContentType("text/html");
  614. BufferedWriter page = new BufferedWriter(
  615. new OutputStreamWriter(out));
  616. page.write("<html><head></head><body>");
  617. page.write("Unsupported browser.");
  618. page.write("</body></html>");
  619. page.close();
  620. return;
  621. }
  622. // Initialize Transformer
  623. UIDLTransformerType transformerType = new UIDLTransformerType(
  624. terminalType, theme);
  625. transformer = this.transformerFactory
  626. .getTransformer(transformerType);
  627. // Set the response type
  628. response.setContentType(terminalType.getContentType());
  629. // Create UIDL writer
  630. WebPaintTarget paintTarget = transformer
  631. .getPaintTarget(variableMap);
  632. // Assure that the correspoding debug window will be
  633. // repainted property
  634. // by clearing it before the actual paint.
  635. DebugWindow debugWindow = (DebugWindow) application
  636. .getWindow(DebugWindow.WINDOW_NAME);
  637. if (debugWindow != null && debugWindow != window) {
  638. debugWindow.setWindowUIDL(window, "Painting...");
  639. }
  640. // Paint window
  641. window.paint(paintTarget);
  642. paintTarget.close();
  643. // For exception handling, memorize the current dirty status
  644. Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap
  645. .get(application);
  646. if (dirtyWindows == null) {
  647. dirtyWindows = new HashSet();
  648. applicationToDirtyWindowSetMap.put(application,
  649. dirtyWindows);
  650. }
  651. currentlyDirtyWindowsForThisApplication
  652. .addAll(dirtyWindows);
  653. // Window is now painted
  654. windowPainted(application, window);
  655. // Debug
  656. if (debugWindow != null && debugWindow != window) {
  657. debugWindow
  658. .setWindowUIDL(window, paintTarget.getUIDL());
  659. }
  660. // Set the function library state for this thread
  661. ThemeFunctionLibrary.setState(application, window,
  662. transformerType.getWebBrowser(), request
  663. .getSession(), this, transformerType
  664. .getTheme().getName());
  665. }
  666. }
  667. // For normal requests, transform the window
  668. if (download == null) {
  669. // Transform and output the result to browser
  670. // Note that the transform and transfer of the result is
  671. // not synchronized with the variable map. This allows
  672. // parallel transfers and transforms for better performance,
  673. // but requires that all calls from the XSL to java are
  674. // thread-safe
  675. transformer.transform(out);
  676. }
  677. // For download request, transfer the downloaded data
  678. else {
  679. handleDownload(download, request, response);
  680. }
  681. } catch (UIDLTransformerException te) {
  682. try {
  683. // Write the error report to client
  684. response.setContentType("text/html");
  685. BufferedWriter err = new BufferedWriter(new OutputStreamWriter(
  686. out));
  687. err
  688. .write("<html><head><title>Application Internal Error</title></head><body>");
  689. err.write("<h1>" + te.getMessage() + "</h1>");
  690. err.write(te.getHTMLDescription());
  691. err.write("</body></html>");
  692. err.close();
  693. } catch (Throwable t) {
  694. Log.except("Failed to write error page: " + t
  695. + ". Original exception was: ", te);
  696. }
  697. // Add previously dirty windows to dirtyWindowList in order
  698. // to make sure that eventually they are repainted
  699. Application currentApplication = getApplication(request);
  700. for (Iterator iter = currentlyDirtyWindowsForThisApplication
  701. .iterator(); iter.hasNext();) {
  702. Window dirtyWindow = (Window) iter.next();
  703. addDirtyWindow(currentApplication, dirtyWindow);
  704. }
  705. } catch (Throwable e) {
  706. // Re-throw other exceptions
  707. throw new ServletException(e);
  708. } finally {
  709. // Release transformer
  710. if (transformer != null)
  711. transformerFactory.releaseTransformer(transformer);
  712. // Notify transaction end
  713. if (application != null)
  714. ((WebApplicationContext) application.getContext())
  715. .endTransaction(application, request);
  716. // Clean the function library state for this thread
  717. // for security reasons
  718. ThemeFunctionLibrary.cleanState();
  719. }
  720. }
  721. /**
  722. * Handle the requested URI. An application can add handlers to do special
  723. * processing, when a certain URI is requested. The handlers are invoked
  724. * before any windows URIs are processed and if a DownloadStream is returned
  725. * it is sent to the client.
  726. *
  727. * @see com.itmill.toolkit.terminal.URIHandler
  728. *
  729. * @param application
  730. * Application owning the URI
  731. * @param request
  732. * HTTP request instance
  733. * @param response
  734. * HTTP response to write to.
  735. * @return boolean True if the request was handled and further processing
  736. * should be suppressed, false otherwise.
  737. */
  738. private DownloadStream handleURI(Application application,
  739. HttpServletRequest request, HttpServletResponse response) {
  740. String uri = request.getPathInfo();
  741. // If no URI is available
  742. if (uri == null || uri.length() == 0 || uri.equals("/"))
  743. return null;
  744. // Remove the leading /
  745. while (uri.startsWith("/") && uri.length() > 0)
  746. uri = uri.substring(1);
  747. // Handle the uri
  748. DownloadStream stream = null;
  749. try {
  750. stream = application.handleURI(application.getURL(), uri);
  751. } catch (Throwable t) {
  752. application.terminalError(new URIHandlerErrorImpl(application, t));
  753. }
  754. return stream;
  755. }
  756. /**
  757. * Handle the requested URI. An application can add handlers to do special
  758. * processing, when a certain URI is requested. The handlers are invoked
  759. * before any windows URIs are processed and if a DownloadStream is returned
  760. * it is sent to the client.
  761. *
  762. * @see com.itmill.toolkit.terminal.URIHandler
  763. *
  764. * @param application
  765. * Application owning the URI
  766. * @param request
  767. * HTTP request instance
  768. * @param response
  769. * HTTP response to write to.
  770. * @return boolean True if the request was handled and further processing
  771. * should be suppressed, false otherwise.
  772. */
  773. private void handleDownload(DownloadStream stream,
  774. HttpServletRequest request, HttpServletResponse response) {
  775. // Download from given stream
  776. InputStream data = stream.getStream();
  777. if (data != null) {
  778. // Set content type
  779. response.setContentType(stream.getContentType());
  780. // Set cache headers
  781. long cacheTime = stream.getCacheTime();
  782. if (cacheTime <= 0) {
  783. response.setHeader("Cache-Control", "no-cache");
  784. response.setHeader("Pragma", "no-cache");
  785. response.setDateHeader("Expires", 0);
  786. } else {
  787. response.setHeader("Cache-Control", "max-age=" + cacheTime
  788. / 1000);
  789. response.setDateHeader("Expires", System.currentTimeMillis()
  790. + cacheTime);
  791. response.setHeader("Pragma", "cache"); // Required to apply
  792. // caching in some
  793. // Tomcats
  794. }
  795. // Copy download stream parameters directly
  796. // to HTTP headers.
  797. Iterator i = stream.getParameterNames();
  798. if (i != null) {
  799. while (i.hasNext()) {
  800. String param = (String) i.next();
  801. response.setHeader((String) param, stream
  802. .getParameter(param));
  803. }
  804. }
  805. int bufferSize = stream.getBufferSize();
  806. if (bufferSize <= 0 || bufferSize > MAX_BUFFER_SIZE)
  807. bufferSize = DEFAULT_BUFFER_SIZE;
  808. byte[] buffer = new byte[bufferSize];
  809. int bytesRead = 0;
  810. try {
  811. OutputStream out = response.getOutputStream();
  812. while ((bytesRead = data.read(buffer)) > 0) {
  813. out.write(buffer, 0, bytesRead);
  814. out.flush();
  815. }
  816. out.close();
  817. } catch (IOException ignored) {
  818. }
  819. }
  820. }
  821. /**
  822. * Look for default theme JAR file.
  823. *
  824. * @return Jar file or null if not found.
  825. */
  826. private File findDefaultThemeJar(String[] fileList) {
  827. // Try to find the default theme JAR file based on the given path
  828. for (int i = 0; i < fileList.length; i++) {
  829. String path = this.getServletContext().getRealPath(fileList[i]);
  830. File file = null;
  831. if (path != null && (file = new File(path)).exists()) {
  832. return file;
  833. }
  834. }
  835. // If we do not have access to individual files, create a temporary
  836. // file from named resource.
  837. for (int i = 0; i < fileList.length; i++) {
  838. InputStream defaultTheme = this.getServletContext()
  839. .getResourceAsStream(fileList[i]);
  840. // Read the content to temporary file and return it
  841. if (defaultTheme != null) {
  842. return createTemporaryFile(defaultTheme, ".jar");
  843. }
  844. }
  845. // Try to find the default theme JAR file based on file naming scheme
  846. // NOTE: This is for backward compability with 3.0.2 and earlier.
  847. String path = this.getServletContext().getRealPath("/WEB-INF/lib");
  848. if (path != null) {
  849. File lib = new File(path);
  850. String[] files = lib.list();
  851. if (files != null) {
  852. for (int i = 0; i < files.length; i++) {
  853. if (files[i].toLowerCase().endsWith(".jar")
  854. && files[i].startsWith(DEFAULT_THEME_JAR_PREFIX)) {
  855. return new File(lib, files[i]);
  856. }
  857. }
  858. }
  859. }
  860. // If no file was found return null
  861. return null;
  862. }
  863. /**
  864. * Create a temporary file for given stream.
  865. *
  866. * @param stream
  867. * Stream to be stored into temporary file.
  868. * @param extension
  869. * File type extension
  870. * @return File
  871. */
  872. private File createTemporaryFile(InputStream stream, String extension) {
  873. File tmpFile;
  874. try {
  875. tmpFile = File.createTempFile(DEFAULT_THEME_TEMP_FILE_PREFIX,
  876. extension);
  877. FileOutputStream out = new FileOutputStream(tmpFile);
  878. byte[] buf = new byte[1024];
  879. int bytes = 0;
  880. while ((bytes = stream.read(buf)) > 0) {
  881. out.write(buf, 0, bytes);
  882. }
  883. out.close();
  884. } catch (IOException e) {
  885. System.err
  886. .println("Failed to create temporary file for default theme: "
  887. + e);
  888. tmpFile = null;
  889. }
  890. return tmpFile;
  891. }
  892. /**
  893. * Handle theme resource file requests. Resources supplied with the themes
  894. * are provided by the WebAdapterServlet.
  895. *
  896. * @param request
  897. * HTTP request
  898. * @param response
  899. * HTTP response
  900. * @return boolean True if the request was handled and further processing
  901. * should be suppressed, false otherwise.
  902. */
  903. private boolean handleResourceRequest(HttpServletRequest request,
  904. HttpServletResponse response) throws ServletException {
  905. // If the resource path is unassigned, initialize it
  906. if (resourcePath == null)
  907. resourcePath = request.getContextPath() + request.getServletPath()
  908. + RESOURCE_URI;
  909. String resourceId = request.getPathInfo();
  910. // Check if this really is a resource request
  911. if (resourceId == null || !resourceId.startsWith(RESOURCE_URI))
  912. return false;
  913. // Check the resource type
  914. resourceId = resourceId.substring(RESOURCE_URI.length());
  915. InputStream data = null;
  916. // Get theme resources
  917. try {
  918. data = themeSource.getResource(resourceId);
  919. } catch (ThemeSource.ThemeException e) {
  920. Log.info(e.getMessage());
  921. data = null;
  922. }
  923. // Write the response
  924. try {
  925. if (data != null) {
  926. response.setContentType(FileTypeResolver
  927. .getMIMEType(resourceId));
  928. // Use default cache time for theme resources
  929. if (this.themeCacheTime > 0) {
  930. response.setHeader("Cache-Control", "max-age="
  931. + this.themeCacheTime / 1000);
  932. response.setDateHeader("Expires", System
  933. .currentTimeMillis()
  934. + this.themeCacheTime);
  935. response.setHeader("Pragma", "cache"); // Required to apply
  936. // caching in some
  937. // Tomcats
  938. }
  939. // Write the data to client
  940. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
  941. int bytesRead = 0;
  942. OutputStream out = response.getOutputStream();
  943. while ((bytesRead = data.read(buffer)) > 0) {
  944. out.write(buffer, 0, bytesRead);
  945. }
  946. out.close();
  947. data.close();
  948. } else {
  949. response.sendError(HttpServletResponse.SC_NOT_FOUND);
  950. }
  951. } catch (java.io.IOException e) {
  952. Log.info("Resource transfer failed: " + request.getRequestURI()
  953. + ". (" + e.getMessage() + ")");
  954. }
  955. return true;
  956. }
  957. /** Get the variable map for the session */
  958. private static synchronized HttpVariableMap getVariableMap(
  959. Application application, HttpServletRequest request) {
  960. HttpSession session = request.getSession();
  961. // Get the application to variablemap map
  962. Map varMapMap = (Map) session.getAttribute(SESSION_ATTR_VARMAP);
  963. if (varMapMap == null) {
  964. varMapMap = new WeakHashMap();
  965. session.setAttribute(SESSION_ATTR_VARMAP, varMapMap);
  966. }
  967. // Create a variable map, if it does not exists.
  968. HttpVariableMap variableMap = (HttpVariableMap) varMapMap
  969. .get(application);
  970. if (variableMap == null) {
  971. variableMap = new HttpVariableMap();
  972. varMapMap.put(application, variableMap);
  973. }
  974. return variableMap;
  975. }
  976. /** Get the current application URL from request */
  977. private URL getApplicationUrl(HttpServletRequest request)
  978. throws MalformedURLException {
  979. URL applicationUrl;
  980. try {
  981. URL reqURL = new URL((request.isSecure() ? "https://" : "http://")
  982. + request.getServerName() + ":" + request.getServerPort()
  983. + request.getRequestURI());
  984. String servletPath = request.getContextPath()
  985. + request.getServletPath();
  986. if (servletPath.length() == 0
  987. || servletPath.charAt(servletPath.length() - 1) != '/')
  988. servletPath = servletPath + "/";
  989. applicationUrl = new URL(reqURL, servletPath);
  990. } catch (MalformedURLException e) {
  991. Log.error("Error constructing application url "
  992. + request.getRequestURI() + " (" + e + ")");
  993. throw e;
  994. }
  995. return applicationUrl;
  996. }
  997. /**
  998. * Get the existing application for given request. Looks for application
  999. * instance for given request based on the requested URL.
  1000. *
  1001. * @param request
  1002. * HTTP request
  1003. * @return Application instance, or null if the URL does not map to valid
  1004. * application.
  1005. */
  1006. private Application getApplication(HttpServletRequest request)
  1007. throws MalformedURLException {
  1008. // Ensure that the session is still valid
  1009. HttpSession session = request.getSession(false);
  1010. if (session == null)
  1011. return null;
  1012. // Get application list for the session.
  1013. LinkedList applications = (LinkedList) session
  1014. .getAttribute(SESSION_ATTR_APPS);
  1015. if (applications == null)
  1016. return null;
  1017. // Search for the application (using the application URI) from the list
  1018. Application application = null;
  1019. for (Iterator i = applications.iterator(); i.hasNext()
  1020. && application == null;) {
  1021. Application a = (Application) i.next();
  1022. String aPath = a.getURL().getPath();
  1023. String servletPath = request.getContextPath()
  1024. + request.getServletPath();
  1025. if (servletPath.length() < aPath.length())
  1026. servletPath += "/";
  1027. if (servletPath.equals(aPath))
  1028. application = a;
  1029. }
  1030. // Remove stopped applications from the list
  1031. if (application != null && !application.isRunning()) {
  1032. applications.remove(application);
  1033. application = null;
  1034. }
  1035. return application;
  1036. }
  1037. /**
  1038. * Create a new application.
  1039. *
  1040. * @return New application instance
  1041. * @throws SAXException
  1042. * @throws LicenseViolation
  1043. * @throws InvalidLicenseFile
  1044. * @throws LicenseSignatureIsInvalid
  1045. * @throws LicenseFileHasNotBeenRead
  1046. */
  1047. private Application createApplication(HttpServletRequest request)
  1048. throws MalformedURLException, InstantiationException,
  1049. IllegalAccessException, LicenseFileHasNotBeenRead,
  1050. LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation,
  1051. SAXException {
  1052. Application application = null;
  1053. // Get the application url
  1054. URL applicationUrl = getApplicationUrl(request);
  1055. // Get application list.
  1056. HttpSession session = request.getSession();
  1057. if (session == null)
  1058. return null;
  1059. LinkedList applications = (LinkedList) session
  1060. .getAttribute(SESSION_ATTR_APPS);
  1061. if (applications == null) {
  1062. applications = new LinkedList();
  1063. session.setAttribute(SESSION_ATTR_APPS, applications);
  1064. HttpSessionBindingListener sessionBindingListener = new SessionBindingListener(
  1065. applications);
  1066. session.setAttribute(SESSION_BINDING_LISTENER,
  1067. sessionBindingListener);
  1068. }
  1069. // Create new application and start it
  1070. try {
  1071. application = (Application) this.applicationClass.newInstance();
  1072. applications.add(application);
  1073. // Listen to window add/removes (for web mode)
  1074. application.addListener((Application.WindowAttachListener) this);
  1075. application.addListener((Application.WindowDetachListener) this);
  1076. // Set localte
  1077. application.setLocale(request.getLocale());
  1078. // Get application context for this session
  1079. WebApplicationContext context = (WebApplicationContext) session
  1080. .getAttribute(SESSION_ATTR_CONTEXT);
  1081. if (context == null) {
  1082. context = new WebApplicationContext(session);
  1083. session.setAttribute(SESSION_ATTR_CONTEXT, context);
  1084. }
  1085. // Start application and check license
  1086. initializeLicense(application);
  1087. application.start(applicationUrl, this.applicationProperties,
  1088. context);
  1089. checkLicense(application);
  1090. } catch (IllegalAccessException e) {
  1091. Log.error("Illegal access to application class "
  1092. + this.applicationClass.getName());
  1093. throw e;
  1094. } catch (InstantiationException e) {
  1095. Log.error("Failed to instantiate application class: "
  1096. + this.applicationClass.getName());
  1097. throw e;
  1098. }
  1099. return application;
  1100. }
  1101. private void initializeLicense(Application application) {
  1102. License license = (License) licenseForApplicationClass.get(application
  1103. .getClass());
  1104. if (license == null) {
  1105. license = new License();
  1106. licenseForApplicationClass.put(application.getClass(), license);
  1107. }
  1108. application.setToolkitLicense(license);
  1109. }
  1110. private void checkLicense(Application application)
  1111. throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid,
  1112. InvalidLicenseFile, LicenseViolation, SAXException {
  1113. License license = application.getToolkitLicense();
  1114. if (!license.hasBeenRead()) {
  1115. InputStream lis;
  1116. try {
  1117. lis = getServletContext().getResource(
  1118. "/WEB-INF/itmill-toolkit-license.xml").openStream();
  1119. license.readLicenseFile(lis);
  1120. } catch (MalformedURLException e) {
  1121. // This should not happen
  1122. throw new RuntimeException(e);
  1123. } catch (IOException e) {
  1124. // This should not happen
  1125. throw new RuntimeException(e);
  1126. } catch (LicenseFileHasAlreadyBeenRead e) {
  1127. // This should not happen
  1128. throw new RuntimeException(e);
  1129. }
  1130. }
  1131. // For each application class, print license description - once
  1132. if (!licensePrintedForApplicationClass.contains(applicationClass)) {
  1133. licensePrintedForApplicationClass.add(applicationClass);
  1134. if (license.shouldLimitsBePrintedOnInit())
  1135. System.out.print(license.getDescription());
  1136. }
  1137. // Check license validity
  1138. try {
  1139. license.check(applicationClass, getNumberOfActiveUsers() + 1,
  1140. VERSION_MAJOR, VERSION_MINOR, "IT Mill Toolkit", null);
  1141. } catch (LicenseFileHasNotBeenRead e) {
  1142. application.close();
  1143. throw e;
  1144. } catch (LicenseSignatureIsInvalid e) {
  1145. application.close();
  1146. throw e;
  1147. } catch (InvalidLicenseFile e) {
  1148. application.close();
  1149. throw e;
  1150. } catch (LicenseViolation e) {
  1151. application.close();
  1152. throw e;
  1153. }
  1154. }
  1155. /**
  1156. * Get the number of active application-user pairs.
  1157. *
  1158. * This returns total number of all applications in the server that are
  1159. * considered to be active. For an application to be active, it must have
  1160. * been accessed less than ACTIVE_USER_REQUEST_INTERVAL ms.
  1161. *
  1162. * @return Number of active application instances in the server.
  1163. */
  1164. private int getNumberOfActiveUsers() {
  1165. Set apps = applicationToLastRequestDate.keySet();
  1166. int active = 0;
  1167. long now = System.currentTimeMillis();
  1168. for (Iterator i = apps.iterator(); i.hasNext();) {
  1169. Date lastReq = (Date) applicationToLastRequestDate.get(i.next());
  1170. if (now - lastReq.getTime() < ACTIVE_USER_REQUEST_INTERVAL)
  1171. active++;
  1172. }
  1173. return active;
  1174. }
  1175. /** End application */
  1176. private void endApplication(HttpServletRequest request,
  1177. HttpServletResponse response, Application application)
  1178. throws IOException {
  1179. String logoutUrl = application.getLogoutURL();
  1180. if (logoutUrl == null)
  1181. logoutUrl = application.getURL().toString();
  1182. HttpSession session = request.getSession();
  1183. if (session != null) {
  1184. LinkedList applications = (LinkedList) session
  1185. .getAttribute(SESSION_ATTR_APPS);
  1186. if (applications != null)
  1187. applications.remove(application);
  1188. }
  1189. response.sendRedirect(response.encodeRedirectURL(logoutUrl));
  1190. }
  1191. /**
  1192. * Get the existing application or create a new one. Get a window within an
  1193. * application based on the requested URI.
  1194. *
  1195. * @param request
  1196. * HTTP Request.
  1197. * @param application
  1198. * Application to query for window.
  1199. * @return Window mathing the given URI or null if not found.
  1200. */
  1201. private Window getApplicationWindow(HttpServletRequest request,
  1202. Application application, Map params) throws ServletException {
  1203. Window window = null;
  1204. // Find the window where the request is handled
  1205. String path = request.getPathInfo();
  1206. // Main window as the URI is empty
  1207. if (path == null || path.length() == 0 || path.equals("/"))
  1208. window = application.getMainWindow();
  1209. // Try to search by window name
  1210. else {
  1211. String windowName = null;
  1212. if (path.charAt(0) == '/')
  1213. path = path.substring(1);
  1214. int index = path.indexOf('/');
  1215. if (index < 0) {
  1216. windowName = path;
  1217. path = "";
  1218. } else {
  1219. windowName = path.substring(0, index);
  1220. path = path.substring(index + 1);
  1221. }
  1222. window = application.getWindow(windowName);
  1223. if (window == null) {
  1224. // If the window has existed, and is now removed
  1225. // send a blank page
  1226. if (allWindows.contains(windowName))
  1227. return null;
  1228. // By default, we use main window
  1229. window = application.getMainWindow();
  1230. } else if (!window.isVisible()) {
  1231. // Implicitly painting without actually invoking paint()
  1232. window.requestRepaintRequests();
  1233. // If the window is invisible send a blank page
  1234. return null;
  1235. }
  1236. }
  1237. // Create and open new debug window for application if requested
  1238. Window debugWindow = application.getWindow(DebugWindow.WINDOW_NAME);
  1239. if (debugWindow == null) {
  1240. if (isDebugMode(params))
  1241. try {
  1242. debugWindow = new DebugWindow(application, request
  1243. .getSession(false), this);
  1244. debugWindow.setWidth(370);
  1245. debugWindow.setHeight(480);
  1246. application.addWindow(debugWindow);
  1247. } catch (Exception e) {
  1248. throw new ServletException(
  1249. "Failed to create debug window for application", e);
  1250. }
  1251. } else if (window != debugWindow) {
  1252. if (isDebugMode(params))
  1253. debugWindow.requestRepaint();
  1254. else
  1255. application.removeWindow(debugWindow);
  1256. }
  1257. return window;
  1258. }
  1259. /**
  1260. * Get relative location of a theme resource.
  1261. *
  1262. * @param theme
  1263. * Theme name
  1264. * @param resource
  1265. * Theme resource
  1266. * @return External URI specifying the resource
  1267. */
  1268. public String getResourceLocation(String theme, ThemeResource resource) {
  1269. if (resourcePath == null)
  1270. return resource.getResourceId();
  1271. return resourcePath + theme + "/" + resource.getResourceId();
  1272. }
  1273. /**
  1274. * Check if web adapter is in debug mode. Extra output is generated to log
  1275. * when debug mode is enabled.
  1276. *
  1277. * @return Debug mode
  1278. */
  1279. public boolean isDebugMode(Map parameters) {
  1280. if (parameters != null) {
  1281. Object[] debug = (Object[]) parameters.get("debug");
  1282. if (debug != null && !"false".equals(debug[0].toString())
  1283. && !"false".equals(debugMode))
  1284. return true;
  1285. }
  1286. return "true".equals(debugMode);
  1287. }
  1288. /**
  1289. * Returns the theme source.
  1290. *
  1291. * @return ThemeSource
  1292. */
  1293. public ThemeSource getThemeSource() {
  1294. return themeSource;
  1295. }
  1296. protected void addDirtyWindow(Application application, Window window) {
  1297. synchronized (applicationToDirtyWindowSetMap) {
  1298. HashSet dirtyWindows = (HashSet) applicationToDirtyWindowSetMap
  1299. .get(application);
  1300. if (dirtyWindows == null) {
  1301. dirtyWindows = new HashSet();
  1302. applicationToDirtyWindowSetMap.put(application, dirtyWindows);
  1303. }
  1304. dirtyWindows.add(window);
  1305. }
  1306. }
  1307. protected void removeDirtyWindow(Application application, Window window) {
  1308. synchronized (applicationToDirtyWindowSetMap) {
  1309. HashSet dirtyWindows = (HashSet) applicationToDirtyWindowSetMap
  1310. .get(application);
  1311. if (dirtyWindows != null)
  1312. dirtyWindows.remove(window);
  1313. }
  1314. }
  1315. /**
  1316. * @see com.itmill.toolkit.Application.WindowAttachListener#windowAttached(Application.WindowAttachEvent)
  1317. */
  1318. public void windowAttached(WindowAttachEvent event) {
  1319. Window win = event.getWindow();
  1320. win.addListener((Paintable.RepaintRequestListener) this);
  1321. // Add to window names
  1322. allWindows.add(win.getName());
  1323. // Add window to dirty window references if it is visible
  1324. // Or request the window to pass on the repaint requests
  1325. if (win.isVisible())
  1326. addDirtyWindow(event.getApplication(), win);
  1327. else
  1328. win.requestRepaintRequests();
  1329. }
  1330. /**
  1331. * @see com.itmill.toolkit.Application.WindowDetachListener#windowDetached(Application.WindowDetachEvent)
  1332. */
  1333. public void windowDetached(WindowDetachEvent event) {
  1334. event.getWindow().removeListener(
  1335. (Paintable.RepaintRequestListener) this);
  1336. // Add dirty window reference for closing the window
  1337. addDirtyWindow(event.getApplication(), event.getWindow());
  1338. }
  1339. /**
  1340. * @see com.itmill.toolkit.terminal.Paintable.RepaintRequestListener#repaintRequested(Paintable.RepaintRequestEvent)
  1341. */
  1342. public void repaintRequested(RepaintRequestEvent event) {
  1343. Paintable p = event.getPaintable();
  1344. Application app = null;
  1345. if (p instanceof Window)
  1346. app = ((Window) p).getApplication();
  1347. if (app != null)
  1348. addDirtyWindow(app, ((Window) p));
  1349. Object lock = applicationToServerCommandStreamLock.get(app);
  1350. if (lock != null)
  1351. synchronized (lock) {
  1352. lock.notifyAll();
  1353. }
  1354. }
  1355. /** Get the list of dirty windows in application */
  1356. protected Set getDirtyWindows(Application app) {
  1357. HashSet dirtyWindows;
  1358. synchronized (applicationToDirtyWindowSetMap) {
  1359. dirtyWindows = (HashSet) applicationToDirtyWindowSetMap.get(app);
  1360. }
  1361. return dirtyWindows;
  1362. }
  1363. /** Remove a window from the list of dirty windows */
  1364. private void windowPainted(Application app, Window window) {
  1365. removeDirtyWindow(app, window);
  1366. }
  1367. /**
  1368. * Generate server commands stream. If the server commands are not
  1369. * requested, return false
  1370. */
  1371. private boolean handleServerCommands(HttpServletRequest request,
  1372. HttpServletResponse response) {
  1373. // Server commands are allways requested with certain parameter
  1374. if (request.getParameter(SERVER_COMMAND_PARAM) == null)
  1375. return false;
  1376. // Get the application
  1377. Application application;
  1378. try {
  1379. application = getApplication(request);
  1380. } catch (MalformedURLException e) {
  1381. return false;
  1382. }
  1383. if (application == null)
  1384. return false;
  1385. // Create continuous server commands stream
  1386. try {
  1387. // Writer for writing the stream
  1388. PrintWriter w = new PrintWriter(response.getOutputStream());
  1389. // Print necessary http page headers and padding
  1390. w.println("<html><head></head><body>");
  1391. for (int i = 0; i < SERVER_COMMAND_HEADER_PADDING; i++)
  1392. w.print(' ');
  1393. // Clock for synchronizing the stream
  1394. Object lock = new Object();
  1395. synchronized (applicationToServerCommandStreamLock) {
  1396. Object oldlock = applicationToServerCommandStreamLock
  1397. .get(application);
  1398. if (oldlock != null)
  1399. synchronized (oldlock) {
  1400. oldlock.notifyAll();
  1401. }
  1402. applicationToServerCommandStreamLock.put(application, lock);
  1403. }
  1404. while (applicationToServerCommandStreamLock.get(application) == lock
  1405. && application.isRunning()) {
  1406. synchronized (application) {
  1407. // Session expiration
  1408. Date lastRequest = (Date) applicationToLastRequestDate
  1409. .get(application);
  1410. if (lastRequest != null
  1411. && lastRequest.getTime()
  1412. + request.getSession()
  1413. .getMaxInactiveInterval() * 1000 < System
  1414. .currentTimeMillis()) {
  1415. // Session expired, close application
  1416. application.close();
  1417. } else {
  1418. // Application still alive - keep updating windows
  1419. Set dws = getDirtyWindows(application);
  1420. if (dws != null && !dws.isEmpty()) {
  1421. // For one of the dirty windows (in each
  1422. // application)
  1423. // request redraw
  1424. Window win = (Window) dws.iterator().next();
  1425. w
  1426. .println("<script>\n"
  1427. + ThemeFunctionLibrary
  1428. .getWindowRefreshScript(
  1429. application,
  1430. win,
  1431. WebBrowserProbe
  1432. .getTerminalType(request
  1433. .getSession()))
  1434. + "</script>");
  1435. removeDirtyWindow(application, win);
  1436. // Windows that are closed immediately are "painted"
  1437. // now
  1438. if (win.getApplication() == null
  1439. || !win.isVisible())
  1440. win.requestRepaintRequests();
  1441. }
  1442. }
  1443. }
  1444. // Send the generated commands and newline immediately to
  1445. // browser
  1446. w.println(" ");
  1447. w.flush();
  1448. response.flushBuffer();
  1449. synchronized (lock) {
  1450. try {
  1451. lock.wait(SERVER_COMMAND_STREAM_MAINTAIN_PERIOD);
  1452. } catch (InterruptedException ignored) {
  1453. }
  1454. }
  1455. }
  1456. } catch (IOException ignore) {
  1457. // In case of an Exceptions the server command stream is
  1458. // terminated
  1459. synchronized (applicationToServerCommandStreamLock) {
  1460. if (applicationToServerCommandStreamLock.get(application) == application)
  1461. applicationToServerCommandStreamLock.remove(application);
  1462. }
  1463. }
  1464. return true;
  1465. }
  1466. private class SessionBindingListener implements HttpSessionBindingListener {
  1467. private LinkedList applications;
  1468. protected SessionBindingListener(LinkedList applications) {
  1469. this.applications = applications;
  1470. }
  1471. /**
  1472. * @see javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
  1473. */
  1474. public void valueBound(HttpSessionBindingEvent arg0) {
  1475. // We are not interested in bindings
  1476. }
  1477. /**
  1478. * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
  1479. */
  1480. public void valueUnbound(HttpSessionBindingEvent event) {
  1481. // If the binding listener is unbound from the session, the
  1482. // session must be closing
  1483. if (event.getName().equals(SESSION_BINDING_LISTENER)) {
  1484. // Close all applications
  1485. Object[] apps = applications.toArray();
  1486. for (int i = 0; i < apps.length; i++) {
  1487. if (apps[i] != null) {
  1488. // Close app
  1489. ((Application) apps[i]).close();
  1490. // Stop application server commands stream
  1491. Object lock = applicationToServerCommandStreamLock
  1492. .get(apps[i]);
  1493. if (lock != null)
  1494. synchronized (lock) {
  1495. lock.notifyAll();
  1496. }
  1497. applicationToServerCommandStreamLock.remove(apps[i]);
  1498. // Remove application from applications list
  1499. applications.remove(apps[i]);
  1500. }
  1501. }
  1502. }
  1503. }
  1504. }
  1505. /** Implementation of ParameterHandler.ErrorEvent interface. */
  1506. public class ParameterHandlerErrorImpl implements
  1507. ParameterHandler.ErrorEvent {
  1508. private ParameterHandler owner;
  1509. private Throwable throwable;
  1510. private ParameterHandlerErrorImpl(ParameterHandler owner,
  1511. Throwable throwable) {
  1512. this.owner = owner;
  1513. this.throwable = throwable;
  1514. }
  1515. /**
  1516. * @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
  1517. */
  1518. public Throwable getThrowable() {
  1519. return this.throwable;
  1520. }
  1521. /**
  1522. * @see com.itmill.toolkit.terminal.ParameterHandler.ErrorEvent#getParameterHandler()
  1523. */
  1524. public ParameterHandler getParameterHandler() {
  1525. return this.owner;
  1526. }
  1527. }
  1528. /** Implementation of URIHandler.ErrorEvent interface. */
  1529. public class URIHandlerErrorImpl implements URIHandler.ErrorEvent {
  1530. private URIHandler owner;
  1531. private Throwable throwable;
  1532. private URIHandlerErrorImpl(URIHandler owner, Throwable throwable) {
  1533. this.owner = owner;
  1534. this.throwable = throwable;
  1535. }
  1536. /**
  1537. * @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable()
  1538. */
  1539. public Throwable getThrowable() {
  1540. return this.throwable;
  1541. }
  1542. /**
  1543. * @see com.itmill.toolkit.terminal.URIHandler.ErrorEvent#getURIHandler()
  1544. */
  1545. public URIHandler getURIHandler() {
  1546. return this.owner;
  1547. }
  1548. }
  1549. /**
  1550. * Get AJAX application manager for an application.
  1551. *
  1552. * If this application has not been running in ajax mode before, new manager
  1553. * is created and web adapter stops listening to changes.
  1554. *
  1555. * @param application
  1556. * @return AJAX Application Manager
  1557. */
  1558. private AjaxApplicationManager getApplicationManager(Application application) {
  1559. AjaxApplicationManager mgr = (AjaxApplicationManager) applicationToAjaxAppMgrMap
  1560. .get(application);
  1561. // This application is going from Web to AJAX mode, create new manager
  1562. if (mgr == null) {
  1563. // Create new manager
  1564. mgr = new AjaxApplicationManager(application);
  1565. applicationToAjaxAppMgrMap.put(application, mgr);
  1566. // Stop sending changes to this servlet because manager will take
  1567. // control
  1568. application.removeListener((Application.WindowAttachListener) this);
  1569. application.removeListener((Application.WindowDetachListener) this);
  1570. // Manager takes control over the application
  1571. mgr.takeControl();
  1572. }
  1573. return mgr;
  1574. }
  1575. }