OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Rev 182 | 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 org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.element.StyleSQLElement;
18
import org.openconcerto.openoffice.ODPackage;
19
import org.openconcerto.openoffice.spreadsheet.MutableCell;
20
import org.openconcerto.openoffice.spreadsheet.Sheet;
21
import org.openconcerto.openoffice.spreadsheet.SpreadSheet;
22
import org.openconcerto.sql.Configuration;
19 ilm 23
import org.openconcerto.sql.model.SQLRow;
18 ilm 24
import org.openconcerto.utils.ExceptionHandler;
25
import org.openconcerto.utils.StreamUtils;
73 ilm 26
import org.openconcerto.utils.StringUtils;
156 ilm 27
import org.openconcerto.utils.io.BOMSkipper;
18 ilm 28
 
29
import java.awt.Point;
156 ilm 30
import java.io.BufferedReader;
18 ilm 31
import java.io.File;
32
import java.io.FileNotFoundException;
33
import java.io.IOException;
34
import java.io.InputStream;
156 ilm 35
import java.io.InputStreamReader;
36
import java.nio.charset.Charset;
18 ilm 37
import java.util.HashMap;
38
import java.util.Iterator;
39
import java.util.List;
40
import java.util.Map;
41
 
42
import javax.swing.JOptionPane;
43
import javax.swing.SwingUtilities;
44
 
132 ilm 45
import org.jdom2.Document;
46
import org.jdom2.Element;
47
import org.jdom2.JDOMException;
48
import org.jdom2.input.SAXBuilder;
18 ilm 49
 
50
public class OOgenerationListeXML {
51
 
52
    // Cache pour la recherche des styles
53
    private static Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<Sheet, Map<String, Map<Integer, String>>>();
73 ilm 54
    private static Point testPoint = new Point(0, 0);
18 ilm 55
 
25 ilm 56
    public static File genere(String modele, File pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values) {
19 ilm 57
        return genere(modele, pathDest, fileDest, liste, values, new HashMap<Integer, Map<Integer, String>>(), null, null);
18 ilm 58
    }
59
 
25 ilm 60
    public static File genere(String templateId, File pathDest, String fileDest, Map<Integer, List<Map<String, Object>>> liste, Map<Integer, Map<String, Object>> values,
19 ilm 61
            Map<Integer, Map<Integer, String>> mapStyle, List<String> sheetName, SQLRow rowLanguage) {
18 ilm 62
        cacheStyle.clear();
25 ilm 63
        final SAXBuilder builder = new SAXBuilder();
18 ilm 64
        try {
25 ilm 65
            InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
80 ilm 66
            if (xmlConfiguration == null) {
149 ilm 67
                throw new IllegalStateException("Template configuration " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
80 ilm 68
            }
156 ilm 69
            final BufferedReader xmlConfigurationReader = new BufferedReader(new InputStreamReader(xmlConfiguration, Charset.forName("UTF8")));
70
            BOMSkipper.skip(xmlConfigurationReader);
71
            final Document doc = builder.build(xmlConfigurationReader);
72
            xmlConfigurationReader.close();
73
            xmlConfiguration.close();
18 ilm 74
 
19 ilm 75
            // On initialise un nouvel élément racine avec l'élément racine du
76
            // document.
25 ilm 77
            final Element racine = doc.getRootElement();
18 ilm 78
 
79
            // Création et génération du fichier OO
25 ilm 80
            final InputStream template = TemplateManager.getInstance().getTemplate(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);
149 ilm 81
            if (template == null) {
82
                throw new IllegalStateException("Template " + templateId + " not found (" + TemplateManager.getInstance().getClass().getName() + ")");
83
            }
25 ilm 84
            final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
156 ilm 85
 
18 ilm 86
            Sheet sheet0 = spreadSheet.getSheet(0);
87
            if (sheetName != null && sheetName.size() > 0) {
88
                for (int i = 1; i < sheetName.size(); i++) {
89
                    sheet0.copy(i, (sheetName != null) ? sheetName.get(i) : "Feuille " + i);
90
                }
91
                spreadSheet.getSheet(0).setName(sheetName.get(0));
92
            }
93
 
94
            for (Integer i : liste.keySet()) {
156 ilm 95
                final Sheet sheet;
96
                try {
97
                    sheet = spreadSheet.getSheet(i);
98
                } catch (Exception e) {
99
                    throw new InvalidTemplateException("La feuille numéro " + i + " n'est pas dans le modèle", e);
100
                }
18 ilm 101
                List children = racine.getChildren("element" + i);
102
                if (children.size() == 0) {
103
                    children = racine.getChildren("element");
104
                }
105
                parseElementsXML(children, sheet, values.get(i));
106
                Element child = racine.getChild("table" + i);
107
                if (child == null) {
108
                    child = racine.getChild("table");
109
                }
110
                parseListeXML(child, liste.get(i), sheet, mapStyle.get(i));
111
            }
73 ilm 112
            cacheStyle.clear();
156 ilm 113
 
18 ilm 114
            // Sauvegarde du fichier
25 ilm 115
            return saveSpreadSheet(spreadSheet, pathDest, fileDest, templateId, rowLanguage);
18 ilm 116
 
117
        } catch (JDOMException e) {
118
            ExceptionHandler.handle("Erreur lors de la génération du fichier " + fileDest, e);
119
        } catch (IOException e) {
120
            ExceptionHandler.handle("Erreur lors de la création du fichier " + fileDest, e);
121
        }
73 ilm 122
        cacheStyle.clear();
18 ilm 123
        return null;
124
    }
125
 
126
    private static void parseElementsXML(List<Element> elts, Sheet sheet, Map<String, Object> values) {
127
        if (values == null) {
128
            return;
129
        }
130
        for (Element elt : elts) {
131
 
132
            String name = elt.getAttributeValue("ValueName");
133
            Object result = values.get(name);
134
 
135
            if (result != null) {
73 ilm 136
                result = resizeValue(elt, result);
18 ilm 137
                boolean controlLine = elt.getAttributeValue("controleMultiline") == null ? true : !elt.getAttributeValue("controleMultiline").equalsIgnoreCase("false");
138
                boolean replace = elt.getAttributeValue("type").equalsIgnoreCase("Replace");
139
                String replacePattern = elt.getAttributeValue("replacePattern");
73 ilm 140
                fill(sheet.resolveHint(elt.getAttributeValue("location")), result, sheet, replace, replacePattern, null, false, controlLine);
18 ilm 141
            }
142
        }
143
    }
144
 
145
    /**
146
     * Remplit le tableau
147
     *
148
     * @param tableau
149
     * @param elt
150
     * @param id
151
     * @param sheet
152
     */
153
    private static void parseListeXML(Element tableau, List<Map<String, Object>> liste, Sheet sheet, Map<Integer, String> style) {
154
 
155
        if (liste == null || tableau == null) {
156
            return;
157
        }
158
        Object oLastColTmp = tableau.getAttributeValue("lastColumn");
159
        int lastColumn = -1;
160
        int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
161
        if (oLastColTmp != null) {
162
            lastColumn = sheet.resolveHint(oLastColTmp.toString() + 1).x + 1;
163
        }
164
        Map<String, Map<Integer, String>> mapStyle = searchStyle(sheet, lastColumn, endPageLine);
165
 
166
        int nbPage = fillTable(tableau, liste, sheet, mapStyle, true, style);
167
        int firstLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
168
        int endLine = Integer.valueOf(tableau.getAttributeValue("endLine"));
169
        Object printRangeObj = sheet.getPrintRanges();
170
 
171
        System.err.println("Nombre de page == " + nbPage);
172
        if (nbPage == 1) {
173
            fillTable(tableau, liste, sheet, mapStyle, false, style);
174
        } else {
175
 
176
            if (printRangeObj != null) {
177
                String s = printRangeObj.toString();
178
                String[] range = s.split(":");
179
 
180
                for (int i = 0; i < range.length; i++) {
181
                    String string = range[i];
182
                    range[i] = string.subSequence(string.indexOf('.') + 1, string.length()).toString();
183
                }
184
 
185
                int rowEnd = -1;
186
                if (range.length > 1) {
187
                    rowEnd = sheet.resolveHint(range[1]).y + 1;
188
                    int rowEndNew = rowEnd * (nbPage + 1);
189
                    String sNew = s.replaceAll(String.valueOf(rowEnd), String.valueOf(rowEndNew));
190
                    sheet.setPrintRanges(sNew);
191
                    System.err.println(" ******  Replace print ranges; Old:" + rowEnd + "--" + s + " New:" + rowEndNew + "--" + sNew);
192
                }
193
            }
194
 
195
            // le nombre d'éléments ne tient pas dans le tableau du modéle
196
            sheet.duplicateFirstRows(endLine, 1);
197
 
198
            int lineToAdd = endPageLine - endLine;
199
            sheet.insertDuplicatedRows(firstLine, lineToAdd);
200
 
201
            // On duplique la premiere page si on a besoin de plus de deux pages
202
            System.err.println("nbPage == " + nbPage);
203
            if (nbPage > 2) {
204
                sheet.duplicateFirstRows(endPageLine, nbPage - 2);
205
            }
61 ilm 206
            String pageRef = tableau.getAttributeValue("pageRef");
207
            if (pageRef != null && pageRef.trim().length() > 0) {
208
                MutableCell<SpreadSheet> cell = sheet.getCellAt(pageRef);
209
                cell.setValue("Page 1/" + nbPage);
210
                for (int i = 1; i < nbPage; i++) {
211
                    MutableCell<SpreadSheet> cell2 = sheet.getCellAt(cell.getX(), cell.getY() + (endPageLine * i));
212
                    cell2.setValue("Page " + (i + 1) + "/" + nbPage);
213
                }
214
            }
18 ilm 215
            fillTable(tableau, liste, sheet, mapStyle, false, style);
216
        }
217
    }
218
 
219
    /**
220
     * Remplit le tableau d'éléments avec les données
221
     *
222
     * @param tableau Element Xml contenant les informations sur le tableau
223
     * @param elt SQLElement (ex : Bon de livraison)
224
     * @param id id de l'élément de la table
225
     * @param sheet feuille calc à remplir
226
     * @param mapStyle styles trouvés dans la page
227
     * @param test remplir ou non avec les valeurs
228
     * @return le nombre de page
229
     */
230
    private static int fillTable(Element tableau, List<Map<String, Object>> liste, Sheet sheet, Map<String, Map<Integer, String>> mapStyle, boolean test, Map<Integer, String> style) {
231
 
232
        int nbPage = 1;
233
        int currentLineTmp = Integer.valueOf(tableau.getAttributeValue("firstLine"));
234
        int currentLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
235
        int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
236
 
237
        List listElts = tableau.getChildren("element");
238
 
239
        Object o = null;
240
        String columnSousTotal = tableau.getAttributeValue("groupSousTotalColumn");
241
 
242
        Map<String, Double> mapSousTotal = new HashMap<String, Double>();
243
        Map<String, Double> mapTotal = new HashMap<String, Double>();
244
 
245
        // on remplit chaque ligne à partir des rows recuperées
246
 
247
        for (int i = 0; i < liste.size(); i++) {
248
            Map<String, Object> mValues = liste.get(i);
249
            // System.err.println(mValues);
250
 
251
            String styleName = null;
252
            int nbCellule = 1;
253
            // on remplit chaque cellule de la ligne
254
            for (Iterator j = listElts.iterator(); j.hasNext();) {
255
 
73 ilm 256
                if ((currentLine - 1 + fill(testPoint, "test", sheet, false, null, null, true)) > (endPageLine * nbPage)) {
18 ilm 257
                    currentLine = currentLineTmp + endPageLine;
258
                    currentLineTmp = currentLine;
259
                    nbPage++;
260
                }
261
 
262
                Element e = (Element) j.next();
263
                String loc = e.getAttributeValue("location").trim() + currentLine;
264
                boolean controlLine = e.getAttributeValue("controleMultiline") == null ? true : !e.getAttributeValue("controleMultiline").equalsIgnoreCase("false");
265
                // Type normaux fill ou replace
266
                if (e.getAttributeValue("type").equalsIgnoreCase("fill") || e.getAttributeValue("type").equalsIgnoreCase("replace")) {
267
 
268
                    Object value = getElementValue(e, mValues);
73 ilm 269
                    Point resolveHint = sheet.resolveHint(loc);
18 ilm 270
                    if (e.getAttributeValue("location").trim().equals(columnSousTotal)) {
271
                        if (o != null) {
272
                            if (!o.equals(value)) {
273
                                for (String object : mapSousTotal.keySet()) {
274
                                    System.err.println(object + " = " + mapSousTotal.get(object));
275
                                    String styleSousTotalName = "Titre 1";
276
                                    if (style != null && style.get(i) != null) {
277
                                        styleSousTotalName = style.get(i);
278
                                    }
279
                                    Map<Integer, String> mTmp = mapStyle.get(styleSousTotalName);
280
                                    String styleOO = null;
281
                                    String styleOOA = null;
282
                                    if (mTmp != null) {
283
 
73 ilm 284
                                        Object oTmp = mTmp.get(Integer.valueOf(resolveHint.x));
18 ilm 285
                                        styleOO = oTmp == null ? null : oTmp.toString();
286
                                        Object oTmpA = mTmp.get(Integer.valueOf(0));
287
                                        styleOOA = oTmpA == null ? null : oTmpA.toString();
288
                                    }
73 ilm 289
                                    fill(test ? testPoint : sheet.resolveHint("A" + currentLine), "Sous total", sheet, false, null, styleOOA, test, controlLine);
290
                                    fill(test ? testPoint : sheet.resolveHint(object + "" + currentLine), mapSousTotal.get(object), sheet, false, null, styleOO, test, controlLine);
18 ilm 291
                                }
292
                                mapSousTotal.clear();
73 ilm 293
                                currentLine += 2;
18 ilm 294
                                loc = e.getAttributeValue("location").trim() + currentLine;
73 ilm 295
                                resolveHint = sheet.resolveHint(loc);
18 ilm 296
                                o = value;
297
                            }
298
                        } else {
299
                            o = value;
300
                        }
301
                    }
73 ilm 302
                    if (value instanceof Number) {
18 ilm 303
                        final String attributeValue = e.getAttributeValue("total");
304
                        if (attributeValue != null && attributeValue.equalsIgnoreCase("true")) {
73 ilm 305
                            incrementTotal(e.getAttributeValue("location"), (Number) value, mapTotal);
18 ilm 306
                        }
307
 
308
                        final String attributeValue2 = e.getAttributeValue("sousTotal");
309
                        if (attributeValue2 != null && attributeValue2.equalsIgnoreCase("true")) {
73 ilm 310
                            incrementTotal(e.getAttributeValue("location"), (Number) value, mapSousTotal);
18 ilm 311
                        }
312
                    }
313
                    boolean replace = e.getAttributeValue("type").equalsIgnoreCase("replace");
314
 
73 ilm 315
                    if (test || sheet.isCellValid(resolveHint.x, resolveHint.y)) {
18 ilm 316
                        if (style != null) {
317
                            styleName = style.get(i);
318
                        }
319
                        Map mTmp = styleName == null ? null : (Map) mapStyle.get(styleName);
320
                        String styleOO = null;
321
                        if (mTmp != null) {
322
 
73 ilm 323
                            Object oTmp = mTmp.get(new Integer(resolveHint.x));
18 ilm 324
                            styleOO = oTmp == null ? null : oTmp.toString();
61 ilm 325
                            // System.err.println("Set style " + styleOO);
18 ilm 326
                        }
327
 
73 ilm 328
                        int tmpCelluleAffect = fill(test ? testPoint : resolveHint, value, sheet, replace, null, styleOO, test, controlLine);
18 ilm 329
                        nbCellule = Math.max(nbCellule, tmpCelluleAffect);
330
                    } else {
331
                        System.err.println("Cell not valid at " + loc);
332
                    }
333
                }
334
            }
335
            currentLine += nbCellule;
336
 
337
        }
338
        for (String object : mapSousTotal.keySet()) {
339
            System.err.println(object + " = " + mapSousTotal.get(object));
340
            Map<Integer, String> mTmp = mapStyle.get("Titre 1");
341
            String styleOO = null;
342
            String styleOOA = null;
343
            if (mTmp != null) {
344
 
345
                Object oTmp = mTmp.get(Integer.valueOf(sheet.resolveHint(object + "" + currentLine).x));
346
                styleOO = oTmp == null ? null : oTmp.toString();
347
                Object oTmpA = mTmp.get(Integer.valueOf(0));
348
                styleOOA = oTmpA == null ? null : oTmpA.toString();
349
            }
350
 
73 ilm 351
            fill(test ? testPoint : sheet.resolveHint("A" + currentLine), "Sous total", sheet, false, null, styleOOA, test);
352
            fill(test ? testPoint : sheet.resolveHint(object + "" + currentLine), mapSousTotal.get(object), sheet, false, null, styleOO, test);
18 ilm 353
        }
354
        for (String object : mapTotal.keySet()) {
355
            System.err.println(object + " = " + mapTotal.get(object));
356
            Map<Integer, String> mTmp = mapStyle.get("Titre 1");
357
            String styleOO = null;
358
            String styleOOA = null;
359
            if (mTmp != null) {
360
 
361
                Object oTmp = mTmp.get(Integer.valueOf(sheet.resolveHint(object + "" + (currentLine + 1)).x));
362
                styleOO = oTmp == null ? null : oTmp.toString();
363
                Object oTmpA = mTmp.get(Integer.valueOf(0));
364
                styleOOA = oTmpA == null ? null : oTmpA.toString();
365
            }
73 ilm 366
            fill(test ? testPoint : sheet.resolveHint("A" + (currentLine + 1)), "Total", sheet, false, null, styleOOA, test);
367
            fill(test ? testPoint : sheet.resolveHint(object + "" + (currentLine + 1)), mapTotal.get(object), sheet, false, null, styleOO, test);
18 ilm 368
        }
369
        return nbPage;
370
    }
371
 
73 ilm 372
    private static void incrementTotal(String field, Number value, Map<String, Double> map) {
18 ilm 373
        Double d = map.get(field);
374
        if (d == null) {
73 ilm 375
            map.put(field, value.doubleValue());
18 ilm 376
        } else {
73 ilm 377
            map.put(field, d + value.doubleValue());
18 ilm 378
        }
379
    }
380
 
381
    private static Object getElementValue(Element elt, Map<String, Object> mValues) {
382
        Object res = "";
383
 
384
        final List eltFields = elt.getChildren("field");
385
 
386
        if (eltFields != null) {
387
            if (eltFields.size() > 1) {
388
                String result = "";
389
                for (Iterator j = eltFields.iterator(); j.hasNext();) {
390
                    Object o = getValueOfComposant((Element) j.next(), mValues);
391
                    if (o != null) {
392
                        result += o.toString() + " ";
393
                    }
394
                }
395
                res = result;
396
            } else {
397
                res = getValueOfComposant((Element) eltFields.get(0), mValues);
398
            }
399
        }
73 ilm 400
        res = resizeValue(elt, res);
401
        return res;
402
    }
403
 
404
    private static Object resizeValue(Element elt, Object res) {
405
        {
406
            String attributeValueMaxChar = elt.getAttributeValue("maxChar");
407
            if (attributeValueMaxChar != null) {
408
                int maxChar = Integer.valueOf(attributeValueMaxChar);
409
                if (res != null && res.toString().length() > maxChar) {
410
                    res = res.toString().substring(0, maxChar);
411
                }
65 ilm 412
            }
413
        }
73 ilm 414
        {
415
            String attributeValueCellSize = elt.getAttributeValue("cellSize");
416
            if (attributeValueCellSize != null) {
417
                int size = Integer.valueOf(attributeValueCellSize);
418
                if (res != null && res.toString().length() > size) {
419
                    try {
420
                        res = StringUtils.splitString(res.toString(), size);
421
                    } catch (NumberFormatException e) {
422
                        e.printStackTrace();
423
                    }
424
 
425
                }
426
            }
427
        }
18 ilm 428
        return res;
429
    }
430
 
431
    /**
432
     * permet d'obtenir la valeur d'un élément field
433
     *
434
     * @param eltField
435
     * @param row
436
     * @param elt
437
     * @param id
438
     * @return value of composant
439
     */
440
    private static Object getValueOfComposant(Element eltField, Map<String, Object> mValues) {
441
 
442
        String field = eltField.getAttributeValue("name");
443
 
444
        return mValues.get(field);
445
    }
446
 
73 ilm 447
    private static int fill(Point resolveHint, Object value, Sheet sheet, boolean replace, String replacePattern, String styleOO, boolean test) {
448
        return fill(resolveHint, value, sheet, replace, replacePattern, styleOO, test, true);
18 ilm 449
    }
450
 
451
    /**
452
     * Permet de remplir une cellule
453
     *
454
     * @param location position de la cellule exemple : A3
455
     * @param value valeur à insérer dans la cellule
456
     * @param sheet feuille sur laquelle on travaille
457
     * @param replace efface ou non le contenu original de la cellule
458
     * @param styleOO style à appliquer
459
     */
73 ilm 460
    private static int fill(Point resolveHint, Object value, Sheet sheet, boolean replace, String replacePattern, String styleOO, boolean test, boolean controlLine) {
18 ilm 461
 
462
        int nbCellule = 1;
463
        // est ce que la cellule est valide
73 ilm 464
        if (test || sheet.isCellValid(resolveHint.x, resolveHint.y)) {
18 ilm 465
 
466
            // on divise en 2 cellules si il y a des retours à la ligne
467
            if (controlLine && (value != null && value.toString().indexOf('\n') >= 0)) {
73 ilm 468
                String[] values = value.toString().split("\n");
18 ilm 469
                if (!test) {
470
 
73 ilm 471
                    int y = 0;
472
                    for (String string : values) {
473
                        if (string != null && string.trim().length() != 0) {
474
                            try {
475
                                MutableCell c = sheet.getCellAt(resolveHint.x, resolveHint.y + y);
476
                                setCellValue(c, string, replace, replacePattern);
477
                                if (styleOO != null) {
478
                                    c.setStyleName(styleOO);
479
                                }
480
                                y++;
481
                            } catch (IllegalArgumentException e) {
177 ilm 482
                                SwingUtilities.invokeLater(new Runnable() {
483
 
484
                                    @Override
485
                                    public void run() {
486
                                        System.err.println(resolveHint + " : " + value);
487
                                        JOptionPane.showMessageDialog(null, "La cellule " + resolveHint + " n'existe pas ou est fusionnée.", "Erreur pendant la génération", JOptionPane.ERROR_MESSAGE);
488
                                    }
489
                                });
73 ilm 490
                            }
491
                        }
19 ilm 492
                    }
18 ilm 493
                }
73 ilm 494
 
495
                nbCellule = values.length;
18 ilm 496
            } else {
497
                if (!test) {
73 ilm 498
                    MutableCell cell = sheet.getCellAt(resolveHint.x, resolveHint.y);
18 ilm 499
                    // application de la valeur
500
                    setCellValue(cell, value, replace, replacePattern);
501
 
502
                    // Application du style
503
                    if (styleOO != null) {
504
                        cell.setStyleName(styleOO);
505
                    }
506
                }
507
            }
508
        }
509
        return nbCellule;
510
    }
511
 
512
    /**
513
     * remplit une cellule
514
     *
515
     * @param cell
516
     * @param value
517
     * @param replace
518
     */
519
    private static void setCellValue(MutableCell cell, Object value, boolean replace, String replacePattern) {
520
        if (value == null) {
521
            value = "";
522
        }
523
 
524
        if (replace) {
525
            if (replacePattern != null) {
526
                cell.replaceBy(replacePattern, value.toString());
527
            } else {
528
                cell.replaceBy("_", value.toString());
529
            }
530
        } else {
531
            cell.setValue(value);
532
        }
533
    }
534
 
535
    /**
536
     * Sauver le document au format OpenOffice. Si le fichier existe déjà, le fichier existant sera
537
     * renommé sous la forme nomFic_1.sxc.
538
     *
539
     * @param ssheet SpreadSheet à sauvegarder
540
     * @param pathDest répertoire de destination du fichier
541
     * @param fileName nom du fichier à créer
542
     * @return un File pointant sur le fichier créé
543
     * @throws IOException
544
     */
25 ilm 545
    private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage) throws IOException {
18 ilm 546
 
547
        // Test des arguments
548
        if (ssheet == null || pathDest == null || fileName.trim().length() == 0) {
549
            throw new IllegalArgumentException();
550
        }
551
 
552
        // Renommage du fichier si il existe déja
553
        File fDest = new File(pathDest, fileName + ".ods");
554
 
555
        if (!pathDest.exists()) {
556
            pathDest.mkdirs();
557
        }
558
 
57 ilm 559
        SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, pathDest, fDest);
18 ilm 560
 
561
        // Sauvegarde
562
        try {
563
            ssheet.saveAs(fDest);
564
        } catch (FileNotFoundException e) {
565
            final File F = fDest;
566
            SwingUtilities.invokeLater(new Runnable() {
567
                public void run() {
568
                    try {
569
                        JOptionPane.showMessageDialog(null, "Le fichier " + F.getCanonicalPath() + " n'a pu être créé. \n Vérifiez qu'il n'est pas déjà ouvert.");
570
                    } catch (IOException e) {
571
                        e.printStackTrace();
572
                    }
573
                }
574
            });
575
 
576
            e.printStackTrace();
577
        }
578
 
579
        // Copie de l'odsp
156 ilm 580
        File odspOut = new File(pathDest, fileName + ".odsp");
581
        try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);) {
18 ilm 582
            if (odspIn != null) {
583
                StreamUtils.copy(odspIn, odspOut);
584
            }
585
        } catch (FileNotFoundException e) {
586
            System.err.println("Le fichier odsp n'existe pas.");
587
        }
588
 
589
        return fDest;
590
    }
591
 
592
    /**
593
     * parcourt l'ensemble de la feuille pour trouver les style définit
594
     */
595
    private static Map<String, Map<Integer, String>> searchStyle(Sheet sheet, int colEnd, int rowEnd) {
596
 
597
        if (cacheStyle.get(sheet) != null) {
598
            return cacheStyle.get(sheet);
599
        }
600
 
601
        Map<String, Map<Integer, String>> mapStyleDef = StyleSQLElement.getMapAllStyle();
602
 
93 ilm 603
        Map<String, Map<Integer, String>> mapStyleFounded = new HashMap<String, Map<Integer, String>>();
604
 
18 ilm 605
        // on parcourt chaque ligne de la feuille pour recuperer les styles
606
        int columnCount = (colEnd == -1) ? sheet.getColumnCount() : (colEnd + 1);
607
        System.err.println("End column search : " + columnCount);
608
 
609
        int rowCount = (rowEnd > 0) ? rowEnd : sheet.getRowCount();
93 ilm 610
 
18 ilm 611
        System.err.println("End row search : " + rowCount);
93 ilm 612
        for (int i = 0; i < rowCount && (mapStyleDef.keySet().size() - 2) > mapStyleFounded.keySet().size(); i++) {
613
 
18 ilm 614
            int x = 0;
615
            Map<Integer, String> mapCellStyle = new HashMap<Integer, String>();
616
            String style = "";
617
 
618
            for (int j = 0; j < columnCount; j++) {
619
 
620
                try {
621
                    if (sheet.isCellValid(j, i)) {
622
 
623
                        MutableCell c = sheet.getCellAt(j, i);
624
                        String cellStyle = c.getStyleName();
625
 
626
                        try {
627
                            if (mapStyleDef.containsKey(c.getValue().toString())) {
628
                                style = c.getValue().toString();
629
                            }
630
                        } catch (IllegalStateException e) {
631
                            e.printStackTrace();
632
                        }
633
                        mapCellStyle.put(Integer.valueOf(x), cellStyle);
93 ilm 634
                        if (style.trim().length() > 0) {
18 ilm 635
                            c.clearValue();
636
                            if (!style.trim().equalsIgnoreCase("Normal") && mapStyleDef.get("Normal") != null) {
637
                                String styleCell = mapStyleDef.get("Normal").get(Integer.valueOf(x));
638
                                if (styleCell != null && styleCell.length() != 0) {
639
                                    c.setStyleName(styleCell);
640
                                }
641
                            }
93 ilm 642
 
643
                            mapStyleFounded.put(style, mapCellStyle);
644
 
18 ilm 645
                        }
646
                    }
647
                } catch (IndexOutOfBoundsException e) {
648
                    System.err.println("Index out of bounds Exception");
649
                }
650
                x++;
651
            }
652
 
653
        }
93 ilm 654
        cacheStyle.put(sheet, mapStyleFounded);
655
        return mapStyleFounded;
18 ilm 656
    }
657
 
658
    public static void main(String[] args) {
659
        ComptaPropsConfiguration conf = ComptaPropsConfiguration.create();
660
        System.err.println("Conf created");
661
        Configuration.setInstance(conf);
662
        conf.setUpSocieteDataBaseConnexion(36);
663
        System.err.println("Connection Set up");
664
 
665
        System.err.println("Start Genere");
666
        // genere("Devis", "C:\\", "Test", elt, 19);
667
        System.err.println("Stop genere");
668
    }
669
}