OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | 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
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
18 ilm 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
                if (range.length > 1) {
182 ilm 186
                    int rowEnd = sheet.resolveHint(range[1]).y + 1;
187
                    int rowEndNew = rowEnd * nbPage;
18 ilm 188
                    String sNew = s.replaceAll(String.valueOf(rowEnd), String.valueOf(rowEndNew));
189
                    sheet.setPrintRanges(sNew);
182 ilm 190
                    System.err.println("OOgenerationListXML ******  Replace print ranges; Old:" + rowEnd + "--" + s + " New:" + rowEndNew + "--" + sNew);
18 ilm 191
                }
192
            }
193
 
194
            // le nombre d'éléments ne tient pas dans le tableau du modéle
195
            sheet.duplicateFirstRows(endLine, 1);
196
 
197
            int lineToAdd = endPageLine - endLine;
198
            sheet.insertDuplicatedRows(firstLine, lineToAdd);
199
 
200
            // On duplique la premiere page si on a besoin de plus de deux pages
201
            System.err.println("nbPage == " + nbPage);
202
            if (nbPage > 2) {
203
                sheet.duplicateFirstRows(endPageLine, nbPage - 2);
204
            }
61 ilm 205
            String pageRef = tableau.getAttributeValue("pageRef");
206
            if (pageRef != null && pageRef.trim().length() > 0) {
207
                MutableCell<SpreadSheet> cell = sheet.getCellAt(pageRef);
208
                cell.setValue("Page 1/" + nbPage);
209
                for (int i = 1; i < nbPage; i++) {
210
                    MutableCell<SpreadSheet> cell2 = sheet.getCellAt(cell.getX(), cell.getY() + (endPageLine * i));
211
                    cell2.setValue("Page " + (i + 1) + "/" + nbPage);
212
                }
213
            }
18 ilm 214
            fillTable(tableau, liste, sheet, mapStyle, false, style);
215
        }
216
    }
217
 
218
    /**
219
     * Remplit le tableau d'éléments avec les données
220
     *
221
     * @param tableau Element Xml contenant les informations sur le tableau
222
     * @param elt SQLElement (ex : Bon de livraison)
223
     * @param id id de l'élément de la table
224
     * @param sheet feuille calc à remplir
225
     * @param mapStyle styles trouvés dans la page
226
     * @param test remplir ou non avec les valeurs
227
     * @return le nombre de page
228
     */
229
    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) {
230
 
231
        int nbPage = 1;
232
        int currentLineTmp = Integer.valueOf(tableau.getAttributeValue("firstLine"));
233
        int currentLine = Integer.valueOf(tableau.getAttributeValue("firstLine"));
234
        int endPageLine = Integer.valueOf(tableau.getAttributeValue("endPageLine"));
235
 
236
        List listElts = tableau.getChildren("element");
237
 
238
        Object o = null;
239
        String columnSousTotal = tableau.getAttributeValue("groupSousTotalColumn");
240
 
241
        Map<String, Double> mapSousTotal = new HashMap<String, Double>();
242
        Map<String, Double> mapTotal = new HashMap<String, Double>();
243
 
244
        // on remplit chaque ligne à partir des rows recuperées
245
 
246
        for (int i = 0; i < liste.size(); i++) {
247
            Map<String, Object> mValues = liste.get(i);
248
            // System.err.println(mValues);
249
 
250
            String styleName = null;
251
            int nbCellule = 1;
252
            // on remplit chaque cellule de la ligne
253
            for (Iterator j = listElts.iterator(); j.hasNext();) {
254
 
73 ilm 255
                if ((currentLine - 1 + fill(testPoint, "test", sheet, false, null, null, true)) > (endPageLine * nbPage)) {
18 ilm 256
                    currentLine = currentLineTmp + endPageLine;
257
                    currentLineTmp = currentLine;
258
                    nbPage++;
259
                }
260
 
261
                Element e = (Element) j.next();
262
                String loc = e.getAttributeValue("location").trim() + currentLine;
263
                boolean controlLine = e.getAttributeValue("controleMultiline") == null ? true : !e.getAttributeValue("controleMultiline").equalsIgnoreCase("false");
264
                // Type normaux fill ou replace
265
                if (e.getAttributeValue("type").equalsIgnoreCase("fill") || e.getAttributeValue("type").equalsIgnoreCase("replace")) {
266
 
267
                    Object value = getElementValue(e, mValues);
73 ilm 268
                    Point resolveHint = sheet.resolveHint(loc);
18 ilm 269
                    if (e.getAttributeValue("location").trim().equals(columnSousTotal)) {
270
                        if (o != null) {
271
                            if (!o.equals(value)) {
272
                                for (String object : mapSousTotal.keySet()) {
273
                                    System.err.println(object + " = " + mapSousTotal.get(object));
274
                                    String styleSousTotalName = "Titre 1";
275
                                    if (style != null && style.get(i) != null) {
276
                                        styleSousTotalName = style.get(i);
277
                                    }
278
                                    Map<Integer, String> mTmp = mapStyle.get(styleSousTotalName);
279
                                    String styleOO = null;
280
                                    String styleOOA = null;
281
                                    if (mTmp != null) {
282
 
73 ilm 283
                                        Object oTmp = mTmp.get(Integer.valueOf(resolveHint.x));
18 ilm 284
                                        styleOO = oTmp == null ? null : oTmp.toString();
285
                                        Object oTmpA = mTmp.get(Integer.valueOf(0));
286
                                        styleOOA = oTmpA == null ? null : oTmpA.toString();
287
                                    }
73 ilm 288
                                    fill(test ? testPoint : sheet.resolveHint("A" + currentLine), "Sous total", sheet, false, null, styleOOA, test, controlLine);
289
                                    fill(test ? testPoint : sheet.resolveHint(object + "" + currentLine), mapSousTotal.get(object), sheet, false, null, styleOO, test, controlLine);
18 ilm 290
                                }
291
                                mapSousTotal.clear();
73 ilm 292
                                currentLine += 2;
18 ilm 293
                                loc = e.getAttributeValue("location").trim() + currentLine;
73 ilm 294
                                resolveHint = sheet.resolveHint(loc);
18 ilm 295
                                o = value;
296
                            }
297
                        } else {
298
                            o = value;
299
                        }
300
                    }
73 ilm 301
                    if (value instanceof Number) {
18 ilm 302
                        final String attributeValue = e.getAttributeValue("total");
303
                        if (attributeValue != null && attributeValue.equalsIgnoreCase("true")) {
73 ilm 304
                            incrementTotal(e.getAttributeValue("location"), (Number) value, mapTotal);
18 ilm 305
                        }
306
 
307
                        final String attributeValue2 = e.getAttributeValue("sousTotal");
308
                        if (attributeValue2 != null && attributeValue2.equalsIgnoreCase("true")) {
73 ilm 309
                            incrementTotal(e.getAttributeValue("location"), (Number) value, mapSousTotal);
18 ilm 310
                        }
311
                    }
312
                    boolean replace = e.getAttributeValue("type").equalsIgnoreCase("replace");
313
 
73 ilm 314
                    if (test || sheet.isCellValid(resolveHint.x, resolveHint.y)) {
18 ilm 315
                        if (style != null) {
316
                            styleName = style.get(i);
317
                        }
318
                        Map mTmp = styleName == null ? null : (Map) mapStyle.get(styleName);
319
                        String styleOO = null;
320
                        if (mTmp != null) {
321
 
73 ilm 322
                            Object oTmp = mTmp.get(new Integer(resolveHint.x));
18 ilm 323
                            styleOO = oTmp == null ? null : oTmp.toString();
61 ilm 324
                            // System.err.println("Set style " + styleOO);
18 ilm 325
                        }
326
 
73 ilm 327
                        int tmpCelluleAffect = fill(test ? testPoint : resolveHint, value, sheet, replace, null, styleOO, test, controlLine);
18 ilm 328
                        nbCellule = Math.max(nbCellule, tmpCelluleAffect);
329
                    } else {
330
                        System.err.println("Cell not valid at " + loc);
331
                    }
332
                }
333
            }
334
            currentLine += nbCellule;
335
 
336
        }
337
        for (String object : mapSousTotal.keySet()) {
338
            System.err.println(object + " = " + mapSousTotal.get(object));
339
            Map<Integer, String> mTmp = mapStyle.get("Titre 1");
340
            String styleOO = null;
341
            String styleOOA = null;
342
            if (mTmp != null) {
343
 
344
                Object oTmp = mTmp.get(Integer.valueOf(sheet.resolveHint(object + "" + currentLine).x));
345
                styleOO = oTmp == null ? null : oTmp.toString();
346
                Object oTmpA = mTmp.get(Integer.valueOf(0));
347
                styleOOA = oTmpA == null ? null : oTmpA.toString();
348
            }
349
 
73 ilm 350
            fill(test ? testPoint : sheet.resolveHint("A" + currentLine), "Sous total", sheet, false, null, styleOOA, test);
351
            fill(test ? testPoint : sheet.resolveHint(object + "" + currentLine), mapSousTotal.get(object), sheet, false, null, styleOO, test);
18 ilm 352
        }
353
        for (String object : mapTotal.keySet()) {
354
            System.err.println(object + " = " + mapTotal.get(object));
355
            Map<Integer, String> mTmp = mapStyle.get("Titre 1");
356
            String styleOO = null;
357
            String styleOOA = null;
358
            if (mTmp != null) {
359
 
360
                Object oTmp = mTmp.get(Integer.valueOf(sheet.resolveHint(object + "" + (currentLine + 1)).x));
361
                styleOO = oTmp == null ? null : oTmp.toString();
362
                Object oTmpA = mTmp.get(Integer.valueOf(0));
363
                styleOOA = oTmpA == null ? null : oTmpA.toString();
364
            }
73 ilm 365
            fill(test ? testPoint : sheet.resolveHint("A" + (currentLine + 1)), "Total", sheet, false, null, styleOOA, test);
366
            fill(test ? testPoint : sheet.resolveHint(object + "" + (currentLine + 1)), mapTotal.get(object), sheet, false, null, styleOO, test);
18 ilm 367
        }
368
        return nbPage;
369
    }
370
 
73 ilm 371
    private static void incrementTotal(String field, Number value, Map<String, Double> map) {
18 ilm 372
        Double d = map.get(field);
373
        if (d == null) {
73 ilm 374
            map.put(field, value.doubleValue());
18 ilm 375
        } else {
73 ilm 376
            map.put(field, d + value.doubleValue());
18 ilm 377
        }
378
    }
379
 
380
    private static Object getElementValue(Element elt, Map<String, Object> mValues) {
381
        Object res = "";
382
 
383
        final List eltFields = elt.getChildren("field");
384
 
385
        if (eltFields != null) {
386
            if (eltFields.size() > 1) {
387
                String result = "";
388
                for (Iterator j = eltFields.iterator(); j.hasNext();) {
389
                    Object o = getValueOfComposant((Element) j.next(), mValues);
390
                    if (o != null) {
391
                        result += o.toString() + " ";
392
                    }
393
                }
394
                res = result;
395
            } else {
396
                res = getValueOfComposant((Element) eltFields.get(0), mValues);
397
            }
398
        }
73 ilm 399
        res = resizeValue(elt, res);
400
        return res;
401
    }
402
 
403
    private static Object resizeValue(Element elt, Object res) {
404
        {
405
            String attributeValueMaxChar = elt.getAttributeValue("maxChar");
406
            if (attributeValueMaxChar != null) {
407
                int maxChar = Integer.valueOf(attributeValueMaxChar);
408
                if (res != null && res.toString().length() > maxChar) {
409
                    res = res.toString().substring(0, maxChar);
410
                }
65 ilm 411
            }
412
        }
73 ilm 413
        {
414
            String attributeValueCellSize = elt.getAttributeValue("cellSize");
415
            if (attributeValueCellSize != null) {
416
                int size = Integer.valueOf(attributeValueCellSize);
417
                if (res != null && res.toString().length() > size) {
418
                    try {
419
                        res = StringUtils.splitString(res.toString(), size);
420
                    } catch (NumberFormatException e) {
421
                        e.printStackTrace();
422
                    }
423
 
424
                }
425
            }
426
        }
18 ilm 427
        return res;
428
    }
429
 
430
    /**
431
     * permet d'obtenir la valeur d'un élément field
432
     *
433
     * @param eltField
434
     * @param row
435
     * @param elt
436
     * @param id
437
     * @return value of composant
438
     */
439
    private static Object getValueOfComposant(Element eltField, Map<String, Object> mValues) {
440
 
441
        String field = eltField.getAttributeValue("name");
442
 
443
        return mValues.get(field);
444
    }
445
 
73 ilm 446
    private static int fill(Point resolveHint, Object value, Sheet sheet, boolean replace, String replacePattern, String styleOO, boolean test) {
447
        return fill(resolveHint, value, sheet, replace, replacePattern, styleOO, test, true);
18 ilm 448
    }
449
 
450
    /**
451
     * Permet de remplir une cellule
452
     *
453
     * @param location position de la cellule exemple : A3
454
     * @param value valeur à insérer dans la cellule
455
     * @param sheet feuille sur laquelle on travaille
456
     * @param replace efface ou non le contenu original de la cellule
457
     * @param styleOO style à appliquer
458
     */
73 ilm 459
    private static int fill(Point resolveHint, Object value, Sheet sheet, boolean replace, String replacePattern, String styleOO, boolean test, boolean controlLine) {
18 ilm 460
 
461
        int nbCellule = 1;
462
        // est ce que la cellule est valide
73 ilm 463
        if (test || sheet.isCellValid(resolveHint.x, resolveHint.y)) {
18 ilm 464
 
465
            // on divise en 2 cellules si il y a des retours à la ligne
466
            if (controlLine && (value != null && value.toString().indexOf('\n') >= 0)) {
73 ilm 467
                String[] values = value.toString().split("\n");
18 ilm 468
                if (!test) {
469
 
73 ilm 470
                    int y = 0;
471
                    for (String string : values) {
472
                        if (string != null && string.trim().length() != 0) {
473
                            try {
474
                                MutableCell c = sheet.getCellAt(resolveHint.x, resolveHint.y + y);
475
                                setCellValue(c, string, replace, replacePattern);
476
                                if (styleOO != null) {
477
                                    c.setStyleName(styleOO);
478
                                }
479
                                y++;
480
                            } catch (IllegalArgumentException e) {
177 ilm 481
                                SwingUtilities.invokeLater(new Runnable() {
482
 
483
                                    @Override
484
                                    public void run() {
485
                                        System.err.println(resolveHint + " : " + value);
486
                                        JOptionPane.showMessageDialog(null, "La cellule " + resolveHint + " n'existe pas ou est fusionnée.", "Erreur pendant la génération", JOptionPane.ERROR_MESSAGE);
487
                                    }
488
                                });
73 ilm 489
                            }
490
                        }
19 ilm 491
                    }
18 ilm 492
                }
73 ilm 493
 
494
                nbCellule = values.length;
18 ilm 495
            } else {
496
                if (!test) {
73 ilm 497
                    MutableCell cell = sheet.getCellAt(resolveHint.x, resolveHint.y);
18 ilm 498
                    // application de la valeur
499
                    setCellValue(cell, value, replace, replacePattern);
500
 
501
                    // Application du style
502
                    if (styleOO != null) {
503
                        cell.setStyleName(styleOO);
504
                    }
505
                }
506
            }
507
        }
508
        return nbCellule;
509
    }
510
 
511
    /**
512
     * remplit une cellule
513
     *
514
     * @param cell
515
     * @param value
516
     * @param replace
517
     */
518
    private static void setCellValue(MutableCell cell, Object value, boolean replace, String replacePattern) {
519
        if (value == null) {
520
            value = "";
521
        }
522
 
523
        if (replace) {
524
            if (replacePattern != null) {
525
                cell.replaceBy(replacePattern, value.toString());
526
            } else {
527
                cell.replaceBy("_", value.toString());
528
            }
529
        } else {
530
            cell.setValue(value);
531
        }
532
    }
533
 
534
    /**
535
     * Sauver le document au format OpenOffice. Si le fichier existe déjà, le fichier existant sera
536
     * renommé sous la forme nomFic_1.sxc.
537
     *
538
     * @param ssheet SpreadSheet à sauvegarder
539
     * @param pathDest répertoire de destination du fichier
540
     * @param fileName nom du fichier à créer
541
     * @return un File pointant sur le fichier créé
542
     * @throws IOException
543
     */
25 ilm 544
    private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage) throws IOException {
18 ilm 545
 
546
        // Test des arguments
547
        if (ssheet == null || pathDest == null || fileName.trim().length() == 0) {
548
            throw new IllegalArgumentException();
549
        }
550
 
551
        // Renommage du fichier si il existe déja
552
        File fDest = new File(pathDest, fileName + ".ods");
553
 
554
        if (!pathDest.exists()) {
555
            pathDest.mkdirs();
556
        }
557
 
57 ilm 558
        SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, pathDest, fDest);
18 ilm 559
 
560
        // Sauvegarde
561
        try {
562
            ssheet.saveAs(fDest);
563
        } catch (FileNotFoundException e) {
564
            final File F = fDest;
565
            SwingUtilities.invokeLater(new Runnable() {
566
                public void run() {
567
                    try {
568
                        JOptionPane.showMessageDialog(null, "Le fichier " + F.getCanonicalPath() + " n'a pu être créé. \n Vérifiez qu'il n'est pas déjà ouvert.");
569
                    } catch (IOException e) {
570
                        e.printStackTrace();
571
                    }
572
                }
573
            });
574
 
575
            e.printStackTrace();
576
        }
577
 
578
        // Copie de l'odsp
156 ilm 579
        File odspOut = new File(pathDest, fileName + ".odsp");
580
        try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, rowLanguage != null ? rowLanguage.getString("CHEMIN") : null, null);) {
18 ilm 581
            if (odspIn != null) {
582
                StreamUtils.copy(odspIn, odspOut);
583
            }
584
        } catch (FileNotFoundException e) {
585
            System.err.println("Le fichier odsp n'existe pas.");
586
        }
587
 
588
        return fDest;
589
    }
590
 
591
    /**
592
     * parcourt l'ensemble de la feuille pour trouver les style définit
593
     */
594
    private static Map<String, Map<Integer, String>> searchStyle(Sheet sheet, int colEnd, int rowEnd) {
595
 
596
        if (cacheStyle.get(sheet) != null) {
597
            return cacheStyle.get(sheet);
598
        }
599
 
600
        Map<String, Map<Integer, String>> mapStyleDef = StyleSQLElement.getMapAllStyle();
601
 
93 ilm 602
        Map<String, Map<Integer, String>> mapStyleFounded = new HashMap<String, Map<Integer, String>>();
603
 
18 ilm 604
        // on parcourt chaque ligne de la feuille pour recuperer les styles
605
        int columnCount = (colEnd == -1) ? sheet.getColumnCount() : (colEnd + 1);
606
        System.err.println("End column search : " + columnCount);
607
 
608
        int rowCount = (rowEnd > 0) ? rowEnd : sheet.getRowCount();
93 ilm 609
 
18 ilm 610
        System.err.println("End row search : " + rowCount);
93 ilm 611
        for (int i = 0; i < rowCount && (mapStyleDef.keySet().size() - 2) > mapStyleFounded.keySet().size(); i++) {
612
 
18 ilm 613
            int x = 0;
614
            Map<Integer, String> mapCellStyle = new HashMap<Integer, String>();
615
            String style = "";
616
 
617
            for (int j = 0; j < columnCount; j++) {
618
 
619
                try {
620
                    if (sheet.isCellValid(j, i)) {
621
 
622
                        MutableCell c = sheet.getCellAt(j, i);
623
                        String cellStyle = c.getStyleName();
624
 
625
                        try {
626
                            if (mapStyleDef.containsKey(c.getValue().toString())) {
627
                                style = c.getValue().toString();
628
                            }
629
                        } catch (IllegalStateException e) {
630
                            e.printStackTrace();
631
                        }
632
                        mapCellStyle.put(Integer.valueOf(x), cellStyle);
93 ilm 633
                        if (style.trim().length() > 0) {
18 ilm 634
                            c.clearValue();
635
                            if (!style.trim().equalsIgnoreCase("Normal") && mapStyleDef.get("Normal") != null) {
636
                                String styleCell = mapStyleDef.get("Normal").get(Integer.valueOf(x));
637
                                if (styleCell != null && styleCell.length() != 0) {
638
                                    c.setStyleName(styleCell);
639
                                }
640
                            }
93 ilm 641
 
642
                            mapStyleFounded.put(style, mapCellStyle);
643
 
18 ilm 644
                        }
645
                    }
646
                } catch (IndexOutOfBoundsException e) {
647
                    System.err.println("Index out of bounds Exception");
648
                }
649
                x++;
650
            }
651
 
652
        }
93 ilm 653
        cacheStyle.put(sheet, mapStyleFounded);
654
        return mapStyleFounded;
18 ilm 655
    }
656
 
657
    public static void main(String[] args) {
658
        ComptaPropsConfiguration conf = ComptaPropsConfiguration.create();
659
        System.err.println("Conf created");
660
        Configuration.setInstance(conf);
661
        conf.setUpSocieteDataBaseConnexion(36);
662
        System.err.println("Connection Set up");
663
 
664
        System.err.println("Start Genere");
665
        // genere("Devis", "C:\\", "Test", elt, 19);
666
        System.err.println("Stop genere");
667
    }
668
}