aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/plugin/jabberaccregwizz/JabberServerChooserDialog.java
blob: 9abaad6427cbdaea7866a9de998523ad0185a9d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.plugin.jabberaccregwizz;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

import javax.imageio.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.xml.parsers.*;

import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.util.*;

import org.jitsi.service.fileaccess.*;
import org.osgi.framework.*;
import org.w3c.dom.*;
import org.xml.sax.*;

/**
 * A dialog that shows the list of available Jabber servers.
 *
 * @author Nicolas Grandclaude
 */
public class JabberServerChooserDialog
    extends SIPCommDialog
    implements ListSelectionListener
{
    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 0L;

    private static final Logger logger = Logger
        .getLogger(JabberServerChooserDialog.class);

    // Servers Table
    private JTable serversTable;

    private JTextArea chooseArea = new JTextArea(Resources
        .getString("plugin.jabberaccregwizz.CHOOSE_SERVER_TEXT"));

    // Panel
    private JPanel mainPanel = new TransparentPanel(new BorderLayout());

    private JPanel buttonPanel = new TransparentPanel(new FlowLayout(
            FlowLayout.RIGHT));

    private Box buttonBox = new Box(BoxLayout.X_AXIS);

    private JPanel chooseAreaPanel = new TransparentPanel(new BorderLayout());

    private JPanel westPanel = new TransparentPanel(new BorderLayout(10, 10));

    private JPanel eastPanel = new TransparentPanel(new BorderLayout(10, 10));

    private JLabel westIconLabel = new JLabel();

    private JButton okButton
        = new JButton(Resources.getString("service.gui.OK"));

    private JButton cancelButton = new JButton(Resources
        .getString("service.gui.CANCEL"));

    private Vector<String> servers = new Vector<String>();

    private FileAccessService faService = null;

    private String[] columnNames =
    {   Resources.getString("plugin.jabberaccregwizz.SERVER_COLUMN"),
        Resources.getString("plugin.jabberaccregwizz.COMMENT_COLUMN")};

    /**
     * If the OK button is pressed.
     */
    public boolean isOK = false;

    /**
     * The selected server.
     */
    public String serverSelected;

    /**
     * Creates an instance of <tt>JabberServerChooserDialog</tt>.
     */
    public JabberServerChooserDialog()
    {
        this.setSize(new Dimension(550, 450));
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setTitle(Resources.getString(
            "plugin.jabberaccregwizz.CHOOSE_SERVER_TITLE"));
        this.setModal(true);

        // Place the window in the center
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(screenSize.width / 2 - this.getWidth() / 2,
            screenSize.height / 2 - this.getHeight() / 2);

        this.init();
    }
    /**
     * Initializes all panels, buttons, etc.
     */
    private void init()
    {
        chooseArea.setEditable(false);
        chooseArea.setOpaque(false);
        chooseArea.setLineWrap(true);
        chooseArea.setWrapStyleWord(true);

        chooseAreaPanel
            .setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 10));

        chooseAreaPanel.add(chooseArea, BorderLayout.NORTH);

        eastPanel.add(chooseAreaPanel, BorderLayout.NORTH);

        // West Jabber icon
        westIconLabel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(20, 20, 20, 20), BorderFactory
                .createTitledBorder("")));
        try
        {
            westIconLabel.setIcon(new ImageIcon(ImageIO
                .read(new ByteArrayInputStream(Resources
                    .getImage(Resources.PAGE_IMAGE)))));
        }
        catch (IOException e)
        {
            logger.error("Could not read image.", e);
        }

        this.westPanel.add(westIconLabel, BorderLayout.NORTH);
        this.mainPanel.add(westPanel, BorderLayout.WEST);

        // Table with servers and comments
        serversTable = new JTable(new ServerChooserTableModel());
        serversTable.setRowHeight(22);
        serversTable.getSelectionModel().addListSelectionListener(this);
        serversTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        serversTable.setPreferredScrollableViewportSize(new Dimension(500, 70));

        // Fill the servers array with servers from servers.xml
        fillTable();

        JScrollPane scrollPane = new JScrollPane(serversTable);
        eastPanel.add(scrollPane, BorderLayout.CENTER);

        // Ok button
        okButton.setMnemonic(Resources.getMnemonic("service.gui.OK"));
        okButton.setEnabled(false);

        // Cancel button
        cancelButton.setMnemonic(Resources.getMnemonic("service.gui.CANCEL"));

        // Box with Ok and Cancel
        buttonBox.setBorder(new EmptyBorder(new Insets(5, 10, 5, 10)));
        buttonBox.add(okButton);
        buttonBox.add(Box.createHorizontalStrut(10));
        buttonBox.add(cancelButton);
        buttonPanel.add(buttonBox);

        okButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                isOK = true;
                dispose();
            }
        });

        cancelButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                dispose();
            }
        });

        this.mainPanel.add(eastPanel, BorderLayout.CENTER);
        this.mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        this.getContentPane().add(mainPanel, BorderLayout.CENTER);

        this.setVisible(true);
    }


    /**
     * Fill the servers array variable with data from the remote servers.xml
     */
    public void fillTable()
    {
        BundleContext bc = JabberAccRegWizzActivator.bundleContext;

        ServiceReference faServiceReference = bc
            .getServiceReference(FileAccessService.class.getName());

        faService = (FileAccessService) bc.getService(faServiceReference);

        File localServersListFile = null;
        try
        {
            localServersListFile = faService.getTemporaryFile();
            URL file = new URL("http://xmpp.net/services.xml");
            InputStream stream = file.openStream();

            try
            {
                // Copy the remote file to the disk
                byte[] buf = new byte[2048];
                int len;
                if (stream.available() > 0)
                {
                    FileOutputStream fos
                        = new FileOutputStream(localServersListFile);

                    while ((len = stream.read(buf)) > 0)
                    {
                        fos.write(buf, 0, len);
                    }
                    fos.close();
                }
            }
            finally
            {
                stream.close();
            }

            FileInputStream fis = new FileInputStream(localServersListFile);
            DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
            DocumentBuilder constructor = factory.newDocumentBuilder();
            Document document = constructor.parse(fis);
            Element root = document.getDocumentElement();

            NodeList list = root.getElementsByTagName("item");

            // Read the xml and fill servers variable for the JTable
            for (int i = 0; i < list.getLength(); i++)
            {
                Element e = (Element) list.item(i);
                servers.add(new String(e.getAttribute("jid")));
            }
            fis.close();

        }
        catch (Exception e)
        {
            logger.error(
                "Failed to get a reference to the Jabber servers list file.", e);
        }
        finally
        {
            if (localServersListFile != null)
            {
                localServersListFile.delete();
            }
        }
    }

    /**
     * When a table row is selected enable the "Ok" button, otherwise disable it.
     */
    public void valueChanged(ListSelectionEvent e)
    {
        int row = serversTable.getSelectedRow();
        if (row != -1)
        {
            okButton.setEnabled(true);
            serverSelected = (String) serversTable.getValueAt(row, 0);
        }
        else
        {
            okButton.setEnabled(false);
        }
    }

    @Override
    protected void close(boolean isEscaped)
    {
        cancelButton.doClick();
    }

    /**
     * The table model used for the table containing all servers.
     */
    private class ServerChooserTableModel extends AbstractTableModel
    {
        /**
         * Serial version UID.
         */
        private static final long serialVersionUID = 0L;

        private Document serverComments;

        private NodeList commentsList;

        public ServerChooserTableModel()
        {
            try
            {
                // Create a builder factory
                DocumentBuilderFactory factory
                    = DocumentBuilderFactory.newInstance();

                // Create the builder and parse the file
                serverComments = factory.newDocumentBuilder()
                    .parse(Resources.getPropertyInputStream(
                        "plugin.jabberaccregwizz.SERVER_COMMENTS"));
            }
            catch (SAXException e)
            {
                logger.error("Failed to parse server comments.", e);
            }
            catch (ParserConfigurationException e)
            {
                logger.error("Failed to parse server comments.", e);
            }
            catch (IOException e)
            {
                logger.error("Failed to parse server comments.", e);
            }

            Element root = serverComments.getDocumentElement();
            commentsList = root.getElementsByTagName("item");
        }

        public int getColumnCount()
        {
            return 2;
        }

        public int getRowCount()
        {
            return servers.size();
        }

        @Override
        public String getColumnName(int col)
        {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col)
        {
            String commentString = new String("");
            if (col == 0) // Column 1 (Server name)
            {
                return servers.get(row);
            }
            else
            { // Column 2 (Comment)

                int i = 0;
                Element e = (Element) commentsList.item(i);

                while ((i < commentsList.getLength())
                    && (e.getAttribute("jid").equals(servers.get(row)) == false))
                {
                    e = (Element) commentsList.item(i);
                    i++;
                }

                if (e.getAttribute("jid").equals(servers.get(row)))
                {
                    commentString = e.getAttribute("comment");
                }

                return commentString;
            }
        }
    }
}