OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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.
144 ilm 69
 *
17 ilm 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
 
144 ilm 80
        private FileAction(final String label) {
17 ilm 81
            this.label = label;
82
        }
83
 
84
        @Override
85
        public String toString() {
86
            return this.label;
87
        }
88
    }
89
 
144 ilm 90
    private JComboBox<ReportType> typeRapportComboSelection;
17 ilm 91
 
92
    private JButton genererButton;
144 ilm 93
    private JComboBox<FileAction> fileActionCombo;
17 ilm 94
 
144 ilm 95
    private JList<GenerationTask> tasksView;
174 ilm 96
    private final JLabel status;
17 ilm 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");
174 ilm 103
        this.status = new JLabel();
17 ilm 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
 
174 ilm 115
    protected final void uiInit() throws JDOMException, IOException {
17 ilm 116
        setLayout(new GridBagLayout());
144 ilm 117
        final GridBagConstraints c = new GridBagConstraints();
17 ilm 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>();
144 ilm 127
        this.typeRapportComboSelection = new JComboBox<>(new ListComboBoxModel<ReportType>(this.getTypes().getTypes()));
17 ilm 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
144 ilm 147
                public void actionPerformed(final ActionEvent e) {
17 ilm 148
                    try {
149
                        Desktop.getDesktop().browse(reportDir.toURI());
144 ilm 150
                    } catch (final Exception e1) {
17 ilm 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++;
144 ilm 166
        this.fileActionCombo = new JComboBox<>(getAllowedActions());
17 ilm 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.add(this.status, c);
175
 
176
        c.gridy++;
144 ilm 177
        this.tasksView = new JList<>(new TasksModel());
17 ilm 178
        this.tasksView.setCellRenderer(new GenerationTaskView());
179
        c.fill = GridBagConstraints.BOTH;
180
        c.weighty = 1;
144 ilm 181
        final JScrollPane scroll = new JScrollPane(this.tasksView);
17 ilm 182
        scroll.setPreferredSize(new Dimension(200, 400));
183
        this.add(scroll, c);
184
    }
185
 
186
    /**
187
     * Permet de modifier la liste des tâches.
144 ilm 188
     *
17 ilm 189
     * @author Sylvain CUAZ
190
     */
144 ilm 191
    private static final class TasksModel extends AbstractListModel<GenerationTask> implements PropertyChangeListener {
17 ilm 192
        private List<GenerationTask> tasks;
193
 
194
        {
195
            this.tasks = new ArrayList<GenerationTask>(15);
196
        }
197
 
144 ilm 198
        @Override
17 ilm 199
        public int getSize() {
200
            return this.tasks.size();
201
        }
202
 
144 ilm 203
        @Override
204
        public GenerationTask getElementAt(final int index) {
17 ilm 205
            return this.tasks.get(index);
206
        }
207
 
144 ilm 208
        void add(final GenerationTask task) {
17 ilm 209
            this.tasks.add(task);
210
            task.addPropertyChangeListener(this);
211
            this.fireIntervalAdded(this, this.tasks.size(), this.tasks.size());
212
        }
213
 
214
        void clear() {
215
            for (final GenerationTask t : this.tasks) {
216
                t.removePropertyChangeListener(this);
217
            }
218
            this.fireIntervalRemoved(this, 0, this.tasks.size());
219
            this.tasks.clear();
220
        }
221
 
222
        /*
223
         * Une tache a changé.
224
         */
144 ilm 225
        @Override
226
        public void propertyChange(final PropertyChangeEvent evt) {
227
            final int index = this.tasks.indexOf(evt.getSource());
17 ilm 228
            this.fireContentsChanged(this, index, index);
229
        }
230
    }
231
 
232
    /**
233
     * Interrompt la génération.
234
     */
235
    public final void interrupt() {
236
        // pas de threads active, quand pas génération
237
        this.thg.interrupt();
238
    }
239
 
240
    class GenerateAction implements ActionListener {
241
        public GenerateAction() {
242
        }
243
 
144 ilm 244
        @Override
245
        public void actionPerformed(final ActionEvent e) {
17 ilm 246
            enableGeneration(false);
247
            final FileAction sel = (FileAction) BaseGenerationRapport.this.fileActionCombo.getSelectedItem();
248
            // "génération..."
249
            new Thread(BaseGenerationRapport.this.thg, new Runnable() {
250
                @Override
251
                public void run() {
252
                    generate(sel);
253
                    // toujours le faire, même si interrompu
254
                    SwingUtilities.invokeLater(new Runnable() {
144 ilm 255
                        @Override
17 ilm 256
                        public void run() {
257
                            enableGeneration(true);
258
                        }
259
                    });
260
                }
261
            }).start();
262
        }
263
    }
264
 
144 ilm 265
    protected final void enableGeneration(final boolean b) {
17 ilm 266
        this.fileActionCombo.setEnabled(b);
267
        this.genererButton.setEnabled(b);
268
    }
269
 
270
    // doit s'exécuter dans this.thg
271
    protected final void generate(final FileAction sel) {
272
        final ReportType type = (ReportType) this.typeRapportComboSelection.getSelectedItem();
273
        final R rg = this.createGeneration(type);
274
        rg.addTaskListener(new PropertyChangeListener() {
144 ilm 275
            @Override
276
            public void propertyChange(final PropertyChangeEvent evt) {
17 ilm 277
                final TaskStatus st = (TaskStatus) evt.getOldValue();
278
                if (st.getState().equals(TaskStatus.State.NOT_STARTED))
279
                    addTask((GenerationTask) evt.getSource());
280
            }
281
 
282
        });
283
 
284
        if (Thread.currentThread().isInterrupted())
285
            return;
286
 
287
        Map<String, ODSingleXMLDocument> report = null;
288
        try {
289
            report = this.generate(rg);
290
            if (report != null) {
144 ilm 291
                for (final Entry<String, ODSingleXMLDocument> e : report.entrySet()) {
17 ilm 292
                    try {
73 ilm 293
                        final ODSingleXMLDocument singleDoc = e.getValue();
294
                        final File reportFile = singleDoc.saveToPackageAs(this.getFile(rg, e.getKey()));
17 ilm 295
                        if (sel == FileAction.OPEN)
296
                            OOUtils.open(reportFile);
297
                        else if (sel == FileAction.MAIL) {
298
                            final File fileOutPDF = FileUtils.addSuffix(reportFile, ".pdf");
299
                            try {
300
                                final OOConnexion conn = OOConnexion.create();
301
                                if (conn == null)
302
                                    throw new IllegalStateException("OpenOffice n'a pu être trouvé");
303
                                final Component doc = conn.loadDocument(reportFile, true);
73 ilm 304
                                final String filter = singleDoc.getPackage().getContentType().getType() == ContentType.SPREADSHEET ? "calc_pdf_Export" : "writer_pdf_Export";
305
                                final Future<File> pdf = doc.saveToPDF(fileOutPDF, filter);
17 ilm 306
                                doc.close();
307
                                conn.closeConnexion();
308
                                // can wait for the pdf since we're not in the EDT
309
                                EmailClient.getPreferred().compose(getEmailRecipient(rg), "Rapport", null, pdf.get());
144 ilm 310
                            } catch (final Exception exn) {
17 ilm 311
                                exn.printStackTrace();
312
                                ExceptionHandler.handle("Impossible de charger le document OpenOffice dans le logiciel de courriel", exn);
313
                            }
314
                        }
144 ilm 315
                    } catch (final FileNotFoundException exn) {
17 ilm 316
                        // TODO tester pb de droits
317
                        ExceptionHandler.handle(BaseGenerationRapport.this, "Le fichier est déjà ouvert, veuillez le refermer avant de générer.", exn);
144 ilm 318
                    } catch (final IOException exn) {
17 ilm 319
                        ExceptionHandler.handle(BaseGenerationRapport.this, "Impossible de sauver le rapport", exn);
320
                    }
321
                }
322
            }
144 ilm 323
        } catch (final Throwable e) {
17 ilm 324
            ExceptionHandler.handle(BaseGenerationRapport.this, "Impossible de générer le rapport", e);
325
        }
326
    }
327
 
144 ilm 328
    private Map<String, ODSingleXMLDocument> generate(final org.openconcerto.openoffice.generation.ReportGeneration<?> rg) throws Throwable {
17 ilm 329
        clearTasks();
330
        setStatus("Génération en cours...");
331
 
332
        if (Thread.currentThread().isInterrupted())
333
            return null;
334
 
335
        final long start = System.currentTimeMillis();
336
        Map<String, ODSingleXMLDocument> report = null;
337
        String s;
338
        Throwable t = null;
339
        try {
340
            report = rg.generateMulti();
341
            if (report == null) {
342
                s = "Génération interrompue.";
343
            } else {
344
                s = "Rapport généré en " + (System.currentTimeMillis() - start) / 1000 + " secondes.";
345
            }
144 ilm 346
        } catch (final Throwable e) {
17 ilm 347
            s = "Erreur de génération.";
348
            t = e;
349
        }
350
 
351
        setStatus(s);
352
        if (t == null)
353
            return report;
354
        else
355
            throw t;
356
    }
357
 
358
    private final void addTask(final GenerationTask task) {
359
        SwingUtilities.invokeLater(new Runnable() {
144 ilm 360
            @Override
17 ilm 361
            public void run() {
362
                ((TasksModel) BaseGenerationRapport.this.tasksView.getModel()).add(task);
363
            }
364
        });
365
 
366
    }
367
 
368
    private final void clearTasks() {
369
        SwingUtilities.invokeLater(new Runnable() {
144 ilm 370
            @Override
17 ilm 371
            public void run() {
372
                ((TasksModel) BaseGenerationRapport.this.tasksView.getModel()).clear();
373
            }
374
        });
375
    }
376
 
377
    private final void setStatus(final String status) {
378
        Log.get().info(this + " status: " + status);
379
        SwingUtilities.invokeLater(new Runnable() {
144 ilm 380
            @Override
17 ilm 381
            public void run() {
382
                BaseGenerationRapport.this.status.setText(status);
383
            }
384
        });
385
    }
386
 
144 ilm 387
    @Override
17 ilm 388
    public String toString() {
389
        return "Generation panel";
390
    }
391
 
392
    abstract protected ReportTypes getTypes() throws JDOMException, IOException;
393
 
394
    abstract protected R createGeneration(final ReportType type);
395
 
396
    abstract protected File getFile(final R rg, String docID);
397
 
398
    protected String getEmailRecipient(final R rg) {
399
        return null;
400
    }
401
 
402
    protected FileAction[] getAllowedActions() {
403
        return FileAction.values();
404
    }
405
}