Revision 43082

View differences:

tags/org.gvsig.desktop-2.0.167/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/Project.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.i18n.utils;
25

  
26
import java.util.HashMap;
27

  
28
/**
29
 * Convenience class to manage the attributes of the project tag from the config.xml
30
 * file.
31
 * 
32
 * 
33
 * @author cesar
34
 *
35
 */
36
public class Project {
37

  
38
	public String dir;
39
	public String basename;
40
	
41
	/**
42
	 * The directory which stores the property files of the project.
43
	 */
44
	public String propertyDir;
45
	
46
	/**
47
	 * Source of the keys: whether they are loaded from the property files of
48
	 * the project or they are searched inside the sources.
49
	 * <ul><li>sourceKeys="sources": The keys are searched inside the Java source
50
	 * files and the config.xml files from the extensions.</li>
51
	 * <li>sourceKeys="properties": The keys are loaded from the property files
52
	 * of each project.</li></ul> 
53
	 */
54
	public String sourceKeys;
55
	
56
	/**
57
	 * Stores the associated dictionaries. Each value of the
58
	 * HashMap is a Properties object, containing the translations for each
59
	 * language.
60
	 * 
61
	 * <p>Example:</p>
62
	 * Properties dictionary = (Properties)dictionaries.get("es");
63
	 * 
64
	 */
65
	public HashMap dictionaries;
66
	
67
	/**
68
	 * Stores the subdirectories containing sources. When searching for keys in
69
	 * the source files, only these subdirectories will be searched.
70
	 */
71
	public String[] srcDirs;
72
	
73
}
0 74

  
tags/org.gvsig.desktop-2.0.167/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/DoubleProperties.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.i18n.utils;
25

  
26
import java.io.IOException;
27
import java.io.InputStream;
28
import java.util.ArrayList;
29
import java.util.HashMap;
30
import java.util.Iterator;
31

  
32
/**
33
 * The DoubleProperties class represents a set of properties. It provides the
34
 * same functionality as its parent class, Properties. Besides that, it also
35
 * provides an efficient method to get the key associated with a value.  
36
 * 
37
 * @author cesar
38
 *
39
 */
40
public class DoubleProperties extends OrderedProperties {
41
	/**
42
	 * 
43
	 */
44
	private static final long serialVersionUID = -1738114064256800193L;
45
	HashMap reverseMap = new HashMap();
46

  
47
	public DoubleProperties() {
48
		super();
49
	}
50
	
51

  
52
	public DoubleProperties(OrderedProperties defaults) {
53
		super(defaults);
54
		Iterator keysIterator = this.keySet().iterator();
55
		ArrayList keySet;
56
		
57
		String key, value;
58
		while (keysIterator.hasNext()) {
59
			key = (String) keysIterator.next();
60
			value = this.getProperty(key);
61
			if (reverseMap.containsKey(value)) {
62
				keySet = (ArrayList) reverseMap.get(value);
63
				keySet.add(key);
64
			}
65
			else {
66
				keySet = new ArrayList();
67
				keySet.add(key);
68
				reverseMap.put(value, keySet);
69
			}
70
		}
71
	}
72
	
73
	
74
	public void load(InputStream stream) throws IOException {
75
		super.load(stream);
76

  
77
		Iterator keysIterator = this.keySet().iterator();
78
		ArrayList keySet;
79
		
80
		String key, value;
81
		while (keysIterator.hasNext()) {
82
			key = (String) keysIterator.next();
83
			value = this.getProperty(key);
84
			if (reverseMap.containsKey(value)) {
85
				keySet = (ArrayList) reverseMap.get(value);
86
				keySet.add(key);
87
			}
88
			else {
89
				keySet = new ArrayList();
90
				keySet.add(key);
91
				reverseMap.put(value, keySet);
92
			}
93
		}
94
	}
95
	
96
	public Object setProperty(String key, String value) {
97
		ArrayList keySet;
98
		
99
		Object returnValue = super.setProperty(key, value);
100
		if (reverseMap.containsKey(value)) {
101
			keySet = (ArrayList) reverseMap.get(value);
102
			keySet.add(key);
103
		}
104
		else {
105
			keySet = new ArrayList();
106
			keySet.add(key);
107
			reverseMap.put(value, keySet);
108
		}
109
		
110
		return returnValue;
111
	}
112
	
113
	/**
114
	 * Gets the key associated with the provided value. If there
115
	 * are several associated keys, returns one of them.
116
	 * 
117
	 * @param value
118
	 * @return The key associated with the provided value, or null
119
	 * if the value is not present in the dictionary. If there
120
	 * are several associated keys, returns one of them.
121
	 */
122
	public String getAssociatedKey(String value) {
123
		ArrayList keySet = (ArrayList) reverseMap.get(value);
124
		if (keySet==null) return null;
125
		return (String) keySet.get(0);
126
	}
127
	
128
	/**
129
	 * Returns the keys associated with the provided value. If there
130
	 * are several associated keys, returns one of them.
131
	 * 
132
	 * @param value
133
	 * @return An ArrayList containing the keys associated with the
134
	 * provided value, or null if the value is not present in the 
135
	 * dictionary.
136
	 */
137
	public ArrayList getAssociatedKeys(String value) {
138
		return (ArrayList) reverseMap.get(value);
139
	}
140
	
141
	public Object remove(Object key) {
142
		Object value = super.remove(key);
143
		if (value==null) return null;
144
		ArrayList keySet = (ArrayList) reverseMap.get(value);
145
		if (keySet==null) return null;
146
		if (keySet.size()<=1) {
147
			//if it's the last key associated wit the value, remove the
148
			// value from the reverseDictionary			
149
			reverseMap.remove(value);
150
		}
151
		else {
152
			// otherwise, remove the key from the list of associated keys
153
			keySet.remove(key);
154
		}
155
		return value;
156
	}	
157
}
0 158

  
tags/org.gvsig.desktop-2.0.167/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/UpdateTrans.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.i18n.utils;
25

  
26
import java.io.BufferedWriter;
27
import java.io.File;
28
import java.io.FileNotFoundException;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.OutputStreamWriter;
32
import java.io.UnsupportedEncodingException;
33
import java.util.ArrayList;
34
import java.util.HashMap;
35
import java.util.Iterator;
36
import java.util.TreeMap;
37

  
38
/**
39
 * @author cesar
40
 *
41
 */
42
public class UpdateTrans {
43
	// The filename which stores the configuration (may be overriden by the command line parameter)
44
	private String configFileName = "config.xml";
45
	
46
	// Object to load and store the config options
47
	private ConfigOptions config;
48
	
49
	private TranslationDatabase database;
50

  
51
	/**
52
	 * @param args
53
	 */
54
	public static void main(String[] args) {
55
		UpdateTrans process = new UpdateTrans();
56
		
57
		// load command line parameters
58
		if (!process.readParameters(args)) {
59
			usage();
60
			System.exit(-1);
61
		}
62
		
63
		// transfer control to the program's main loop
64
		process.start();
65
	}
66
	
67
	private void start() {
68
		// load config options from the config file
69
		if (!loadConfig()) {
70
			System.out.println("Error leyendo el fichero de configuraci?n.");
71
			usage();
72
			System.exit(-1);
73
		}
74
		
75
		loadKeys();
76
		loadDataBase();
77
		
78
		updateDB();
79
	}
80
	
81
	private void updateDB(){
82
		String lang, auxLang;
83
		String key, value, dbValue;
84
		
85
		HashMap newKeys = detectNewKeys();
86
		TreeMap newKeysDict;
87
		HashMap removedKeys = new HashMap();
88
		
89
		ArrayList removedKeysDict;
90

  
91
		/**
92
		 * Process the new or changed keys
93
		 */
94
		for (int i=0; i<config.languages.length; i++) {
95
			lang = config.languages[i];
96
			File langDir = new File(config.outputDir+File.separator+lang);
97
			langDir.mkdirs();
98
			
99
			// process the keys
100
			newKeysDict = (TreeMap) newKeys.get(lang);
101
			removedKeysDict = new ArrayList();
102
			removedKeys.put(lang, removedKeysDict);
103
			Iterator newKeysIterator = newKeysDict.keySet().iterator();
104
			while (newKeysIterator.hasNext()) {
105
				int numValues=0;
106
				value = null;
107
				key = (String) newKeysIterator.next();
108
				
109
				dbValue = database.getTranslation(lang, key);
110
				ArrayList newKeyList = (ArrayList) newKeysDict.get(key);
111
				String[] newKey;
112
				boolean equal=true;
113
				for (int j=0; j<newKeyList.size(); j++) {
114
					newKey = (String[]) newKeyList.get(j);
115
					if (!newKey[0].equals("")) {
116
						if (dbValue!=null && !dbValue.equals(newKey[0]))
117
							equal = false;
118
						if (numValues==0) { //if there are several non-empty values, take the first one
119
							value = newKey[0];
120
						}
121
						else if (!value.equals(newKey[0])) {
122
							equal=false;
123
						}
124
						numValues++;	
125
					}
126
				}
127
				if (equal==false) {
128
					System.err.println("\nAtenci?n -- La clave '"+key+"' tiene diferentes valores para el idioma "  + lang + ".");
129
					System.err.println("Valor en base de datos: "+key+"="+dbValue);
130
					for (int j=0; j<newKeyList.size(); j++) {
131
						newKey = (String[]) newKeyList.get(j);
132
						System.err.println(newKey[1] + " -- " + key + "=" + newKey[0]);
133
					}
134
				}
135
				if (value!=null && !value.equals("")) { // the translation has a value
136
					if (dbValue==null) {
137
						// new translation
138
						database.setTranslation(lang, key, value);
139
						// it has been added to database, it isn't new anymore
140
						// we add the key to the list of keys to remove. We don't remove it now because then there is troubles with the iterator
141
						removedKeysDict.add(key);
142
					}
143
					else if (!dbValue.equals("")) {
144
						// if dbValue contains a translation, it isn't a new translation
145
						removedKeysDict.add(key);
146
					}
147
					/*
148
					 * else { // if dbValue.equals(""), it means that the key has been changed, and it must be sent for translation
149
					 *       //It should not be added to the database with the value from the property file, as it is not valid anymore.
150
					 * 
151
					 * }
152
					 */
153
				}
154
			}
155
		}
156
		
157
		// remove 
158
		for (int i=0; i<config.languages.length; i++) {
159
			lang = config.languages[i];
160
			removedKeysDict = (ArrayList) removedKeys.get(lang);
161
			newKeysDict = (TreeMap) newKeys.get(lang);
162
			Iterator removeIterator = removedKeysDict.iterator();
163
			while (removeIterator.hasNext()) {
164
				key = (String) removeIterator.next();
165
				newKeysDict.remove(key);
166
			}
167
		}
168
		
169
		removedKeys = new HashMap();
170
		
171
		// we already added all the new keys with value to the database
172
		// now we try to find a translation for the keys without translation
173
		for (int i=0; i<config.languages.length; i++) {
174
			lang = config.languages[i];
175
			File langDir = new File(config.outputDir+File.separator+lang);
176
			langDir.mkdirs();
177
			
178
			// process the keys
179
			newKeysDict = (TreeMap) newKeys.get(lang);
180
			removedKeysDict = new ArrayList();
181
			removedKeys.put(lang, removedKeysDict);
182
			Iterator newKeysIterator = newKeysDict.keySet().iterator();
183
			while (newKeysIterator.hasNext()) {
184
				key = (String) newKeysIterator.next();
185
				value = "";
186
				String auxValue;
187
				for (int currentAuxLang=0; currentAuxLang<config.languages.length && (value==null || value.equals("")); currentAuxLang++) {
188
					auxLang = config.languages[currentAuxLang];
189
					auxValue = database.getTranslation(auxLang, key);
190
					if (auxValue!=null && !auxValue.equals("")) {
191
						ArrayList keyList = database.getAssociatedKeys(auxLang, value);
192
						if (keyList!=null) {
193
							for (int j=0; j<keyList.size() && (value==null || !value.equals("")); j++) {
194
								value = database.getTranslation(lang, (String)keyList.get(j));
195
							}
196
						}
197
					}
198
				}
199
				if (value!=null && !value.equals("")) { // the translation has a value
200
					dbValue = database.getTranslation(lang, key);
201
					if (dbValue==null || !dbValue.equals("")) {
202
						/* if dbValue == "" means that the key has been changed and should be sent for translation.
203
						 * It should not be added to the database with the value from the property file, as it is not valid anymore.
204
						 */
205
											
206
						database.setTranslation(lang, key, value);
207
						// it has been added to database, it isn't new anymore
208
						// we add the key to the list of keys to remove. We don't remove it now because then there is troubles with the iterator
209
						removedKeysDict.add(key);
210
					}
211
				}
212
			}
213
		}
214
		
215
		// remove 
216
		for (int i=0; i<config.languages.length; i++) {
217
			lang = config.languages[i];
218
			removedKeysDict = (ArrayList) removedKeys.get(lang);
219
			newKeysDict = (TreeMap) newKeys.get(lang);
220
			Iterator removeIterator = removedKeysDict.iterator();
221
			while (removeIterator.hasNext()) {
222
				key = (String) removeIterator.next();
223
				newKeysDict.remove(key);
224
			}
225
		}
226
		
227
		// output the keys to be translated
228
		outputNewKeys(newKeys);
229
		
230
		// update the values of each project's property files and store to disk
231
		saveKeys();
232
		
233
		// store datase to disk
234
		database.save();
235
	}
236
	
237
	private void outputNewKeys(HashMap newKeys) {
238
		String lang, auxLang;
239
		/**
240
		 * Process the new or changed keys
241
		 */
242
		for (int i=0; i<config.languages.length; i++) {
243
			lang = config.languages[i];
244
			File langDir = new File(config.outputDir+File.separator+lang);
245
			langDir.mkdirs();
246
			HashMap outputFiles = new HashMap();
247
			HashMap outputPropertiesStream = new HashMap();
248
			HashMap outputProperties = new HashMap();
249
			
250
			// open the output files, one for each defined language
251
			for (int j=0; j<config.outputLanguages.length; j++) {
252
				auxLang = config.outputLanguages[j];
253
				FileOutputStream fos, fosProp;
254
				OrderedProperties prop;
255
				try {
256
					fos = new FileOutputStream(langDir.getPath()+File.separator+config.defaultBaseName+"_"+auxLang+".properties-"+config.outputEncoding);
257
					fosProp = new FileOutputStream(langDir.getPath()+File.separator+config.defaultBaseName+"_"+auxLang+".properties");
258
					prop = new OrderedProperties();
259
					outputPropertiesStream.put(auxLang, fosProp);
260
					outputProperties.put(auxLang, prop);
261
					try {
262
						outputFiles.put(auxLang, new BufferedWriter(new OutputStreamWriter(fos, config.outputEncoding)));
263
					} catch (UnsupportedEncodingException e) {
264
						// TODO Auto-generated catch block
265
						System.err.println(e.getLocalizedMessage());
266
						System.exit(-1);
267
					}
268
				} catch (FileNotFoundException e) {
269
					// TODO Auto-generated catch block
270
					System.err.println(e.getLocalizedMessage());
271
					System.exit(-1);
272
				}
273
			}
274
			
275
			// also open the file for language we're processing currently
276
			if (!outputFiles.containsKey(lang)) {
277
				FileOutputStream fos, fosProp;
278
				OrderedProperties prop;
279
				try {
280
					fos = new FileOutputStream(langDir.getPath()+File.separator+config.defaultBaseName+"_"+lang+".properties-"+config.outputEncoding);
281
					fosProp = new FileOutputStream(langDir.getPath()+File.separator+config.defaultBaseName+"_"+lang+".properties");
282
					prop = new OrderedProperties();
283
					outputPropertiesStream.put(lang, fosProp);
284
					outputProperties.put(lang, prop);
285
					try {
286
						outputFiles.put(lang, new BufferedWriter(new OutputStreamWriter(fos, config.outputEncoding)));
287
					} catch (UnsupportedEncodingException e) {
288
						// TODO Auto-generated catch block
289
						System.err.println(e.getLocalizedMessage());
290
						System.exit(-1);
291
					}
292
				} catch (FileNotFoundException e) {
293
					// TODO Auto-generated catch block
294
					System.err.println(e.getLocalizedMessage());
295
					System.exit(-1);
296
				}
297
			}
298
			
299
			TreeMap dict = (TreeMap) newKeys.get(lang);
300
			Iterator keyIterator = dict.keySet().iterator();
301
			String key, value;
302
			while (keyIterator.hasNext()) {
303
				key = (String) keyIterator.next();
304

  
305
				Iterator files = outputFiles.keySet().iterator();
306
				BufferedWriter writer;
307
				while (files.hasNext()) {
308
					// we output the pair key-value for the defined output languages (they're used for reference by translators)							
309
					auxLang = (String) files.next();
310
					writer = (BufferedWriter) outputFiles.get(auxLang);
311
					value = database.getTranslation(auxLang, key);
312
					try {
313
						if (value!=null)
314
							writer.write(key+"="+value+"\n");
315
						else
316
							writer.write(key+"=\n");
317
					} catch (IOException e) {
318
						// TODO Auto-generated catch block
319
						e.printStackTrace();
320
					}
321
				}
322
				Iterator props = outputProperties.keySet().iterator();
323
				OrderedProperties prop;
324
				while (props.hasNext()) {
325
					// we output the pair key-value for the defined output languages (they're used for reference by translators)							
326
					auxLang = (String) props.next();
327
					prop = (OrderedProperties) outputProperties.get(auxLang);
328
					value = database.getTranslation(auxLang, key);
329
					if (value!=null)
330
						prop.put(key, value);
331
					else
332
						prop.put(key, "");
333
				}
334
			}
335
			
336
			Iterator props = outputProperties.keySet().iterator();
337
			OrderedProperties prop;
338
			FileOutputStream fos;
339
			while (props.hasNext()) {
340
				auxLang = (String) props.next();
341
				fos = (FileOutputStream) outputPropertiesStream.get(auxLang);
342
				prop = (OrderedProperties) outputProperties.get(auxLang);
343
				try {
344
					prop.store(fos, "Translations for language ["+auxLang+"]");
345
				} catch (IOException e) {
346
					// TODO Auto-generated catch block
347
					e.printStackTrace();
348
				}
349
			}
350
			
351
			// close the files now
352
			Iterator files = outputFiles.keySet().iterator();
353
			while (files.hasNext()) {							
354
				auxLang = (String) files.next();
355
				BufferedWriter writer = (BufferedWriter) outputFiles.get(auxLang);
356
				try {
357
					writer.close();
358
				} catch (IOException e) {
359
					// do nothing here
360
				}
361
			}
362
		}		
363
	}
364
		
365
	private HashMap detectNewKeys() {
366
		Project currentProject;
367
		String lang;
368
		OrderedProperties dict;
369
		TreeMap auxDict;
370
		Iterator keys;
371
		String key, value, dbValue;
372
		HashMap newKeys = new HashMap();
373
		for (int i=0; i<config.languages.length; i++) {
374
			lang = config.languages[i];
375
			newKeys.put(lang, new TreeMap());
376
		}
377
	
378
		/**
379
		 * Detect the new or changed keys
380
		 * We just make a list, we will check the list later (to detect conflicting changes)
381
		 */
382
		for (int i=0; i<config.projects.size(); i++) {
383
			currentProject = (Project) config.projects.get(i);
384
			for (int j=0; j<config.languages.length; j++) {
385
				lang = config.languages[j];
386
				dict = (OrderedProperties) currentProject.dictionaries.get(lang);
387
				keys = dict.keySet().iterator();
388
				while (keys.hasNext()) {
389
					key = (String) keys.next();
390
					value = dict.getProperty(key);
391
					dbValue = database.getTranslation(lang, key);
392
					if (dbValue==null || dbValue.equals("") || (!value.equals("") && !dbValue.equals(value))) {
393
						String []newKey = new String[2];
394
						newKey[0]=value;
395
						newKey[1]= currentProject.dir;
396
						auxDict = (TreeMap) newKeys.get(lang);
397
						ArrayList keyList = (ArrayList) auxDict.get(key);
398
						if (keyList==null) {
399
							keyList = new ArrayList();
400
						}
401
						keyList.add(newKey);
402
						auxDict.put(key, keyList);
403
					}
404
				}
405
			}
406
		}
407
		return newKeys;
408
	}
409
	
410
	private static void usage() {
411
		System.out.println("Uso: UpdateTrans [OPCION]");
412
		System.out.println("\t-c\t--config=configFile");
413
	}
414
	
415
	/**
416
	 *  Reads the command line parameters */
417
	private boolean readParameters(String[] args) {
418
		String configPair[];
419

  
420
		for (int i=0; i<args.length; i++) {
421
			configPair = args[i].split("=",2);
422
			if ( (configPair[0].equals("-c") || configPair[0].equals("--config"))
423
					&& configPair.length==2) {
424
				configFileName = configPair[1];
425
			}
426
			else {
427
				return false;
428
			}
429
		}
430
		return true;
431
	}
432
	
433
	private boolean loadConfig() {
434
		config = new ConfigOptions(configFileName);
435
		config.load();
436
		return true;
437
	}
438
	
439
	/**
440
	 * Reads the translation keys from the projects speficied in
441
	 * the config file. The keys are stored for each project in
442
	 * 'config.projects'. 
443
	 * 
444
	 * @return
445
	 */
446
	private void loadKeys() {
447
		Keys keys = new Keys(config);
448
		keys.load();
449
	}
450
	
451
	private void saveKeys() {
452
		Project project;
453
		OrderedProperties dict;
454
		String lang;
455
		
456
		for (int currentProject=0; currentProject<config.projects.size(); currentProject++) {
457
			project = ((Project)config.projects.get(currentProject));
458
			
459
			for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
460
				lang = (String) config.languages[currentLang];
461
				dict = (OrderedProperties) project.dictionaries.get(lang);
462
				String dbValue, key;
463

  
464
				Iterator keysIterator = dict.keySet().iterator();
465
				while (keysIterator.hasNext()) {
466
					key = (String) keysIterator.next();
467
					dbValue = database.getTranslation(lang, key);
468
					if (dbValue!=null) {
469
						dict.setProperty(key, dbValue);
470
					}
471
				}
472
			}
473
		}
474
		
475
		Keys keys = new Keys(config);
476
		keys.save();
477
	}
478
	
479
	private void loadDataBase() {
480
		database = new TranslationDatabase(config);
481
		database.load();
482
	}
483

  
484
}
0 485

  
tags/org.gvsig.desktop-2.0.167/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/Keys.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.i18n.utils;
25

  
26
import java.io.BufferedReader;
27
import java.io.File;
28
import java.io.FileInputStream;
29
import java.io.FileNotFoundException;
30
import java.io.FileOutputStream;
31
import java.io.IOException;
32
import java.io.InputStreamReader;
33
import java.io.UnsupportedEncodingException;
34
import java.util.HashMap;
35
import java.util.HashSet;
36
import java.util.Iterator;
37
import java.util.regex.Matcher;
38
import java.util.regex.Pattern;
39

  
40
import org.kxml2.io.KXmlParser;
41
import org.xmlpull.v1.XmlPullParserException;
42

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

  
146
			OrderedProperties currentDict = (OrderedProperties) dictionaries.get(lang);
147
			Iterator keysIterator = keys.iterator();
148
			String key;
149
			// add missing keys
150
			while (keysIterator.hasNext()) {
151
				key = (String) keysIterator.next();
152
				if (!currentDict.containsKey(key)) {
153
					currentDict.put(key, "");
154
					System.out.println(project.dir+" -- Aviso -- clave a?adida: "+key);
155
				}
156
			}
157
			
158
			// remove extra keys
159
			// first make a list of keys to remove, because it's not possible to access the iterator and the TreeMap at the same time
160
		/*	HashSet removedKeys = new HashSet();
161
			Iterator dictKey = currentDict.keySet().iterator();
162
			while (dictKey.hasNext()) {
163
				key = (String) dictKey.next();
164
				if (!keys.contains(key)) {
165
					removedKeys.add(key);
166
					System.out.println(project.dir+" -- Aviso -- clave eliminada: "+key);
167
				}
168
			}
169
			// now we really remove the keys
170
			Iterator removedKeysIt = removedKeys.iterator();
171
			while (removedKeysIt.hasNext()) {
172
				key = (String) removedKeysIt.next();
173
				currentDict.remove(key);
174
			}*/	
175
		}
176

  
177
		return dictionaries;
178
	}
179
	
180
	/**
181
	 * Reads the keys from all the languages, to make a unique list containing
182
	 * all the keys. 
183
	 */
184
	public void completeKeys(Project project) {
185
		/* The list of all the keys */
186
		HashSet keys = new HashSet();
187
		// always start with an empty HashMap when loading
188
		//HashMap dictionaries = new HashMap();		
189
		String lang;
190
		
191
		// calculate all the keys
192
		for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
193
			lang = config.languages[currentLang];
194
			
195
			OrderedProperties currentDict = (OrderedProperties) project.dictionaries.get(lang);
196
			if (currentDict==null) {
197
				currentDict = new OrderedProperties();
198
				project.dictionaries.put(lang, currentDict);
199
			}
200
			else {
201
				Iterator keysIterator = currentDict.keySet().iterator();
202
				String key;
203
				// add missing keys
204
				while (keysIterator.hasNext()) {
205
					key = (String) keysIterator.next();
206
					keys.add(key);
207
				}	
208
			}
209
		}
210
		
211
		// add missing keys to each language
212
		for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
213
			lang = config.languages[currentLang];
214
			
215
			OrderedProperties currentDict = (OrderedProperties) project.dictionaries.get(lang);
216
			Iterator keysIterator = keys.iterator();
217
			String key;
218
			// add missing keys
219
			while (keysIterator.hasNext()) {
220
				key = (String) keysIterator.next();
221
				if (!currentDict.containsKey(key)) {
222
					currentDict.put(key, "");
223
					System.out.println(project.dir+" -- Aviso -- clave a?adida: "+key);
224
				}
225
			}			
226
		}
227
	}
228
	
229
	
230
	private HashSet loadKeysFromSources(String directory, HashSet keys) {
231
		String key;
232
		File dir = new File(directory);
233
		File files[] = dir.listFiles();
234
		final int BLOCKSIZE = 8192;
235
		char[] partialBuffer = new char[BLOCKSIZE+1];
236
		String text;
237
		StringBuffer buffer;
238
		
239
		// stores the position of the newlines
240
		//ArrayList newLines = new ArrayList();
241
		//	int lineNumber;
242
		
243
		if (files!=null) {
244
			//Pattern keyPattern = Pattern.compile("(PluginServices|Messages)\\.(getText|getString|get)\\([^\"\\)]*\"([^\"]*)\"[^\\)]*\\)");
245
			Pattern keyPattern = Pattern.compile(
246
					"(PluginServices|Messages)\\p{Space}*\\.\\p{Space}*(getText|getString|get)\\p{Space}*\\([^\"\\)]*\"([^\"]*)\"[^\\+\\)]*(\\+[^\\)]*)*\\)");
247
			Matcher keyMatcher = keyPattern.matcher("");
248
					//"(PluginServices|Messages)\\.(getText|getString|get)\\p{Space}*\\([^\"\\)]*\"([^\"]*)\"[^\\+\\)]*(\\+[^\"]*\"([^\"]*)\"[^\\+\\)]*)*\\)");
249
			//Pattern newLinePattern = Pattern.compile("\n");
250
			//Matcher newLineMatcher = newLinePattern.matcher("");
251
			
252
			for (int i=0; i<files.length; i++) {
253
				if (files[i].isDirectory()) {
254
					keys = loadKeysFromSources(files[i].toString(), keys);
255
					continue;
256
				}
257
				else if (files[i].getName().toLowerCase().equals("PluginServices.java")) {
258
					
259
					//[Messages.]getText(...)
260
					Pattern PsPattern = Pattern.compile("(Messages\\.)*getText\\([^\"\\)]*\"([^\"]*)\"[^\\)]*\\)");
261
					Matcher PsMatcher = PsPattern.matcher("");
262
					
263
					FileInputStream fis=null;
264
					try {
265
						fis = new FileInputStream(files[i]);
266
						
267
						buffer = new StringBuffer();
268
						BufferedReader currentFile=null;
269
						
270
						currentFile = new BufferedReader(new InputStreamReader(fis, config.sourcesEncoding));
271
						while (currentFile.read(partialBuffer, 0, BLOCKSIZE)!=-1) {
272
							buffer.append(partialBuffer);
273
						}
274
						text = buffer.toString();
275
						
276
						
277
						PsMatcher.reset(text);
278
						
279
						while (PsMatcher.find()) {
280
							key = PsMatcher.group(2);
281
							if (!key.equals(""))
282
								keys.add(key);
283
						}
284
						currentFile.close();
285
					} catch (UnsupportedEncodingException e1) {
286
						System.err.println(e1.getLocalizedMessage());
287
						continue;
288
					}
289
					catch (IOException e1) {
290
						System.err.println(e1.getLocalizedMessage());
291
						continue;
292
					}
293
				}
294
				else if (files[i].getName().toLowerCase().endsWith(".java")) {
295
					FileInputStream fis=null;
296
					try {
297
						fis = new FileInputStream(files[i]);
298
						BufferedReader currentFile=null;
299
						
300
						currentFile = new BufferedReader(new InputStreamReader(fis, config.sourcesEncoding));
301
						buffer = new StringBuffer();
302
						
303
						int readChars; // number of characters which were read
304
						while ( (readChars = currentFile.read(partialBuffer, 0, BLOCKSIZE)) != -1) {
305
							buffer.append(partialBuffer, 0, readChars);
306
						}
307
						text = buffer.toString();
308
						
309
						/*newLineMatcher.reset(text);
310
						 while (newLineMatcher.find()) {
311
						 newLines.add(new Integer(newLineMatcher.end()-1));
312
						 }*/
313
						// lineNumber=1;
314
						
315
						keyMatcher.reset(text);
316
						
317
						while (keyMatcher.find()) {
318
							
319
							// find out in which line number we are
320
							/*while (keyMatcher.start() > ((Integer)newLines.get(lineNumber)).intValue() ) lineNumber++;
321
							 System.out.println("FileName: "+files[i].getCanonicalPath()+"; lineNumber: "+lineNumber);*/
322
							
323
//							StringBuffer keyBuffer = new StringBuffer();
324
							
325
//							for (int ii=0; ii<=keyMatcher.groupCount(); ii++) {
326
//							System.out.println("group: "+ ii+ "; " + keyMatcher.group(ii));
327
//							}
328
//							for (int groupNumb=3; groupNumb<=keyMatcher.groupCount(); groupNumb+=2) {
329
//							if (keyMatcher.group(groupNumb)!=null)
330
//							keyBuffer.append(keyMatcher.group(groupNumb));
331
//							}
332
							
333
							if (keyMatcher.group(4)!=null) {
334
								System.err.println("\nError: clave repartida en varias l?neas");
335
								System.err.println("Fichero: "+files[i].getCanonicalPath());
336
								System.err.println("C?digo: ");
337
								System.err.println(keyMatcher.group());
338
							}
339
							else {
340
								key = keyMatcher.group(3);
341
								if (!key.equals(""))
342
									keys.add(key);
343
							}
344
						}
345
						currentFile.close();
346
					} catch (UnsupportedEncodingException e1) {
347
						System.err.println(e1.getLocalizedMessage());
348
						continue;
349
					}
350
					catch (IOException e1) {
351
						System.err.println(e1.getLocalizedMessage());
352
						continue;
353
					}
354
				}
355
				else if (files[i].getName().equalsIgnoreCase("config.xml")) {
356
					keys = loadKeysFromXml(files[i], keys);
357
				}
358
			}
359
		}
360
		
361
		return keys;
362
	}
363
	
364
	
365
	private HashSet loadKeysFromXml(File fileName, HashSet keys) {
366
		KXmlParser parser = new KXmlParser();
367
		String tagname, attribute;
368
		
369
		// we use null encoding, in this way kxml2 tries to detect the encoding
370
		try {
371
			parser.setInput(new FileInputStream(fileName), null);
372
		} catch (FileNotFoundException e1) {
373
			System.err.println(e1.getLocalizedMessage());
374
			return keys;
375
		} catch (XmlPullParserException e1) {
376
			// No podemos leer el fichero de configuraci?n. Usamos valores por defecto
377
			System.err.println("Aviso: error al cargar el fichero "+fileName);
378
			return keys;
379
		}
380
		
381
		try {
382
			for (parser.next(); parser.getEventType()!=KXmlParser.END_DOCUMENT; parser.next()) {
383
				// este bucle externo recorre las etiquetas de primer y segundo nivel
384
				if (parser.getEventType()==KXmlParser.START_TAG) {
385
					tagname = parser.getName();
386
					if (tagname.equals("menu") || tagname.equals("action-tool") || tagname.equals("selectable-tool") || tagname.equals("entry")) {
387
						attribute = parser.getAttributeValue(null, "text");
388
						if (attribute!=null) {
389
							String menuParts[] = attribute.split("/");
390
							for (int i=0; i<menuParts.length; i++) {
391
								if (!menuParts[i].equals(""))
392
									keys.add(menuParts[i]);
393
							}
394
						}
395
						
396
						attribute = parser.getAttributeValue(null, "tooltip");
397
						if (attribute!=null && !attribute.equals("")) {
398
							keys.add(attribute);
399
						}
400
						
401
						
402
					}
403
					else if (tagname.equals("combo-scale")) {
404
						attribute = parser.getAttributeValue(null, "label");
405
						if (attribute!=null && !attribute.equals("")) {
406
							keys.add(attribute);
407
						}
408
					}
409
					else if (tagname.equals("tool-bar")) {
410
						attribute = parser.getAttributeValue(null, "name");
411
						if (attribute!=null && !attribute.equals("")) {
412
							keys.add(attribute);
413
						}
414
					}
415

  
416
				}
417
			}	
418
		} catch (XmlPullParserException e1) {
419
			e1.getLocalizedMessage();
420
		} catch (IOException e1) {
421
			e1.getLocalizedMessage();
422
		}
423
		return keys;
424
	}
425
	
426
	private HashMap loadProjectFromProperties(Project project) {
427
		// always start with an empty HashMap when loading
428
		HashMap dictionaries = new HashMap();
429
		String lang;
430
		OrderedProperties dictionary;
431
		
432
		FileInputStream stream=null;
433
		
434
		for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
435
			lang = config.languages[currentLang];
436
			dictionary = new OrderedProperties();
437
			try {
438
				// different for spanish...
439
				if (lang.equals("es")) {
440
					stream = new FileInputStream(project.propertyDir+File.separator+project.basename+".properties");
441
				}
442
				else {
443
					stream = new FileInputStream(project.propertyDir+File.separator+project.basename+"_"+lang+".properties");
444
				}
445
				try {
446
					dictionary.load(stream);
447
				} catch (IOException e) {
448
					System.err.println("Error cargando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
449
				}
450
			} catch (FileNotFoundException e) {
451
				System.err.println(project.dir + " -- Error cargando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
452
			}
453
			dictionaries.put(lang, dictionary);
454
		}
455
		return dictionaries;
456
	}
457
}
0 458

  
tags/org.gvsig.desktop-2.0.167/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/ConfigOptions.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.i18n.utils;
25

  
26
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.IOException;
30
import java.util.ArrayList;
31

  
32
import org.kxml2.io.KXmlParser;
33
import org.xmlpull.v1.XmlPullParserException;
34

  
35
public class ConfigOptions {
36
	// Default values
37
	public String defaultBaseName = "text";
38
	public String defaultBaseDir = ".";
39
	public String databaseDir = "database";
40
	private String configFileName = "config.xml";
41
	public String[] languages;
42
	public ArrayList projects = new ArrayList();
43
	private String defaultLangList="ca;cs;de;en;es;eu;fr;gl;it;pt";
44
	public String sourceKeys = "sources";
45
	private String defaultPropertyDir = "config";
46
	public String[] outputLanguages={"en", "es"};
47
	public String outputDir="output";
48
	public String inputDir="input";
49
	public String[] defaultSrcDirs={"src"};
50
	
51
	
52
	/**
53
	 * The character encoding of the Java source files, used to search keys in the sources.
54
	 */
55
	public String sourcesEncoding = "ISO8859_1";
56
	/**
57
	 * The character encoding of the generated output files for missing keys.
58
	 */
59
	public String outputEncoding = "UTF8";
60
	
61
	/**
62
	 * Creates a new ConfigOptions object.
63
	 */
64
	public ConfigOptions() {
65
		// Now we transform all directories to absolute canonical paths, so
66
		// that the are easier to manage afterwards.
67
		// It's also done at the end of parseVars method, but we must also do
68
		// it here, because parseVars() might not get executed.
69
		try {
70
			this.defaultBaseDir = getAbsolutePath(".", this.defaultBaseDir);
71
			this.databaseDir = getAbsolutePath(this.defaultBaseDir, this.databaseDir);
72
			this.outputDir = getAbsolutePath(this.defaultBaseDir, this.outputDir);
73
			this.inputDir = getAbsolutePath(this.defaultBaseDir, this.inputDir);
74
			
75
			/*
76
			 * 
77
			 File baseDirFile = new File(this.defaultBaseDir);
78
			this.defaultBaseDir = baseDirFile.getCanonicalPath();
79
			File databaseDirFile = new File(this.databaseDir);
80
			if (databaseDirFile.isAbsolute()) {
81
				this.databaseDir = databaseDirFile.getCanonicalPath();
82
			}
83
			else {
84
				this.databaseDir = (new File(this.defaultBaseDir+File.separator+this.databaseDir)).getCanonicalPath();
85
			}
86
			File outputDirFile = new File(this.outputDir);
87
			if (outputDirFile.isAbsolute()) {
88
				this.outputDir = outputDirFile.getCanonicalPath();
89
			}
90
			else {
91
				this.outputDir = (new File(this.defaultBaseDir+File.separator+this.outputDir)).getCanonicalPath();
92
			}
93
			File inputDirFile = new File(this.inputDir);
94
			if (inputDirFile.isAbsolute()) {
95
				this.inputDir = inputDirFile.getCanonicalPath();
96
			}
97
			else {
98
				this.inputDir = (new File(this.defaultBaseDir+File.separator+this.inputDir)).getCanonicalPath();
99
			}
100
			*/
101
		} catch (IOException e) {
102
			System.err.println("Error accediendo a los directorios de las traducciones: "+e.getLocalizedMessage());
103
		}
104
	}
105
	
106
	/**
107
	 *  Creates a new ConfigOptions object, defining the config file to use.
108
	 *  
109
	 * @param configFileName The file name of the config file to use.
110
	 */
111
	public ConfigOptions(String configFileName) {
112
		this.configFileName = configFileName;
113
		
114
		// Now we transform all directories to absolute canonical paths, so
115
		// that the are easier to manage afterwards.
116
		// It's also done at the end of parseVars method, but we must also do
117
		// it here, because parseVars() might not get executed.
118
		try {
119
			this.defaultBaseDir = getAbsolutePath(".", this.defaultBaseDir);
120
			this.databaseDir = getAbsolutePath(this.defaultBaseDir, this.databaseDir);
121
			this.outputDir = getAbsolutePath(this.defaultBaseDir, this.outputDir);
122
			this.inputDir = getAbsolutePath(this.defaultBaseDir, this.inputDir);
123
			
124
			/*File baseDirFile = new File(this.defaultBaseDir);
125
			this.defaultBaseDir = baseDirFile.getCanonicalPath();
126
			File databaseDirFile = new File(this.databaseDir);
127
			if (databaseDirFile.isAbsolute()) {
128
				this.databaseDir = databaseDirFile.getCanonicalPath();
129
			}
130
			else {
131
				this.databaseDir = (new File(this.defaultBaseDir+File.separator+this.databaseDir)).getCanonicalPath();
132
			}
133
			File outputDirFile = new File(this.outputDir);
134
			if (outputDirFile.isAbsolute()) {
135
				this.outputDir = outputDirFile.getCanonicalPath();
136
			}
137
			else {
138
				this.outputDir = (new File(this.defaultBaseDir+File.separator+this.outputDir)).getCanonicalPath();
139
			}
140
			File inputDirFile = new File(this.inputDir);
141
			if (inputDirFile.isAbsolute()) {
142
				this.inputDir = inputDirFile.getCanonicalPath();
143
			}
144
			else {
145
				this.inputDir = (new File(this.defaultBaseDir+File.separator+this.inputDir)).getCanonicalPath();
146
			}*/
147
		} catch (IOException e) {
148
			System.err.println("Error accediendo a los directorios de las traducciones: "+e.getLocalizedMessage());
149
		}
150
	}
151
	
152
	/**
153
	 * Sets the name of the config file to use.
154
	 * 
155
	 * @param configFileName
156
	 */
157
	public void setConfigFile(String configFileName) {
158
		this.configFileName = configFileName;
159
	}
160
	
161
	/**
162
	 * Gets the name of the config file in use.
163
	 * 
164
	 * @return The name of the config file in use.
165
	 */
166
	public String getConfigFile() {
167
		return configFileName;
168
	}
169
	
170
	/**
171
	 *  Loads the config parameters and the projects to consider from the XML
172
	 * config file */
173
	public boolean load() {
174
		KXmlParser parser = new KXmlParser();
175
		
176
		// we use null encoding, in this way kxml2 tries to detect the encoding
177
		try {
178
			parser.setInput(new FileInputStream(configFileName), null);
179
		} catch (FileNotFoundException e1) {
180
			System.err.println(e1.getLocalizedMessage());
181
			return false;
182
		} catch (XmlPullParserException e1) {
183
			// No podemos leer el fichero de configuraci?n. Usamos valores por defecto
184
			System.err.println("Aviso: no se pudo leer correctamente el fichero de configuraci?n. Se usar?n los valores por defecto.");
185
			return false;
186
		}
187
		
188
		try {
189
			for (parser.next(); parser.getEventType()!=KXmlParser.END_DOCUMENT; parser.next()) {
190
				// este bucle externo recorre las etiquetas de primer y segundo nivel
191
				if (parser.getEventType()==KXmlParser.START_TAG) {
192
					if (parser.getName().equals("config")) {
193
						parseVars(parser);
194
					}
195
					else if (parser.getName().equals("projects")) {
196
						parseProjects(parser);
197
					}
198
				}
199
			}	
200
		} catch (XmlPullParserException e1) {
201
			e1.getLocalizedMessage();
202
		} catch (IOException e1) {
203
			e1.getLocalizedMessage();
204
		}
205
		
206
		File outputDirFile = new File(outputDir);
207
		outputDirFile.mkdirs();
208
		File databaseDirFile = new File(databaseDir);
209
		databaseDirFile.mkdirs();
210
		return true;
211
	}
212

  
213
	private void parseVars(KXmlParser parser) throws XmlPullParserException, IOException {
214
		// recorremos todas las etiquetas 'variable' dentro de config
215
		int state;
216
		String name, value;
217
		
218
		for (state = parser.next(); state!=KXmlParser.END_TAG || !parser.getName().equals("config") ; state=parser.next()) {
219
			if (state==KXmlParser.START_TAG) {
220
				if (parser.getName().equals("variable")) {
221
					name = parser.getAttributeValue(null, "name");
222
					value = parser.getAttributeValue(null, "value");
223
					if (name!=null && value!=null) {
224
						value = parser.getAttributeValue(null, "value");
225
						if (parser.getAttributeValue(null, "name").equals("basename")) {
226
							defaultBaseName = parser.getAttributeValue(null, "value");
227
						}
228
						else if (parser.getAttributeValue(null, "name").equals("basedir")) {
229
							defaultBaseDir = parser.getAttributeValue(null, "value");
230
						}
231
						else if (parser.getAttributeValue(null, "name").equals("databaseDir")) {
232
							databaseDir = parser.getAttributeValue(null, "value");
233
						}
234
						else if (parser.getAttributeValue(null, "name").equals("defaultPropertyDir")) {
235
							defaultPropertyDir = parser.getAttributeValue(null, "value");
236
						}
237
						else if (parser.getAttributeValue(null, "name").equals("outputDir")) {
238
							outputDir = parser.getAttributeValue(null, "value");
239
						}
240
						else if (parser.getAttributeValue(null, "name").equals("inputDir")) {
241
							inputDir = parser.getAttributeValue(null, "value");
242
						}
243
						else if (parser.getAttributeValue(null, "name").equals("sourceKeys")) {
244
							sourceKeys = parser.getAttributeValue(null, "value");
245
						}
246
						else if (parser.getAttributeValue(null, "name").equals("srcDirs")) {
247
							String srcDirs = parser.getAttributeValue(null, "value");
248
							this.defaultSrcDirs = srcDirs.split(";");
249
						}
250
						else if (parser.getAttributeValue(null, "name").equals("languages")) {
251
							languages = parser.getAttributeValue(null, "value").split(";");
252
							if (languages.length==0) {
253
								System.err.println("Aviso: No se definieron idiomas a considerar. Se usar? la lista de idiomas\n por defecto: "+defaultLangList);
254
								languages = defaultLangList.split(";");
255
							}
256
						}
257
					}
258
					else {
259
						if (name==null)
260
							System.err.println("Error leyendo el fichero de configuraci?n. No se encontr? el atributo 'name'\nrequerido en la etiqueta <variable>. La etiqueta ser? ignorada.");
261
						if (value==null)
262
							System.err.println("Error leyendo el fichero de configuraci?n. No se encontr? el atributo 'value'\nrequerido en la etiqueta <variable>. La etiqueta ser? ignorada.");
263
					}
264
				}
265
				else {
266
					System.err.println("Aviso: se ignor? una etiqueta desconocida o inesperada: " + parser.getName());
267
				}
268
			}
269
		}
270
		
271
		// Now we transform all directories to absolute canonical paths, so
272
		// that they are easier to manage afterwards.
273
		try {
274
			this.defaultBaseDir = getAbsolutePath(".", this.defaultBaseDir);
275
			this.databaseDir = getAbsolutePath(this.defaultBaseDir, this.databaseDir);
276
			this.outputDir = getAbsolutePath(this.defaultBaseDir, this.outputDir);
277
			this.inputDir = getAbsolutePath(this.defaultBaseDir, this.inputDir);
278
			/**
279
			File baseDirFile = new File(this.defaultBaseDir);
280
			this.defaultBaseDir = baseDirFile.getCanonicalPath();
281
			System.out.println(this.defaultBaseDir);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff