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 84KB

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