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

Last change on this file since 3408 was 3344, checked in by bastiK, 14 years ago

fixed #4259 - Authentication dialog appears several times while uploading a changeset

  • Property svn:eol-style set to native
File size: 5.5 KB
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.net.HttpURLConnection;
7import java.net.Authenticator.RequestorType;
8import java.nio.ByteBuffer;
9import java.nio.CharBuffer;
10import java.nio.charset.CharacterCodingException;
11import java.nio.charset.Charset;
12import java.nio.charset.CharsetEncoder;
13import java.util.logging.Logger;
14
15import oauth.signpost.OAuthConsumer;
16import oauth.signpost.exception.OAuthException;
17
18import org.openstreetmap.josm.Main;
19import org.openstreetmap.josm.data.oauth.OAuthParameters;
20import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
21import org.openstreetmap.josm.io.auth.CredentialsManagerException;
22import org.openstreetmap.josm.io.auth.CredentialsManagerFactory;
23import org.openstreetmap.josm.io.auth.CredentialsManagerResponse;
24import org.openstreetmap.josm.tools.Base64;
25
26/**
27 * Base class that handles common things like authentication for the reader and writer
28 * to the osm server.
29 *
30 * @author imi
31 */
32public class OsmConnection {
33 @SuppressWarnings("unused")
34 private static final Logger logger = Logger.getLogger(OsmConnection.class.getName());
35
36 protected boolean cancel = false;
37 protected HttpURLConnection activeConnection;
38 protected OAuthParameters oauthParameters;
39
40 /**
41 * Initialize the http defaults and the authenticator.
42 */
43 static {
44 try {
45 HttpURLConnection.setFollowRedirects(true);
46 } catch (SecurityException e) {
47 e.printStackTrace();
48 }
49 }
50
51 public void cancel() {
52 cancel = true;
53 synchronized (this) {
54 if (activeConnection != null) {
55 activeConnection.setConnectTimeout(100);
56 activeConnection.setReadTimeout(100);
57 }
58 }
59 try {
60 Thread.sleep(100);
61 } catch (InterruptedException ex) {
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 = Charset.forName("UTF-8").newEncoder();
79 CredentialsManagerResponse response;
80 String token;
81 try {
82 synchronized (CredentialsManagerFactory.getCredentialManager()) {
83 response = CredentialsManagerFactory.getCredentialManager().getCredentials(RequestorType.SERVER, false /* don't know yet whether the credentials will succeed */);
84 }
85 } catch (CredentialsManagerException e) {
86 throw new OsmTransferException(e);
87 }
88 if (response == null) {
89 token = ":";
90 } else if (response.isCanceled()) {
91 cancel = true;
92 return;
93 } else {
94 String username= response.getUsername() == null ? "" : response.getUsername();
95 String password = response.getPassword() == null ? "" : String.valueOf(response.getPassword());
96 token = username + ":" + password;
97 try {
98 ByteBuffer bytes = encoder.encode(CharBuffer.wrap(token));
99 con.addRequestProperty("Authorization", "Basic "+Base64.encode(bytes));
100 } catch(CharacterCodingException e) {
101 throw new OsmTransferException(e);
102 }
103 }
104 }
105
106 /**
107 * Signs the connection with an OAuth authentication header
108 *
109 * @param connection the connection
110 *
111 * @throws OsmTransferException thrown if there is currently no OAuth Access Token configured
112 * @throws OsmTransferException thrown if signing fails
113 */
114 protected void addOAuthAuthorizationHeader(HttpURLConnection connection) throws OsmTransferException {
115 if (oauthParameters == null) {
116 oauthParameters = OAuthParameters.createFromPreferences(Main.pref);
117 }
118 OAuthConsumer consumer = oauthParameters.buildConsumer();
119 OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
120 if (! holder.containsAccessToken())
121 throw new MissingOAuthAccessTokenException();
122 consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret());
123 try {
124 consumer.sign(connection);
125 } catch(OAuthException e) {
126 throw new OsmTransferException(tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e);
127 }
128 }
129
130 protected void addAuth(HttpURLConnection connection) throws OsmTransferException {
131 String authMethod = Main.pref.get("osm-server.auth-method", "basic");
132 if (authMethod.equals("basic")) {
133 addBasicAuthorizationHeader(connection);
134 } else if (authMethod.equals("oauth")) {
135 addOAuthAuthorizationHeader(connection);
136 } else {
137 String msg = tr("Warning: unexpected value for preference ''{0}''. Got ''{1}''.", "osm-server.auth-method", authMethod);
138 System.err.println(msg);
139 throw new OsmTransferException(msg);
140 }
141 }
142
143 /**
144 * Replies true if this connection is canceled
145 *
146 * @return true if this connection is canceled
147 * @return
148 */
149 public boolean isCanceled() {
150 return cancel;
151 }
152}
Note: See TracBrowser for help on using the repository browser.