OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
20 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.openoffice.style.data;
15
 
16
import org.openconcerto.openoffice.Log;
25 ilm 17
import org.openconcerto.openoffice.ODEpoch;
20 ilm 18
import org.openconcerto.openoffice.ODPackage;
25 ilm 19
import org.openconcerto.openoffice.ODValueType;
20 ilm 20
import org.openconcerto.openoffice.Style;
21
import org.openconcerto.openoffice.StyleDesc;
22
import org.openconcerto.openoffice.StyleProperties;
23
import org.openconcerto.openoffice.XMLVersion;
24
import org.openconcerto.openoffice.spreadsheet.CellStyle;
25
import org.openconcerto.openoffice.text.TextStyle.StyleTextProperties;
26
import org.openconcerto.utils.NumberUtils;
27
 
28
import java.math.RoundingMode;
29
import java.text.DecimalFormat;
30
import java.util.Arrays;
31
import java.util.Collections;
32
import java.util.List;
33
import java.util.Map.Entry;
34
import java.util.SortedMap;
35
import java.util.TreeMap;
36
import java.util.regex.Matcher;
37
import java.util.regex.Pattern;
38
 
39
import org.jdom.Attribute;
40
import org.jdom.Element;
41
import org.jdom.Namespace;
42
 
43
// from section 16.27 in v1.2-cs01-part1
44
public abstract class DataStyle extends Style {
45
    private static final int DEFAULT_GROUPING_SIZE = new DecimalFormat().getGroupingSize();
46
    private static final int DEFAULT_DECIMAL_PLACES = 2;
47
    private static final Pattern QUOTE_PATRN = Pattern.compile("'", Pattern.LITERAL);
48
    private static final Pattern EXP_PATTERN = Pattern.compile("E(\\d+)$");
49
 
50
    public static int getDecimalPlaces(final CellStyle defaultStyle) {
51
        final int res;
52
        if (defaultStyle != null && defaultStyle.getTableCellProperties().getDecimalPlaces() != null)
53
            res = defaultStyle.getTableCellProperties().getDecimalPlaces().intValue();
54
        else
55
            res = DEFAULT_DECIMAL_PLACES;
56
        return res;
57
    }
58
 
59
    public static void addStringLiteral(final StringBuilder formatSB, final String s) {
60
        formatSB.append('\'');
61
        formatSB.append(QUOTE_PATRN.matcher(s).replaceAll("''"));
62
        formatSB.append('\'');
63
    }
64
 
65
    public static final DataStyleDesc<?>[] DATA_STYLES_DESCS = new DataStyleDesc<?>[] { NumberStyle.DESC, PercentStyle.DESC, TextStyle.DESC, CurrencyStyle.DESC, DateStyle.DESC, TimeStyle.DESC,
66
            BooleanStyle.DESC };
67
 
68
    public static abstract class DataStyleDesc<S extends DataStyle> extends StyleDesc<S> {
69
 
70
        protected DataStyleDesc(Class<S> clazz, XMLVersion version, String elemName, String baseName) {
71
            super(clazz, version, elemName, baseName);
72
            this.setElementNS(getVersion().getNS("number"));
73
            // from 19.469 in v1.2-cs01-part1
74
            this.getRefElementsMap().putAll(
75
                    "style:data-style-name",
76
                    Arrays.asList("presentation:date-time-decl", "style:style", "text:creation-date", "text:creation-time", "text:database-display", "text:date", "text:editing-duration",
77
                            "text:expression", "text:meta-field", "text:modification-date", "text:modification-time", "text:print-date", "text:print-time", "text:table-formula", "text:time",
78
                            "text:user-defined", "text:user-field-get", "text:user-field-input", "text:variable-get", "text:variable-input", "text:variable-set"));
25 ilm 79
            this.getRefElementsMap().put("style:apply-style-name", "style:map");
20 ilm 80
        }
81
    }
82
 
25 ilm 83
    private final ODValueType type;
20 ilm 84
    private StyleTextProperties textProps;
85
 
25 ilm 86
    protected DataStyle(final ODPackage pkg, Element elem, final ODValueType type) {
20 ilm 87
        super(pkg, elem);
88
        this.type = type;
89
    }
90
 
25 ilm 91
    public final ODValueType getDataType() {
20 ilm 92
        return this.type;
93
    }
94
 
25 ilm 95
    public final ODEpoch getEpoch() {
96
        return this.getPackage().getODDocument().getEpoch();
97
    }
98
 
99
    /**
100
     * Convert the passed object to something that {@link #format(Object, CellStyle, boolean)} can
101
     * accept.
102
     *
103
     * @param o the object to convert.
104
     * @return an object that can be formatted, <code>null</code> if <code>o</code> cannot be
105
     *         converted.
106
     * @throws NullPointerException if <code>o</code> is <code>null</code>.
107
     * @see #canFormat(Class)
108
     */
109
    public final Object convert(final Object o) throws NullPointerException {
110
        if (o == null)
111
            throw new NullPointerException();
112
 
113
        final Object res;
114
        if (this.canFormat(o.getClass()))
115
            res = o;
116
        else
117
            res = this.convertNonNull(o);
118
        assert res == null || this.canFormat(res.getClass());
119
        return res;
120
    }
121
 
122
    // o is not null and canFormat(o.getClass()) is false
123
    // return null if o cannot be converted
124
    protected abstract Object convertNonNull(Object o);
125
 
126
    /**
127
     * Whether instances of the passed class can be {@link #format(Object, CellStyle, boolean)
128
     * formatted}.
129
     *
130
     * @param toFormat the class.
131
     * @return <code>true</code> if instances of <code>toFormat</code> can be formatted.
132
     */
20 ilm 133
    public final boolean canFormat(Class<?> toFormat) {
25 ilm 134
        return this.getDataType().canFormat(toFormat);
20 ilm 135
    }
136
 
137
    public final String getTitle() {
138
        return this.getElement().getAttributeValue("title", getElement().getNamespace());
139
    }
140
 
141
    public final StyleTextProperties getTextProperties() {
142
        if (this.textProps == null)
143
            this.textProps = new StyleTextProperties(this);
144
        return this.textProps;
145
    }
146
 
147
    public abstract String format(final Object o, final CellStyle defaultStyle, boolean lenient) throws UnsupportedOperationException;
148
 
61 ilm 149
    static protected final void reportError(String msg, boolean lenient) throws UnsupportedOperationException {
20 ilm 150
        if (lenient)
151
            Log.get().warning(msg);
152
        else
153
            throw new UnsupportedOperationException(msg);
154
    }
155
 
156
    protected final String formatNumberOrScientificNumber(final Element elem, final Number n, CellStyle defaultStyle) {
157
        return this.formatNumberOrScientificNumber(elem, n, 1, defaultStyle);
158
    }
159
 
160
    protected final String formatNumberOrScientificNumber(final Element elem, final Number n, final int multiplier, CellStyle defaultStyle) {
161
        final Namespace numberNS = this.getElement().getNamespace();
162
        final StringBuilder numberSB = new StringBuilder();
163
 
164
        final List<?> embeddedTexts = elem.getChildren("embedded-text", numberNS);
165
        final SortedMap<Integer, String> embeddedTextByPosition = new TreeMap<Integer, String>(Collections.reverseOrder());
166
        for (final Object o : embeddedTexts) {
167
            final Element embeddedText = (Element) o;
168
            embeddedTextByPosition.put(Integer.valueOf(embeddedText.getAttributeValue("position", numberNS)), embeddedText.getText());
169
        }
170
 
171
        final Attribute factorAttr = elem.getAttribute("display-factor", numberNS);
172
        final double factor = (factorAttr != null ? Double.valueOf(factorAttr.getValue()) : 1) / multiplier;
173
 
174
        // default value from 19.348
175
        final boolean grouping = StyleProperties.parseBoolean(elem.getAttributeValue("grouping", numberNS), false);
176
 
177
        final String minIntDigitsAttr = elem.getAttributeValue("min-integer-digits", numberNS);
178
        final int minIntDig = minIntDigitsAttr == null ? 0 : Integer.parseInt(minIntDigitsAttr);
179
        if (minIntDig == 0) {
180
            numberSB.append('#');
181
        } else {
182
            for (int i = 0; i < minIntDig; i++)
183
                numberSB.append('0');
184
        }
185
 
186
        // e.g. if it's "--", 12,3 is displayed "12,3" and 12 is displayed "12,--"
187
        final String decReplacement = elem.getAttributeValue("decimal-replacement", numberNS);
188
        final boolean decSeparatorAlwaysShown;
189
        if (decReplacement != null && !NumberUtils.hasFractionalPart(n)) {
190
            decSeparatorAlwaysShown = true;
191
            numberSB.append('.');
192
            // escape quote in replacement
193
            addStringLiteral(numberSB, decReplacement);
194
        } else {
195
            decSeparatorAlwaysShown = false;
196
            // see 19.343.2
197
            final Attribute decPlacesAttr = elem.getAttribute("decimal-places", numberNS);
198
            final int decPlaces;
199
            if (decPlacesAttr != null)
200
                decPlaces = Integer.parseInt(decPlacesAttr.getValue());
201
            else
202
                decPlaces = getDecimalPlaces(defaultStyle);
203
 
204
            if (decPlaces > 0) {
205
                numberSB.append('.');
206
                for (int i = 0; i < decPlaces; i++)
207
                    numberSB.append('0');
208
            }
209
        }
210
 
211
        final Attribute minExpAttr = elem.getAttribute("min-exponent-digits", numberNS);
212
        if (minExpAttr != null) {
213
            numberSB.append('E');
214
            for (int i = 0; i < Integer.parseInt(minExpAttr.getValue()); i++)
215
                numberSB.append('0');
216
        }
217
 
218
        final DecimalFormat decFormat = new DecimalFormat(numberSB.toString());
219
        // Java always use HALF_EVEN
220
        decFormat.setRoundingMode(RoundingMode.HALF_UP);
221
        decFormat.setGroupingUsed(grouping);
222
        // needed since the default size is overwritten by the pattern
223
        decFormat.setGroupingSize(DEFAULT_GROUPING_SIZE);
224
        decFormat.setDecimalSeparatorAlwaysShown(decSeparatorAlwaysShown);
225
        String res = decFormat.format(NumberUtils.divide(n, factor));
226
        // java only puts the minus sign, OO also puts the plus sign
227
        if (minExpAttr != null) {
228
            final Matcher m = EXP_PATTERN.matcher(res);
229
            if (m.find())
230
                res = res.substring(0, m.start()) + "E+" + m.group(1);
231
        }
232
        if (embeddedTextByPosition.size() > 0) {
233
            final int intDigits = Math.max(minIntDig, NumberUtils.intDigits(n));
234
            // each time we insert text the decimal point moves
235
            int offset = 0;
236
            // sorted descending to avoid overwriting
237
            for (Entry<Integer, String> e : embeddedTextByPosition.entrySet()) {
238
                final String embeddedText = e.getValue();
239
                // the text will be before this index
240
                final int index = Math.max(0, offset + intDigits - e.getKey().intValue());
241
                res = res.substring(0, index) + embeddedText + res.substring(index);
242
                offset += embeddedText.length();
243
            }
244
        }
245
        return res;
246
    }
247
}