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

Last change on this file since 2512 was 2512, checked in by stoecker, 14 years ago

i18n updated, fixed files to reduce problems when applying patches, fix #4017

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