OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 65 | Rev 80 | 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;
73 ilm 32
import java.util.HashSet;
20 ilm 33
import java.util.List;
34
import java.util.Map.Entry;
73 ilm 35
import java.util.Set;
20 ilm 36
import java.util.SortedMap;
37
import java.util.TreeMap;
38
import java.util.regex.Matcher;
39
import java.util.regex.Pattern;
40
 
41
import org.jdom.Attribute;
42
import org.jdom.Element;
43
import org.jdom.Namespace;
44
 
45
// from section 16.27 in v1.2-cs01-part1
46
public abstract class DataStyle extends Style {
47
    private static final int DEFAULT_GROUPING_SIZE = new DecimalFormat().getGroupingSize();
73 ilm 48
    public static final int DEFAULT_DECIMAL_PLACES = 10;
20 ilm 49
    private static final Pattern QUOTE_PATRN = Pattern.compile("'", Pattern.LITERAL);
50
    private static final Pattern EXP_PATTERN = Pattern.compile("E(\\d+)$");
51
 
52
    public static int getDecimalPlaces(final CellStyle defaultStyle) {
73 ilm 53
        if (defaultStyle != null) {
54
            return defaultStyle.getTableCellProperties(null).getDecimalPlaces();
55
        } else {
56
            return DEFAULT_DECIMAL_PLACES;
57
        }
20 ilm 58
    }
59
 
60
    public static void addStringLiteral(final StringBuilder formatSB, final String s) {
61
        formatSB.append('\'');
62
        formatSB.append(QUOTE_PATRN.matcher(s).replaceAll("''"));
63
        formatSB.append('\'');
64
    }
65
 
73 ilm 66
    public static final Set<Class<? extends DataStyle>> DATA_STYLES;
65 ilm 67
    private static final DataStyleDesc<?>[] DATA_STYLES_DESCS = new DataStyleDesc<?>[] { NumberStyle.DESC, PercentStyle.DESC, TextStyle.DESC, CurrencyStyle.DESC, DateStyle.DESC, TimeStyle.DESC,
20 ilm 68
            BooleanStyle.DESC };
73 ilm 69
    static {
70
        final Set<Class<? extends DataStyle>> l = new HashSet<Class<? extends DataStyle>>(DATA_STYLES_DESCS.length);
71
        l.add(NumberStyle.class);
72
        l.add(PercentStyle.class);
73
        l.add(TextStyle.class);
74
        l.add(CurrencyStyle.class);
75
        l.add(DateStyle.class);
76
        l.add(TimeStyle.class);
77
        l.add(BooleanStyle.class);
78
        DATA_STYLES = Collections.unmodifiableSet(l);
79
        assert DATA_STYLES_DESCS.length == DATA_STYLES.size() : "Discrepancy between classes and descs";
80
    }
20 ilm 81
 
82
    public static abstract class DataStyleDesc<S extends DataStyle> extends StyleDesc<S> {
83
 
84
        protected DataStyleDesc(Class<S> clazz, XMLVersion version, String elemName, String baseName) {
85
            super(clazz, version, elemName, baseName);
86
            this.setElementNS(getVersion().getNS("number"));
87
            // from 19.469 in v1.2-cs01-part1
88
            this.getRefElementsMap().putAll(
89
                    "style:data-style-name",
90
                    Arrays.asList("presentation:date-time-decl", "style:style", "text:creation-date", "text:creation-time", "text:database-display", "text:date", "text:editing-duration",
91
                            "text:expression", "text:meta-field", "text:modification-date", "text:modification-time", "text:print-date", "text:print-time", "text:table-formula", "text:time",
92
                            "text:user-defined", "text:user-field-get", "text:user-field-input", "text:variable-get", "text:variable-input", "text:variable-set"));
25 ilm 93
            this.getRefElementsMap().put("style:apply-style-name", "style:map");
20 ilm 94
        }
95
    }
96
 
65 ilm 97
    static public void registerDesc() {
98
        for (final StyleDesc<?> d : DATA_STYLES_DESCS)
99
            Style.registerAllVersions(d);
100
    }
101
 
102
    static public <S extends DataStyle> DataStyleDesc<S> getDesc(final Class<S> clazz, final XMLVersion version) {
103
        return (DataStyleDesc<S>) Style.getStyleDesc(clazz, version);
104
    }
105
 
25 ilm 106
    private final ODValueType type;
20 ilm 107
    private StyleTextProperties textProps;
108
 
25 ilm 109
    protected DataStyle(final ODPackage pkg, Element elem, final ODValueType type) {
20 ilm 110
        super(pkg, elem);
111
        this.type = type;
112
    }
113
 
25 ilm 114
    public final ODValueType getDataType() {
20 ilm 115
        return this.type;
116
    }
117
 
25 ilm 118
    public final ODEpoch getEpoch() {
119
        return this.getPackage().getODDocument().getEpoch();
120
    }
121
 
122
    /**
123
     * Convert the passed object to something that {@link #format(Object, CellStyle, boolean)} can
124
     * accept.
125
     *
126
     * @param o the object to convert.
127
     * @return an object that can be formatted, <code>null</code> if <code>o</code> cannot be
128
     *         converted.
129
     * @throws NullPointerException if <code>o</code> is <code>null</code>.
130
     * @see #canFormat(Class)
131
     */
132
    public final Object convert(final Object o) throws NullPointerException {
133
        if (o == null)
134
            throw new NullPointerException();
135
 
136
        final Object res;
137
        if (this.canFormat(o.getClass()))
138
            res = o;
139
        else
140
            res = this.convertNonNull(o);
141
        assert res == null || this.canFormat(res.getClass());
142
        return res;
143
    }
144
 
145
    // o is not null and canFormat(o.getClass()) is false
146
    // return null if o cannot be converted
147
    protected abstract Object convertNonNull(Object o);
148
 
149
    /**
150
     * Whether instances of the passed class can be {@link #format(Object, CellStyle, boolean)
151
     * formatted}.
152
     *
153
     * @param toFormat the class.
154
     * @return <code>true</code> if instances of <code>toFormat</code> can be formatted.
155
     */
20 ilm 156
    public final boolean canFormat(Class<?> toFormat) {
25 ilm 157
        return this.getDataType().canFormat(toFormat);
20 ilm 158
    }
159
 
160
    public final String getTitle() {
161
        return this.getElement().getAttributeValue("title", getElement().getNamespace());
162
    }
163
 
164
    public final StyleTextProperties getTextProperties() {
165
        if (this.textProps == null)
166
            this.textProps = new StyleTextProperties(this);
167
        return this.textProps;
168
    }
169
 
170
    public abstract String format(final Object o, final CellStyle defaultStyle, boolean lenient) throws UnsupportedOperationException;
171
 
61 ilm 172
    static protected final void reportError(String msg, boolean lenient) throws UnsupportedOperationException {
20 ilm 173
        if (lenient)
174
            Log.get().warning(msg);
175
        else
176
            throw new UnsupportedOperationException(msg);
177
    }
178
 
179
    protected final String formatNumberOrScientificNumber(final Element elem, final Number n, CellStyle defaultStyle) {
180
        return this.formatNumberOrScientificNumber(elem, n, 1, defaultStyle);
181
    }
182
 
183
    protected final String formatNumberOrScientificNumber(final Element elem, final Number n, final int multiplier, CellStyle defaultStyle) {
184
        final Namespace numberNS = this.getElement().getNamespace();
185
        final StringBuilder numberSB = new StringBuilder();
186
 
187
        final List<?> embeddedTexts = elem.getChildren("embedded-text", numberNS);
188
        final SortedMap<Integer, String> embeddedTextByPosition = new TreeMap<Integer, String>(Collections.reverseOrder());
189
        for (final Object o : embeddedTexts) {
190
            final Element embeddedText = (Element) o;
191
            embeddedTextByPosition.put(Integer.valueOf(embeddedText.getAttributeValue("position", numberNS)), embeddedText.getText());
192
        }
193
 
194
        final Attribute factorAttr = elem.getAttribute("display-factor", numberNS);
195
        final double factor = (factorAttr != null ? Double.valueOf(factorAttr.getValue()) : 1) / multiplier;
196
 
197
        // default value from 19.348
198
        final boolean grouping = StyleProperties.parseBoolean(elem.getAttributeValue("grouping", numberNS), false);
199
 
200
        final String minIntDigitsAttr = elem.getAttributeValue("min-integer-digits", numberNS);
201
        final int minIntDig = minIntDigitsAttr == null ? 0 : Integer.parseInt(minIntDigitsAttr);
202
        if (minIntDig == 0) {
203
            numberSB.append('#');
204
        } else {
205
            for (int i = 0; i < minIntDig; i++)
206
                numberSB.append('0');
207
        }
208
 
209
        // e.g. if it's "--", 12,3 is displayed "12,3" and 12 is displayed "12,--"
210
        final String decReplacement = elem.getAttributeValue("decimal-replacement", numberNS);
211
        final boolean decSeparatorAlwaysShown;
212
        if (decReplacement != null && !NumberUtils.hasFractionalPart(n)) {
213
            decSeparatorAlwaysShown = true;
214
            numberSB.append('.');
215
            // escape quote in replacement
216
            addStringLiteral(numberSB, decReplacement);
217
        } else {
218
            decSeparatorAlwaysShown = false;
219
            // see 19.343.2
220
            final Attribute decPlacesAttr = elem.getAttribute("decimal-places", numberNS);
221
            final int decPlaces;
73 ilm 222
            final char decChar;
223
            if (decPlacesAttr != null) {
224
                decChar = '0';
20 ilm 225
                decPlaces = Integer.parseInt(decPlacesAttr.getValue());
73 ilm 226
            } else {
227
                // default style specifies the maximum
228
                decChar = '#';
20 ilm 229
                decPlaces = getDecimalPlaces(defaultStyle);
73 ilm 230
            }
20 ilm 231
 
232
            if (decPlaces > 0) {
233
                numberSB.append('.');
234
                for (int i = 0; i < decPlaces; i++)
73 ilm 235
                    numberSB.append(decChar);
20 ilm 236
            }
237
        }
238
 
239
        final Attribute minExpAttr = elem.getAttribute("min-exponent-digits", numberNS);
240
        if (minExpAttr != null) {
241
            numberSB.append('E');
242
            for (int i = 0; i < Integer.parseInt(minExpAttr.getValue()); i++)
243
                numberSB.append('0');
244
        }
245
 
246
        final DecimalFormat decFormat = new DecimalFormat(numberSB.toString());
247
        // Java always use HALF_EVEN
248
        decFormat.setRoundingMode(RoundingMode.HALF_UP);
249
        decFormat.setGroupingUsed(grouping);
250
        // needed since the default size is overwritten by the pattern
251
        decFormat.setGroupingSize(DEFAULT_GROUPING_SIZE);
252
        decFormat.setDecimalSeparatorAlwaysShown(decSeparatorAlwaysShown);
253
        String res = decFormat.format(NumberUtils.divide(n, factor));
254
        // java only puts the minus sign, OO also puts the plus sign
255
        if (minExpAttr != null) {
256
            final Matcher m = EXP_PATTERN.matcher(res);
257
            if (m.find())
258
                res = res.substring(0, m.start()) + "E+" + m.group(1);
259
        }
260
        if (embeddedTextByPosition.size() > 0) {
261
            final int intDigits = Math.max(minIntDig, NumberUtils.intDigits(n));
262
            // each time we insert text the decimal point moves
263
            int offset = 0;
264
            // sorted descending to avoid overwriting
265
            for (Entry<Integer, String> e : embeddedTextByPosition.entrySet()) {
266
                final String embeddedText = e.getValue();
267
                // the text will be before this index
268
                final int index = Math.max(0, offset + intDigits - e.getKey().intValue());
269
                res = res.substring(0, index) + embeddedText + res.substring(index);
270
                offset += embeddedText.length();
271
            }
272
        }
273
        return res;
274
    }
275
}