OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 149 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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