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

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