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

Last change on this file since 8673 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • Property svn:eol-style set to native
File size: 11.1 KB
RevLine 
[2801]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.URL;
10
11import javax.swing.JOptionPane;
12import javax.xml.parsers.DocumentBuilderFactory;
13import javax.xml.parsers.ParserConfigurationException;
14
15import oauth.signpost.OAuthConsumer;
16import oauth.signpost.exception.OAuthException;
17
[6643]18import org.openstreetmap.josm.Main;
[2801]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.OsmServerUserInfoReader;
27import org.openstreetmap.josm.io.OsmTransferException;
28import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
29import org.openstreetmap.josm.tools.CheckParameterUtil;
[5587]30import org.openstreetmap.josm.tools.Utils;
[6906]31import org.openstreetmap.josm.tools.XmlParsingException;
[2801]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.
[3530]37 *
[2801]38 * It retrieves the user details for the user which is authorized to access the server with
39 * this token.
[3530]40 *
[2801]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
[3530]52 *
[5266]53 * @param parent the parent component relative to which the {@link PleaseWaitRunnable}-Dialog is displayed
[2801]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;
[8510]72 synchronized (this) {
[2801]73 if (connection != null) {
74 connection.disconnect();
75 }
76 }
77 }
78
79 @Override
80 protected void finish() {}
81
[8510]82 protected void sign(HttpURLConnection con) throws OAuthException {
[2801]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
[8510]93 while (url.endsWith("/")) {
[6083]94 url = url.substring(0, url.lastIndexOf('/'));
[2801]95 }
96 return url;
97 }
98
[6906]99 protected UserInfo getUserDetails() throws OsmOAuthAuthorizationException, XmlParsingException, OsmTransferException {
[2801]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);
[8510]105 synchronized (this) {
[5587]106 connection = Utils.openHttpConnection(url);
[2801]107 }
108
109 connection.setDoOutput(true);
110 connection.setRequestMethod("GET");
111 sign(connection);
112 connection.connect();
113
114 if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
[8509]115 throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED,
116 tr("Retrieving user details with Access Token Key ''{0}'' was rejected.", token.getKey()), null);
[2801]117
118 if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)
[8509]119 throw new OsmApiException(HttpURLConnection.HTTP_FORBIDDEN,
120 tr("Retrieving user details with Access Token Key ''{0}'' was forbidden.", token.getKey()), null);
[2801]121
122 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
[8510]123 throw new OsmApiException(connection.getResponseCode(), connection.getHeaderField("Error"), null);
[2801]124 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connection.getInputStream());
125 return OsmServerUserInfoReader.buildFromXML(d);
[8510]126 } catch (SAXException | ParserConfigurationException e) {
[6906]127 throw new XmlParsingException(e);
[8510]128 } catch (IOException e) {
[2801]129 throw new OsmTransferException(e);
[8510]130 } catch (OAuthException e) {
[2861]131 throw new OsmOAuthAuthorizationException(e);
[2801]132 } finally {
133 DefaultAuthenticator.getInstance().setEnabled(authenticatorEnabled);
134 }
135 }
136
137 protected void notifySuccess(UserInfo userInfo) {
[6116]138 HelpAwareOptionPane.showMessageDialogInEDT(
[2801]139 parent,
140 tr("<html>"
141 + "Successfully used the Access Token ''{0}'' to<br>"
142 + "access the OSM server at ''{1}''.<br>"
[2850]143 + "You are accessing the OSM server as user ''{2}'' with id ''{3}''."
144 + "</html>",
[2801]145 token.getKey(),
146 apiUrl,
147 userInfo.getDisplayName(),
148 userInfo.getId()
149 ),
150 tr("Success"),
151 JOptionPane.INFORMATION_MESSAGE,
152 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenOK")
153 );
154 }
155
156 protected void alertFailedAuthentication() {
[6116]157 HelpAwareOptionPane.showMessageDialogInEDT(
[2801]158 parent,
159 tr("<html>"
160 + "Failed to access the OSM server ''{0}''<br>"
[5411]161 + "with the Access Token ''{1}''.<br>"
[2877]162 + "The server rejected the Access Token as unauthorized. You will not<br>"
[2801]163 + "be able to access any protected resource on this server using this token."
164 +"</html>",
165 apiUrl,
166 token.getKey()
167 ),
168 tr("Test failed"),
169 JOptionPane.ERROR_MESSAGE,
170 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
171 );
172 }
173
174 protected void alertFailedAuthorisation() {
[6116]175 HelpAwareOptionPane.showMessageDialogInEDT(
[2801]176 parent,
177 tr("<html>"
[2840]178 + "The Access Token ''{1}'' is known to the OSM server ''{0}''.<br>"
[2801]179 + "The test to retrieve the user details for this token failed, though.<br>"
180 + "Depending on what rights are granted to this token you may nevertheless use it<br>"
181 + "to upload data, upload GPS traces, and/or access other protected resources."
182 +"</html>",
183 apiUrl,
184 token.getKey()
185 ),
186 tr("Token allows restricted access"),
187 JOptionPane.WARNING_MESSAGE,
188 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
189 );
190 }
191
192 protected void alertFailedConnection() {
[6116]193 HelpAwareOptionPane.showMessageDialogInEDT(
[2801]194 parent,
195 tr("<html>"
196 + "Failed to retrieve information about the current user"
[2840]197 + " from the OSM server ''{0}''.<br>"
[2801]198 + "This is probably not a problem caused by the tested Access Token, but<br>"
199 + "rather a problem with the server configuration. Carefully check the server<br>"
200 + "URL and your Internet connection."
201 +"</html>",
202 apiUrl,
203 token.getKey()
204 ),
205 tr("Test failed"),
206 JOptionPane.ERROR_MESSAGE,
207 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
208 );
209 }
210
211 protected void alertFailedSigning() {
[6116]212 HelpAwareOptionPane.showMessageDialogInEDT(
[2801]213 parent,
214 tr("<html>"
215 + "Failed to sign the request for the OSM server ''{0}'' with the "
216 + "token ''{1}''.<br>"
217 + "The token ist probably invalid."
218 +"</html>",
219 apiUrl,
220 token.getKey()
221 ),
222 tr("Test failed"),
223 JOptionPane.ERROR_MESSAGE,
224 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
225 );
226 }
227
228 protected void alertInternalError() {
[6116]229 HelpAwareOptionPane.showMessageDialogInEDT(
[2801]230 parent,
231 tr("<html>"
232 + "The test failed because the server responded with an internal error.<br>"
[2850]233 + "JOSM could not decide whether the token is valid. Please try again later."
234 + "</html>",
[2801]235 apiUrl,
236 token.getKey()
237 ),
238 tr("Test failed"),
239 JOptionPane.WARNING_MESSAGE,
240 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
241 );
242 }
243
244 @Override
245 protected void realRun() throws SAXException, IOException, OsmTransferException {
246 try {
247 getProgressMonitor().indeterminateSubTask(tr("Retrieving user info..."));
248 UserInfo userInfo = getUserDetails();
249 if (canceled) return;
250 notifySuccess(userInfo);
[8510]251 } catch (OsmOAuthAuthorizationException e) {
[2801]252 if (canceled) return;
[6643]253 Main.error(e);
[2801]254 alertFailedSigning();
[8510]255 } catch (OsmApiException e) {
[2801]256 if (canceled) return;
[6643]257 Main.error(e);
[2801]258 if (e.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
259 alertInternalError();
260 return;
[6362]261 } else if (e.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
[2801]262 alertFailedAuthentication();
263 return;
264 } else if (e.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
265 alertFailedAuthorisation();
266 return;
267 }
268 alertFailedConnection();
[8510]269 } catch (OsmTransferException e) {
[2801]270 if (canceled) return;
[6643]271 Main.error(e);
[2801]272 alertFailedConnection();
273 }
274 }
275}
Note: See TracBrowser for help on using the repository browser.