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

Last change on this file since 3246 was 2748, checked in by Gubaer, 14 years ago

new: JOSM now supports OAuth

See also online help for server preferences and new OAuth Authorisation Wizard

  • Property svn:eol-style set to native
File size: 8.7 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 // FIXME:
80 // - doesn't work if CredentialManager isn't JosmPreferencesCredentialManager
81 // - doesn't work for OAuth
82
83 con.addRequestProperty("Authorization", "Basic "+Base64.encode(get("osm-server.username")+":"+get("osm-server.password")));
84 con.setRequestMethod("POST");
85 con.setDoOutput(true);
86 con.connect();
87 PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
88 out.println(s);
89 out.close();
90 con.getInputStream().close();
91 con.disconnect();
92 JOptionPane.showMessageDialog(
93 Main.parent,
94 tr("Preferences stored on {0}", u.getHost()),
95 tr("Information"),
96 JOptionPane.INFORMATION_MESSAGE
97 );
98 } catch (Exception e) {
99 e.printStackTrace();
100 JOptionPane.showMessageDialog(
101 Main.parent,
102 tr("Could not upload preferences. Reason: {0}", e.getMessage()),
103 tr("Error"),
104 JOptionPane.ERROR_MESSAGE
105 );
106 }
107 }
108 }
109
110 public ServerSidePreferences(URL serverUrl) {
111 Connection connection = null;
112 try {
113 connection = new Connection(new URL(serverUrl+"user/preferences"));
114 } catch (MalformedURLException e) {
115 e.printStackTrace();
116 JOptionPane.showMessageDialog(
117 Main.parent,
118 tr("Could not load preferences from server."),
119 tr("Error"),
120 JOptionPane.ERROR_MESSAGE
121 );
122 }
123 this.connection = connection;
124 }
125
126 @Override public String getPreferencesDir() {
127 return connection.serverUrl.toString();
128 }
129
130 /**
131 * Do nothing on load. Preferences are loaded with download().
132 */
133 @Override public void load() {
134 }
135
136 /**
137 * Do nothing on save. Preferences are uploaded using upload().
138 */
139 @Override public void save() {
140 }
141
142 public static class Prop {
143 public String key;
144 public String value;
145 }
146
147 public void download(String userName, String password) {
148 resetToDefault();
149 if (!properties.containsKey("osm-server.username") && userName != null) {
150 properties.put("osm-server.username", userName);
151 }
152 if (!properties.containsKey("osm-server.password") && password != null) {
153 properties.put("osm-server.password", password);
154 }
155 String cont = connection.download();
156 if (cont == null) return;
157 Reader in = new StringReader(cont);
158 try {
159 XmlObjectParser.Uniform<Prop> parser = new XmlObjectParser.Uniform<Prop>(in, "tag", Prop.class);
160 for (Prop p : parser) {
161 properties.put(p.key, p.value);
162 }
163 } catch (RuntimeException e) {
164 e.printStackTrace();
165 }
166 }
167
168 /**
169 * Use this instead of save() for the ServerSidePreferences, since uploads
170 * are costly while save is called often.
171 *
172 * This is triggered by an explicit menu option.
173 */
174 public void upload() {
175 StringBuilder b = new StringBuilder("<preferences>\n");
176 for (Entry<String, String> p : properties.entrySet()) {
177 if (p.getKey().equals("osm-server.password")) {
178 continue; // do not upload password. It would get stored in plain!
179 }
180 b.append("<tag key='");
181 b.append(XmlWriter.encode(p.getKey()));
182 b.append("' value='");
183 b.append(XmlWriter.encode(p.getValue()));
184 b.append("' />\n");
185 }
186 b.append("</preferences>");
187 connection.upload(b.toString());
188 }
189
190 @Override public Collection<Bookmark> loadBookmarks() {
191 URL url = null;
192 try {
193 Collection<Bookmark> bookmarks;
194 bookmarks = new LinkedList<Bookmark>();
195 url = new URL("http://"+connection.serverUrl.getHost()+"/josm/bookmarks");
196 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
197
198 for (String line = in.readLine(); line != null; line = in.readLine()) {
199 StringTokenizer st = new StringTokenizer(line, ",");
200 if (st.countTokens() != 5) {
201 System.err.println(tr("Error: Unexpected line ''{0}'' in bookmark list from server",line));
202 continue;
203 }
204 Bookmark b = new Bookmark();
205 b.setName(st.nextToken());
206 double[] values= new double[4];
207 for (int i = 0; i < 4; ++i) {
208 String token = st.nextToken();
209 try {
210 values[i] = Double.parseDouble(token);
211 } catch(NumberFormatException e) {
212 System.err.println(tr("Error: Illegal double value ''{0}'' on line ''{1}'' in bookmark list from server",token,line));
213 continue;
214 }
215 }
216 b.setArea(new Bounds(values));
217 bookmarks.add(b);
218 }
219 in.close();
220 return bookmarks;
221 } catch (MalformedURLException e) {
222 e.printStackTrace();
223 } catch (IllegalArgumentException e) {
224 e.printStackTrace();
225 } catch (IOException e) {
226 e.printStackTrace();
227 } catch(SecurityException e) {
228 e.printStackTrace();
229 logger.warning(tr("Failed to load bookmarks from ''{0}'' for security reasons. Exception was: {1}", url == null ? "null" : url.toExternalForm(), e.toString()));
230 }
231 return Collections.emptyList();
232 }
233
234 @Override public void saveBookmarks(Collection<Bookmark> bookmarks) {
235 }
236}
Note: See TracBrowser for help on using the repository browser.