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

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