You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractCommunicationManager.java 88KB

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