source: extensions/jiwigo/trunk/src/main/java/fr/mael/jiwigo/ui/ConnexionDialog.java @ 10813

Last change on this file since 10813 was 10813, checked in by mlg, 13 years ago

Bug correction
due to nullpointerexception when retrieving some informations from the config file

File size: 14.0 KB
Line 
1package fr.mael.jiwigo.ui;
2
3import java.awt.BorderLayout;
4import java.awt.Dimension;
5import java.awt.FlowLayout;
6import java.awt.GridBagConstraints;
7import java.awt.GridBagLayout;
8import java.awt.Insets;
9import java.awt.event.ActionEvent;
10import java.awt.event.ActionListener;
11import java.awt.event.ItemEvent;
12import java.awt.event.ItemListener;
13import java.awt.event.KeyEvent;
14import java.awt.event.KeyListener;
15import java.awt.event.WindowEvent;
16import java.awt.event.WindowListener;
17import java.text.SimpleDateFormat;
18import java.util.ArrayList;
19import java.util.Arrays;
20import java.util.Locale;
21
22import javax.swing.AbstractListModel;
23import javax.swing.ComboBoxModel;
24import javax.swing.JButton;
25import javax.swing.JCheckBox;
26import javax.swing.JComboBox;
27import javax.swing.JDialog;
28import javax.swing.JLabel;
29import javax.swing.JOptionPane;
30import javax.swing.JPanel;
31import javax.swing.JPasswordField;
32import javax.swing.JTextField;
33
34import fr.mael.jiwigo.Main;
35import fr.mael.jiwigo.transverse.enumeration.PreferencesEnum;
36import fr.mael.jiwigo.transverse.exception.JiwigoException;
37import fr.mael.jiwigo.transverse.exception.ProxyAuthenticationException;
38import fr.mael.jiwigo.transverse.session.SessionManager;
39import fr.mael.jiwigo.transverse.util.Messages;
40import fr.mael.jiwigo.transverse.util.Tools;
41import fr.mael.jiwigo.transverse.util.preferences.PreferencesManagement;
42import fr.mael.jiwigo.transverse.util.spring.SpringUtils;
43import fr.mael.jiwigo.ui.mainframe.CursorSetter;
44
45/**
46   Copyright (c) 2010, Mael
47   All rights reserved.
48
49   Redistribution and use in source and binary forms, with or without
50   modification, are permitted provided that the following conditions are met:
51    * Redistributions of source code must retain the above copyright
52      notice, this list of conditions and the following disclaimer.
53    * Redistributions in binary form must reproduce the above copyright
54      notice, this list of conditions and the following disclaimer in the
55      documentation and/or other materials provided with the distribution.
56    * Neither the name of jiwigo nor the
57      names of its contributors may be used to endorse or promote products
58      derived from this software without specific prior written permission.
59
60   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
61   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
62   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
63   DISCLAIMED. IN NO EVENT SHALL Mael BE LIABLE FOR ANY
64   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
65   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
66   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
67   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
69   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70
71 * @author mael
72 * Dialog de connexion au site
73 */
74public class ConnexionDialog extends JDialog implements ActionListener, ItemListener, KeyListener, WindowListener {
75
76    /**
77     * Logger
78     */
79    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
80            .getLog(ConnexionDialog.class);
81    /**
82     * field that contains the url
83     */
84    private JTextField fieldUrl;
85    /**
86     * field that contains the login
87     */
88    private JTextField loginField;
89    /**
90     * field that contains de password
91     */
92    private JPasswordField passwordField;
93    /**
94     * label of the url field
95     */
96    private JLabel labelUrl;
97    /**
98     * label of the login field
99     */
100    private JLabel labelLogin;
101    /**
102     *  label of the password field
103     */
104    private JLabel labelPass;
105    /**
106     * ok button for the connection
107     */
108    private JButton boutonOk;
109
110    /**
111     * Box that allows to save informations
112     */
113    private JCheckBox checkBoxRetenir;
114
115    /**
116     * Combo containing all locales
117     */
118    private JComboBox comboLocales;
119
120    /**
121     * Panel that allows to define a proxy to use
122     */
123    private ProxyPanel proxyPanel;
124
125    private SessionManager sessionManager;
126
127    /**
128     * Constructor
129     */
130    public ConnexionDialog() {
131        Locale defautLocale = Messages.usedLocale;
132        labelUrl = new JLabel(Messages.getMessage("connexionDialog_urlSite"));
133        labelLogin = new JLabel(Messages.getMessage("connexionDialog_login"));
134        labelPass = new JLabel(Messages.getMessage("connexionDialog_pass"));
135        proxyPanel = new ProxyPanel(this);
136        comboLocales = new JComboBox();
137        boutonOk = new JButton("Ok");
138        String url = PreferencesManagement.getValue(PreferencesEnum.URL_SITE.getLabel());
139        String login = PreferencesManagement.getValue(PreferencesEnum.LOGIN.getLabel());
140        String pass = PreferencesManagement.getValue(PreferencesEnum.PASSWORD.getLabel());
141
142        fieldUrl = new JTextField(url);
143        loginField = new JTextField(login);
144        passwordField = new JPasswordField(pass);
145        checkBoxRetenir = new JCheckBox(Messages.getMessage("connexionDialog_sauvegarder"));
146        if ((url != null && login != null && pass != null)
147                && (!"".equals(url) && !"".equals(login) && !"".equals(pass))) {
148            checkBoxRetenir.setSelected(true);
149        }
150        JPanel panelInformations = new JPanel(new GridBagLayout());
151        Dimension fieldDimensions = new Dimension(300, 30);
152        fieldUrl.setPreferredSize(fieldDimensions);
153        fieldUrl.addActionListener(this);
154        loginField.setPreferredSize(fieldDimensions);
155        loginField.addActionListener(this);
156        passwordField.setPreferredSize(fieldDimensions);
157        passwordField.addActionListener(this);
158        this.getContentPane().setLayout(new BorderLayout());
159        GridBagConstraints constraints = new GridBagConstraints();
160        constraints.gridx = 0;
161        constraints.gridy = 0;
162        constraints.insets = new Insets(3, 3, 3, 3);
163        panelInformations.add(labelUrl, constraints);
164        constraints.gridx++;
165        panelInformations.add(fieldUrl, constraints);
166        constraints.gridx = 0;
167        constraints.gridy++;
168        panelInformations.add(labelLogin, constraints);
169        constraints.gridx++;
170        panelInformations.add(loginField, constraints);
171        constraints.gridx = 0;
172        constraints.gridy++;
173        panelInformations.add(labelPass, constraints);
174        constraints.gridx++;
175        panelInformations.add(passwordField, constraints);
176        constraints.gridx = 0;
177        constraints.gridy++;
178        panelInformations.add(comboLocales, constraints);
179        constraints.gridx++;
180        panelInformations.add(checkBoxRetenir, constraints);
181        constraints.gridx = 0;
182        constraints.gridy++;//
183        //      for (Locale locale : SimpleDateFormat.getAvailableLocales()) {
184        //          comboLocales.addItem(locale.getDisplayName(Locale.ENGLISH));
185        //      }
186        comboLocales.setPreferredSize(new Dimension(130, 25));
187        comboLocales.addItemListener(this);
188        boutonOk.setPreferredSize(new Dimension(80, 30));
189        boutonOk.addActionListener(this);
190        JPanel panelBouton = new JPanel(new FlowLayout(FlowLayout.CENTER));
191        panelBouton.add(boutonOk);
192        localeModel model = new localeModel();
193        comboLocales.setModel(model);
194        model.setSelectedItem(defautLocale.getDisplayLanguage(Locale.ENGLISH));
195
196        this.sessionManager = SpringUtils.getSessionManager();
197
198        this.getContentPane().add(panelInformations, BorderLayout.NORTH);
199        this.getContentPane().add(proxyPanel, BorderLayout.CENTER);
200        this.getContentPane().add(panelBouton, BorderLayout.SOUTH);
201        this.addWindowListener(this);
202        this.setResizable(false);
203    }
204
205    public void showDialog() {
206        this.pack();
207        this.setLocationRelativeTo(null);
208        this.setVisible(true);
209    }
210
211    @Override
212    public void actionPerformed(ActionEvent paramActionEvent) {
213        CursorSetter.setWaitCursor(this);
214        //if one field is empty, an error is displayed
215        if (fieldUrl.getText().equals("") || loginField.getText().equals("") || passwordField.getText().equals("")) {
216            JOptionPane.showMessageDialog(null, Messages.getMessage("connexionDialog_emptyField"),
217                    Messages.getMessage("error"), JOptionPane.ERROR_MESSAGE);
218        } else {
219            if (!fieldUrl.getText().startsWith("http://")) {
220                fieldUrl.setText("http://" + fieldUrl.getText());
221            }
222            //instanciation of the session manager
223            sessionManager.setLogin(loginField.getText());
224            sessionManager.setPassword(new String(passwordField.getPassword()));
225            sessionManager.setUrl(fieldUrl.getText() + "/ws.php");
226            boolean echecProxy = false;
227            if (proxyPanel.getCheckBox().isSelected()) {
228                int portProxy = 0;
229                try {
230                    portProxy = Integer.valueOf(proxyPanel.getFieldPort().getText());
231                    sessionManager.setPortProxy(portProxy);
232                    sessionManager.setUrlProxy(proxyPanel.getFieldUrl().getText());
233                    sessionManager.setLoginProxy(proxyPanel.getFieldLogin().getText());
234                    sessionManager.setPassProxy(new String(proxyPanel.getFieldPassword().getPassword()));
235                    sessionManager.setUsesProxy(true);
236                } catch (Exception e) {
237                    echecProxy = true;
238                }
239
240            }
241
242            //save informations...
243            if (checkBoxRetenir.isSelected()) {
244                PreferencesManagement.setValue(PreferencesEnum.LOGIN.getLabel(), loginField.getText());
245                PreferencesManagement.setValue(PreferencesEnum.PASSWORD.getLabel(),
246                        new String(passwordField.getPassword()));
247                PreferencesManagement.setValue(PreferencesEnum.URL_SITE.getLabel(), fieldUrl.getText());
248                PreferencesManagement
249                        .setValue(PreferencesEnum.URL_PROXY.getLabel(), proxyPanel.getFieldUrl().getText());
250                PreferencesManagement.setValue(PreferencesEnum.PORT_PROXY.getLabel(), proxyPanel.getFieldPort()
251                        .getText());
252                PreferencesManagement.setValue(PreferencesEnum.USER_PROXY.getLabel(), proxyPanel.getFieldLogin()
253                        .getText());
254                PreferencesManagement.setValue(PreferencesEnum.PASS_PROXY.getLabel(), new String(proxyPanel
255                        .getFieldPassword().getPassword()));
256                PreferencesManagement.setValue(PreferencesEnum.USE_PROXY.getLabel(),
257                        String.valueOf(proxyPanel.getCheckBox().isSelected()));
258            }
259            //... or not
260            else {
261                PreferencesManagement.setValue(PreferencesEnum.LOGIN.getLabel(), "");
262                PreferencesManagement.setValue(PreferencesEnum.PASSWORD.getLabel(), "");
263                PreferencesManagement.setValue(PreferencesEnum.URL_SITE.getLabel(), "");
264                PreferencesManagement
265                        .setValue(PreferencesEnum.URL_PROXY.getLabel(), proxyPanel.getFieldUrl().getText());
266                PreferencesManagement.setValue(PreferencesEnum.PORT_PROXY.getLabel(), "");
267                PreferencesManagement.setValue(PreferencesEnum.USER_PROXY.getLabel(), "");
268                PreferencesManagement.setValue(PreferencesEnum.PASS_PROXY.getLabel(), "");
269                PreferencesManagement.setValue(PreferencesEnum.USE_PROXY.getLabel(), "false");
270            }
271            if (echecProxy) {
272                JOptionPane.showMessageDialog(null, Messages.getMessage("proxyError"), Messages.getMessage("error"),
273                        JOptionPane.ERROR_MESSAGE);
274            } else {
275                int response = 0;
276                try {
277                    response = sessionManager.processLogin();
278                } catch (JiwigoException e) {
279                    if (e.getCause() != null && ProxyAuthenticationException.class.equals(e.getCause().getClass())) {
280                        response = 2;
281                    } else {
282                        response = 1;
283                    }
284                }
285                if (response == 0) {
286                    Main.showFrame();
287                    //hides the dialog
288                    this.dispose();
289                } else if (response == 1) {
290                    //if the login fails, an error is displayed
291                    JOptionPane.showMessageDialog(null, Messages.getMessage("connexionDialog_connexionError"),
292                            Messages.getMessage("error"), JOptionPane.ERROR_MESSAGE);
293                } else if (response == 2) {
294                    JOptionPane.showMessageDialog(null, Messages.getMessage("connexionDialog_proxyAuthError"),
295                            Messages.getMessage("error"), JOptionPane.ERROR_MESSAGE);
296                }
297            }
298
299        }
300        CursorSetter.setDefaultCursor(this);
301    }
302
303    @Override
304    public void itemStateChanged(ItemEvent paramItemEvent) {
305        for (Locale locale : SimpleDateFormat.getAvailableLocales()) {
306            if (locale.getDisplayName(Locale.ENGLISH).equals(paramItemEvent.getItem())) {
307                Messages.usedLocale = locale;
308                dispose();
309                ConnexionDialog dial = new ConnexionDialog();
310                dial.showDialog();
311
312            }
313
314        }
315    }
316
317    @Override
318    public void keyPressed(KeyEvent arg0) {
319    }
320
321    @Override
322    public void keyReleased(KeyEvent arg0) {
323
324    }
325
326    @Override
327    public void keyTyped(KeyEvent arg0) {
328    }
329
330    @Override
331    public void windowActivated(WindowEvent e) {
332        // TODO Auto-generated method stub
333
334    }
335
336    @Override
337    public void windowClosed(WindowEvent e) {
338    }
339
340    @Override
341    public void windowClosing(WindowEvent e) {
342        System.exit(0);
343    }
344
345    @Override
346    public void windowDeactivated(WindowEvent e) {
347        // TODO Auto-generated method stub
348
349    }
350
351    @Override
352    public void windowDeiconified(WindowEvent e) {
353        // TODO Auto-generated method stub
354
355    }
356
357    @Override
358    public void windowIconified(WindowEvent e) {
359        // TODO Auto-generated method stub
360
361    }
362
363    @Override
364    public void windowOpened(WindowEvent e) {
365        // TODO Auto-generated method stub
366
367    }
368
369    /**
370     * @author mael
371     * Internal class that represents the model of the combobox that allows
372     * to choose a locale
373     */
374    class localeModel extends AbstractListModel implements ComboBoxModel {
375
376        //List<Locale> locales = Messages.getAvailableBundles();
377        String[] localesNames;
378
379        String selection = null;
380
381        public localeModel() {
382            ArrayList<String> loc = new ArrayList<String>();
383            Locale[] locales = SimpleDateFormat.getAvailableLocales();
384            for (Locale locale : locales) {
385                if (Tools.getURL("fr/mael/jiwigo/trad/messages_" + locale.getLanguage() + ".properties") != null) {
386                    loc.add(locale.getDisplayName(Locale.ENGLISH));
387                }
388            }
389            localesNames = new String[loc.size()];
390            //      localesNames = new String[nbLocales];
391            //      int compteur = 0;
392            //      for (Locale locale : locales) {
393            //          if (Tools.getURL("fr/mael/jiwigo/trad/messages_" + locale.getLanguage() + ".properties") != null) {
394            //              localesNames[compteur] = locale.getDisplayName(Locale.ENGLISH);
395            //              compteur++;
396            //          }
397            //      }
398            loc.toArray(localesNames);
399            Arrays.sort(localesNames);
400        }
401
402        public Object getElementAt(int index) {
403            return localesNames[index];
404        }
405
406        public int getSize() {
407            return localesNames.length;
408        }
409
410        public void setSelectedItem(Object anItem) {
411            selection = (String) anItem;
412        }
413
414        public Object getSelectedItem() {
415            if (selection != null)
416                return selection;
417            else
418                return null;
419        }
420    }
421}
Note: See TracBrowser for help on using the repository browser.