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 package org.ximtec.igesture.util;
28
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import org.jdom.Document;
40 import org.jdom.Element;
41 import org.jdom.JDOMException;
42 import org.jdom.input.SAXBuilder;
43 import org.sigtec.jdom.id.Factory;
44 import org.sigtec.util.Constant;
45 import org.xml.sax.InputSource;
46
47
48
49
50
51
52
53
54
55 public class Mapping {
56
57 private static final Logger LOGGER = Logger
58 .getLogger(Mapping.class.getName());
59
60 public static final int UNDEFINED = -1;
61
62 public static final String MAP_TAG = "map";
63
64 public static final String NAME_ATTRIBUTE = "name";
65
66 public static final String VALUE_ATTRIBUTE = "value";
67
68 private static HashMap<String, Integer> str2int;
69
70 private static HashMap<Integer, String> int2str;
71
72 private static boolean initialised;
73
74 static {
75 initialised = false;
76 }
77
78
79 @SuppressWarnings("unchecked")
80 public static void init(File file) {
81 str2int = new HashMap<String, Integer>();
82 int2str = new HashMap<Integer, String>();
83
84 try {
85 final InputStream inputStream = new FileInputStream(file);
86 final SAXBuilder builder = new SAXBuilder(false);
87 builder.setFactory(new Factory());
88 builder.setIgnoringElementContentWhitespace(true);
89 final InputSource is = new InputSource(inputStream);
90 final Document document = builder.build(is);
91
92 for (final Element element : (List<Element>)document.getRootElement()
93 .getChildren(MAP_TAG)) {
94 final String value = element.getAttributeValue(VALUE_ATTRIBUTE);
95 final String name = element.getAttributeValue(NAME_ATTRIBUTE);
96 str2int.put(name, Integer.valueOf(value));
97 int2str.put(Integer.valueOf(value), name);
98 }
99
100 }
101 catch (final FileNotFoundException e) {
102 LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
103 }
104 catch (final JDOMException e) {
105 LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
106 }
107 catch (final IOException e) {
108 LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
109 }
110
111 initialised = true;
112 }
113
114
115 private static void testInit() {
116 if (!initialised) {
117 throw new RuntimeException("Mapping: Class not initialised!");
118 }
119
120 }
121
122
123
124
125
126
127
128 public static final int toInt(String name) {
129 testInit();
130 final Integer result = str2int.get(name);
131 return (result != null) ? result.intValue() : UNDEFINED;
132 }
133
134
135
136
137
138
139
140 public static final String toString(int value) {
141 testInit();
142 final String result = int2str.get(value);
143 return (result != null) ? result : null;
144 }
145
146 }