Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

AbstractCommunicationManager.java 90KB

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