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.

AbstractCommunicationManager.java 82KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.server;
  5. import java.io.BufferedWriter;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.CharArrayWriter;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.OutputStream;
  12. import java.io.OutputStreamWriter;
  13. import java.io.PrintWriter;
  14. import java.io.Serializable;
  15. import java.io.StringWriter;
  16. import java.lang.reflect.InvocationTargetException;
  17. import java.lang.reflect.Method;
  18. import java.security.GeneralSecurityException;
  19. import java.text.CharacterIterator;
  20. import java.text.DateFormat;
  21. import java.text.DateFormatSymbols;
  22. import java.text.SimpleDateFormat;
  23. import java.text.StringCharacterIterator;
  24. import java.util.ArrayList;
  25. import java.util.Calendar;
  26. import java.util.Collection;
  27. import java.util.Collections;
  28. import java.util.Comparator;
  29. import java.util.GregorianCalendar;
  30. import java.util.HashMap;
  31. import java.util.HashSet;
  32. import java.util.Iterator;
  33. import java.util.LinkedList;
  34. import java.util.List;
  35. import java.util.Locale;
  36. import java.util.Map;
  37. import java.util.Set;
  38. import java.util.StringTokenizer;
  39. import java.util.UUID;
  40. import java.util.logging.Level;
  41. import java.util.logging.Logger;
  42. import com.vaadin.Application;
  43. import com.vaadin.Application.SystemMessages;
  44. import com.vaadin.RootRequiresMoreInformationException;
  45. import com.vaadin.external.json.JSONException;
  46. import com.vaadin.external.json.JSONObject;
  47. import com.vaadin.terminal.CombinedRequest;
  48. import com.vaadin.terminal.PaintException;
  49. import com.vaadin.terminal.PaintTarget;
  50. import com.vaadin.terminal.Paintable;
  51. import com.vaadin.terminal.Paintable.RepaintRequestEvent;
  52. import com.vaadin.terminal.RequestHandler;
  53. import com.vaadin.terminal.StreamVariable;
  54. import com.vaadin.terminal.StreamVariable.StreamingEndEvent;
  55. import com.vaadin.terminal.StreamVariable.StreamingErrorEvent;
  56. import com.vaadin.terminal.Terminal.ErrorEvent;
  57. import com.vaadin.terminal.Terminal.ErrorListener;
  58. import com.vaadin.terminal.VariableOwner;
  59. import com.vaadin.terminal.WrappedRequest;
  60. import com.vaadin.terminal.WrappedResponse;
  61. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  62. import com.vaadin.terminal.gwt.server.BootstrapHandler.BootstrapContext;
  63. import com.vaadin.terminal.gwt.server.ComponentSizeValidator.InvalidLayout;
  64. import com.vaadin.ui.AbstractComponent;
  65. import com.vaadin.ui.AbstractField;
  66. import com.vaadin.ui.Component;
  67. import com.vaadin.ui.Root;
  68. /**
  69. * This is a common base class for the server-side implementations of the
  70. * communication system between the client code (compiled with GWT into
  71. * JavaScript) and the server side components. Its client side counterpart is
  72. * {@link ApplicationConnection}.
  73. *
  74. * A server side component sends its state to the client in a paint request (see
  75. * {@link Paintable} and {@link PaintTarget} on the server side). The client
  76. * widget receives these paint requests as calls to
  77. * {@link com.vaadin.terminal.gwt.client.VPaintableWidget#updateFromUIDL()}. The client
  78. * component communicates back to the server by sending a list of variable
  79. * changes (see {@link ApplicationConnection#updateVariable()} and
  80. * {@link VariableOwner#changeVariables(Object, Map)}).
  81. *
  82. * TODO Document better!
  83. */
  84. @SuppressWarnings("serial")
  85. public abstract class AbstractCommunicationManager implements
  86. Paintable.RepaintRequestListener, Serializable {
  87. private static final String DASHDASH = "--";
  88. private static final Logger logger = Logger
  89. .getLogger(AbstractCommunicationManager.class.getName());
  90. private static final RequestHandler APP_RESOURCE_HANDLER = new ApplicationResourceHandler();
  91. private static final RequestHandler UNSUPPORTED_BROWSER_HANDLER = new UnsupportedBrowserHandler();
  92. /**
  93. * TODO Document me!
  94. *
  95. * @author peholmst
  96. */
  97. public interface Callback extends Serializable {
  98. public void criticalNotification(WrappedRequest request,
  99. WrappedResponse response, String cap, String msg,
  100. String details, String outOfSyncURL) throws IOException;
  101. }
  102. static class UploadInterruptedException extends Exception {
  103. public UploadInterruptedException() {
  104. super("Upload interrupted by other thread");
  105. }
  106. }
  107. private static String GET_PARAM_REPAINT_ALL = "repaintAll";
  108. // flag used in the request to indicate that the security token should be
  109. // written to the response
  110. private static final String WRITE_SECURITY_TOKEN_FLAG = "writeSecurityToken";
  111. /* Variable records indexes */
  112. private static final int VAR_PID = 1;
  113. private static final int VAR_NAME = 2;
  114. private static final int VAR_TYPE = 3;
  115. private static final int VAR_VALUE = 0;
  116. private static final char VTYPE_PAINTABLE = 'p';
  117. private static final char VTYPE_BOOLEAN = 'b';
  118. private static final char VTYPE_DOUBLE = 'd';
  119. private static final char VTYPE_FLOAT = 'f';
  120. private static final char VTYPE_LONG = 'l';
  121. private static final char VTYPE_INTEGER = 'i';
  122. private static final char VTYPE_STRING = 's';
  123. private static final char VTYPE_ARRAY = 'a';
  124. private static final char VTYPE_STRINGARRAY = 'c';
  125. private static final char VTYPE_MAP = 'm';
  126. private static final char VAR_RECORD_SEPARATOR = '\u001e';
  127. private static final char VAR_FIELD_SEPARATOR = '\u001f';
  128. public static final char VAR_BURST_SEPARATOR = '\u001d';
  129. public static final char VAR_ARRAYITEM_SEPARATOR = '\u001c';
  130. public static final char VAR_ESCAPE_CHARACTER = '\u001b';
  131. private final HashMap<Integer, OpenWindowCache> currentlyOpenWindowsInClient = new HashMap<Integer, OpenWindowCache>();
  132. private static final int MAX_BUFFER_SIZE = 64 * 1024;
  133. /* Same as in apache commons file upload library that was previously used. */
  134. private static final int MAX_UPLOAD_BUFFER_SIZE = 4 * 1024;
  135. private static final String GET_PARAM_ANALYZE_LAYOUTS = "analyzeLayouts";
  136. private final ArrayList<Paintable> dirtyPaintables = new ArrayList<Paintable>();
  137. private final HashMap<Paintable, String> paintableIdMap = new HashMap<Paintable, String>();
  138. private final HashMap<String, Paintable> idPaintableMap = new HashMap<String, Paintable>();
  139. private int idSequence = 0;
  140. private final Application application;
  141. private List<String> locales;
  142. private int pendingLocalesIndex;
  143. private int timeoutInterval = -1;
  144. private DragAndDropService dragAndDropService;
  145. private String requestThemeName;
  146. private int maxInactiveInterval;
  147. /**
  148. * TODO New constructor - document me!
  149. *
  150. * @param application
  151. */
  152. public AbstractCommunicationManager(Application application) {
  153. this.application = application;
  154. application.addRequestHandler(getBootstrapHandler());
  155. application.addRequestHandler(APP_RESOURCE_HANDLER);
  156. application.addRequestHandler(UNSUPPORTED_BROWSER_HANDLER);
  157. requireLocale(application.getLocale().toString());
  158. }
  159. protected Application getApplication() {
  160. return application;
  161. }
  162. private static final int LF = "\n".getBytes()[0];
  163. private static final String CRLF = "\r\n";
  164. private static final String UTF8 = "UTF8";
  165. private static final String GET_PARAM_HIGHLIGHT_COMPONENT = "highlightComponent";
  166. private Paintable highLightedPaintable;
  167. private static String readLine(InputStream stream) throws IOException {
  168. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  169. int readByte = stream.read();
  170. while (readByte != LF) {
  171. bout.write(readByte);
  172. readByte = stream.read();
  173. }
  174. byte[] bytes = bout.toByteArray();
  175. return new String(bytes, 0, bytes.length - 1, UTF8);
  176. }
  177. /**
  178. * Method used to stream content from a multipart request (either from
  179. * servlet or portlet request) to given StreamVariable
  180. *
  181. *
  182. * @param request
  183. * @param response
  184. * @param streamVariable
  185. * @param owner
  186. * @param boundary
  187. * @throws IOException
  188. */
  189. protected void doHandleSimpleMultipartFileUpload(WrappedRequest request,
  190. WrappedResponse response, StreamVariable streamVariable,
  191. String variableName, VariableOwner owner, String boundary)
  192. throws IOException {
  193. // multipart parsing, supports only one file for request, but that is
  194. // fine for our current terminal
  195. final InputStream inputStream = request.getInputStream();
  196. int contentLength = request.getContentLength();
  197. boolean atStart = false;
  198. boolean firstFileFieldFound = false;
  199. String rawfilename = "unknown";
  200. String rawMimeType = "application/octet-stream";
  201. /*
  202. * Read the stream until the actual file starts (empty line). Read
  203. * filename and content type from multipart headers.
  204. */
  205. while (!atStart) {
  206. String readLine = readLine(inputStream);
  207. contentLength -= (readLine.length() + 2);
  208. if (readLine.startsWith("Content-Disposition:")
  209. && readLine.indexOf("filename=") > 0) {
  210. rawfilename = readLine.replaceAll(".*filename=", "");
  211. String parenthesis = rawfilename.substring(0, 1);
  212. rawfilename = rawfilename.substring(1);
  213. rawfilename = rawfilename.substring(0,
  214. rawfilename.indexOf(parenthesis));
  215. firstFileFieldFound = true;
  216. } else if (firstFileFieldFound && readLine.equals("")) {
  217. atStart = true;
  218. } else if (readLine.startsWith("Content-Type")) {
  219. rawMimeType = readLine.split(": ")[1];
  220. }
  221. }
  222. contentLength -= (boundary.length() + CRLF.length() + 2
  223. * DASHDASH.length() + 2); // 2 == CRLF
  224. /*
  225. * Reads bytes from the underlying stream. Compares the read bytes to
  226. * the boundary string and returns -1 if met.
  227. *
  228. * The matching happens so that if the read byte equals to the first
  229. * char of boundary string, the stream goes to "buffering mode". In
  230. * buffering mode bytes are read until the character does not match the
  231. * corresponding from boundary string or the full boundary string is
  232. * found.
  233. *
  234. * Note, if this is someday needed elsewhere, don't shoot yourself to
  235. * foot and split to a top level helper class.
  236. */
  237. InputStream simpleMultiPartReader = new SimpleMultiPartInputStream(
  238. inputStream, boundary);
  239. /*
  240. * Should report only the filename even if the browser sends the path
  241. */
  242. final String filename = removePath(rawfilename);
  243. final String mimeType = rawMimeType;
  244. try {
  245. /*
  246. * safe cast as in GWT terminal all variable owners are expected to
  247. * be components.
  248. */
  249. Component component = (Component) owner;
  250. if (component.isReadOnly()) {
  251. throw new UploadException(
  252. "Warning: file upload ignored because the componente was read-only");
  253. }
  254. boolean forgetVariable = streamToReceiver(simpleMultiPartReader,
  255. streamVariable, filename, mimeType, contentLength);
  256. if (forgetVariable) {
  257. cleanStreamVariable(owner, variableName);
  258. }
  259. } catch (Exception e) {
  260. synchronized (application) {
  261. handleChangeVariablesError(application, (Component) owner, e,
  262. new HashMap<String, Object>());
  263. }
  264. }
  265. sendUploadResponse(request, response);
  266. }
  267. /**
  268. * Used to stream plain file post (aka XHR2.post(File))
  269. *
  270. * @param request
  271. * @param response
  272. * @param streamVariable
  273. * @param owner
  274. * @param contentLength
  275. * @throws IOException
  276. */
  277. protected void doHandleXhrFilePost(WrappedRequest request,
  278. WrappedResponse response, StreamVariable streamVariable,
  279. String variableName, VariableOwner owner, int contentLength)
  280. throws IOException {
  281. // These are unknown in filexhr ATM, maybe add to Accept header that
  282. // is accessible in portlets
  283. final String filename = "unknown";
  284. final String mimeType = filename;
  285. final InputStream stream = request.getInputStream();
  286. try {
  287. /*
  288. * safe cast as in GWT terminal all variable owners are expected to
  289. * be components.
  290. */
  291. Component component = (Component) owner;
  292. if (component.isReadOnly()) {
  293. throw new UploadException(
  294. "Warning: file upload ignored because the component was read-only");
  295. }
  296. boolean forgetVariable = streamToReceiver(stream, streamVariable,
  297. filename, mimeType, contentLength);
  298. if (forgetVariable) {
  299. cleanStreamVariable(owner, variableName);
  300. }
  301. } catch (Exception e) {
  302. synchronized (application) {
  303. handleChangeVariablesError(application, (Component) owner, e,
  304. new HashMap<String, Object>());
  305. }
  306. }
  307. sendUploadResponse(request, response);
  308. }
  309. /**
  310. * @param in
  311. * @param streamVariable
  312. * @param filename
  313. * @param type
  314. * @param contentLength
  315. * @return true if the streamvariable has informed that the terminal can
  316. * forget this variable
  317. * @throws UploadException
  318. */
  319. protected final boolean streamToReceiver(final InputStream in,
  320. StreamVariable streamVariable, String filename, String type,
  321. int contentLength) throws UploadException {
  322. if (streamVariable == null) {
  323. throw new IllegalStateException(
  324. "StreamVariable for the post not found");
  325. }
  326. final Application application = getApplication();
  327. OutputStream out = null;
  328. int totalBytes = 0;
  329. StreamingStartEventImpl startedEvent = new StreamingStartEventImpl(
  330. filename, type, contentLength);
  331. try {
  332. boolean listenProgress;
  333. synchronized (application) {
  334. streamVariable.streamingStarted(startedEvent);
  335. out = streamVariable.getOutputStream();
  336. listenProgress = streamVariable.listenProgress();
  337. }
  338. // Gets the output target stream
  339. if (out == null) {
  340. throw new NoOutputStreamException();
  341. }
  342. if (null == in) {
  343. // No file, for instance non-existent filename in html upload
  344. throw new NoInputStreamException();
  345. }
  346. final byte buffer[] = new byte[MAX_UPLOAD_BUFFER_SIZE];
  347. int bytesReadToBuffer = 0;
  348. while ((bytesReadToBuffer = in.read(buffer)) > 0) {
  349. out.write(buffer, 0, bytesReadToBuffer);
  350. totalBytes += bytesReadToBuffer;
  351. if (listenProgress) {
  352. // update progress if listener set and contentLength
  353. // received
  354. synchronized (application) {
  355. StreamingProgressEventImpl progressEvent = new StreamingProgressEventImpl(
  356. filename, type, contentLength, totalBytes);
  357. streamVariable.onProgress(progressEvent);
  358. }
  359. }
  360. if (streamVariable.isInterrupted()) {
  361. throw new UploadInterruptedException();
  362. }
  363. }
  364. // upload successful
  365. out.close();
  366. StreamingEndEvent event = new StreamingEndEventImpl(filename, type,
  367. totalBytes);
  368. synchronized (application) {
  369. streamVariable.streamingFinished(event);
  370. }
  371. } catch (UploadInterruptedException e) {
  372. // Download interrupted by application code
  373. tryToCloseStream(out);
  374. StreamingErrorEvent event = new StreamingErrorEventImpl(filename,
  375. type, contentLength, totalBytes, e);
  376. synchronized (application) {
  377. streamVariable.streamingFailed(event);
  378. }
  379. // Note, we are not throwing interrupted exception forward as it is
  380. // not a terminal level error like all other exception.
  381. } catch (final Exception e) {
  382. tryToCloseStream(out);
  383. synchronized (application) {
  384. StreamingErrorEvent event = new StreamingErrorEventImpl(
  385. filename, type, contentLength, totalBytes, e);
  386. synchronized (application) {
  387. streamVariable.streamingFailed(event);
  388. }
  389. // throw exception for terminal to be handled (to be passed to
  390. // terminalErrorHandler)
  391. throw new UploadException(e);
  392. }
  393. }
  394. return startedEvent.isDisposed();
  395. }
  396. static void tryToCloseStream(OutputStream out) {
  397. try {
  398. // try to close output stream (e.g. file handle)
  399. if (out != null) {
  400. out.close();
  401. }
  402. } catch (IOException e1) {
  403. // NOP
  404. }
  405. }
  406. /**
  407. * Removes any possible path information from the filename and returns the
  408. * filename. Separators / and \\ are used.
  409. *
  410. * @param name
  411. * @return
  412. */
  413. private static String removePath(String filename) {
  414. if (filename != null) {
  415. filename = filename.replaceAll("^.*[/\\\\]", "");
  416. }
  417. return filename;
  418. }
  419. /**
  420. * TODO document
  421. *
  422. * @param request
  423. * @param response
  424. * @throws IOException
  425. */
  426. protected void sendUploadResponse(WrappedRequest request,
  427. WrappedResponse response) throws IOException {
  428. response.setContentType("text/html");
  429. final OutputStream out = response.getOutputStream();
  430. final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
  431. new OutputStreamWriter(out, "UTF-8")));
  432. outWriter.print("<html><body>download handled</body></html>");
  433. outWriter.flush();
  434. out.close();
  435. }
  436. /**
  437. * Internally process a UIDL request from the client.
  438. *
  439. * This method calls
  440. * {@link #handleVariables(WrappedRequest, WrappedResponse, Callback, Application, Root)}
  441. * to process any changes to variables by the client and then repaints
  442. * affected components using {@link #paintAfterVariableChanges()}.
  443. *
  444. * Also, some cleanup is done when a request arrives for an application that
  445. * has already been closed.
  446. *
  447. * The method handleUidlRequest(...) in subclasses should call this method.
  448. *
  449. * TODO better documentation
  450. *
  451. * @param request
  452. * @param response
  453. * @param callback
  454. * @param root
  455. * target window for the UIDL request, can be null if target not
  456. * found
  457. * @throws IOException
  458. * @throws InvalidUIDLSecurityKeyException
  459. */
  460. public void handleUidlRequest(WrappedRequest request,
  461. WrappedResponse response, Callback callback, Root root)
  462. throws IOException, InvalidUIDLSecurityKeyException {
  463. requestThemeName = request.getParameter("theme");
  464. maxInactiveInterval = request.getSessionMaxInactiveInterval();
  465. // repaint requested or session has timed out and new one is created
  466. boolean repaintAll;
  467. final OutputStream out;
  468. repaintAll = (request.getParameter(GET_PARAM_REPAINT_ALL) != null);
  469. // || (request.getSession().isNew()); FIXME What the h*ll is this??
  470. out = response.getOutputStream();
  471. boolean analyzeLayouts = false;
  472. if (repaintAll) {
  473. // analyzing can be done only with repaintAll
  474. analyzeLayouts = (request.getParameter(GET_PARAM_ANALYZE_LAYOUTS) != null);
  475. if (request.getParameter(GET_PARAM_HIGHLIGHT_COMPONENT) != null) {
  476. String pid = request
  477. .getParameter(GET_PARAM_HIGHLIGHT_COMPONENT);
  478. highLightedPaintable = idPaintableMap.get(pid);
  479. highlightPaintable(highLightedPaintable);
  480. }
  481. }
  482. final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
  483. new OutputStreamWriter(out, "UTF-8")));
  484. // The rest of the process is synchronized with the application
  485. // in order to guarantee that no parallel variable handling is
  486. // made
  487. synchronized (application) {
  488. // Finds the window within the application
  489. if (application.isRunning()) {
  490. // Returns if no window found
  491. if (root == null) {
  492. // This should not happen, no windows exists but
  493. // application is still open.
  494. logger.warning("Could not get root for application");
  495. return;
  496. }
  497. } else {
  498. // application has been closed
  499. endApplication(request, response, application);
  500. return;
  501. }
  502. // Change all variables based on request parameters
  503. if (!handleVariables(request, response, callback, application, root)) {
  504. // var inconsistency; the client is probably out-of-sync
  505. SystemMessages ci = null;
  506. try {
  507. Method m = application.getClass().getMethod(
  508. "getSystemMessages", (Class[]) null);
  509. ci = (Application.SystemMessages) m.invoke(null,
  510. (Object[]) null);
  511. } catch (Exception e2) {
  512. // FIXME: Handle exception
  513. // Not critical, but something is still wrong; print
  514. // stacktrace
  515. logger.log(Level.WARNING,
  516. "getSystemMessages() failed - continuing", e2);
  517. }
  518. if (ci != null) {
  519. String msg = ci.getOutOfSyncMessage();
  520. String cap = ci.getOutOfSyncCaption();
  521. if (msg != null || cap != null) {
  522. callback.criticalNotification(request, response, cap,
  523. msg, null, ci.getOutOfSyncURL());
  524. // will reload page after this
  525. return;
  526. }
  527. }
  528. // No message to show, let's just repaint all.
  529. repaintAll = true;
  530. }
  531. paintAfterVariableChanges(request, response, callback, repaintAll,
  532. outWriter, root, analyzeLayouts);
  533. }
  534. outWriter.close();
  535. requestThemeName = null;
  536. }
  537. protected void highlightPaintable(Paintable highLightedPaintable2) {
  538. StringBuilder sb = new StringBuilder();
  539. sb.append("*** Debug details of a component: *** \n");
  540. sb.append("Type: ");
  541. sb.append(highLightedPaintable2.getClass().getName());
  542. if (highLightedPaintable2 instanceof AbstractComponent) {
  543. AbstractComponent component = (AbstractComponent) highLightedPaintable2;
  544. sb.append("\nId:");
  545. sb.append(paintableIdMap.get(component));
  546. if (component.getCaption() != null) {
  547. sb.append("\nCaption:");
  548. sb.append(component.getCaption());
  549. }
  550. printHighlightedComponentHierarchy(sb, component);
  551. }
  552. logger.info(sb.toString());
  553. }
  554. protected void printHighlightedComponentHierarchy(StringBuilder sb,
  555. AbstractComponent component) {
  556. LinkedList<Component> h = new LinkedList<Component>();
  557. h.add(component);
  558. Component parent = component.getParent();
  559. while (parent != null) {
  560. h.addFirst(parent);
  561. parent = parent.getParent();
  562. }
  563. sb.append("\nComponent hierarchy:\n");
  564. Application application2 = component.getApplication();
  565. sb.append(application2.getClass().getName());
  566. sb.append(".");
  567. sb.append(application2.getClass().getSimpleName());
  568. sb.append("(");
  569. sb.append(application2.getClass().getSimpleName());
  570. sb.append(".java");
  571. sb.append(":1)");
  572. int l = 1;
  573. for (Component component2 : h) {
  574. sb.append("\n");
  575. for (int i = 0; i < l; i++) {
  576. sb.append(" ");
  577. }
  578. l++;
  579. Class<? extends Component> componentClass = component2.getClass();
  580. Class<?> topClass = componentClass;
  581. while (topClass.getEnclosingClass() != null) {
  582. topClass = topClass.getEnclosingClass();
  583. }
  584. sb.append(componentClass.getName());
  585. sb.append(".");
  586. sb.append(componentClass.getSimpleName());
  587. sb.append("(");
  588. sb.append(topClass.getSimpleName());
  589. sb.append(".java:1)");
  590. }
  591. }
  592. /**
  593. * TODO document
  594. *
  595. * @param request
  596. * @param response
  597. * @param callback
  598. * @param repaintAll
  599. * @param outWriter
  600. * @param window
  601. * @param analyzeLayouts
  602. * @throws PaintException
  603. * @throws IOException
  604. */
  605. private void paintAfterVariableChanges(WrappedRequest request,
  606. WrappedResponse response, Callback callback, boolean repaintAll,
  607. final PrintWriter outWriter, Root root, boolean analyzeLayouts)
  608. throws PaintException, IOException {
  609. if (repaintAll) {
  610. makeAllPaintablesDirty(root);
  611. }
  612. // Removes application if it has stopped during variable changes
  613. if (!application.isRunning()) {
  614. endApplication(request, response, application);
  615. return;
  616. }
  617. openJsonMessage(outWriter, response);
  618. // security key
  619. Object writeSecurityTokenFlag = request
  620. .getAttribute(WRITE_SECURITY_TOKEN_FLAG);
  621. if (writeSecurityTokenFlag != null) {
  622. outWriter.print(getSecurityKeyUIDL(request));
  623. }
  624. writeUidlResponce(repaintAll, outWriter, root, analyzeLayouts);
  625. closeJsonMessage(outWriter);
  626. outWriter.close();
  627. }
  628. /**
  629. * Gets the security key (and generates one if needed) as UIDL.
  630. *
  631. * @param request
  632. * @return the security key UIDL or "" if the feature is turned off
  633. */
  634. public String getSecurityKeyUIDL(WrappedRequest request) {
  635. final String seckey = getSecurityKey(request);
  636. if (seckey != null) {
  637. return "\"" + ApplicationConnection.UIDL_SECURITY_TOKEN_ID
  638. + "\":\"" + seckey + "\",";
  639. } else {
  640. return "";
  641. }
  642. }
  643. /**
  644. * Gets the security key (and generates one if needed).
  645. *
  646. * @param request
  647. * @return the security key
  648. */
  649. protected String getSecurityKey(WrappedRequest request) {
  650. String seckey = null;
  651. seckey = (String) request
  652. .getSessionAttribute(ApplicationConnection.UIDL_SECURITY_TOKEN_ID);
  653. if (seckey == null) {
  654. seckey = UUID.randomUUID().toString();
  655. request.setSessionAttribute(
  656. ApplicationConnection.UIDL_SECURITY_TOKEN_ID, seckey);
  657. }
  658. return seckey;
  659. }
  660. public void writeUidlResponce(boolean repaintAll,
  661. final PrintWriter outWriter, Root root, boolean analyzeLayouts)
  662. throws PaintException {
  663. outWriter.print("\"changes\":[");
  664. ArrayList<Paintable> paintables = null;
  665. List<InvalidLayout> invalidComponentRelativeSizes = null;
  666. JsonPaintTarget paintTarget = new JsonPaintTarget(this, outWriter,
  667. !repaintAll);
  668. OpenWindowCache windowCache = currentlyOpenWindowsInClient.get(Integer
  669. .valueOf(root.getRootId()));
  670. if (windowCache == null) {
  671. windowCache = new OpenWindowCache();
  672. currentlyOpenWindowsInClient.put(Integer.valueOf(root.getRootId()),
  673. windowCache);
  674. }
  675. // Paints components
  676. if (repaintAll) {
  677. paintables = new ArrayList<Paintable>();
  678. paintables.add(root);
  679. // Reset sent locales
  680. locales = null;
  681. requireLocale(application.getLocale().toString());
  682. } else {
  683. // remove detached components from paintableIdMap so they
  684. // can be GC'ed
  685. /*
  686. * TODO figure out if we could move this beyond the painting phase,
  687. * "respond as fast as possible, then do the cleanup". Beware of
  688. * painting the dirty detatched components.
  689. */
  690. for (Iterator<Paintable> it = paintableIdMap.keySet().iterator(); it
  691. .hasNext();) {
  692. Component p = (Component) it.next();
  693. if (p.getApplication() == null) {
  694. unregisterPaintable(p);
  695. // Take into account that some other component may have
  696. // reused p's ID by now (this can happen when manually
  697. // assigning IDs with setDebugId().) See #8090.
  698. String pid = paintableIdMap.get(p);
  699. if (idPaintableMap.get(pid) == p) {
  700. idPaintableMap.remove(pid);
  701. }
  702. it.remove();
  703. dirtyPaintables.remove(p);
  704. }
  705. }
  706. paintables = getDirtyVisibleComponents(root);
  707. }
  708. if (paintables != null) {
  709. // We need to avoid painting children before parent.
  710. // This is ensured by ordering list by depth in component
  711. // tree
  712. Collections.sort(paintables, new Comparator<Paintable>() {
  713. public int compare(Paintable o1, Paintable o2) {
  714. Component c1 = (Component) o1;
  715. Component c2 = (Component) o2;
  716. int d1 = 0;
  717. while (c1.getParent() != null) {
  718. d1++;
  719. c1 = c1.getParent();
  720. }
  721. int d2 = 0;
  722. while (c2.getParent() != null) {
  723. d2++;
  724. c2 = c2.getParent();
  725. }
  726. if (d1 < d2) {
  727. return -1;
  728. }
  729. if (d1 > d2) {
  730. return 1;
  731. }
  732. return 0;
  733. }
  734. });
  735. for (final Iterator<Paintable> i = paintables.iterator(); i
  736. .hasNext();) {
  737. final Paintable p = i.next();
  738. // // TODO CLEAN
  739. // if (p instanceof Root) {
  740. // final Root r = (Root) p;
  741. // if (r.getTerminal() == null) {
  742. // r.setTerminal(application.getRoot().getTerminal());
  743. // }
  744. // }
  745. /*
  746. * This does not seem to happen in tk5, but remember this case:
  747. * else if (p instanceof Component) { if (((Component)
  748. * p).getParent() == null || ((Component) p).getApplication() ==
  749. * null) { // Component requested repaint, but is no // longer
  750. * attached: skip paintablePainted(p); continue; } }
  751. */
  752. // TODO we may still get changes that have been
  753. // rendered already (changes with only cached flag)
  754. if (paintTarget.needsToBePainted(p)) {
  755. paintTarget.startTag("change");
  756. paintTarget.addAttribute("format", "uidl");
  757. final String pid = getPaintableId(p);
  758. paintTarget.addAttribute("pid", pid);
  759. p.paint(paintTarget);
  760. paintTarget.endTag("change");
  761. }
  762. paintablePainted(p);
  763. if (analyzeLayouts) {
  764. Root w = (Root) p;
  765. invalidComponentRelativeSizes = ComponentSizeValidator
  766. .validateComponentRelativeSizes(w.getContent(),
  767. null, null);
  768. // // Also check any existing subwindows
  769. // if (w.getChildWindows() != null) {
  770. // for (Window subWindow : w.getChildWindows()) {
  771. // invalidComponentRelativeSizes = ComponentSizeValidator
  772. // .validateComponentRelativeSizes(
  773. // subWindow.getContent(),
  774. // invalidComponentRelativeSizes, null);
  775. // }
  776. // }
  777. }
  778. }
  779. }
  780. paintTarget.close();
  781. outWriter.print("]"); // close changes
  782. outWriter.print(", \"meta\" : {");
  783. boolean metaOpen = false;
  784. if (repaintAll) {
  785. metaOpen = true;
  786. outWriter.write("\"repaintAll\":true");
  787. if (analyzeLayouts) {
  788. outWriter.write(", \"invalidLayouts\":");
  789. outWriter.write("[");
  790. if (invalidComponentRelativeSizes != null) {
  791. boolean first = true;
  792. for (InvalidLayout invalidLayout : invalidComponentRelativeSizes) {
  793. if (!first) {
  794. outWriter.write(",");
  795. } else {
  796. first = false;
  797. }
  798. invalidLayout.reportErrors(outWriter, this, System.err);
  799. }
  800. }
  801. outWriter.write("]");
  802. }
  803. if (highLightedPaintable != null) {
  804. outWriter.write(", \"hl\":\"");
  805. outWriter.write(paintableIdMap.get(highLightedPaintable));
  806. outWriter.write("\"");
  807. highLightedPaintable = null;
  808. }
  809. }
  810. SystemMessages ci = null;
  811. try {
  812. Method m = application.getClass().getMethod("getSystemMessages",
  813. (Class[]) null);
  814. ci = (Application.SystemMessages) m.invoke(null, (Object[]) null);
  815. } catch (NoSuchMethodException e) {
  816. logger.log(Level.WARNING,
  817. "getSystemMessages() failed - continuing", e);
  818. } catch (IllegalArgumentException e) {
  819. logger.log(Level.WARNING,
  820. "getSystemMessages() failed - continuing", e);
  821. } catch (IllegalAccessException e) {
  822. logger.log(Level.WARNING,
  823. "getSystemMessages() failed - continuing", e);
  824. } catch (InvocationTargetException e) {
  825. logger.log(Level.WARNING,
  826. "getSystemMessages() failed - continuing", e);
  827. }
  828. // meta instruction for client to enable auto-forward to
  829. // sessionExpiredURL after timer expires.
  830. if (ci != null && ci.getSessionExpiredMessage() == null
  831. && ci.getSessionExpiredCaption() == null
  832. && ci.isSessionExpiredNotificationEnabled()) {
  833. int newTimeoutInterval = getTimeoutInterval();
  834. if (repaintAll || (timeoutInterval != newTimeoutInterval)) {
  835. String escapedURL = ci.getSessionExpiredURL() == null ? "" : ci
  836. .getSessionExpiredURL().replace("/", "\\/");
  837. if (metaOpen) {
  838. outWriter.write(",");
  839. }
  840. outWriter.write("\"timedRedirect\":{\"interval\":"
  841. + (newTimeoutInterval + 15) + ",\"url\":\""
  842. + escapedURL + "\"}");
  843. metaOpen = true;
  844. }
  845. timeoutInterval = newTimeoutInterval;
  846. }
  847. outWriter.print("}, \"resources\" : {");
  848. // Precache custom layouts
  849. // TODO We should only precache the layouts that are not
  850. // cached already (plagiate from usedPaintableTypes)
  851. int resourceIndex = 0;
  852. for (final Iterator<Object> i = paintTarget.getUsedResources()
  853. .iterator(); i.hasNext();) {
  854. final String resource = (String) i.next();
  855. InputStream is = null;
  856. try {
  857. is = getThemeResourceAsStream(root, getTheme(root), resource);
  858. } catch (final Exception e) {
  859. // FIXME: Handle exception
  860. logger.log(Level.FINER, "Failed to get theme resource stream.",
  861. e);
  862. }
  863. if (is != null) {
  864. outWriter.print((resourceIndex++ > 0 ? ", " : "") + "\""
  865. + resource + "\" : ");
  866. final StringBuffer layout = new StringBuffer();
  867. try {
  868. final InputStreamReader r = new InputStreamReader(is,
  869. "UTF-8");
  870. final char[] buffer = new char[20000];
  871. int charsRead = 0;
  872. while ((charsRead = r.read(buffer)) > 0) {
  873. layout.append(buffer, 0, charsRead);
  874. }
  875. r.close();
  876. } catch (final java.io.IOException e) {
  877. // FIXME: Handle exception
  878. logger.log(Level.INFO, "Resource transfer failed", e);
  879. }
  880. outWriter.print("\""
  881. + JsonPaintTarget.escapeJSON(layout.toString()) + "\"");
  882. } else {
  883. // FIXME: Handle exception
  884. logger.severe("CustomLayout not found: " + resource);
  885. }
  886. }
  887. outWriter.print("}");
  888. Collection<Class<? extends Paintable>> usedPaintableTypes = paintTarget
  889. .getUsedPaintableTypes();
  890. boolean typeMappingsOpen = false;
  891. for (Class<? extends Paintable> class1 : usedPaintableTypes) {
  892. if (windowCache.cache(class1)) {
  893. // client does not know the mapping key for this type, send
  894. // mapping to client
  895. if (!typeMappingsOpen) {
  896. typeMappingsOpen = true;
  897. outWriter.print(", \"typeMappings\" : { ");
  898. } else {
  899. outWriter.print(" , ");
  900. }
  901. String canonicalName = class1.getCanonicalName();
  902. outWriter.print("\"");
  903. outWriter.print(canonicalName);
  904. outWriter.print("\" : ");
  905. outWriter.print(getTagForType(class1));
  906. }
  907. }
  908. if (typeMappingsOpen) {
  909. outWriter.print(" }");
  910. }
  911. // add any pending locale definitions requested by the client
  912. printLocaleDeclarations(outWriter);
  913. if (dragAndDropService != null) {
  914. dragAndDropService.printJSONResponse(outWriter);
  915. }
  916. }
  917. protected abstract InputStream getThemeResourceAsStream(Root root,
  918. String themeName, String resource);
  919. private int getTimeoutInterval() {
  920. return maxInactiveInterval;
  921. }
  922. private String getTheme(Root root) {
  923. String themeName = root.getApplication().getThemeForRoot(root);
  924. String requestThemeName = getRequestTheme();
  925. if (requestThemeName != null) {
  926. themeName = requestThemeName;
  927. }
  928. if (themeName == null) {
  929. themeName = AbstractApplicationServlet.getDefaultTheme();
  930. }
  931. return themeName;
  932. }
  933. private String getRequestTheme() {
  934. return requestThemeName;
  935. }
  936. public void makeAllPaintablesDirty(Root root) {
  937. // If repaint is requested, clean all ids in this root window
  938. for (final Iterator<String> it = idPaintableMap.keySet().iterator(); it
  939. .hasNext();) {
  940. final Component c = (Component) idPaintableMap.get(it.next());
  941. if (isChildOf(root, c)) {
  942. it.remove();
  943. paintableIdMap.remove(c);
  944. }
  945. }
  946. // clean WindowCache
  947. OpenWindowCache openWindowCache = currentlyOpenWindowsInClient
  948. .get(Integer.valueOf(root.getRootId()));
  949. if (openWindowCache != null) {
  950. openWindowCache.clear();
  951. }
  952. }
  953. /**
  954. * Called when communication manager stops listening for repaints for given
  955. * component.
  956. *
  957. * @param p
  958. */
  959. protected void unregisterPaintable(Component p) {
  960. p.removeListener(this);
  961. }
  962. /**
  963. * Returns false if the cross site request forgery protection is turned off.
  964. *
  965. * @param application
  966. * @return false if the XSRF is turned off, true otherwise
  967. */
  968. public boolean isXSRFEnabled(Application application) {
  969. return !"true"
  970. .equals(application
  971. .getProperty(AbstractApplicationServlet.SERVLET_PARAMETER_DISABLE_XSRF_PROTECTION));
  972. }
  973. /**
  974. * TODO document
  975. *
  976. * If this method returns false, something was submitted that we did not
  977. * expect; this is probably due to the client being out-of-sync and sending
  978. * variable changes for non-existing pids
  979. *
  980. * @return true if successful, false if there was an inconsistency
  981. */
  982. private boolean handleVariables(WrappedRequest request,
  983. WrappedResponse response, Callback callback,
  984. Application application2, Root root) throws IOException,
  985. InvalidUIDLSecurityKeyException {
  986. boolean success = true;
  987. String changes = getRequestPayload(request);
  988. if (changes != null) {
  989. // Manage bursts one by one
  990. final String[] bursts = changes.split(String
  991. .valueOf(VAR_BURST_SEPARATOR));
  992. // Security: double cookie submission pattern unless disabled by
  993. // property
  994. if (isXSRFEnabled(application2)) {
  995. if (bursts.length == 1 && "init".equals(bursts[0])) {
  996. // init request; don't handle any variables, key sent in
  997. // response.
  998. request.setAttribute(WRITE_SECURITY_TOKEN_FLAG, true);
  999. return true;
  1000. } else {
  1001. // ApplicationServlet has stored the security token in the
  1002. // session; check that it matched the one sent in the UIDL
  1003. String sessId = (String) request
  1004. .getSessionAttribute(ApplicationConnection.UIDL_SECURITY_TOKEN_ID);
  1005. if (sessId == null || !sessId.equals(bursts[0])) {
  1006. throw new InvalidUIDLSecurityKeyException(
  1007. "Security key mismatch");
  1008. }
  1009. }
  1010. }
  1011. for (int bi = 1; bi < bursts.length; bi++) {
  1012. final String burst = bursts[bi];
  1013. success = handleVariableBurst(request, application2, success,
  1014. burst);
  1015. // In case that there were multiple bursts, we know that this is
  1016. // a special synchronous case for closing window. Thus we are
  1017. // not interested in sending any UIDL changes back to client.
  1018. // Still we must clear component tree between bursts to ensure
  1019. // that no removed components are updated. The painting after
  1020. // the last burst is handled normally by the calling method.
  1021. if (bi < bursts.length - 1) {
  1022. // We will be discarding all changes
  1023. final PrintWriter outWriter = new PrintWriter(
  1024. new CharArrayWriter());
  1025. paintAfterVariableChanges(request, response, callback,
  1026. true, outWriter, root, false);
  1027. }
  1028. }
  1029. }
  1030. /*
  1031. * Note that we ignore inconsistencies while handling unload request.
  1032. * The client can't remove invalid variable changes from the burst, and
  1033. * we don't have the required logic implemented on the server side. E.g.
  1034. * a component is removed in a previous burst.
  1035. */
  1036. return success;
  1037. }
  1038. public boolean handleVariableBurst(Object source, Application app,
  1039. boolean success, final String burst) {
  1040. // extract variables to two dim string array
  1041. final String[] tmp = burst.split(String.valueOf(VAR_RECORD_SEPARATOR));
  1042. final String[][] variableRecords = new String[tmp.length][4];
  1043. for (int i = 0; i < tmp.length; i++) {
  1044. variableRecords[i] = tmp[i].split(String
  1045. .valueOf(VAR_FIELD_SEPARATOR));
  1046. }
  1047. for (int i = 0; i < variableRecords.length; i++) {
  1048. String[] variable = variableRecords[i];
  1049. String[] nextVariable = null;
  1050. if (i + 1 < variableRecords.length) {
  1051. nextVariable = variableRecords[i + 1];
  1052. }
  1053. final VariableOwner owner = getVariableOwner(variable[VAR_PID]);
  1054. if (owner != null && owner.isEnabled()) {
  1055. Map<String, Object> m;
  1056. if (nextVariable != null
  1057. && variable[VAR_PID].equals(nextVariable[VAR_PID])) {
  1058. // we have more than one value changes in row for
  1059. // one variable owner, collect them in HashMap
  1060. m = new HashMap<String, Object>();
  1061. m.put(variable[VAR_NAME],
  1062. convertVariableValue(variable[VAR_TYPE].charAt(0),
  1063. variable[VAR_VALUE]));
  1064. } else {
  1065. // use optimized single value map
  1066. m = Collections.singletonMap(
  1067. variable[VAR_NAME],
  1068. convertVariableValue(variable[VAR_TYPE].charAt(0),
  1069. variable[VAR_VALUE]));
  1070. }
  1071. // collect following variable changes for this owner
  1072. while (nextVariable != null
  1073. && variable[VAR_PID].equals(nextVariable[VAR_PID])) {
  1074. i++;
  1075. variable = nextVariable;
  1076. if (i + 1 < variableRecords.length) {
  1077. nextVariable = variableRecords[i + 1];
  1078. } else {
  1079. nextVariable = null;
  1080. }
  1081. m.put(variable[VAR_NAME],
  1082. convertVariableValue(variable[VAR_TYPE].charAt(0),
  1083. variable[VAR_VALUE]));
  1084. }
  1085. try {
  1086. changeVariables(source, owner, m);
  1087. } catch (Exception e) {
  1088. if (owner instanceof Component) {
  1089. handleChangeVariablesError(app, (Component) owner, e, m);
  1090. } else {
  1091. // TODO DragDropService error handling
  1092. throw new RuntimeException(e);
  1093. }
  1094. }
  1095. } else {
  1096. // Handle special case where window-close is called
  1097. // after the window has been removed from the
  1098. // application or the application has closed
  1099. if ("close".equals(variable[VAR_NAME])
  1100. && "true".equals(variable[VAR_VALUE])) {
  1101. // Silently ignore this
  1102. continue;
  1103. }
  1104. // Ignore variable change
  1105. String msg = "Warning: Ignoring variable change for ";
  1106. if (owner != null) {
  1107. msg += "disabled component " + owner.getClass();
  1108. String caption = ((Component) owner).getCaption();
  1109. if (caption != null) {
  1110. msg += ", caption=" + caption;
  1111. }
  1112. } else {
  1113. msg += "non-existent component, VAR_PID="
  1114. + variable[VAR_PID];
  1115. success = false;
  1116. }
  1117. logger.warning(msg);
  1118. continue;
  1119. }
  1120. }
  1121. return success;
  1122. }
  1123. protected void changeVariables(Object source, final VariableOwner owner,
  1124. Map<String, Object> m) {
  1125. owner.changeVariables(source, m);
  1126. }
  1127. protected VariableOwner getVariableOwner(String string) {
  1128. VariableOwner owner = (VariableOwner) idPaintableMap.get(string);
  1129. if (owner == null && string.startsWith("DD")) {
  1130. return getDragAndDropService();
  1131. }
  1132. return owner;
  1133. }
  1134. private VariableOwner getDragAndDropService() {
  1135. if (dragAndDropService == null) {
  1136. dragAndDropService = new DragAndDropService(this);
  1137. }
  1138. return dragAndDropService;
  1139. }
  1140. /**
  1141. * Reads the request data from the Request and returns it converted to an
  1142. * UTF-8 string.
  1143. *
  1144. * @param request
  1145. * @return
  1146. * @throws IOException
  1147. */
  1148. protected String getRequestPayload(WrappedRequest request)
  1149. throws IOException {
  1150. int requestLength = request.getContentLength();
  1151. if (requestLength == 0) {
  1152. return null;
  1153. }
  1154. ByteArrayOutputStream bout = requestLength <= 0 ? new ByteArrayOutputStream()
  1155. : new ByteArrayOutputStream(requestLength);
  1156. InputStream inputStream = request.getInputStream();
  1157. byte[] buffer = new byte[MAX_BUFFER_SIZE];
  1158. while (true) {
  1159. int read = inputStream.read(buffer);
  1160. if (read == -1) {
  1161. break;
  1162. }
  1163. bout.write(buffer, 0, read);
  1164. }
  1165. String result = new String(bout.toByteArray(), "utf-8");
  1166. return result;
  1167. }
  1168. public class ErrorHandlerErrorEvent implements ErrorEvent, Serializable {
  1169. private final Throwable throwable;
  1170. public ErrorHandlerErrorEvent(Throwable throwable) {
  1171. this.throwable = throwable;
  1172. }
  1173. public Throwable getThrowable() {
  1174. return throwable;
  1175. }
  1176. }
  1177. /**
  1178. * Handles an error (exception) that occurred when processing variable
  1179. * changes from the client or a failure of a file upload.
  1180. *
  1181. * For {@link AbstractField} components,
  1182. * {@link AbstractField#handleError(com.vaadin.ui.AbstractComponent.ComponentErrorEvent)}
  1183. * is called. In all other cases (or if the field does not handle the
  1184. * error), {@link ErrorListener#terminalError(ErrorEvent)} for the
  1185. * application error handler is called.
  1186. *
  1187. * @param application
  1188. * @param owner
  1189. * component that the error concerns
  1190. * @param e
  1191. * exception that occurred
  1192. * @param m
  1193. * map from variable names to values
  1194. */
  1195. private void handleChangeVariablesError(Application application,
  1196. Component owner, Exception e, Map<String, Object> m) {
  1197. boolean handled = false;
  1198. ChangeVariablesErrorEvent errorEvent = new ChangeVariablesErrorEvent(
  1199. owner, e, m);
  1200. if (owner instanceof AbstractField) {
  1201. try {
  1202. handled = ((AbstractField<?>) owner).handleError(errorEvent);
  1203. } catch (Exception handlerException) {
  1204. /*
  1205. * If there is an error in the component error handler we pass
  1206. * the that error to the application error handler and continue
  1207. * processing the actual error
  1208. */
  1209. application.getErrorHandler().terminalError(
  1210. new ErrorHandlerErrorEvent(handlerException));
  1211. handled = false;
  1212. }
  1213. }
  1214. if (!handled) {
  1215. application.getErrorHandler().terminalError(errorEvent);
  1216. }
  1217. }
  1218. private Object convertVariableValue(char variableType, String strValue) {
  1219. Object val = null;
  1220. switch (variableType) {
  1221. case VTYPE_ARRAY:
  1222. val = convertArray(strValue);
  1223. break;
  1224. case VTYPE_MAP:
  1225. val = convertMap(strValue);
  1226. break;
  1227. case VTYPE_STRINGARRAY:
  1228. val = convertStringArray(strValue);
  1229. break;
  1230. case VTYPE_STRING:
  1231. // decode encoded separators
  1232. val = decodeVariableValue(strValue);
  1233. break;
  1234. case VTYPE_INTEGER:
  1235. val = Integer.valueOf(strValue);
  1236. break;
  1237. case VTYPE_LONG:
  1238. val = Long.valueOf(strValue);
  1239. break;
  1240. case VTYPE_FLOAT:
  1241. val = Float.valueOf(strValue);
  1242. break;
  1243. case VTYPE_DOUBLE:
  1244. val = Double.valueOf(strValue);
  1245. break;
  1246. case VTYPE_BOOLEAN:
  1247. val = Boolean.valueOf(strValue);
  1248. break;
  1249. case VTYPE_PAINTABLE:
  1250. val = idPaintableMap.get(strValue);
  1251. break;
  1252. }
  1253. return val;
  1254. }
  1255. private Object convertMap(String strValue) {
  1256. String[] parts = strValue
  1257. .split(String.valueOf(VAR_ARRAYITEM_SEPARATOR));
  1258. HashMap<String, Object> map = new HashMap<String, Object>();
  1259. for (int i = 0; i < parts.length; i += 2) {
  1260. String key = parts[i];
  1261. if (key.length() > 0) {
  1262. char variabletype = key.charAt(0);
  1263. // decode encoded separators
  1264. String decodedValue = decodeVariableValue(parts[i + 1]);
  1265. String decodedKey = decodeVariableValue(key.substring(1));
  1266. Object value = convertVariableValue(variabletype, decodedValue);
  1267. map.put(decodedKey, value);
  1268. }
  1269. }
  1270. return map;
  1271. }
  1272. private String[] convertStringArray(String strValue) {
  1273. // need to return delimiters and filter them out; otherwise empty
  1274. // strings are lost
  1275. // an extra empty delimiter at the end is automatically eliminated
  1276. final String arrayItemSeparator = String
  1277. .valueOf(VAR_ARRAYITEM_SEPARATOR);
  1278. StringTokenizer tokenizer = new StringTokenizer(strValue,
  1279. arrayItemSeparator, true);
  1280. List<String> tokens = new ArrayList<String>();
  1281. String prevToken = arrayItemSeparator;
  1282. while (tokenizer.hasMoreTokens()) {
  1283. String token = tokenizer.nextToken();
  1284. if (!arrayItemSeparator.equals(token)) {
  1285. // decode encoded separators
  1286. tokens.add(decodeVariableValue(token));
  1287. } else if (arrayItemSeparator.equals(prevToken)) {
  1288. tokens.add("");
  1289. }
  1290. prevToken = token;
  1291. }
  1292. return tokens.toArray(new String[tokens.size()]);
  1293. }
  1294. private Object convertArray(String strValue) {
  1295. String[] val = strValue.split(String.valueOf(VAR_ARRAYITEM_SEPARATOR));
  1296. if (val.length == 0 || (val.length == 1 && val[0].length() == 0)) {
  1297. return new Object[0];
  1298. }
  1299. Object[] values = new Object[val.length];
  1300. for (int i = 0; i < values.length; i++) {
  1301. String string = val[i];
  1302. // first char of string is type
  1303. char variableType = string.charAt(0);
  1304. values[i] = convertVariableValue(variableType, string.substring(1));
  1305. }
  1306. return values;
  1307. }
  1308. /**
  1309. * Decode encoded burst, record, field and array item separator characters
  1310. * in a variable value String received from the client. This protects from
  1311. * separator injection attacks.
  1312. *
  1313. * @param encodedValue
  1314. * to decode
  1315. * @return decoded value
  1316. */
  1317. protected String decodeVariableValue(String encodedValue) {
  1318. final StringBuilder result = new StringBuilder();
  1319. final StringCharacterIterator iterator = new StringCharacterIterator(
  1320. encodedValue);
  1321. char character = iterator.current();
  1322. while (character != CharacterIterator.DONE) {
  1323. if (VAR_ESCAPE_CHARACTER == character) {
  1324. character = iterator.next();
  1325. switch (character) {
  1326. case VAR_ESCAPE_CHARACTER + 0x30:
  1327. // escaped escape character
  1328. result.append(VAR_ESCAPE_CHARACTER);
  1329. break;
  1330. case VAR_BURST_SEPARATOR + 0x30:
  1331. case VAR_RECORD_SEPARATOR + 0x30:
  1332. case VAR_FIELD_SEPARATOR + 0x30:
  1333. case VAR_ARRAYITEM_SEPARATOR + 0x30:
  1334. // +0x30 makes these letters for easier reading
  1335. result.append((char) (character - 0x30));
  1336. break;
  1337. case CharacterIterator.DONE:
  1338. // error
  1339. throw new RuntimeException(
  1340. "Communication error: Unexpected end of message");
  1341. default:
  1342. // other escaped character - probably a client-server
  1343. // version mismatch
  1344. throw new RuntimeException(
  1345. "Invalid escaped character from the client - check that the widgetset and server versions match");
  1346. }
  1347. } else {
  1348. // not a special character - add it to the result as is
  1349. result.append(character);
  1350. }
  1351. character = iterator.next();
  1352. }
  1353. return result.toString();
  1354. }
  1355. /**
  1356. * Prints the queued (pending) locale definitions to a {@link PrintWriter}
  1357. * in a (UIDL) format that can be sent to the client and used there in
  1358. * formatting dates, times etc.
  1359. *
  1360. * @param outWriter
  1361. */
  1362. private void printLocaleDeclarations(PrintWriter outWriter) {
  1363. /*
  1364. * ----------------------------- Sending Locale sensitive date
  1365. * -----------------------------
  1366. */
  1367. // Send locale informations to client
  1368. outWriter.print(", \"locales\":[");
  1369. for (; pendingLocalesIndex < locales.size(); pendingLocalesIndex++) {
  1370. final Locale l = generateLocale(locales.get(pendingLocalesIndex));
  1371. // Locale name
  1372. outWriter.print("{\"name\":\"" + l.toString() + "\",");
  1373. /*
  1374. * Month names (both short and full)
  1375. */
  1376. final DateFormatSymbols dfs = new DateFormatSymbols(l);
  1377. final String[] short_months = dfs.getShortMonths();
  1378. final String[] months = dfs.getMonths();
  1379. outWriter.print("\"smn\":[\""
  1380. + // ShortMonthNames
  1381. short_months[0] + "\",\"" + short_months[1] + "\",\""
  1382. + short_months[2] + "\",\"" + short_months[3] + "\",\""
  1383. + short_months[4] + "\",\"" + short_months[5] + "\",\""
  1384. + short_months[6] + "\",\"" + short_months[7] + "\",\""
  1385. + short_months[8] + "\",\"" + short_months[9] + "\",\""
  1386. + short_months[10] + "\",\"" + short_months[11] + "\""
  1387. + "],");
  1388. outWriter.print("\"mn\":[\""
  1389. + // MonthNames
  1390. months[0] + "\",\"" + months[1] + "\",\"" + months[2]
  1391. + "\",\"" + months[3] + "\",\"" + months[4] + "\",\""
  1392. + months[5] + "\",\"" + months[6] + "\",\"" + months[7]
  1393. + "\",\"" + months[8] + "\",\"" + months[9] + "\",\""
  1394. + months[10] + "\",\"" + months[11] + "\"" + "],");
  1395. /*
  1396. * Weekday names (both short and full)
  1397. */
  1398. final String[] short_days = dfs.getShortWeekdays();
  1399. final String[] days = dfs.getWeekdays();
  1400. outWriter.print("\"sdn\":[\""
  1401. + // ShortDayNames
  1402. short_days[1] + "\",\"" + short_days[2] + "\",\""
  1403. + short_days[3] + "\",\"" + short_days[4] + "\",\""
  1404. + short_days[5] + "\",\"" + short_days[6] + "\",\""
  1405. + short_days[7] + "\"" + "],");
  1406. outWriter.print("\"dn\":[\""
  1407. + // DayNames
  1408. days[1] + "\",\"" + days[2] + "\",\"" + days[3] + "\",\""
  1409. + days[4] + "\",\"" + days[5] + "\",\"" + days[6] + "\",\""
  1410. + days[7] + "\"" + "],");
  1411. /*
  1412. * First day of week (0 = sunday, 1 = monday)
  1413. */
  1414. final Calendar cal = new GregorianCalendar(l);
  1415. outWriter.print("\"fdow\":" + (cal.getFirstDayOfWeek() - 1) + ",");
  1416. /*
  1417. * Date formatting (MM/DD/YYYY etc.)
  1418. */
  1419. DateFormat dateFormat = DateFormat.getDateTimeInstance(
  1420. DateFormat.SHORT, DateFormat.SHORT, l);
  1421. if (!(dateFormat instanceof SimpleDateFormat)) {
  1422. logger.warning("Unable to get default date pattern for locale "
  1423. + l.toString());
  1424. dateFormat = new SimpleDateFormat();
  1425. }
  1426. final String df = ((SimpleDateFormat) dateFormat).toPattern();
  1427. int timeStart = df.indexOf("H");
  1428. if (timeStart < 0) {
  1429. timeStart = df.indexOf("h");
  1430. }
  1431. final int ampm_first = df.indexOf("a");
  1432. // E.g. in Korean locale AM/PM is before h:mm
  1433. // TODO should take that into consideration on client-side as well,
  1434. // now always h:mm a
  1435. if (ampm_first > 0 && ampm_first < timeStart) {
  1436. timeStart = ampm_first;
  1437. }
  1438. // Hebrew locale has time before the date
  1439. final boolean timeFirst = timeStart == 0;
  1440. String dateformat;
  1441. if (timeFirst) {
  1442. int dateStart = df.indexOf(' ');
  1443. if (ampm_first > dateStart) {
  1444. dateStart = df.indexOf(' ', ampm_first);
  1445. }
  1446. dateformat = df.substring(dateStart + 1);
  1447. } else {
  1448. dateformat = df.substring(0, timeStart - 1);
  1449. }
  1450. outWriter.print("\"df\":\"" + dateformat.trim() + "\",");
  1451. /*
  1452. * Time formatting (24 or 12 hour clock and AM/PM suffixes)
  1453. */
  1454. final String timeformat = df.substring(timeStart, df.length());
  1455. /*
  1456. * Doesn't return second or milliseconds.
  1457. *
  1458. * We use timeformat to determine 12/24-hour clock
  1459. */
  1460. final boolean twelve_hour_clock = timeformat.indexOf("a") > -1;
  1461. // TODO there are other possibilities as well, like 'h' in french
  1462. // (ignore them, too complicated)
  1463. final String hour_min_delimiter = timeformat.indexOf(".") > -1 ? "."
  1464. : ":";
  1465. // outWriter.print("\"tf\":\"" + timeformat + "\",");
  1466. outWriter.print("\"thc\":" + twelve_hour_clock + ",");
  1467. outWriter.print("\"hmd\":\"" + hour_min_delimiter + "\"");
  1468. if (twelve_hour_clock) {
  1469. final String[] ampm = dfs.getAmPmStrings();
  1470. outWriter.print(",\"ampm\":[\"" + ampm[0] + "\",\"" + ampm[1]
  1471. + "\"]");
  1472. }
  1473. outWriter.print("}");
  1474. if (pendingLocalesIndex < locales.size() - 1) {
  1475. outWriter.print(",");
  1476. }
  1477. }
  1478. outWriter.print("]"); // Close locales
  1479. }
  1480. /**
  1481. * Ends the Application.
  1482. *
  1483. * The browser is redirected to the Application logout URL set with
  1484. * {@link Application#setLogoutURL(String)}, or to the application URL if no
  1485. * logout URL is given.
  1486. *
  1487. * @param request
  1488. * the request instance.
  1489. * @param response
  1490. * the response to write to.
  1491. * @param application
  1492. * the Application to end.
  1493. * @throws IOException
  1494. * if the writing failed due to input/output error.
  1495. */
  1496. private void endApplication(WrappedRequest request,
  1497. WrappedResponse response, Application application)
  1498. throws IOException {
  1499. String logoutUrl = application.getLogoutURL();
  1500. if (logoutUrl == null) {
  1501. logoutUrl = application.getURL().toString();
  1502. }
  1503. // clients JS app is still running, send a special json file to tell
  1504. // client that application has quit and where to point browser now
  1505. // Set the response type
  1506. final OutputStream out = response.getOutputStream();
  1507. final PrintWriter outWriter = new PrintWriter(new BufferedWriter(
  1508. new OutputStreamWriter(out, "UTF-8")));
  1509. openJsonMessage(outWriter, response);
  1510. outWriter.print("\"redirect\":{");
  1511. outWriter.write("\"url\":\"" + logoutUrl + "\"}");
  1512. closeJsonMessage(outWriter);
  1513. outWriter.flush();
  1514. outWriter.close();
  1515. out.flush();
  1516. }
  1517. protected void closeJsonMessage(PrintWriter outWriter) {
  1518. outWriter.print("}]");
  1519. }
  1520. /**
  1521. * Writes the opening of JSON message to be sent to client.
  1522. *
  1523. * @param outWriter
  1524. * @param response
  1525. */
  1526. protected void openJsonMessage(PrintWriter outWriter,
  1527. WrappedResponse response) {
  1528. // Sets the response type
  1529. response.setContentType("application/json; charset=UTF-8");
  1530. // some dirt to prevent cross site scripting
  1531. outWriter.print("for(;;);[{");
  1532. }
  1533. /**
  1534. * Gets the Paintable Id. If Paintable has debug id set it will be used
  1535. * prefixed with "PID_S". Otherwise a sequenced ID is created.
  1536. *
  1537. * @param paintable
  1538. * @return the paintable Id.
  1539. */
  1540. public String getPaintableId(Paintable paintable) {
  1541. String id = paintableIdMap.get(paintable);
  1542. if (id == null) {
  1543. // use testing identifier as id if set
  1544. id = paintable.getDebugId();
  1545. if (id == null) {
  1546. id = "PID" + Integer.toString(idSequence++);
  1547. } else {
  1548. id = "PID_S" + id;
  1549. }
  1550. Paintable old = idPaintableMap.put(id, paintable);
  1551. if (old != null && old != paintable) {
  1552. /*
  1553. * Two paintables have the same id. We still make sure the old
  1554. * one is a component which is still attached to the
  1555. * application. This is just a precaution and should not be
  1556. * absolutely necessary.
  1557. */
  1558. if (old instanceof Component
  1559. && ((Component) old).getApplication() != null) {
  1560. throw new IllegalStateException("Two paintables ("
  1561. + paintable.getClass().getSimpleName() + ","
  1562. + old.getClass().getSimpleName()
  1563. + ") have been assigned the same id: "
  1564. + paintable.getDebugId());
  1565. }
  1566. }
  1567. paintableIdMap.put(paintable, id);
  1568. }
  1569. return id;
  1570. }
  1571. public boolean hasPaintableId(Paintable paintable) {
  1572. return paintableIdMap.containsKey(paintable);
  1573. }
  1574. /**
  1575. * Returns dirty components which are in given window. Components in an
  1576. * invisible subtrees are omitted.
  1577. *
  1578. * @param w
  1579. * root window for which dirty components is to be fetched
  1580. * @return
  1581. */
  1582. private ArrayList<Paintable> getDirtyVisibleComponents(Root r) {
  1583. final ArrayList<Paintable> resultset = new ArrayList<Paintable>(
  1584. dirtyPaintables);
  1585. // The following algorithm removes any components that would be painted
  1586. // as a direct descendant of other components from the dirty components
  1587. // list. The result is that each component should be painted exactly
  1588. // once and any unmodified components will be painted as "cached=true".
  1589. for (final Iterator<Paintable> i = dirtyPaintables.iterator(); i
  1590. .hasNext();) {
  1591. final Paintable p = i.next();
  1592. if (p instanceof Component) {
  1593. final Component component = (Component) p;
  1594. if (component.getApplication() == null) {
  1595. // component is detached after requestRepaint is called
  1596. resultset.remove(p);
  1597. i.remove();
  1598. } else {
  1599. Root componentsRoot = component.getRoot();
  1600. if (componentsRoot == null) {
  1601. // This should not happen unless somebody has overriden
  1602. // getApplication or getWindow in an illegal way.
  1603. throw new IllegalStateException(
  1604. "component.getWindow() returned null for a component attached to the application");
  1605. }
  1606. // if (componentsRoot.getParent() != null) {
  1607. // // this is a subwindow
  1608. // componentsRoot = componentsRoot.getParent();
  1609. // }
  1610. if (componentsRoot != r) {
  1611. resultset.remove(p);
  1612. } else if (component.getParent() != null
  1613. && !component.getParent().isVisible()) {
  1614. /*
  1615. * Do not return components in an invisible subtree.
  1616. *
  1617. * Components that are invisible in visible subree, must
  1618. * be rendered (to let client know that they need to be
  1619. * hidden).
  1620. */
  1621. resultset.remove(p);
  1622. }
  1623. }
  1624. }
  1625. }
  1626. return resultset;
  1627. }
  1628. /**
  1629. * @see com.vaadin.terminal.Paintable.RepaintRequestListener#repaintRequested(com.vaadin.terminal.Paintable.RepaintRequestEvent)
  1630. */
  1631. public void repaintRequested(RepaintRequestEvent event) {
  1632. final Paintable p = event.getPaintable();
  1633. if (!dirtyPaintables.contains(p)) {
  1634. dirtyPaintables.add(p);
  1635. }
  1636. }
  1637. /**
  1638. * Internally mark a {@link Paintable} as painted and start collecting new
  1639. * repaint requests for it.
  1640. *
  1641. * @param paintable
  1642. */
  1643. private void paintablePainted(Paintable paintable) {
  1644. dirtyPaintables.remove(paintable);
  1645. paintable.requestRepaintRequests();
  1646. }
  1647. /**
  1648. * Queues a locale to be sent to the client (browser) for date and time
  1649. * entry etc. All locale specific information is derived from server-side
  1650. * {@link Locale} instances and sent to the client when needed, eliminating
  1651. * the need to use the {@link Locale} class and all the framework behind it
  1652. * on the client.
  1653. *
  1654. * @see Locale#toString()
  1655. *
  1656. * @param value
  1657. */
  1658. public void requireLocale(String value) {
  1659. if (locales == null) {
  1660. locales = new ArrayList<String>();
  1661. locales.add(application.getLocale().toString());
  1662. pendingLocalesIndex = 0;
  1663. }
  1664. if (!locales.contains(value)) {
  1665. locales.add(value);
  1666. }
  1667. }
  1668. /**
  1669. * Constructs a {@link Locale} instance to be sent to the client based on a
  1670. * short locale description string.
  1671. *
  1672. * @see #requireLocale(String)
  1673. *
  1674. * @param value
  1675. * @return
  1676. */
  1677. private Locale generateLocale(String value) {
  1678. final String[] temp = value.split("_");
  1679. if (temp.length == 1) {
  1680. return new Locale(temp[0]);
  1681. } else if (temp.length == 2) {
  1682. return new Locale(temp[0], temp[1]);
  1683. } else {
  1684. return new Locale(temp[0], temp[1], temp[2]);
  1685. }
  1686. }
  1687. /**
  1688. * Helper method to test if a component contains another
  1689. *
  1690. * @param parent
  1691. * @param child
  1692. */
  1693. private static boolean isChildOf(Component parent, Component child) {
  1694. Component p = child.getParent();
  1695. while (p != null) {
  1696. if (parent == p) {
  1697. return true;
  1698. }
  1699. p = p.getParent();
  1700. }
  1701. return false;
  1702. }
  1703. protected class InvalidUIDLSecurityKeyException extends
  1704. GeneralSecurityException {
  1705. InvalidUIDLSecurityKeyException(String message) {
  1706. super(message);
  1707. }
  1708. }
  1709. private final HashMap<Class<? extends Paintable>, Integer> typeToKey = new HashMap<Class<? extends Paintable>, Integer>();
  1710. private int nextTypeKey = 0;
  1711. private BootstrapHandler bootstrapHandler;
  1712. String getTagForType(Class<? extends Paintable> class1) {
  1713. Integer object = typeToKey.get(class1);
  1714. if (object == null) {
  1715. object = nextTypeKey++;
  1716. typeToKey.put(class1, object);
  1717. }
  1718. return object.toString();
  1719. }
  1720. /**
  1721. * Helper class for terminal to keep track of data that client is expected
  1722. * to know.
  1723. *
  1724. * TODO make customlayout templates (from theme) to be cached here.
  1725. */
  1726. class OpenWindowCache implements Serializable {
  1727. private final Set<Object> res = new HashSet<Object>();
  1728. /**
  1729. *
  1730. * @param paintable
  1731. * @return true if the given class was added to cache
  1732. */
  1733. boolean cache(Object object) {
  1734. return res.add(object);
  1735. }
  1736. public void clear() {
  1737. res.clear();
  1738. }
  1739. }
  1740. abstract String getStreamVariableTargetUrl(VariableOwner owner,
  1741. String name, StreamVariable value);
  1742. abstract protected void cleanStreamVariable(VariableOwner owner, String name);
  1743. /**
  1744. * Gets the bootstrap handler that should be used for generating the pages
  1745. * bootstrapping applications for this communication manager.
  1746. *
  1747. * @return the bootstrap handler to use
  1748. */
  1749. private BootstrapHandler getBootstrapHandler() {
  1750. if (bootstrapHandler == null) {
  1751. bootstrapHandler = createBootstrapHandler();
  1752. }
  1753. return bootstrapHandler;
  1754. }
  1755. protected abstract BootstrapHandler createBootstrapHandler();
  1756. protected boolean handleApplicationRequest(WrappedRequest request,
  1757. WrappedResponse response) throws IOException {
  1758. return application.handleRequest(request, response);
  1759. }
  1760. public void handleBrowserDetailsRequest(WrappedRequest request,
  1761. WrappedResponse response, Application application)
  1762. throws IOException {
  1763. // if we do not yet have a currentRoot, it should be initialized
  1764. // shortly, and we should send the initial UIDL
  1765. boolean sendUIDL = Root.getCurrentRoot() == null;
  1766. try {
  1767. CombinedRequest combinedRequest = new CombinedRequest(request);
  1768. Root root = application.getRootForRequest(combinedRequest);
  1769. response.setContentType("application/json; charset=UTF-8");
  1770. // Use the same logic as for determined roots
  1771. BootstrapHandler bootstrapHandler = getBootstrapHandler();
  1772. BootstrapContext context = bootstrapHandler.createContext(
  1773. combinedRequest, response, application, root.getRootId());
  1774. String widgetset = context.getWidgetsetName();
  1775. String theme = context.getThemeName();
  1776. String themeUri = bootstrapHandler.getThemeUri(context, theme);
  1777. // TODO These are not required if it was only the init of the root
  1778. // that was delayed
  1779. JSONObject params = new JSONObject();
  1780. params.put("widgetset", widgetset);
  1781. params.put("themeUri", themeUri);
  1782. // Root id might have changed based on e.g. window.name
  1783. params.put(ApplicationConnection.ROOT_ID_PARAMETER,
  1784. root.getRootId());
  1785. if (sendUIDL) {
  1786. String initialUIDL = getInitialUIDL(combinedRequest, root);
  1787. params.put("uidl", initialUIDL);
  1788. }
  1789. response.getWriter().write(params.toString());
  1790. } catch (RootRequiresMoreInformationException e) {
  1791. // Requiring more information at this point is not allowed
  1792. // TODO handle in a better way
  1793. throw new RuntimeException(e);
  1794. } catch (JSONException e) {
  1795. // TODO Auto-generated catch block
  1796. e.printStackTrace();
  1797. }
  1798. }
  1799. /**
  1800. * Generates the initial UIDL message that can e.g. be included in a html
  1801. * page to avoid a separate round trip just for getting the UIDL.
  1802. *
  1803. * @param request
  1804. * the request that caused the initialization
  1805. * @param root
  1806. * the root for which the UIDL should be generated
  1807. * @return a string with the initial UIDL message
  1808. * @throws PaintException
  1809. * if an exception occurs while painting
  1810. */
  1811. protected String getInitialUIDL(WrappedRequest request, Root root)
  1812. throws PaintException {
  1813. // TODO maybe unify writeUidlResponCe()?
  1814. makeAllPaintablesDirty(root);
  1815. StringWriter sWriter = new StringWriter();
  1816. PrintWriter pWriter = new PrintWriter(sWriter);
  1817. pWriter.print("{");
  1818. if (isXSRFEnabled(root.getApplication())) {
  1819. pWriter.print(getSecurityKeyUIDL(request));
  1820. }
  1821. writeUidlResponce(true, pWriter, root, false);
  1822. pWriter.print("}");
  1823. String initialUIDL = sWriter.toString();
  1824. return initialUIDL;
  1825. }
  1826. /**
  1827. * Stream that extracts content from another stream until the boundary
  1828. * string is encountered.
  1829. *
  1830. * Public only for unit tests, should be considered private for all other
  1831. * purposes.
  1832. */
  1833. public static class SimpleMultiPartInputStream extends InputStream {
  1834. /**
  1835. * Counter of how many characters have been matched to boundary string
  1836. * from the stream
  1837. */
  1838. int matchedCount = -1;
  1839. /**
  1840. * Used as pointer when returning bytes after partly matched boundary
  1841. * string.
  1842. */
  1843. int curBoundaryIndex = 0;
  1844. /**
  1845. * The byte found after a "promising start for boundary"
  1846. */
  1847. private int bufferedByte = -1;
  1848. private boolean atTheEnd = false;
  1849. private final char[] boundary;
  1850. private final InputStream realInputStream;
  1851. public SimpleMultiPartInputStream(InputStream realInputStream,
  1852. String boundaryString) {
  1853. boundary = (CRLF + DASHDASH + boundaryString).toCharArray();
  1854. this.realInputStream = realInputStream;
  1855. }
  1856. @Override
  1857. public int read() throws IOException {
  1858. if (atTheEnd) {
  1859. // End boundary reached, nothing more to read
  1860. return -1;
  1861. } else if (bufferedByte >= 0) {
  1862. /* Purge partially matched boundary if there was such */
  1863. return getBuffered();
  1864. } else if (matchedCount != -1) {
  1865. /*
  1866. * Special case where last "failed" matching ended with first
  1867. * character from boundary string
  1868. */
  1869. return matchForBoundary();
  1870. } else {
  1871. int fromActualStream = realInputStream.read();
  1872. if (fromActualStream == -1) {
  1873. // unexpected end of stream
  1874. throw new IOException(
  1875. "The multipart stream ended unexpectedly");
  1876. }
  1877. if (boundary[0] == fromActualStream) {
  1878. /*
  1879. * If matches the first character in boundary string, start
  1880. * checking if the boundary is fetched.
  1881. */
  1882. return matchForBoundary();
  1883. }
  1884. return fromActualStream;
  1885. }
  1886. }
  1887. /**
  1888. * Reads the input to expect a boundary string. Expects that the first
  1889. * character has already been matched.
  1890. *
  1891. * @return -1 if the boundary was matched, else returns the first byte
  1892. * from boundary
  1893. * @throws IOException
  1894. */
  1895. private int matchForBoundary() throws IOException {
  1896. matchedCount = 0;
  1897. /*
  1898. * Going to "buffered mode". Read until full boundary match or a
  1899. * different character.
  1900. */
  1901. while (true) {
  1902. matchedCount++;
  1903. if (matchedCount == boundary.length) {
  1904. /*
  1905. * The whole boundary matched so we have reached the end of
  1906. * file
  1907. */
  1908. atTheEnd = true;
  1909. return -1;
  1910. }
  1911. int fromActualStream = realInputStream.read();
  1912. if (fromActualStream != boundary[matchedCount]) {
  1913. /*
  1914. * Did not find full boundary, cache the mismatching byte
  1915. * and start returning the partially matched boundary.
  1916. */
  1917. bufferedByte = fromActualStream;
  1918. return getBuffered();
  1919. }
  1920. }
  1921. }
  1922. /**
  1923. * Returns the partly matched boundary string and the byte following
  1924. * that.
  1925. *
  1926. * @return
  1927. * @throws IOException
  1928. */
  1929. private int getBuffered() throws IOException {
  1930. int b;
  1931. if (matchedCount == 0) {
  1932. // The boundary has been returned, return the buffered byte.
  1933. b = bufferedByte;
  1934. bufferedByte = -1;
  1935. matchedCount = -1;
  1936. } else {
  1937. b = boundary[curBoundaryIndex++];
  1938. if (curBoundaryIndex == matchedCount) {
  1939. // The full boundary has been returned, remaining is the
  1940. // char that did not match the boundary.
  1941. curBoundaryIndex = 0;
  1942. if (bufferedByte != boundary[0]) {
  1943. /*
  1944. * next call for getBuffered will return the
  1945. * bufferedByte that came after the partial boundary
  1946. * match
  1947. */
  1948. matchedCount = 0;
  1949. } else {
  1950. /*
  1951. * Special case where buffered byte again matches the
  1952. * boundaryString. This could be the start of the real
  1953. * end boundary.
  1954. */
  1955. matchedCount = 0;
  1956. bufferedByte = -1;
  1957. }
  1958. }
  1959. }
  1960. if (b == -1) {
  1961. throw new IOException("The multipart stream ended unexpectedly");
  1962. }
  1963. return b;
  1964. }
  1965. }
  1966. }