OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 61 | Rev 144 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.openoffice.generation.view;
15
 
73 ilm 16
import org.openconcerto.openoffice.ContentType;
17 ilm 17
import org.openconcerto.openoffice.Log;
18
import org.openconcerto.openoffice.ODSingleXMLDocument;
19
import org.openconcerto.openoffice.OOUtils;
20
import org.openconcerto.openoffice.generation.GenerationTask;
21
import org.openconcerto.openoffice.generation.ReportGeneration;
22
import org.openconcerto.openoffice.generation.TaskStatus;
23
import org.openconcerto.openoffice.generation.desc.ReportType;
24
import org.openconcerto.openoffice.generation.desc.ReportTypes;
25
import org.jopendocument.link.Component;
26
import org.jopendocument.link.OOConnexion;
27
import org.openconcerto.utils.EmailClient;
28
import org.openconcerto.utils.ExceptionHandler;
29
import org.openconcerto.utils.FileUtils;
30
import org.openconcerto.utils.model.ListComboBoxModel;
31
 
32
import java.awt.Desktop;
33
import java.awt.Dimension;
34
import java.awt.GridBagConstraints;
35
import java.awt.GridBagLayout;
36
import java.awt.Insets;
37
import java.awt.event.ActionEvent;
38
import java.awt.event.ActionListener;
39
import java.beans.PropertyChangeEvent;
40
import java.beans.PropertyChangeListener;
41
import java.io.File;
42
import java.io.FileNotFoundException;
43
import java.io.IOException;
44
import java.util.ArrayList;
45
import java.util.LinkedHashMap;
46
import java.util.List;
47
import java.util.Map;
48
import java.util.Map.Entry;
49
import java.util.concurrent.Future;
50
 
51
import javax.swing.AbstractAction;
52
import javax.swing.AbstractListModel;
53
import javax.swing.JButton;
54
import javax.swing.JComboBox;
55
import javax.swing.JComponent;
56
import javax.swing.JLabel;
57
import javax.swing.JList;
58
import javax.swing.JOptionPane;
59
import javax.swing.JPanel;
60
import javax.swing.JScrollPane;
61
import javax.swing.SwingUtilities;
62
 
63
import org.jdom.JDOMException;
64
 
65
/**
66
 * A panel to choose a ReportType, see the tasks of the generation, and optionnaly open the
67
 * document. NOTE: you have to call {@link #enableGeneration(boolean)} before being able to
68
 * generate, because it's set to false in the constructor.
69
 *
70
 * @author ILM Informatique 27 déc. 2003
71
 * @param <R> type of generation
72
 */
73
public abstract class BaseGenerationRapport<R extends ReportGeneration<?>> extends JPanel {
74
 
75
    static public enum FileAction {
76
        DO_NOTHING("ne rien faire"), OPEN("ouvrir le fichier"), MAIL("envoyer par courriel");
77
 
78
        private final String label;
79
 
80
        private FileAction(String label) {
81
            this.label = label;
82
        }
83
 
84
        @Override
85
        public String toString() {
86
            return this.label;
87
        }
88
    }
89
 
90
    private JComboBox typeRapportComboSelection;
91
 
92
    private JButton genererButton;
93
    private JComboBox fileActionCombo;
94
 
95
    private JList tasksView;
96
    private JLabel status;
97
 
98
    // le groupe dans lequel doivent être toutes les thread de la génération
99
    private final ThreadGroup thg;
100
 
101
    public BaseGenerationRapport() throws JDOMException, IOException {
102
        this.thg = new ThreadGroup(this + " thread group");
103
        this.uiInit();
104
        this.setStatus("Inactif");
105
    }
106
 
107
    protected Map<String, JComponent> getEntries() {
108
        return new LinkedHashMap<String, JComponent>();
109
    }
110
 
111
    protected File getReportDir() {
112
        return null;
113
    }
114
 
115
    private void uiInit() throws JDOMException, IOException {
116
        setLayout(new GridBagLayout());
117
        GridBagConstraints c = new GridBagConstraints();
118
        c.ipadx = 40;
119
        c.insets = new Insets(2, 5, 0, 0);
120
        c.gridx = 0;
121
        c.gridy = 0;
122
        c.gridheight = 1;
123
        c.gridwidth = 1;
124
        c.fill = GridBagConstraints.HORIZONTAL;
125
 
126
        final Map<String, JComponent> allEntries = new LinkedHashMap<String, JComponent>();
127
        this.typeRapportComboSelection = new JComboBox(new ListComboBoxModel(this.getTypes().getTypes()));
128
        allEntries.put("Type de rapport", this.typeRapportComboSelection);
129
        allEntries.putAll(this.getEntries());
130
 
131
        for (final Map.Entry<String, JComponent> e : allEntries.entrySet()) {
132
            c.gridx = 0;
133
            c.gridy++;
134
            this.add(new JLabel(e.getKey()), c);
135
            c.gridx++;
136
            c.weightx = 1;
137
            this.add(e.getValue(), c);
138
            c.weightx = 0;
139
        }
140
        final File reportDir = getReportDir();
141
        if (reportDir != null) {
142
            c.gridx = 1;
143
            c.gridy++;
144
            c.weightx = 1;
145
            this.add(new JButton(new AbstractAction("Ouvrir le dossier des rapports") {
146
                @Override
147
                public void actionPerformed(ActionEvent e) {
148
                    try {
149
                        Desktop.getDesktop().browse(reportDir.toURI());
150
                    } catch (Exception e1) {
151
                        JOptionPane.showMessageDialog(BaseGenerationRapport.this, "Impossible d'ouvrir le dossier", "Erreur", JOptionPane.ERROR_MESSAGE);
152
                    }
153
                }
154
            }), c);
155
            c.weightx = 0;
156
        }
157
 
158
        c.gridx = 0;
159
        c.gridy++;
160
        this.genererButton = new JButton("Générer le rapport et");
161
        this.add(this.genererButton, c);
162
        this.genererButton.setEnabled(false);
163
        this.genererButton.addActionListener(new GenerateAction());
164
 
165
        c.gridx++;
166
        this.fileActionCombo = new JComboBox(getAllowedActions());
167
        this.fileActionCombo.setSelectedItem(FileAction.OPEN);
168
        this.add(this.fileActionCombo, c);
169
        this.fileActionCombo.setEnabled(false);
170
 
171
        c.gridx = 0;
172
        c.gridy++;
173
        c.gridwidth = GridBagConstraints.REMAINDER;
174
        this.status = new JLabel();
175
        this.add(this.status, c);
176
 
177
        c.gridy++;
178
        this.tasksView = new JList(new TasksModel());
179
        this.tasksView.setCellRenderer(new GenerationTaskView());
180
        c.fill = GridBagConstraints.BOTH;
181
        c.weighty = 1;
182
        JScrollPane scroll = new JScrollPane(this.tasksView);
183
        scroll.setPreferredSize(new Dimension(200, 400));
184
        this.add(scroll, c);
185
    }
186
 
187
    /**
188
     * Permet de modifier la liste des tâches.
189
     *
190
     * @author Sylvain CUAZ
191
     */
192
    private static final class TasksModel extends AbstractListModel implements PropertyChangeListener {
193
        private List<GenerationTask> tasks;
194
 
195
        {
196
            this.tasks = new ArrayList<GenerationTask>(15);
197
        }
198
 
199
        public int getSize() {
200
            return this.tasks.size();
201
        }
202
 
203
        public Object getElementAt(int index) {
204
            return this.tasks.get(index);
205
        }
206
 
207
        void add(GenerationTask task) {
208
            this.tasks.add(task);
209
            task.addPropertyChangeListener(this);
210
            this.fireIntervalAdded(this, this.tasks.size(), this.tasks.size());
211
        }
212
 
213
        void clear() {
214
            for (final GenerationTask t : this.tasks) {
215
                t.removePropertyChangeListener(this);
216
            }
217
            this.fireIntervalRemoved(this, 0, this.tasks.size());
218
            this.tasks.clear();
219
        }
220
 
221
        /*
222
         * Une tache a changé.
223
         */
224
        public void propertyChange(PropertyChangeEvent evt) {
225
            int index = this.tasks.indexOf(evt.getSource());
226
            this.fireContentsChanged(this, index, index);
227
        }
228
    }
229
 
230
    /**
231
     * Interrompt la génération.
232
     */
233
    public final void interrupt() {
234
        // pas de threads active, quand pas génération
235
        this.thg.interrupt();
236
    }
237
 
238
    class GenerateAction implements ActionListener {
239
        public GenerateAction() {
240
        }
241
 
242
        public void actionPerformed(ActionEvent e) {
243
            enableGeneration(false);
244
            final FileAction sel = (FileAction) BaseGenerationRapport.this.fileActionCombo.getSelectedItem();
245
            // "génération..."
246
            new Thread(BaseGenerationRapport.this.thg, new Runnable() {
247
                @Override
248
                public void run() {
249
                    generate(sel);
250
                    // toujours le faire, même si interrompu
251
                    SwingUtilities.invokeLater(new Runnable() {
252
                        public void run() {
253
                            enableGeneration(true);
254
                        }
255
                    });
256
                }
257
            }).start();
258
        }
259
    }
260
 
261
    protected final void enableGeneration(boolean b) {
262
        this.fileActionCombo.setEnabled(b);
263
        this.genererButton.setEnabled(b);
264
    }
265
 
266
    // doit s'exécuter dans this.thg
267
    protected final void generate(final FileAction sel) {
268
        final ReportType type = (ReportType) this.typeRapportComboSelection.getSelectedItem();
269
        final R rg = this.createGeneration(type);
270
        rg.addTaskListener(new PropertyChangeListener() {
271
            public void propertyChange(PropertyChangeEvent evt) {
272
                final TaskStatus st = (TaskStatus) evt.getOldValue();
273
                if (st.getState().equals(TaskStatus.State.NOT_STARTED))
274
                    addTask((GenerationTask) evt.getSource());
275
            }
276
 
277
        });
278
 
279
        if (Thread.currentThread().isInterrupted())
280
            return;
281
 
282
        Map<String, ODSingleXMLDocument> report = null;
283
        try {
284
            report = this.generate(rg);
285
            if (report != null) {
286
                for (Entry<String, ODSingleXMLDocument> e : report.entrySet()) {
287
                    try {
73 ilm 288
                        final ODSingleXMLDocument singleDoc = e.getValue();
289
                        final File reportFile = singleDoc.saveToPackageAs(this.getFile(rg, e.getKey()));
17 ilm 290
                        if (sel == FileAction.OPEN)
291
                            OOUtils.open(reportFile);
292
                        else if (sel == FileAction.MAIL) {
293
                            final File fileOutPDF = FileUtils.addSuffix(reportFile, ".pdf");
294
                            try {
295
                                final OOConnexion conn = OOConnexion.create();
296
                                if (conn == null)
297
                                    throw new IllegalStateException("OpenOffice n'a pu être trouvé");
298
                                final Component doc = conn.loadDocument(reportFile, true);
73 ilm 299
                                final String filter = singleDoc.getPackage().getContentType().getType() == ContentType.SPREADSHEET ? "calc_pdf_Export" : "writer_pdf_Export";
300
                                final Future<File> pdf = doc.saveToPDF(fileOutPDF, filter);
17 ilm 301
                                doc.close();
302
                                conn.closeConnexion();
303
                                // can wait for the pdf since we're not in the EDT
304
                                EmailClient.getPreferred().compose(getEmailRecipient(rg), "Rapport", null, pdf.get());
305
                            } catch (Exception exn) {
306
                                exn.printStackTrace();
307
                                ExceptionHandler.handle("Impossible de charger le document OpenOffice dans le logiciel de courriel", exn);
308
                            }
309
                        }
310
                    } catch (FileNotFoundException exn) {
311
                        // TODO tester pb de droits
312
                        ExceptionHandler.handle(BaseGenerationRapport.this, "Le fichier est déjà ouvert, veuillez le refermer avant de générer.", exn);
313
                    } catch (IOException exn) {
314
                        ExceptionHandler.handle(BaseGenerationRapport.this, "Impossible de sauver le rapport", exn);
315
                    }
316
                }
317
            }
318
        } catch (Throwable e) {
319
            ExceptionHandler.handle(BaseGenerationRapport.this, "Impossible de générer le rapport", e);
320
        }
321
    }
322
 
323
    private Map<String, ODSingleXMLDocument> generate(org.openconcerto.openoffice.generation.ReportGeneration<?> rg) throws Throwable {
324
        clearTasks();
325
        setStatus("Génération en cours...");
326
 
327
        if (Thread.currentThread().isInterrupted())
328
            return null;
329
 
330
        final long start = System.currentTimeMillis();
331
        Map<String, ODSingleXMLDocument> report = null;
332
        String s;
333
        Throwable t = null;
334
        try {
335
            report = rg.generateMulti();
336
            if (report == null) {
337
                s = "Génération interrompue.";
338
            } else {
339
                s = "Rapport généré en " + (System.currentTimeMillis() - start) / 1000 + " secondes.";
340
            }
341
        } catch (Throwable e) {
342
            s = "Erreur de génération.";
343
            t = e;
344
        }
345
 
346
        setStatus(s);
347
        if (t == null)
348
            return report;
349
        else
350
            throw t;
351
    }
352
 
353
    private final void addTask(final GenerationTask task) {
354
        SwingUtilities.invokeLater(new Runnable() {
355
            public void run() {
356
                ((TasksModel) BaseGenerationRapport.this.tasksView.getModel()).add(task);
357
            }
358
        });
359
 
360
    }
361
 
362
    private final void clearTasks() {
363
        SwingUtilities.invokeLater(new Runnable() {
364
            public void run() {
365
                ((TasksModel) BaseGenerationRapport.this.tasksView.getModel()).clear();
366
            }
367
        });
368
    }
369
 
370
    private final void setStatus(final String status) {
371
        Log.get().info(this + " status: " + status);
372
        SwingUtilities.invokeLater(new Runnable() {
373
            public void run() {
374
                BaseGenerationRapport.this.status.setText(status);
375
            }
376
        });
377
    }
378
 
379
    public String toString() {
380
        return "Generation panel";
381
    }
382
 
383
    abstract protected ReportTypes getTypes() throws JDOMException, IOException;
384
 
385
    abstract protected R createGeneration(final ReportType type);
386
 
387
    abstract protected File getFile(final R rg, String docID);
388
 
389
    protected String getEmailRecipient(final R rg) {
390
        return null;
391
    }
392
 
393
    protected FileAction[] getAllowedActions() {
394
        return FileAction.values();
395
    }
396
}