Statistics
| Revision:

root / trunk / libraries / libInternationalization / src-utils / org / gvsig / i18n / utils / Keys.java @ 6260

History | View | Annotate | Download (10.3 KB)

1
/**
2
 * 
3
 */
4
package org.gvsig.i18n.utils;
5

    
6
import java.io.BufferedReader;
7
import java.io.File;
8
import java.io.FileInputStream;
9
import java.io.FileNotFoundException;
10
import java.io.FileOutputStream;
11
import java.io.IOException;
12
import java.io.InputStreamReader;
13
import java.io.UnsupportedEncodingException;
14
import java.util.Enumeration;
15
import java.util.HashMap;
16
import java.util.HashSet;
17
import java.util.Iterator;
18
import java.util.Properties;
19
import java.util.regex.Matcher;
20
import java.util.regex.Pattern;
21
import java.util.regex.PatternSyntaxException;
22

    
23
import org.kxml2.io.KXmlParser;
24
import org.xmlpull.v1.XmlPullParserException;
25

    
26
/**
27
 * @author cesar
28
 *
29
 */
30
public class Keys {
31
        private ConfigOptions config;
32
        
33
        public Keys(ConfigOptions config) {
34
                this.config = config;
35
        }
36
        
37
        public void load() {
38
                Project project;
39
                for (int currentProject=0; currentProject<config.projects.size(); currentProject++) {
40
                        project = ((Project)config.projects.get(currentProject));
41
                        /**
42
                         * There is two options, "properties" and "sources". "sources" is the default, so
43
                         * if there was something different to "properties", we assume "sources".
44
                         */
45
                        if (!project.sourceKeys.equals("properties")) {
46
                                project.dictionaries = loadProjectFromSources(project);
47
                        }
48
                        else {
49
                                 project.dictionaries = loadProjectFromProperties(project);
50
                         }
51
                }
52
        }
53
        
54
        public void save() {
55
                Project project;
56
                Properties dict;
57
                FileOutputStream stream=null;
58
                String lang;
59
                
60
                for (int currentProject=0; currentProject<config.projects.size(); currentProject++) {
61
                        project = ((Project)config.projects.get(currentProject));
62
                        
63
                        for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
64
                                lang = (String) config.languages[currentLang];
65
                                dict = (Properties) project.dictionaries.get(lang);
66
                                
67
                                if (dict.size()>0) {
68
                                        // ensure the directory exists
69
                                        File propertyDir = new File(project.propertyDir);
70
                                        if (propertyDir.mkdirs())
71
                                                System.out.println("Aviso -- directorio creado: "+project.propertyDir);
72
                                        
73
                                        try {
74
                                                // different for spanish...
75
                                                if (lang.equals("es")) {
76
                                                        stream = new FileOutputStream(project.propertyDir+File.separator+project.basename+".properties");
77
                                                }
78
                                                else {
79
                                                        stream = new FileOutputStream(project.propertyDir+File.separator+project.basename+"_"+lang+".properties");
80
                                                }
81
                                        } catch (FileNotFoundException e) {
82
                                                // TODO Auto-generated catch block
83
                                                e.printStackTrace();
84
                                        }
85
        
86
                                        try {
87
                                                dict.store(stream, "Translations for language ["+lang+"]");
88
                                        } catch (IOException e) {
89
                                                // TODO Auto-generated catch block
90
                                                e.printStackTrace();
91
                                        }
92
                                }
93
                        }
94
                }        
95
        }
96
        
97
        private HashMap loadProjectFromSources(Project project) {
98
                // always start with an empty HashMap when loading
99
                HashMap dictionaries = new HashMap();                
100
                String lang;
101
                
102
                /**
103
                 * The keys obtained from the sources and the config.xml files of the
104
                 * plugins.
105
                 */
106
                HashSet keys = new HashSet();
107
                /**
108
                 * The translations loaded from the property files of the project.
109
                 */
110
                
111
                dictionaries =  loadProjectFromProperties(project);
112
                
113
                for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
114
                        lang = config.languages[currentLang];
115
                        
116
                        for (int i=0; i<project.srcDirs.length; i++) {
117
                                try {
118
                                        keys = loadKeysFromSources(ConfigOptions.getAbsolutePath(File.separator, project.dir+File.separator+project.srcDirs[i]), keys);
119
                                }
120
                                catch (IOException ex) {
121
                                        // It there was an error reading the directory, just warn and skip the dir
122
                                        System.err.println(project.dir +" -- Aviso: no se pudo leer el directorio "+project.dir+File.separator+project.srcDirs[i]);
123
                                }
124
                        }
125
                        Properties currentDict = (Properties) dictionaries.get(lang);
126
                        Iterator keysIterator = keys.iterator();
127
                        String key;
128
                        // add missing keys
129
                        while (keysIterator.hasNext()) {
130
                                key = (String) keysIterator.next();
131
                                if (!currentDict.containsKey(key)) {
132
                                        currentDict.put(key, "");
133
                                        System.out.println(project.dir+" -- Aviso -- clave a?adida: "+key);
134
                                }
135
                        }
136
                        // remove extra keys
137
                        Enumeration dictKey = currentDict.keys();
138
                        while (dictKey.hasMoreElements()) {
139
                                key = (String) dictKey.nextElement();
140
                                if (!keys.contains(key)) {
141
                                        currentDict.remove(key);
142
                                        System.out.println(project.dir+" -- Aviso -- clave eliminada: "+key);
143
                                }
144
                        }
145
                }
146

    
147
                return dictionaries;
148
        }
149
        
150
        
151
        private HashSet loadKeysFromSources(String directory, HashSet keys) {
152
                String key;
153
                File dir = new File(directory);
154
                File files[] = dir.listFiles();
155
                if (files!=null) {
156
                        
157
                        //Pattern keyPattern1 = Pattern.compile("(PluginServices|Messages)\\.(getText|getString|get)\\(.*\"(.*)\".*\\)");
158
                        Pattern keyPattern1 = Pattern.compile("(PluginServices|Messages)\\.(getText|getString|get)\\([^\"\\)]*\"([^\"]*)\"[^\\)]*\\)");
159
 
160
                        Matcher keyMatcher1 = keyPattern1.matcher("");
161
                        
162
                        for (int i=0; i<files.length; i++) {
163
                                if (files[i].isDirectory()) {
164
                                        keys = loadKeysFromSources(files[i].toString(), keys);                                
165
                                }
166
                                if (files[i].getName().toLowerCase().equals("PluginServices")) {
167
                                        //[Messages.]getText(...)
168
                                //        Pattern PsPattern = Pattern.compile("(Messages\\.)*getText\\(.*\"(.*)\".*\\)");
169
                                        Pattern PsPattern = Pattern.compile("(Messages\\.)*getText\\([^\"\\)]*\"([^\"]*)\"[^\\)]*\\)");
170
                                        Matcher PsMatcher = PsPattern.matcher("");
171
                                        
172
                                        FileInputStream fis=null;
173
                                        try {
174
                                                fis = new FileInputStream(files[i]);
175
                                                
176
                                                BufferedReader currentFile=null;
177
                                                try {
178
                                                        currentFile = new BufferedReader(new InputStreamReader(fis, config.sourcesEncoding));
179
                                                } catch (UnsupportedEncodingException e1) {
180
                                                        // TODO Auto-generated catch block
181
                                                        e1.printStackTrace();
182
                                                }
183
                                                
184
                                            String line = null;
185
                                            try {
186
                                                        while((line = currentFile.readLine()) != null) {
187
                                                                PsMatcher.reset(line);
188
                                                                while (PsMatcher.find()) {
189
                                                                        key = PsMatcher.group(2);
190
                                                                        if (!key.equals(""))
191
                                                                                keys.add(key);
192
                                                                }
193
                                                        }
194
                                                    currentFile.close();
195
                                                } catch (IOException e) {
196
                                                        System.err.println("Error inesperado:"+ e.getLocalizedMessage());
197
                                                }
198
                                        } catch (FileNotFoundException e) {
199
                                                // the file is supposed to exist, so we are never supposed to arrive here
200
                                                System.err.println("Error inesperado:"+ e.getLocalizedMessage());
201
                                        }
202
                                }
203
                                else if (files[i].getName().toLowerCase().endsWith(".java")) {
204
                                        FileInputStream fis=null;
205
                                        try {
206
                                                fis = new FileInputStream(files[i]);
207
                                                
208
                                                BufferedReader currentFile=null;
209
                                                try {
210
                                                        currentFile = new BufferedReader(new InputStreamReader(fis, config.sourcesEncoding));
211
                                                } catch (UnsupportedEncodingException e1) {
212
                                                        // TODO Auto-generated catch block
213
                                                        e1.printStackTrace();
214
                                                }
215
                                                
216
                                            String line = null;
217
                                            try {
218
                                                        while((line = currentFile.readLine()) != null) {
219
                                                                keyMatcher1.reset(line);
220
                                                                while (keyMatcher1.find()) {
221
                                                                        key = keyMatcher1.group(3);
222
                                                                        if (!key.equals(""))
223
                                                                                keys.add(key);
224
                                                                }
225
                                                        }
226
                                                    currentFile.close();
227
                                                } catch (IOException e) {
228
                                                        System.err.println("Error inesperado:"+ e.getLocalizedMessage());
229
                                                }
230
                                        } catch (FileNotFoundException e) {
231
                                                // the file is supposed to exist, so we are never supposed to arrive here
232
                                                System.err.println("Error inesperado:"+ e.getLocalizedMessage());
233
                                        }
234
                                }
235
                                else if (files[i].getName().equalsIgnoreCase("config.xml")) {
236
                                        keys = loadKeysFromXml(files[i], keys);
237
                                }
238
                        }
239
                }
240
                
241
                return keys;
242
        }
243
        
244
        
245
        private HashSet loadKeysFromXml(File fileName, HashSet keys) {
246
                KXmlParser parser = new KXmlParser();
247
                String tagname, attribute;
248
                
249
                // we use null encoding, in this way kxml2 tries to detect the encoding
250
                try {
251
                        parser.setInput(new FileInputStream(fileName), null);
252
                } catch (FileNotFoundException e1) {
253
                        System.err.println(e1.getLocalizedMessage());
254
                        return keys;
255
                } catch (XmlPullParserException e1) {
256
                        // No podemos leer el fichero de configuraci?n. Usamos valores por defecto
257
                        System.err.println("Aviso: error al cargar el fichero "+fileName);
258
                        return keys;
259
                }
260
                
261
                try {
262
                        for (parser.next(); parser.getEventType()!=KXmlParser.END_DOCUMENT; parser.next()) {
263
                                // este bucle externo recorre las etiquetas de primer y segundo nivel
264
                                if (parser.getEventType()==KXmlParser.START_TAG) {
265
                                        tagname = parser.getName();
266
                                        if (tagname.equals("menu") || tagname.equals("action-tool") || tagname.equals("selectable-tool") || tagname.equals("entry")) {
267
                                                attribute = parser.getAttributeValue(null, "text");
268
                                                if (attribute!=null) {
269
                                                        String menuParts[] = attribute.split("/");
270
                                                        for (int i=0; i<menuParts.length; i++) {
271
                                                                if (!menuParts[i].equals(""))
272
                                                                        keys.add(menuParts[i]);
273
                                                        }
274
                                                }
275
                                                
276
                                                attribute = parser.getAttributeValue(null, "tooltip");
277
                                                if (attribute!=null && !attribute.equals("")) {
278
                                                        keys.add(attribute);
279
                                                }
280
                                                
281
                                                
282
                                        }
283
                                        /*else if (tagname.equals("extension")) {
284
                                                attribute = parser.getAttributeValue(null, "description");
285
                                                if (attribute!=null) {
286
                                                        keys.add(attribute);
287
                                                }
288
                                        }*/
289
                                }
290
                        }        
291
                } catch (XmlPullParserException e1) {
292
                        e1.getLocalizedMessage();
293
                } catch (IOException e1) {
294
                        e1.getLocalizedMessage();
295
                }
296
                return keys;
297
        }
298
        
299
        private HashMap loadProjectFromProperties(Project project) {
300
                // always start with an empty HashMap when loading
301
                HashMap dictionaries = new HashMap();
302
                String lang;
303
                Properties dictionary;
304
                
305
                FileInputStream stream=null;
306
                
307
                for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
308
                        lang = config.languages[currentLang];
309
                        dictionary = new Properties();
310
                        try {
311
                                // different for spanish...
312
                                if (lang.equals("es")) {
313
                                        stream = new FileInputStream(project.propertyDir+File.separator+project.basename+".properties");
314
                                }
315
                                else {
316
                                        stream = new FileInputStream(project.propertyDir+File.separator+project.basename+"_"+lang+".properties");
317
                                }
318
                                try {
319
                                        dictionary.load(stream);
320
                                } catch (IOException e) {
321
                                        System.err.println("Error cargando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
322
                                }
323
                        } catch (FileNotFoundException e) {
324
                                System.err.println(project.dir + " -- Error cargando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
325
                        }
326
                        dictionaries.put(lang, dictionary);
327
                }
328
                return dictionaries;
329
        }
330
}