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

Revision 4874, 6.5 KB checked in by jttt, 2 weeks ago (diff)

Use static class were appropriate

  • Property svn:eol-style set to native
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;
17
18import javax.swing.JOptionPane;
19import javax.xml.stream.XMLStreamException;
20
21import org.openstreetmap.josm.Main;
22import org.openstreetmap.josm.io.OsmConnection;
23import org.openstreetmap.josm.tools.Base64;
24
25/**
26 * This class tweak the Preferences class to provide server side preference settings, as example
27 * used in the applet version.
28 *
29 * @author Imi
30 */
31public class ServerSidePreferences extends Preferences {
32    public static class MissingPassword extends Exception{
33        public String realm;
34        public MissingPassword(String r) {
35            realm = r;
36        }
37    }
38
39    private final Connection connection;
40
41    private class Connection extends OsmConnection {
42        URL serverUrl;
43        public Connection(URL serverUrl) {
44            this.serverUrl = serverUrl;
45        }
46        public String download() throws MissingPassword {
47            try {
48                System.out.println("reading preferences from "+serverUrl);
49                URLConnection con = serverUrl.openConnection();
50                String username = get("applet.username");
51                String password = get("applet.password");
52                if(password.isEmpty() && username.isEmpty()) {
53                    con.addRequestProperty("Authorization", "Basic "+Base64.encode(username+":"+password));
54                }
55                con.connect();
56                if(username.isEmpty() && con instanceof HttpURLConnection
57                        && ((HttpURLConnection) con).getResponseCode()
58                        == HttpURLConnection.HTTP_UNAUTHORIZED) {
59                    String t = ((HttpURLConnection) con).getHeaderField("WWW-Authenticate");
60                    t = t.replace("Basic realm=\"","").replace("\"","");
61                    throw new MissingPassword(t);
62                }
63                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
64                StringBuilder b = new StringBuilder();
65                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
66                    b.append(line);
67                    b.append("\n");
68                }
69                if (con instanceof HttpURLConnection) {
70                    ((HttpURLConnection) con).disconnect();
71                }
72                return b.toString();
73            } catch (IOException e) {
74                e.printStackTrace();
75            }
76            return null;
77        }
78        public void upload(String s) {
79            try {
80                URL u = new URL(getPreferencesDir());
81                System.out.println("uploading preferences to "+u);
82                HttpURLConnection con = (HttpURLConnection)u.openConnection();
83                String username = get("applet.username");
84                String password = get("applet.password");
85                if(password.isEmpty() && username.isEmpty()) {
86                    con.addRequestProperty("Authorization", "Basic "+Base64.encode(username+":"+password));
87                }
88                con.setRequestMethod("POST");
89                con.setDoOutput(true);
90                con.connect();
91                PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
92                out.println(s);
93                out.close();
94                con.getInputStream().close();
95                con.disconnect();
96                JOptionPane.showMessageDialog(
97                        Main.parent,
98                        tr("Preferences stored on {0}", u.getHost()),
99                        tr("Information"),
100                        JOptionPane.INFORMATION_MESSAGE
101                        );
102            } catch (Exception e) {
103                e.printStackTrace();
104                JOptionPane.showMessageDialog(
105                        Main.parent,
106                        tr("Could not upload preferences. Reason: {0}", e.getMessage()),
107                        tr("Error"),
108                        JOptionPane.ERROR_MESSAGE
109                        );
110            }
111        }
112    }
113
114    public ServerSidePreferences(URL serverUrl) {
115        Connection connection = null;
116        try {
117            connection = new Connection(new URL(serverUrl+"user/preferences"));
118        } catch (MalformedURLException e) {
119            e.printStackTrace();
120            JOptionPane.showMessageDialog(
121                    Main.parent,
122                    tr("Could not load preferences from server."),
123                    tr("Error"),
124                    JOptionPane.ERROR_MESSAGE
125                    );
126        }
127        this.connection = connection;
128    }
129
130    @Override public String getPreferencesDir() {
131        return connection.serverUrl.toString();
132    }
133
134    /**
135     * Do nothing on load. Preferences are loaded with download().
136     */
137    @Override public void load() {
138    }
139
140    /**
141     * Do nothing on save. Preferences are uploaded using upload().
142     */
143    @Override public void save() {
144    }
145
146    public void download(String userName, String password) {
147        if (!properties.containsKey("applet.username") && userName != null) {
148            properties.put("applet.username", userName);
149        }
150        if (!properties.containsKey("applet.password") && password != null) {
151            properties.put("applet.password", password);
152        }
153        try {
154            download();
155        } catch (MissingPassword e) {
156        }
157    }
158
159    public boolean download() throws MissingPassword {
160        resetToDefault();
161        String cont = connection.download();
162        if (cont == null) return false;
163        Reader in = new StringReader(cont);
164        boolean res = false;
165        try {
166            fromXML(in);
167        } catch (RuntimeException e) {
168            e.printStackTrace();
169        } catch (XMLStreamException e) {
170            e.printStackTrace();
171        }
172        return res;
173    }
174
175    /**
176     * Use this instead of save() for the ServerSidePreferences, since uploads
177     * are costly while save is called often.
178     *
179     * This is triggered by an explicit menu option.
180     */
181    public void upload() {
182        connection.upload(toXML(true));
183    }
184}
Note: See TracBrowser for help on using the repository browser.