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

AbstractCommunicationManager.java 107KB

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