source: josm/trunk/src/org/openstreetmap/josm/io/OsmConnection.java@ 8230

Last change on this file since 8230 was 7082, checked in by Don-vip, 10 years ago

see #8465 - replace Utils.UTF_8 by StandardCharsets.UTF_8, new in Java 7

  • Property svn:eol-style set to native
File size: 5.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.net.Authenticator.RequestorType;
7import java.net.HttpURLConnection;
8import java.nio.ByteBuffer;
9import java.nio.CharBuffer;
10import java.nio.charset.CharacterCodingException;
11import java.nio.charset.CharsetEncoder;
12import java.nio.charset.StandardCharsets;
13
14import oauth.signpost.OAuthConsumer;
15import oauth.signpost.exception.OAuthException;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.oauth.OAuthParameters;
19import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
20import org.openstreetmap.josm.io.auth.CredentialsAgentException;
21import org.openstreetmap.josm.io.auth.CredentialsAgentResponse;
22import org.openstreetmap.josm.io.auth.CredentialsManager;
23import org.openstreetmap.josm.tools.Base64;
24
25/**
26 * Base class that handles common things like authentication for the reader and writer
27 * to the osm server.
28 *
29 * @author imi
30 */
31public class OsmConnection {
32 protected boolean cancel = false;
33 protected HttpURLConnection activeConnection;
34 protected OAuthParameters oauthParameters;
35
36 /**
37 * Initialize the http defaults and the authenticator.
38 */
39 static {
40 try {
41 HttpURLConnection.setFollowRedirects(true);
42 } catch (SecurityException e) {
43 Main.error(e);
44 }
45 }
46
47 /**
48 * Cancels the connection.
49 */
50 public void cancel() {
51 cancel = true;
52 synchronized (this) {
53 if (activeConnection != null) {
54 activeConnection.setConnectTimeout(100);
55 activeConnection.setReadTimeout(100);
56 }
57 }
58 try {
59 Thread.sleep(100);
60 } catch (InterruptedException ex) {
61 Main.warn("InterruptedException in "+getClass().getSimpleName()+" during cancel");
62 }
63
64 synchronized (this) {
65 if (activeConnection != null) {
66 activeConnection.disconnect();
67 }
68 }
69 }
70
71 /**
72 * Adds an authentication header for basic authentication
73 *
74 * @param con the connection
75 * @throws OsmTransferException thrown if something went wrong. Check for nested exceptions
76 */
77 protected void addBasicAuthorizationHeader(HttpURLConnection con) throws OsmTransferException {
78 CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
79 CredentialsAgentResponse response;
80 String token;
81 try {
82 synchronized (CredentialsManager.getInstance()) {
83 response = CredentialsManager.getInstance().getCredentials(RequestorType.SERVER,
84 con.getURL().getHost(), false /* don't know yet whether the credentials will succeed */);
85 }
86 } catch (CredentialsAgentException e) {
87 throw new OsmTransferException(e);
88 }
89 if (response == null) {
90 token = ":";
91 } else if (response.isCanceled()) {
92 cancel = true;
93 return;
94 } else {
95 String username= response.getUsername() == null ? "" : response.getUsername();
96 String password = response.getPassword() == null ? "" : String.valueOf(response.getPassword());
97 token = username + ":" + password;
98 try {
99 ByteBuffer bytes = encoder.encode(CharBuffer.wrap(token));
100 con.addRequestProperty("Authorization", "Basic "+Base64.encode(bytes));
101 } catch(CharacterCodingException e) {
102 throw new OsmTransferException(e);
103 }
104 }
105 }
106
107 /**
108 * Signs the connection with an OAuth authentication header
109 *
110 * @param connection the connection
111 *
112 * @throws OsmTransferException thrown if there is currently no OAuth Access Token configured
113 * @throws OsmTransferException thrown if signing fails
114 */
115 protected void addOAuthAuthorizationHeader(HttpURLConnection connection) throws OsmTransferException {
116 if (oauthParameters == null) {
117 oauthParameters = OAuthParameters.createFromPreferences(Main.pref);
118 }
119 OAuthConsumer consumer = oauthParameters.buildConsumer();
120 OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
121 if (! holder.containsAccessToken())
122 throw new MissingOAuthAccessTokenException();
123 consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret());
124 try {
125 consumer.sign(connection);
126 } catch(OAuthException e) {
127 throw new OsmTransferException(tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e);
128 }
129 }
130
131 protected void addAuth(HttpURLConnection connection) throws OsmTransferException {
132 String authMethod = Main.pref.get("osm-server.auth-method", "basic");
133 if ("basic".equals(authMethod)) {
134 addBasicAuthorizationHeader(connection);
135 } else if ("oauth".equals(authMethod)) {
136 addOAuthAuthorizationHeader(connection);
137 } else {
138 String msg = tr("Unexpected value for preference ''{0}''. Got ''{1}''.", "osm-server.auth-method", authMethod);
139 Main.warn(msg);
140 throw new OsmTransferException(msg);
141 }
142 }
143
144 /**
145 * Replies true if this connection is canceled
146 *
147 * @return true if this connection is canceled
148 */
149 public boolean isCanceled() {
150 return cancel;
151 }
152}
Note: See TracBrowser for help on using the repository browser.