source: josm/trunk/src/org/openstreetmap/josm/data/ServerSidePreferences.java@ 2667

Last change on this file since 2667 was 2641, checked in by Gubaer, 14 years ago

new: supports system defined proxies if JOSM is started with -Djava.net.useSystemProxies=true
fixed #1641: JOSM doesn't allow for setting HTTP proxy user/password distrinct from OSM server user/password
fixed #2865: SOCKS Proxy Support
fixed #4182: Proxy Authentication

  • Property svn:eol-style set to native
File size: 8.5 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.data;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStreamReader;
9import java.io.OutputStreamWriter;
10import java.io.PrintWriter;
11import java.io.Reader;
12import java.io.StringReader;
13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
15import java.net.URL;
16import java.net.URLConnection;
17import java.util.Collection;
18import java.util.Collections;
19import java.util.LinkedList;
20import java.util.StringTokenizer;
21import java.util.Map.Entry;
22import java.util.logging.Logger;
23
24import javax.swing.JOptionPane;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.io.OsmConnection;
28import org.openstreetmap.josm.io.OsmTransferException;
29import org.openstreetmap.josm.io.XmlWriter;
30import org.openstreetmap.josm.tools.Base64;
31import org.openstreetmap.josm.tools.XmlObjectParser;
32
33/**
34 * This class tweak the Preferences class to provide server side preference settings, as example
35 * used in the applet version.
36 *
37 * @author Imi
38 */
39public class ServerSidePreferences extends Preferences {
40 static private final Logger logger = Logger.getLogger(ServerSidePreferences.class.getName());
41
42 private final Connection connection;
43
44 private class Connection extends OsmConnection {
45 URL serverUrl;
46 public Connection(URL serverUrl) {
47 this.serverUrl = serverUrl;
48 }
49 public String download() {
50 try {
51 System.out.println("reading preferences from "+serverUrl);
52 URLConnection con = serverUrl.openConnection();
53 if (con instanceof HttpURLConnection) {
54 addAuth((HttpURLConnection) con);
55 }
56 con.connect();
57 BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
58 StringBuilder b = new StringBuilder();
59 for (String line = reader.readLine(); line != null; line = reader.readLine()) {
60 b.append(line);
61 b.append("\n");
62 }
63 if (con instanceof HttpURLConnection) {
64 ((HttpURLConnection) con).disconnect();
65 }
66 return b.toString();
67 } catch (IOException e) {
68 e.printStackTrace();
69 } catch(OsmTransferException e) {
70 e.printStackTrace();
71 }
72 return null;
73 }
74 public void upload(String s) {
75 try {
76 URL u = new URL(getPreferencesDir());
77 System.out.println("uploading preferences to "+u);
78 HttpURLConnection con = (HttpURLConnection)u.openConnection();
79 con.addRequestProperty("Authorization", "Basic "+Base64.encode(get("osm-server.username")+":"+get("osm-server.password")));
80 con.setRequestMethod("POST");
81 con.setDoOutput(true);
82 con.connect();
83 PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
84 out.println(s);
85 out.close();
86 con.getInputStream().close();
87 con.disconnect();
88 JOptionPane.showMessageDialog(
89 Main.parent,
90 tr("Preferences stored on {0}", u.getHost()),
91 tr("Information"),
92 JOptionPane.INFORMATION_MESSAGE
93 );
94 } catch (Exception e) {
95 e.printStackTrace();
96 JOptionPane.showMessageDialog(
97 Main.parent,
98 tr("Could not upload preferences. Reason: {0}", e.getMessage()),
99 tr("Error"),
100 JOptionPane.ERROR_MESSAGE
101 );
102 }
103 }
104 }
105
106 public ServerSidePreferences(URL serverUrl) {
107 Connection connection = null;
108 try {
109 connection = new Connection(new URL(serverUrl+"user/preferences"));
110 } catch (MalformedURLException e) {
111 e.printStackTrace();
112 JOptionPane.showMessageDialog(
113 Main.parent,
114 tr("Could not load preferences from server."),
115 tr("Error"),
116 JOptionPane.ERROR_MESSAGE
117 );
118 }
119 this.connection = connection;
120 }
121
122 @Override public String getPreferencesDir() {
123 return connection.serverUrl.toString();
124 }
125
126 /**
127 * Do nothing on load. Preferences are loaded with download().
128 */
129 @Override public void load() {
130 }
131
132 /**
133 * Do nothing on save. Preferences are uploaded using upload().
134 */
135 @Override public void save() {
136 }
137
138 public static class Prop {
139 public String key;
140 public String value;
141 }
142
143 public void download(String userName, String password) {
144 resetToDefault();
145 if (!properties.containsKey("osm-server.username") && userName != null) {
146 properties.put("osm-server.username", userName);
147 }
148 if (!properties.containsKey("osm-server.password") && password != null) {
149 properties.put("osm-server.password", password);
150 }
151 String cont = connection.download();
152 if (cont == null) return;
153 Reader in = new StringReader(cont);
154 try {
155 XmlObjectParser.Uniform<Prop> parser = new XmlObjectParser.Uniform<Prop>(in, "tag", Prop.class);
156 for (Prop p : parser) {
157 properties.put(p.key, p.value);
158 }
159 } catch (RuntimeException e) {
160 e.printStackTrace();
161 }
162 }
163
164 /**
165 * Use this instead of save() for the ServerSidePreferences, since uploads
166 * are costly while save is called often.
167 *
168 * This is triggered by an explicit menu option.
169 */
170 public void upload() {
171 StringBuilder b = new StringBuilder("<preferences>\n");
172 for (Entry<String, String> p : properties.entrySet()) {
173 if (p.getKey().equals("osm-server.password")) {
174 continue; // do not upload password. It would get stored in plain!
175 }
176 b.append("<tag key='");
177 b.append(XmlWriter.encode(p.getKey()));
178 b.append("' value='");
179 b.append(XmlWriter.encode(p.getValue()));
180 b.append("' />\n");
181 }
182 b.append("</preferences>");
183 connection.upload(b.toString());
184 }
185
186 @Override public Collection<Bookmark> loadBookmarks() {
187 URL url = null;
188 try {
189 Collection<Bookmark> bookmarks;
190 bookmarks = new LinkedList<Bookmark>();
191 url = new URL("http://"+connection.serverUrl.getHost()+"/josm/bookmarks");
192 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
193
194 for (String line = in.readLine(); line != null; line = in.readLine()) {
195 StringTokenizer st = new StringTokenizer(line, ",");
196 if (st.countTokens() != 5) {
197 System.err.println(tr("Error: Unexpected line ''{0}'' in bookmark list from server",line));
198 continue;
199 }
200 Bookmark b = new Bookmark();
201 b.setName(st.nextToken());
202 double[] values= new double[4];
203 for (int i = 0; i < 4; ++i) {
204 String token = st.nextToken();
205 try {
206 values[i] = Double.parseDouble(token);
207 } catch(NumberFormatException e) {
208 System.err.println(tr("Error: Illegal double value ''{0}'' on line ''{1}'' in bookmark list from server",token,line));
209 continue;
210 }
211 }
212 b.setArea(new Bounds(values));
213 bookmarks.add(b);
214 }
215 in.close();
216 return bookmarks;
217 } catch (MalformedURLException e) {
218 e.printStackTrace();
219 } catch (IllegalArgumentException e) {
220 e.printStackTrace();
221 } catch (IOException e) {
222 e.printStackTrace();
223 } catch(SecurityException e) {
224 e.printStackTrace();
225 logger.warning(tr("Failed to load bookmarks from ''{0}'' for security reasons. Exception was: {1}", url == null ? "null" : url.toExternalForm(), e.toString()));
226 }
227 return Collections.emptyList();
228 }
229
230 @Override public void saveBookmarks(Collection<Bookmark> bookmarks) {
231 }
232}
Note: See TracBrowser for help on using the repository browser.