OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 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.erp.generationDoc;
15
 
16
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStreamStatic;
17
import org.openconcerto.erp.config.ComptaPropsConfiguration;
18
import org.openconcerto.erp.core.common.ui.PreviewFrame;
19
import org.openconcerto.erp.preferences.TemplateNXProps;
20
import org.openconcerto.openoffice.ODPackage;
21
import org.jopendocument.link.Component;
22
import org.openconcerto.openoffice.spreadsheet.MutableCell;
23
import org.openconcerto.openoffice.spreadsheet.Sheet;
24
import org.openconcerto.openoffice.spreadsheet.SpreadSheet;
25
import org.openconcerto.sql.Configuration;
26
import org.openconcerto.utils.ExceptionHandler;
27
import org.openconcerto.utils.StreamUtils;
28
 
29
import java.awt.Point;
30
import java.io.File;
31
import java.io.FileNotFoundException;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.util.ArrayList;
35
import java.util.HashMap;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.Map;
39
 
40
import javax.swing.JOptionPane;
41
import javax.swing.SwingUtilities;
42
 
43
import org.jopendocument.model.OpenDocument;
44
 
45
public abstract class SpreadSheetGenerator implements Runnable {
46
 
47
    private Map mCell, mapStyleRow;
48
 
49
    static private String modelDir;
50
    private String modele, destFileName;
51
    private File destDirOO, destDirPDF;
52
    protected int nbPage, nbRowsPerPage;
53
    private boolean visu, impression;
54
    private String printer;
55
    private boolean exportPDF;
56
    private Map mapReplaceText;
57
    private String fODSP = null;
58
 
59
    protected static final String defaultLocationTemplate = "/Configuration/Template/Default/";
60
 
61
    static {
62
        String loc = TemplateNXProps.getInstance().getStringProperty("LocationTemplate");
63
        if (loc.trim().length() == 0) {
64
            loc = defaultLocationTemplate;
65
        }
66
        setModelDir(loc);
67
    }
68
 
69
    public static void setModelDir(String loc) {
70
        modelDir = loc;
71
        System.err.println("Repertoire des template : " + modelDir);
72
    }
73
 
74
    protected void searchStyle(Sheet sheet, Map<String, Map<Integer, String>> mapStyleDef, int colEnd, int rowEnd) {
75
 
76
        // on parcourt chaque ligne de la feuille pour recuperer les styles
77
        int columnCount = (colEnd == -1) ? sheet.getColumnCount() : (colEnd + 1);
78
        System.err.println("End column search : " + columnCount);
79
 
80
        int rowCount = (rowEnd > 0) ? rowEnd : sheet.getRowCount();
81
        for (int i = 0; i < rowCount; i++) {
82
            int x = 0;
83
            Map<Integer, String> mapCellStyle = new HashMap<Integer, String>();
84
            String style = "";
85
 
86
            for (int j = 0; j < columnCount; j++) {
87
 
88
                if (sheet.isCellValid(j, i)) {
89
 
90
                    MutableCell c = sheet.getCellAt(j, i);
91
                    String cellStyle = c.getStyleName();
92
 
93
                    if (mapStyleDef.containsKey(c.getValue().toString())) {
94
                        style = c.getValue().toString();
95
 
96
                    }
97
 
98
                    mapCellStyle.put(new Integer(x), cellStyle);
99
                    if (style.trim().length() != 0) {
100
                        c.clearValue();
101
                    }
102
                }
103
                x++;
104
            }
105
 
106
            if (style.length() > 0) {
107
                mapStyleDef.put(style, mapCellStyle);
108
 
109
            }
110
        }
111
    }
112
 
113
    protected void fill(Sheet sheet, Map<String, Map<Integer, String>> mapStyleDef) {
114
 
115
        for (Iterator i = this.mCell.keySet().iterator(); i.hasNext();) {
116
 
117
            Object o = i.next();
118
            if (this.mCell.get(o) != null) {
119
                // System.err.println(o + " ---> " + m.get(o).toString());
120
                final Point p = sheet.resolveHint(o.toString());
121
                Object value = this.mCell.get(o);
122
                boolean cellValid = false;
123
                try {
124
                    cellValid = sheet.isCellValid(p.x, p.y);
125
                } catch (IndexOutOfBoundsException e) {
126
                    e.printStackTrace();
127
                }
128
                if (cellValid) {
129
                    MutableCell cell = sheet.getCellAt(p.x, p.y);
130
                    // on replace les retours a la ligne
131
                    final String stringValue = value.toString();
132
                    if (value != null && stringValue.indexOf('\n') >= 0) {
133
 
134
                        String firstPart = stringValue.substring(0, stringValue.indexOf('\n'));
135
                        String secondPart = stringValue.substring(stringValue.indexOf('\n') + 1, stringValue.length());
136
                        secondPart = secondPart.replace('\n', ',');
137
                        cell.setValue(firstPart);
138
 
139
                        try {
140
                            MutableCell cellSec = sheet.getCellAt(p.x, p.y + 1);
141
                            cellSec.setValue(secondPart);
142
                        } catch (Exception e) {
143
                            e.printStackTrace();
144
                            SwingUtilities.invokeLater(new Runnable() {
145
                                public void run() {
146
                                    JOptionPane.showMessageDialog(null, "Impossible d'accéder à la cellule " + p.x + ";" + (p.y + 1), "Erreur accés cellule", JOptionPane.INFORMATION_MESSAGE);
147
                                }
148
                            });
149
                        }
150
                    } else {
151
                        cell.setValue(((value == null) ? "" : value));
152
 
153
                        Object sty = this.mapStyleRow.get(new Integer(p.y + 1));
154
                        if (sty != null) {
155
                            Map<Integer, String> styleToApply = mapStyleDef.get(sty.toString());
156
                            if (styleToApply != null) {
157
 
158
                                if (styleToApply.get(new Integer(p.x)) != null) {
159
                                    cell.setStyleName(styleToApply.get(new Integer(p.x)));
160
                                }
161
                            }
162
                        }
163
                    }
164
                }
165
            }
166
        }
167
 
168
    }
169
 
170
    protected void replace(Sheet sheet) {
171
        for (Iterator i = this.mapReplaceText.keySet().iterator(); i.hasNext();) {
172
            Object o = i.next();
173
            if (this.mapReplaceText.get(o) != null) {
174
 
175
                Object value = this.mapReplaceText.get(o);
176
                MutableCell cell = sheet.getCellAt(o.toString());
177
 
178
                cell.replaceBy("_", ((value == null) ? "" : value.toString()));
179
            }
180
        }
181
    }
182
 
183
    protected SpreadSheet loadTemplate() throws IOException {
19 ilm 184
        InputStream f = getStreamStatic(modelDir + File.separator + this.modele);
185
        fODSP = modelDir + File.separator + this.modele + "p";
18 ilm 186
        if (f == null) {
19 ilm 187
            f = getStreamStatic(defaultLocationTemplate + File.separator + this.modele);
188
            fODSP = defaultLocationTemplate + File.separator + this.modele + "p";
18 ilm 189
            if (f == null) {
190
                ExceptionHandler.handle("Modele " + this.modele + " introuvable. Impossible de générer le document.");
19 ilm 191
                System.err.println("Modele introuvable : " + (defaultLocationTemplate + File.separator + this.modele));
18 ilm 192
                fODSP = null;
193
                return null;
194
            }
195
        }
25 ilm 196
        final SpreadSheet res = new ODPackage(f).getSpreadSheet();
18 ilm 197
        f.close();
198
        return res;
199
    }
200
 
201
    protected File save(SpreadSheet ssheet) throws IOException {
202
        File fDest = new File(this.destDirOO, this.destFileName + ".ods");
203
 
204
        int i = 0;
205
        String destName = this.destFileName;
206
 
207
        File oldPath = new File(this.destDirOO, "Historique");
208
        oldPath.mkdirs();
209
        while (fDest.exists()) {
210
            destName = this.destFileName + "_" + i;
211
            fDest = new File(oldPath, destName + ".ods");
212
            i++;
213
        }
214
        File fTmp = new File(this.destDirOO, this.destFileName + ".ods");
215
        fTmp.renameTo(fDest);
216
 
217
        fDest = new File(this.destDirOO, this.destFileName + ".ods");
218
        final InputStream stream = getStreamStatic(fODSP);
219
        if (stream != null) {
220
            // Copie de l'odsp
221
            File odspOut = new File(this.destDirOO, this.destFileName + ".odsp");
222
            StreamUtils.copy(stream, odspOut);
223
            stream.close();
224
 
225
        }
226
        try {
227
            ssheet.saveAs(fDest);
228
        } catch (FileNotFoundException e) {
229
            final File file = fDest;
230
            SwingUtilities.invokeLater(new Runnable() {
231
                public void run() {
232
                    try {
233
                        ExceptionHandler.handle("Le fichier " + ((file == null) ? "" : file.getCanonicalPath()) + " n'a pu être créé. \n Vérifiez qu'il n'est pas déjà ouvert.");
234
                    } catch (IOException e) {
235
                        e.printStackTrace();
236
                    }
237
                }
238
            });
239
 
240
            e.printStackTrace();
241
        }
242
        return fDest;
243
    }
244
 
245
    public SpreadSheetGenerator(SheetInterface sheet, String destFileName, boolean impr, boolean visu) {
246
        this(sheet, destFileName, impr, visu, true);
247
    }
248
 
249
    public SpreadSheetGenerator(SheetInterface sheet, String destFileName, boolean impr, boolean visu, boolean exportPDF) {
250
 
251
        this.modele = sheet.modele;
252
        this.mCell = sheet.mCell;
25 ilm 253
        this.destDirOO = sheet.getDocumentOutputDirectory();
18 ilm 254
        this.destDirOO.mkdirs();
25 ilm 255
        this.destDirPDF = sheet.getPDFOutputDirectory();
18 ilm 256
        this.destDirPDF.mkdirs();
257
        this.nbPage = sheet.nbPage;
258
        this.nbRowsPerPage = sheet.nbRowsPerPage;
259
        this.destFileName = destFileName;
260
        this.mapStyleRow = sheet.mapStyleRow;
261
        this.mapReplaceText = sheet.mapReplace;
262
        this.visu = visu;
263
        this.impression = impr;
264
        this.printer = sheet.getPrinter();
265
        this.exportPDF = exportPDF;
266
    }
267
 
268
    protected abstract File generateWithStyle() throws IOException;
269
 
270
    public void run() {
271
        File f = null;
272
        try {
273
 
274
            f = generateWithStyle();
25 ilm 275
            final File pdfFileToCreate = new File(this.destDirPDF.getAbsolutePath(), this.destFileName + ".pdf");
18 ilm 276
            try {
277
 
278
                if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
279
 
280
                    final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, !this.visu);
281
                    if (this.exportPDF) {
25 ilm 282
 
283
                        doc.saveToPDF(pdfFileToCreate);
18 ilm 284
                    }
285
 
286
                    if (this.impression) {
287
                        Map<String, Object> map = new HashMap<String, Object>();
288
                        map.put("Name", this.printer);
289
                        doc.printDocument(map);
290
 
291
                    }
292
                    doc.close();
293
                } else {
294
                    final OpenDocument doc = new OpenDocument(f);
295
                    if (this.visu) {
296
                        PreviewFrame.show(f);
297
                    }
298
 
25 ilm 299
                    SheetUtils.convert2PDF(doc, pdfFileToCreate);
18 ilm 300
                    if (this.impression) {
301
                        // Print !
302
                        DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
303
                        printer.print(doc);
304
                    }
305
 
306
                }
307
            } catch (Exception e) {
308
                e.printStackTrace();
309
                ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
310
            }
311
 
312
            // }
313
        } catch (IOException e) {
314
            e.printStackTrace();
315
            System.err.println("Fichier déjà ouvert!");
316
 
317
            final File ff = f;
318
            SwingUtilities.invokeLater(new Runnable() {
319
                public void run() {
320
                    ExceptionHandler.handle("Le fichier " + ((ff == null) ? "" : ff.getAbsolutePath()) + " n'a pu être créé. \n Vérifiez qu'il n'est pas déjà ouvert.");
321
                }
322
            });
323
        }
324
 
325
        fireGenerateEnd();
326
    }
327
 
328
    private final List<SpreadSheetGeneratorListener> listeners = new ArrayList<SpreadSheetGeneratorListener>();
329
 
330
    private void fireGenerateEnd() {
331
        for (SpreadSheetGeneratorListener listener : listeners) {
332
            listener.taskEnd();
333
        }
334
    }
335
 
336
    public void addGenerateListener(SpreadSheetGeneratorListener l) {
337
        this.listeners.add(l);
338
    }
339
}