Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

AbstractCommunicationManager.java 110KB

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