Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

AbstractCommunicationManager.java 92KB

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