View Javadoc

1   /**********************************************
2    * Copyright (C) 2010 Lukas Laag
3    * This file is part of lib-gwt-svg.
4    * 
5    * libgwtsvg is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU Lesser General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    * 
10   * libgwtsvg is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU Lesser General Public License for more details.
14   * 
15   * You should have received a copy of the GNU Lesser General Public License
16   * along with libgwtsvg.  If not, see http://www.gnu.org/licenses/
17   **********************************************/
18  package org.vectomatic.dom.svg.utils;
19  
20  import org.vectomatic.dom.svg.impl.SVGParserImpl;
21  
22  import com.google.gwt.core.client.GWT;
23  import com.google.gwt.dom.client.Element;
24  import com.google.gwt.http.client.Request;
25  import com.google.gwt.http.client.RequestBuilder;
26  import com.google.gwt.http.client.RequestCallback;
27  import com.google.gwt.http.client.RequestException;
28  import com.google.gwt.http.client.Response;
29  
30  
31  /**
32   * Implementation of the AsyncXmlLoader based on RequestBuilder.
33   */
34  public class HttpRequestXmlLoader implements AsyncXmlLoader {
35  
36  	@Override
37  	public void loadResource(final String resourceUrl, final AsyncXmlLoaderCallback callback) {
38  		String currentResourceUrl = resourceUrl + ((resourceUrl.indexOf("?") == -1) ? ("?ts=" + System.currentTimeMillis()) : ("&ts=" + + System.currentTimeMillis()));
39  		RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, currentResourceUrl);
40  		requestBuilder.setCallback(new RequestCallback() {
41  			public void onError(Request request, Throwable exception) {
42  				callback.onError(resourceUrl, exception);
43  			}
44  
45  			private void onSuccess(Request request, Response response) {
46  				SVGParserImpl impl = GWT.create(SVGParserImpl.class);
47  				Element root = impl.parse(response.getText(), true);
48  				callback.onSuccess(resourceUrl, root);
49  			}
50  			
51  			public void onResponseReceived(Request request, Response response) {
52  				if (response.getStatusCode() == Response.SC_OK) {
53  					onSuccess(request, response);
54  				} else {
55  					onError(request, null);
56  				}
57  			}
58  		});
59  		try {
60  			requestBuilder.send();
61  		} catch (RequestException e) {
62  			GWT.log("Cannot fetch " + resourceUrl, e);
63  		}
64  	}
65  }