File: TeXFormulaParser.java

package info (click to toggle)
libjmathtex-java 0.7~pre-4
  • links: PTS, VCS
  • area: main
  • in suites: lenny, squeeze
  • size: 952 kB
  • ctags: 1,112
  • sloc: java: 5,129; xml: 2,151; makefile: 24
file content (420 lines) | stat: -rw-r--r-- 17,106 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/* TeXFormulaParser.java
 * =========================================================================
 * This file is part of the JMathTeX Library - http://jmathtex.sourceforge.net
 *
 * Copyright (C) 2004-2007 Universiteit Gent
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * A copy of the GNU General Public License can be found in the file
 * LICENSE.txt provided with the source distribution of this program (see
 * the META-INF directory in the source jar). This license can also be
 * found on the GNU website at http://www.gnu.org/licenses/gpl.html.
 *
 * If you did not receive a copy of the GNU General Public License along
 * with this program, contact the lead developer, or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 *
 */

package be.ugent.caagt.jmathtex;

import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import org.jdom.Element;

/**
 * Parses a "TeXFormula"-element representing a predefined TeXFormula's from an XML-file.
 */
class TeXFormulaParser {
    
    private interface ActionParser { // NOPMD
        public void parse(Element el) throws ResourceParseException;
    }
    
    private interface ArgumentValueParser { // NOPMD
        public Object parseValue(String value, String type)
        throws ResourceParseException;
    }
    
    private class MethodInvocationParser implements ActionParser {
        
        MethodInvocationParser () {
            // avoids creation of special accessor type
        }
        
        public void parse(Element el) throws ResourceParseException {
            // get required string attributes
            String methodName = getAttrValueAndCheckIfNotNull("name", el);
            String objectName = getAttrValueAndCheckIfNotNull(ARG_OBJ_ATTR, el);
            // check if temporary TeXFormula exists
            Object object = tempFormulas.get(objectName);
            if (object == null) // doesn't exist
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_OBJ_ATTR,
                        "has an unknown temporary TeXFormula name as value : '"
                        + objectName + "'!");
            else {
                // parse arguments
                List args = el.getChildren("Argument");
                // get argument classes and values
                Class[] argClasses = getArgumentClasses(args);
                Object[] argValues = getArgumentValues(args);
                // invoke method
                try {
                    TeXFormula.class.getMethod(methodName, argClasses).invoke(
                            (TeXFormula) object, argValues);
                } catch (Exception e) {
                    throw new XMLResourceParseException(
                            "Error invoking the method '" + methodName
                            + "' on the temporary TeXFormula '" + objectName
                            + "' while constructing the predefined TeXFormula '"
                            + formulaName + "'!", e);
                }
            }
        }
    }
    
    private class CreateTeXFormulaParser implements ActionParser {
        
        CreateTeXFormulaParser () {
            // avoids creation of special accessor type
        }
        
        public void parse(Element el) throws ResourceParseException {
            // get required string attribute
            String name = getAttrValueAndCheckIfNotNull("name", el);
            // parse arguments
            List args = el.getChildren("Argument");
            // get argument classes and values
            Class[] argClasses = getArgumentClasses(args);
            Object[] argValues = getArgumentValues(args);
            // create TeXFormula object
            try {
                TeXFormula f = (TeXFormula) TeXFormula.class.getConstructor(
                        argClasses).newInstance(argValues);
                // succesfully created, so add to "temporary formula's"-hashtable
                tempFormulas.put(name, f);
            } catch (Exception e) {
                throw new XMLResourceParseException(
                        "Error creating the temporary TeXFormula '" + name
                        + "' while constructing the predefined TeXFormula '"
                        + formulaName + "'!", e);
            }
        }
    }
    
    private class FloatValueParser implements ArgumentValueParser {
        
        FloatValueParser  () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            checkNullValue(value, type);
            try {
                return new Float(Float.parseFloat(value));
            } catch (NumberFormatException e) {
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_VAL_ATTR, "has an invalid '" + type + "'-value : '"
                        + value + "'!", e);
            }
        }
    }
    
    private class CharValueParser implements ArgumentValueParser {
        
        CharValueParser  () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            checkNullValue(value, type);
            if (value.length() == 1)
                return new Character(value.charAt(0));
            else
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_VAL_ATTR,
                        "must have a value that consists of exactly 1 character!");
        }
    }
    
    private class BooleanValueParser implements ArgumentValueParser {
        
        BooleanValueParser () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            checkNullValue(value, type);
            if ("true".equals(value))
                return Boolean.TRUE;
            else if ("false".equals(value))
                return Boolean.FALSE;
            else
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_VAL_ATTR, "has an invalid '" + type + "'-value : '"
                        + value + "'!");
            
        }
    }
    
    private class IntValueParser implements ArgumentValueParser {
        
        IntValueParser  () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            checkNullValue(value, type);
            try {
                int val = Integer.parseInt(value);
                return new Float((int) val);
            } catch (NumberFormatException e) {
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_VAL_ATTR, "has an invalid '" + type + "'-value : '"
                        + value + "'!", e);
            }
        }
    }
    
    private class ReturnParser implements ActionParser {
        
        ReturnParser () {
            // avoids creation of special accessor type
        }
        
        public void parse(Element el) throws ResourceParseException {
            // get required string attribute
            String name = getAttrValueAndCheckIfNotNull("name", el);
            Object res = tempFormulas.get(name);
            if (res == null)
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, RETURN_EL, "name",
                        "contains an unknown temporary TeXFormula variable name '"
                        + name + "' for the predefined TeXFormula '"
                        + formulaName + "'!");
            else
                result = (TeXFormula) res;
        }
    }
    
    private class StringValueParser implements ArgumentValueParser {
        
        StringValueParser  () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            return value;
        }
    }
    
    private class TeXFormulaValueParser implements ArgumentValueParser {
        
        TeXFormulaValueParser () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            if (value == null) // null pointer argument
                return null;
            else {
                Object formula = tempFormulas.get(value);
                if (formula == null) // unknown temporary TeXFormula!
                    throw new XMLResourceParseException(
                            PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                            ARG_VAL_ATTR,
                            "has an unknown temporary TeXFormula name as value : '"
                            + value + "'!");
                else
                    return (TeXFormula) formula;
            }
        }
    }
    
    private class TeXConstantsValueParser implements ArgumentValueParser {
        
        TeXConstantsValueParser () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            checkNullValue(value, type);
            try {
                // get constant value (if present)
                int constant = TeXConstants.class.getDeclaredField(value).getInt(
                        null);
                // return constant integer value
                return Integer.valueOf(constant);
            } catch (Exception e) {
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_VAL_ATTR, "has an unknown constant name as value : '"
                        + value + "'!", e);
            }
        }
    }
    
    private class ColorConstantValueParser implements ArgumentValueParser {
        
        ColorConstantValueParser () {
            // avoids creation of special accessor type
        }
        
        public Object parseValue(String value, String type)
        throws ResourceParseException {
            checkNullValue(value, type);
            try {
                // return Color constant (if present)
                return Color.class.getDeclaredField(value).get(null);
            } catch (Exception e) {
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                        ARG_VAL_ATTR,
                        "has an unknown color constant name as value : '" + value
                        + "'!", e);
            }
        }
    }
    
    private static final String ARG_VAL_ATTR = "value", RETURN_EL = "Return",
            ARG_OBJ_ATTR = "formula";
    
    private static Map<String,Class<?>> classMappings = new HashMap<String,Class<?>>();
    
    private final Map<String,ArgumentValueParser> argValueParsers = new HashMap<String,ArgumentValueParser>();
    private final Map<String,ActionParser> actionParsers = new HashMap<String,ActionParser>();
    private final Map<String,TeXFormula> tempFormulas = new HashMap<String,TeXFormula>();
    
    private TeXFormula result = new TeXFormula();
    
    private final String formulaName;
    
    private final Element formula;
    
    static {
        // string-to-class mappings
        classMappings.put("TeXConstants", int.class); // all integer constants
        classMappings.put("TeXFormula", TeXFormula.class);
        classMappings.put("String", String.class);
        classMappings.put("float", float.class);
        classMappings.put("int", int.class);
        classMappings.put("boolean", boolean.class);
        classMappings.put("char", char.class);
        classMappings.put("ColorConstant", Color.class);
    }
    
    public TeXFormulaParser(String name, Element formula) {
        formulaName = name;
        this.formula = formula;
        
        // action parsers
        actionParsers.put("CreateTeXFormula", new CreateTeXFormulaParser());
        actionParsers.put("MethodInvocation", new MethodInvocationParser());
        actionParsers.put(RETURN_EL, new ReturnParser());
        
        // argument value parsers
        argValueParsers.put("TeXConstants", new TeXConstantsValueParser());
        argValueParsers.put("TeXFormula", new TeXFormulaValueParser());
        argValueParsers.put("String", new StringValueParser());
        argValueParsers.put("float", new FloatValueParser());
        argValueParsers.put("int", new IntValueParser());
        argValueParsers.put("boolean", new BooleanValueParser());
        argValueParsers.put("char", new CharValueParser());
        argValueParsers.put("ColorConstant", new ColorConstantValueParser());
    }
    
    public TeXFormula parse() throws ResourceParseException {
        // parse and execute actions
        for (Object obj : formula.getChildren()) {
            Element el = (Element) obj;
            ActionParser p = actionParsers.get(el.getName());
            if (p != null) // ignore unknown elements
               p.parse(el);
        }
        return result;
    }
    
    private Object[] getArgumentValues(List args) {
        Object[] res = new Object[args.size()];
        int i = 0;
        for (Object obj : args) {
            Element arg = (Element) obj;
            // get required string attribute
            String type = getAttrValueAndCheckIfNotNull("type", arg);
            // get value, not present means a nullpointer
            String value = arg.getAttributeValue(ARG_VAL_ATTR);
            // parse value, hashtable will certainly contain a parser for the class type,
            // because the class types have been checked before!
            res[i] = ((ArgumentValueParser) argValueParsers.get(type)).parseValue(
                    value, type);
            i++;
        }
        return res;
    }
    
    private static Class[] getArgumentClasses(List args)
    throws ResourceParseException {
        Class[] res = new Class[args.size()];
        int i = 0;
        for (Object obj : args) {
            Element arg = (Element) obj;
            // get required string attribute
            String type = getAttrValueAndCheckIfNotNull("type", arg);
            // find class mapping
            Object cl = classMappings.get(type);
            if (cl == null) // no class mapping found
                throw new XMLResourceParseException(
                        PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument", "type",
                        "has an invalid class name value!");
            else
                res[i] = (Class) cl;
            i++;
        }
        return res;
    }
    
    private static void checkNullValue(String value, String type)
    throws ResourceParseException {
        if (value == null)
            throw new XMLResourceParseException(
                    PredefinedTeXFormulaParser.RESOURCE_NAME, "Argument",
                    ARG_VAL_ATTR, "is required for an argument of type '" + type
                    + "'!");
    }
    
    private static String getAttrValueAndCheckIfNotNull(String attrName,
            Element element) throws ResourceParseException {
        String attrValue = element.getAttributeValue(attrName);
        if (attrValue == null)
            throw new XMLResourceParseException(
                    PredefinedTeXFormulaParser.RESOURCE_NAME, element.getName(),
                    attrName, null);
        return attrValue;
    }
}