source: josm/trunk/src/org/openstreetmap/josm/io/OsmServerReader.java @ 5241

Revision 5097, 6.7 KB checked in by simon04, 2 months ago (diff)

see #7511 - make DownloadDialog, Osm download related classes more adaptable

  • Property svn:eol-style set to native
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStream;
9import java.io.InputStreamReader;
10import java.net.HttpURLConnection;
11import java.net.MalformedURLException;
12import java.net.URL;
13import java.util.zip.GZIPInputStream;
14import java.util.zip.Inflater;
15import java.util.zip.InflaterInputStream;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.gpx.GpxData;
19import org.openstreetmap.josm.data.osm.DataSet;
20import org.openstreetmap.josm.gui.progress.ProgressMonitor;
21
22/**
23 * This DataReader reads directly from the REST API of the osm server.
24 *
25 * It supports plain text transfer as well as gzip or deflate encoded transfers;
26 * if compressed transfers are unwanted, set property osm-server.use-compression
27 * to false.
28 *
29 * @author imi
30 */
31public abstract class OsmServerReader extends OsmConnection {
32    private OsmApi api = OsmApi.getOsmApi();
33    private boolean doAuthenticate = false;
34
35    /**
36     * Open a connection to the given url and return a reader on the input stream
37     * from that connection. In case of user cancel, return <code>null</code>.
38     * @param urlStr The exact url to connect to.
39     * @param pleaseWaitDlg
40     * @return An reader reading the input stream (servers answer) or <code>null</code>.
41     */
42    protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor) throws OsmTransferException  {
43        try {
44            api.initialize(progressMonitor);
45            urlStr = urlStr.startsWith("http") ? urlStr : (getBaseUrl() + urlStr);
46            return getInputStreamRaw(urlStr, progressMonitor);
47        } finally {
48            progressMonitor.invalidate();
49        }
50    }
51
52    protected String getBaseUrl() {
53        return api.getBaseUrl();
54    }
55
56    protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor) throws OsmTransferException {
57        try {
58            URL url = null;
59            try {
60                url = new URL(urlStr.replace(" ", "%20"));
61            } catch(MalformedURLException e) {
62                throw new OsmTransferException(e);
63            }
64            try {
65                activeConnection = (HttpURLConnection)url.openConnection();
66            } catch(Exception e) {
67                throw new OsmTransferException(tr("Failed to open connection to API {0}.", url.toExternalForm()), e);
68            }
69            if (cancel) {
70                activeConnection.disconnect();
71                return null;
72            }
73
74            if (doAuthenticate) {
75                addAuth(activeConnection);
76            }
77            if (cancel)
78                throw new OsmTransferCanceledException();
79            if (Main.pref.getBoolean("osm-server.use-compression", true)) {
80                activeConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
81            }
82
83            activeConnection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
84
85            try {
86                System.out.println("GET " + url);
87                activeConnection.connect();
88            } catch (Exception e) {
89                e.printStackTrace();
90                throw new OsmTransferException(tr("Could not connect to the OSM server. Please check your internet connection."), e);
91            }
92            try {
93                if (activeConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
94                    throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED,null,null);
95
96                if (activeConnection.getResponseCode() == HttpURLConnection.HTTP_PROXY_AUTH)
97                    throw new OsmTransferCanceledException();
98
99                String encoding = activeConnection.getContentEncoding();
100                if (activeConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
101                    String errorHeader = activeConnection.getHeaderField("Error");
102                    StringBuilder errorBody = new StringBuilder();
103                    try
104                    {
105                        InputStream i = FixEncoding(activeConnection.getErrorStream(), encoding);
106                        if (i != null) {
107                            BufferedReader in = new BufferedReader(new InputStreamReader(i));
108                            String s;
109                            while((s = in.readLine()) != null) {
110                                errorBody.append(s);
111                                errorBody.append("\n");
112                            }
113                        }
114                    }
115                    catch(Exception e) {
116                        errorBody.append(tr("Reading error text failed."));
117                    }
118
119                    throw new OsmApiException(activeConnection.getResponseCode(), errorHeader, errorBody.toString());
120                }
121
122                return FixEncoding(new ProgressInputStream(activeConnection, progressMonitor), encoding);
123            } catch(Exception e) {
124                if (e instanceof OsmTransferException)
125                    throw (OsmTransferException)e;
126                else
127                    throw new OsmTransferException(e);
128
129            }
130        } finally {
131            progressMonitor.invalidate();
132        }
133    }
134
135    private InputStream FixEncoding(InputStream stream, String encoding) throws IOException
136    {
137        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
138            stream = new GZIPInputStream(stream);
139        }
140        else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
141            stream = new InflaterInputStream(stream, new Inflater(true));
142        }
143        return stream;
144    }
145
146    public abstract DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException;
147
148    public DataSet parseOsmChange(ProgressMonitor progressMonitor) throws OsmTransferException {
149        return null;
150    }
151   
152    public GpxData parseRawGps(ProgressMonitor progressMonitor) throws OsmTransferException {
153        return null;
154    }
155   
156    /**
157     * Returns true if this reader is adding authentication credentials to the read
158     * request sent to the server.
159     *
160     * @return true if this reader is adding authentication credentials to the read
161     * request sent to the server
162     */
163    public boolean isDoAuthenticate() {
164        return doAuthenticate;
165    }
166
167    /**
168     * Sets whether this reader adds authentication credentials to the read
169     * request sent to the server.
170     *
171     * @param doAuthenticate  true if  this reader adds authentication credentials to the read
172     * request sent to the server
173     */
174    public void setDoAuthenticate(boolean doAuthenticate) {
175        this.doAuthenticate = doAuthenticate;
176    }
177}
Note: See TracBrowser for help on using the repository browser.