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

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