OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 61 | Rev 73 | 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 ilm 65
    private static final DataStyleDesc<?>[] DATA_STYLES_DESCS = new DataStyleDesc<?>[] { NumberStyle.DESC, PercentStyle.DESC, TextStyle.DESC, CurrencyStyle.DESC, DateStyle.DESC, TimeStyle.DESC,
20 ilm 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
 
65 ilm 83
    static public void registerDesc() {
84
        for (final StyleDesc<?> d : DATA_STYLES_DESCS)
85
            Style.registerAllVersions(d);
86
    }
87
 
88
    static public <S extends DataStyle> DataStyleDesc<S> getDesc(final Class<S> clazz, final XMLVersion version) {
89
        return (DataStyleDesc<S>) Style.getStyleDesc(clazz, version);
90
    }
91
 
25 ilm 92
    private final ODValueType type;
20 ilm 93
    private StyleTextProperties textProps;
94
 
25 ilm 95
    protected DataStyle(final ODPackage pkg, Element elem, final ODValueType type) {
20 ilm 96
        super(pkg, elem);
97
        this.type = type;
98
    }
99
 
25 ilm 100
    public final ODValueType getDataType() {
20 ilm 101
        return this.type;
102
    }
103
 
25 ilm 104
    public final ODEpoch getEpoch() {
105
        return this.getPackage().getODDocument().getEpoch();
106
    }
107
 
108
    /**
109
     * Convert the passed object to something that {@link #format(Object, CellStyle, boolean)} can
110
     * accept.
111
     *
112
     * @param o the object to convert.
113
     * @return an object that can be formatted, <code>null</code> if <code>o</code> cannot be
114
     *         converted.
115
     * @throws NullPointerException if <code>o</code> is <code>null</code>.
116
     * @see #canFormat(Class)
117
     */
118
    public final Object convert(final Object o) throws NullPointerException {
119
        if (o == null)
120
            throw new NullPointerException();
121
 
122
        final Object res;
123
        if (this.canFormat(o.getClass()))
124
            res = o;
125
        else
126
            res = this.convertNonNull(o);
127
        assert res == null || this.canFormat(res.getClass());
128
        return res;
129
    }
130
 
131
    // o is not null and canFormat(o.getClass()) is false
132
    // return null if o cannot be converted
133
    protected abstract Object convertNonNull(Object o);
134
 
135
    /**
136
     * Whether instances of the passed class can be {@link #format(Object, CellStyle, boolean)
137
     * formatted}.
138
     *
139
     * @param toFormat the class.
140
     * @return <code>true</code> if instances of <code>toFormat</code> can be formatted.
141
     */
20 ilm 142
    public final boolean canFormat(Class<?> toFormat) {
25 ilm 143
        return this.getDataType().canFormat(toFormat);
20 ilm 144
    }
145
 
146
    public final String getTitle() {
147
        return this.getElement().getAttributeValue("title", getElement().getNamespace());
148
    }
149
 
150
    public final StyleTextProperties getTextProperties() {
151
        if (this.textProps == null)
152
            this.textProps = new StyleTextProperties(this);
153
        return this.textProps;
154
    }
155
 
156
    public abstract String format(final Object o, final CellStyle defaultStyle, boolean lenient) throws UnsupportedOperationException;
157
 
61 ilm 158
    static protected final void reportError(String msg, boolean lenient) throws UnsupportedOperationException {
20 ilm 159
        if (lenient)
160
            Log.get().warning(msg);
161
        else
162
            throw new UnsupportedOperationException(msg);
163
    }
164
 
165
    protected final String formatNumberOrScientificNumber(final Element elem, final Number n, CellStyle defaultStyle) {
166
        return this.formatNumberOrScientificNumber(elem, n, 1, defaultStyle);
167
    }
168
 
169
    protected final String formatNumberOrScientificNumber(final Element elem, final Number n, final int multiplier, CellStyle defaultStyle) {
170
        final Namespace numberNS = this.getElement().getNamespace();
171
        final StringBuilder numberSB = new StringBuilder();
172
 
173
        final List<?> embeddedTexts = elem.getChildren("embedded-text", numberNS);
174
        final SortedMap<Integer, String> embeddedTextByPosition = new TreeMap<Integer, String>(Collections.reverseOrder());
175
        for (final Object o : embeddedTexts) {
176
            final Element embeddedText = (Element) o;
177
            embeddedTextByPosition.put(Integer.valueOf(embeddedText.getAttributeValue("position", numberNS)), embeddedText.getText());
178
        }
179
 
180
        final Attribute factorAttr = elem.getAttribute("display-factor", numberNS);
181
        final double factor = (factorAttr != null ? Double.valueOf(factorAttr.getValue()) : 1) / multiplier;
182
 
183
        // default value from 19.348
184
        final boolean grouping = StyleProperties.parseBoolean(elem.getAttributeValue("grouping", numberNS), false);
185
 
186
        final String minIntDigitsAttr = elem.getAttributeValue("min-integer-digits", numberNS);
187
        final int minIntDig = minIntDigitsAttr == null ? 0 : Integer.parseInt(minIntDigitsAttr);
188
        if (minIntDig == 0) {
189
            numberSB.append('#');
190
        } else {
191
            for (int i = 0; i < minIntDig; i++)
192
                numberSB.append('0');
193
        }
194
 
195
        // e.g. if it's "--", 12,3 is displayed "12,3" and 12 is displayed "12,--"
196
        final String decReplacement = elem.getAttributeValue("decimal-replacement", numberNS);
197
        final boolean decSeparatorAlwaysShown;
198
        if (decReplacement != null && !NumberUtils.hasFractionalPart(n)) {
199
            decSeparatorAlwaysShown = true;
200
            numberSB.append('.');
201
            // escape quote in replacement
202
            addStringLiteral(numberSB, decReplacement);
203
        } else {
204
            decSeparatorAlwaysShown = false;
205
            // see 19.343.2
206
            final Attribute decPlacesAttr = elem.getAttribute("decimal-places", numberNS);
207
            final int decPlaces;
208
            if (decPlacesAttr != null)
209
                decPlaces = Integer.parseInt(decPlacesAttr.getValue());
210
            else
211
                decPlaces = getDecimalPlaces(defaultStyle);
212
 
213
            if (decPlaces > 0) {
214
                numberSB.append('.');
215
                for (int i = 0; i < decPlaces; i++)
216
                    numberSB.append('0');
217
            }
218
        }
219
 
220
        final Attribute minExpAttr = elem.getAttribute("min-exponent-digits", numberNS);
221
        if (minExpAttr != null) {
222
            numberSB.append('E');
223
            for (int i = 0; i < Integer.parseInt(minExpAttr.getValue()); i++)
224
                numberSB.append('0');
225
        }
226
 
227
        final DecimalFormat decFormat = new DecimalFormat(numberSB.toString());
228
        // Java always use HALF_EVEN
229
        decFormat.setRoundingMode(RoundingMode.HALF_UP);
230
        decFormat.setGroupingUsed(grouping);
231
        // needed since the default size is overwritten by the pattern
232
        decFormat.setGroupingSize(DEFAULT_GROUPING_SIZE);
233
        decFormat.setDecimalSeparatorAlwaysShown(decSeparatorAlwaysShown);
234
        String res = decFormat.format(NumberUtils.divide(n, factor));
235
        // java only puts the minus sign, OO also puts the plus sign
236
        if (minExpAttr != null) {
237
            final Matcher m = EXP_PATTERN.matcher(res);
238
            if (m.find())
239
                res = res.substring(0, m.start()) + "E+" + m.group(1);
240
        }
241
        if (embeddedTextByPosition.size() > 0) {
242
            final int intDigits = Math.max(minIntDig, NumberUtils.intDigits(n));
243
            // each time we insert text the decimal point moves
244
            int offset = 0;
245
            // sorted descending to avoid overwriting
246
            for (Entry<Integer, String> e : embeddedTextByPosition.entrySet()) {
247
                final String embeddedText = e.getValue();
248
                // the text will be before this index
249
                final int index = Math.max(0, offset + intDigits - e.getKey().intValue());
250
                res = res.substring(0, index) + embeddedText + res.substring(index);
251
                offset += embeddedText.length();
252
            }
253
        }
254
        return res;
255
    }
256
}