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

Last change on this file since 2876 was 2862, checked in by Gubaer, 14 years ago

fixed #4322: No error message if trying to upload without OAuth token

  • 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 private static final Logger logger = Logger.getLogger(OsmConnection.class.getName());
34
35 protected boolean cancel = false;
36 protected HttpURLConnection activeConnection;
37 protected OAuthParameters oauthParameters;
38
39 /**
40 * Initialize the http defaults and the authenticator.
41 */
42 static {
43 try {
44 HttpURLConnection.setFollowRedirects(true);
45 } catch (SecurityException e) {
46 e.printStackTrace();
47 }
48 }
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 }
62
63 synchronized (this) {
64 if (activeConnection != null) {
65 activeConnection.disconnect();
66 }
67 }
68 }
69
70 /**
71 * Adds an authentication header for basic authentication
72 *
73 * @param con the connection
74 * @throws OsmTransferException thrown is something went wrong. Check for nested exceptions
75 */
76 protected void addBasicAuthorizationHeader(HttpURLConnection con) throws OsmTransferException {
77 CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
78 CredentialsManagerResponse response;
79 String token;
80 try {
81 synchronized (CredentialsManagerFactory.getCredentialManager()) {
82 response = CredentialsManagerFactory.getCredentialManager().getCredentials(RequestorType.SERVER, false /* don't know yet whether the credentials will succeed */);
83 }
84 } catch (CredentialsManagerException e) {
85 throw new OsmTransferException(e);
86 }
87 if (response == null) {
88 token = ":";
89 } else if (response.isCanceled()) {
90 cancel = true;
91 return;
92 } else {
93 String username= response.getUsername() == null ? "" : response.getUsername();
94 String password = response.getPassword() == null ? "" : String.valueOf(response.getPassword());
95 token = username + ":" + password;
96 try {
97 ByteBuffer bytes = encoder.encode(CharBuffer.wrap(token));
98 con.addRequestProperty("Authorization", "Basic "+Base64.encode(bytes));
99 } catch(CharacterCodingException e) {
100 throw new OsmTransferException(e);
101 }
102 }
103 }
104
105 /**
106 * Signs the connection with an OAuth authentication header
107 *
108 * @param connection the connection
109 *
110 * @throws OsmTransferException thrown if there is currently no OAuth Access Token configured
111 * @throws OsmTransferException thrown if signing fails
112 */
113 protected void addOAuthAuthorizationHeader(HttpURLConnection connection) throws OsmTransferException {
114 if (oauthParameters == null) {
115 oauthParameters = OAuthParameters.createFromPreferences(Main.pref);
116 }
117 OAuthConsumer consumer = oauthParameters.buildConsumer();
118 OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
119 if (! holder.containsAccessToken())
120 throw new MissingOAuthAccessTokenException();
121 consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret());
122 try {
123 consumer.sign(connection);
124 } catch(OAuthException e) {
125 throw new OsmTransferException(tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e);
126 }
127 }
128
129 protected void addAuth(HttpURLConnection connection) throws OsmTransferException {
130 String authMethod = Main.pref.get("osm-server.auth-method", "basic");
131 if (authMethod.equals("basic")) {
132 addBasicAuthorizationHeader(connection);
133 } else if (authMethod.equals("oauth")) {
134 addOAuthAuthorizationHeader(connection);
135 } else {
136 String msg = tr("Warning: unexpected value for preference ''{0}''. Got ''{1}''.", "osm-server.auth-method", authMethod);
137 System.err.println(msg);
138 throw new OsmTransferException(msg);
139 }
140 }
141
142 /**
143 * Replies true if this connection is canceled
144 *
145 * @return true if this connection is canceled
146 * @return
147 */
148 public boolean isCanceled() {
149 return cancel;
150 }
151}
Note: See TracBrowser for help on using the repository browser.