source: josm/trunk/src/org/openstreetmap/josm/gui/oauth/TestAccessTokenTask.java@ 6116

Last change on this file since 6116 was 6116, checked in by Don-vip, 11 years ago

fix EDT violations

  • Property svn:eol-style set to native
File size: 11.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.oauth;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.io.IOException;
8import java.net.HttpURLConnection;
9import java.net.MalformedURLException;
10import java.net.URL;
11
12import javax.swing.JOptionPane;
13import javax.xml.parsers.DocumentBuilderFactory;
14import javax.xml.parsers.ParserConfigurationException;
15
16import oauth.signpost.OAuthConsumer;
17import oauth.signpost.exception.OAuthException;
18
19import org.openstreetmap.josm.data.oauth.OAuthParameters;
20import org.openstreetmap.josm.data.oauth.OAuthToken;
21import org.openstreetmap.josm.data.osm.UserInfo;
22import org.openstreetmap.josm.gui.HelpAwareOptionPane;
23import org.openstreetmap.josm.gui.PleaseWaitRunnable;
24import org.openstreetmap.josm.gui.help.HelpUtil;
25import org.openstreetmap.josm.io.OsmApiException;
26import org.openstreetmap.josm.io.OsmDataParsingException;
27import org.openstreetmap.josm.io.OsmServerUserInfoReader;
28import org.openstreetmap.josm.io.OsmTransferException;
29import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
30import org.openstreetmap.josm.tools.CheckParameterUtil;
31import org.openstreetmap.josm.tools.Utils;
32import org.w3c.dom.Document;
33import org.xml.sax.SAXException;
34
35/**
36 * Checks whether an OSM API server can be accessed with a specific Access Token.
37 *
38 * It retrieves the user details for the user which is authorized to access the server with
39 * this token.
40 *
41 */
42public class TestAccessTokenTask extends PleaseWaitRunnable {
43 private OAuthToken token;
44 private OAuthParameters oauthParameters;
45 private boolean canceled;
46 private Component parent;
47 private String apiUrl;
48 private HttpURLConnection connection;
49
50 /**
51 * Create the task
52 *
53 * @param parent the parent component relative to which the {@link PleaseWaitRunnable}-Dialog is displayed
54 * @param apiUrl the API URL. Must not be null.
55 * @param parameters the OAuth parameters. Must not be null.
56 * @param accessToken the Access Token. Must not be null.
57 */
58 public TestAccessTokenTask(Component parent, String apiUrl, OAuthParameters parameters, OAuthToken accessToken) {
59 super(parent, tr("Testing OAuth Access Token"), false /* don't ignore exceptions */);
60 CheckParameterUtil.ensureParameterNotNull(apiUrl, "apiUrl");
61 CheckParameterUtil.ensureParameterNotNull(parameters, "parameters");
62 CheckParameterUtil.ensureParameterNotNull(accessToken, "accessToken");
63 this.token = accessToken;
64 this.oauthParameters = parameters;
65 this.parent = parent;
66 this.apiUrl = apiUrl;
67 }
68
69 @Override
70 protected void cancel() {
71 canceled = true;
72 synchronized(this) {
73 if (connection != null) {
74 connection.disconnect();
75 }
76 }
77 }
78
79 @Override
80 protected void finish() {}
81
82 protected void sign(HttpURLConnection con) throws OAuthException{
83 OAuthConsumer consumer = oauthParameters.buildConsumer();
84 consumer.setTokenWithSecret(token.getKey(), token.getSecret());
85 consumer.sign(con);
86 }
87
88 protected String normalizeApiUrl(String url) {
89 // remove leading and trailing white space
90 url = url.trim();
91
92 // remove trailing slashes
93 while(url.endsWith("/")) {
94 url = url.substring(0, url.lastIndexOf('/'));
95 }
96 return url;
97 }
98
99 protected UserInfo getUserDetails() throws OsmOAuthAuthorizationException, OsmDataParsingException,OsmTransferException {
100 boolean authenticatorEnabled = true;
101 try {
102 URL url = new URL(normalizeApiUrl(apiUrl) + "/0.6/user/details");
103 authenticatorEnabled = DefaultAuthenticator.getInstance().isEnabled();
104 DefaultAuthenticator.getInstance().setEnabled(false);
105 synchronized(this) {
106 connection = Utils.openHttpConnection(url);
107 }
108
109 connection.setDoOutput(true);
110 connection.setRequestMethod("GET");
111 sign(connection);
112 connection.connect();
113
114 if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
115 throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, tr("Retrieving user details with Access Token Key ''{0}'' was rejected.", token.getKey()), null);
116
117 if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)
118 throw new OsmApiException(HttpURLConnection.HTTP_FORBIDDEN, tr("Retrieving user details with Access Token Key ''{0}'' was forbidden.", token.getKey()), null);
119
120 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
121 throw new OsmApiException(connection.getResponseCode(),connection.getHeaderField("Error"), null);
122 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connection.getInputStream());
123 return OsmServerUserInfoReader.buildFromXML(d);
124 } catch(SAXException e) {
125 throw new OsmDataParsingException(e);
126 } catch(ParserConfigurationException e){
127 throw new OsmDataParsingException(e);
128 } catch(MalformedURLException e) {
129 throw new OsmTransferException(e);
130 } catch(IOException e){
131 throw new OsmTransferException(e);
132 } catch(OAuthException e) {
133 throw new OsmOAuthAuthorizationException(e);
134 } finally {
135 DefaultAuthenticator.getInstance().setEnabled(authenticatorEnabled);
136 }
137 }
138
139 protected void notifySuccess(UserInfo userInfo) {
140 HelpAwareOptionPane.showMessageDialogInEDT(
141 parent,
142 tr("<html>"
143 + "Successfully used the Access Token ''{0}'' to<br>"
144 + "access the OSM server at ''{1}''.<br>"
145 + "You are accessing the OSM server as user ''{2}'' with id ''{3}''."
146 + "</html>",
147 token.getKey(),
148 apiUrl,
149 userInfo.getDisplayName(),
150 userInfo.getId()
151 ),
152 tr("Success"),
153 JOptionPane.INFORMATION_MESSAGE,
154 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenOK")
155 );
156 }
157
158 protected void alertFailedAuthentication() {
159 HelpAwareOptionPane.showMessageDialogInEDT(
160 parent,
161 tr("<html>"
162 + "Failed to access the OSM server ''{0}''<br>"
163 + "with the Access Token ''{1}''.<br>"
164 + "The server rejected the Access Token as unauthorized. You will not<br>"
165 + "be able to access any protected resource on this server using this token."
166 +"</html>",
167 apiUrl,
168 token.getKey()
169 ),
170 tr("Test failed"),
171 JOptionPane.ERROR_MESSAGE,
172 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
173 );
174 }
175
176 protected void alertFailedAuthorisation() {
177 HelpAwareOptionPane.showMessageDialogInEDT(
178 parent,
179 tr("<html>"
180 + "The Access Token ''{1}'' is known to the OSM server ''{0}''.<br>"
181 + "The test to retrieve the user details for this token failed, though.<br>"
182 + "Depending on what rights are granted to this token you may nevertheless use it<br>"
183 + "to upload data, upload GPS traces, and/or access other protected resources."
184 +"</html>",
185 apiUrl,
186 token.getKey()
187 ),
188 tr("Token allows restricted access"),
189 JOptionPane.WARNING_MESSAGE,
190 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
191 );
192 }
193
194 protected void alertFailedConnection() {
195 HelpAwareOptionPane.showMessageDialogInEDT(
196 parent,
197 tr("<html>"
198 + "Failed to retrieve information about the current user"
199 + " from the OSM server ''{0}''.<br>"
200 + "This is probably not a problem caused by the tested Access Token, but<br>"
201 + "rather a problem with the server configuration. Carefully check the server<br>"
202 + "URL and your Internet connection."
203 +"</html>",
204 apiUrl,
205 token.getKey()
206 ),
207 tr("Test failed"),
208 JOptionPane.ERROR_MESSAGE,
209 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
210 );
211 }
212
213 protected void alertFailedSigning() {
214 HelpAwareOptionPane.showMessageDialogInEDT(
215 parent,
216 tr("<html>"
217 + "Failed to sign the request for the OSM server ''{0}'' with the "
218 + "token ''{1}''.<br>"
219 + "The token ist probably invalid."
220 +"</html>",
221 apiUrl,
222 token.getKey()
223 ),
224 tr("Test failed"),
225 JOptionPane.ERROR_MESSAGE,
226 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
227 );
228 }
229
230 protected void alertInternalError() {
231 HelpAwareOptionPane.showMessageDialogInEDT(
232 parent,
233 tr("<html>"
234 + "The test failed because the server responded with an internal error.<br>"
235 + "JOSM could not decide whether the token is valid. Please try again later."
236 + "</html>",
237 apiUrl,
238 token.getKey()
239 ),
240 tr("Test failed"),
241 JOptionPane.WARNING_MESSAGE,
242 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
243 );
244 }
245
246 @Override
247 protected void realRun() throws SAXException, IOException, OsmTransferException {
248 try {
249 getProgressMonitor().indeterminateSubTask(tr("Retrieving user info..."));
250 UserInfo userInfo = getUserDetails();
251 if (canceled) return;
252 notifySuccess(userInfo);
253 }catch(OsmOAuthAuthorizationException e) {
254 if (canceled) return;
255 e.printStackTrace();
256 alertFailedSigning();
257 } catch(OsmApiException e) {
258 if (canceled) return;
259 e.printStackTrace();
260 if (e.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
261 alertInternalError();
262 return;
263 } if (e.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
264 alertFailedAuthentication();
265 return;
266 } else if (e.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
267 alertFailedAuthorisation();
268 return;
269 }
270 alertFailedConnection();
271 } catch(OsmTransferException e) {
272 if (canceled) return;
273 e.printStackTrace();
274 alertFailedConnection();
275 }
276 }
277}
Note: See TracBrowser for help on using the repository browser.