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

AbstractCommunicationManager.java 95KB

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