Revision 41870

View differences:

tags/org.gvsig.desktop-2.0.72/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/test/src/org/gvsig/i18n/utils/TestUtils.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.IOException;
28

  
29
import junit.framework.TestCase;
30

  
31
/**
32
 * @author cesar
33
 *
34
 */
35
public class TestUtils extends TestCase {
36
	
37
	public ConfigOptions loadConfig() {
38
		ConfigOptions config = new ConfigOptions();
39
		config.setConfigFile("src-test"+File.separator+"org"+File.separator+"gvsig"+File.separator+"i18n"+File.separator+"utils"+File.separator+"config.xml");
40
		config.load();
41
		return config;
42
	}
43
	
44
	public void testConfigOptions() {
45
		ConfigOptions config = loadConfig();
46
		
47
		String databaseDir=null, basedir=null;
48
		try {
49
			databaseDir = new File("test-data/database").getCanonicalPath();
50
			basedir =  new File("test-data").getCanonicalPath();
51
		} catch (IOException e) {
52
			// TODO Auto-generated catch block
53
			e.printStackTrace();
54
		}
55
		
56
		// the values of the projects. They are pairs (dir, basename).
57
		String projectValues[]={"src/appgvSIG", "otro", "sources", "src/_fwAndami", "text", "sources"};
58
		for (int i=0; i<projectValues.length; i=i+3) {
59
			try {
60
				// set the canonical path
61
				projectValues[i]= new File(basedir+File.separator+projectValues[i]).getCanonicalPath();
62
			} catch (IOException e) {
63
				// TODO Auto-generated catch block
64
				e.printStackTrace();
65
			}
66
		}
67
		
68
		TestCase.assertEquals(databaseDir, config.databaseDir);
69
		TestCase.assertEquals(basedir, config.defaultBaseDir);
70
		TestCase.assertEquals("text", config.defaultBaseName);
71
		
72
		String languages = config.languages[0];
73
		for (int i=1; i<config.languages.length; i++) {
74
			languages=languages+";"+config.languages[i];
75
		}
76
		TestCase.assertEquals("ca;cs;de;en;es;eu;fr;gl;it;pt", languages);
77
		
78
		for (int i=0; i<config.projects.size(); i=i+3) {
79
			Project project = (Project) config.projects.get(i);
80
			TestCase.assertEquals(projectValues[i], project.dir);
81
			TestCase.assertEquals(projectValues[i+1], project.basename);
82
			TestCase.assertEquals(projectValues[i+2], project.sourceKeys);
83
		}
84
	}
85
	
86
	public void testTranslationDatabase() {
87
		ConfigOptions config = loadConfig();
88
		TranslationDatabase database = new TranslationDatabase(config);
89
		database.load();
90
		TestCase.assertEquals("A?adir Capa" , database.getTranslation("es", "Anadir_Capa"));
91
		TestCase.assertEquals("Add Layer" , database.getTranslation("en", "Anadir_Capa"));
92
		TestCase.assertEquals("Afegir Capa" , database.getTranslation("ca", "Anadir_Capa"));
93
		TestCase.assertEquals("Layer hinzuf?gen" , database.getTranslation("de", "Anadir_Capa"));
94
		TestCase.assertEquals("Ayuda" , database.getTranslation("es", "Ayuda"));
95
		TestCase.assertEquals(null , database.getTranslation("es", "test_case.clave_que_no_existe"));
96
		
97
		// add a translation
98
		database.setTranslation("es", "test_case.clave_que_no_existe", "Clave que no existe");
99
		// is it present now?
100
		TestCase.assertEquals("Clave que no existe" , database.getTranslation("es", "test_case.clave_que_no_existe"));
101
		
102
		// remove the translation
103
		database.removeTranslation("es", "test_case.clave_que_no_existe");
104
		// was really removed?
105
		TestCase.assertEquals(null , database.getTranslation("es", "test_case.clave_que_no_existe"));
106
		
107
		// add the translation again
108
		database.setTranslation("es", "test_case.clave_que_no_existe", "Clave que no existe");
109
		// save to disk
110
		database.save();
111
		// load from disk
112
		database.load();
113
		// is the translation still there?
114
		TestCase.assertEquals("Clave que no existe" , database.getTranslation("es", "test_case.clave_que_no_existe"));
115
		
116
		// remove the translation again and save to disk
117
		database.removeTranslation("es", "test_case.clave_que_no_existe");
118
		TestCase.assertEquals(null , database.getTranslation("es", "test_case.clave_que_no_existe"));
119
		TestCase.assertEquals("", database.getTranslation("es", "prueba"));
120
		database.save();
121
	}
122

  
123
	public void testKeys() {
124
		ConfigOptions config = loadConfig();
125
		Keys keys = new Keys(config);
126
		keys.load();
127
	}
128

  
129
}
0 130

  
tags/org.gvsig.desktop-2.0.72/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/test/src/org/gvsig/i18n/utils/config.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
3

  
4
    gvSIG. Desktop Geographic Information System.
5

  
6
    Copyright (C) 2007-2013 gvSIG Association.
7

  
8
    This program is free software; you can redistribute it and/or
9
    modify it under the terms of the GNU General Public License
10
    as published by the Free Software Foundation; either version 3
11
    of the License, or (at your option) any later version.
12

  
13
    This program is distributed in the hope that it will be useful,
14
    but WITHOUT ANY WARRANTY; without even the implied warranty of
15
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
    GNU General Public License for more details.
17

  
18
    You should have received a copy of the GNU General Public License
19
    along with this program; if not, write to the Free Software
20
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
    MA  02110-1301, USA.
22

  
23
    For any additional information, do not hesitate to contact us
24
    at info AT gvsig.com, or visit our website www.gvsig.com.
25

  
26
-->
27
<config>
28
	<!-- Aquí especificamos algunas variables de configuración -->
29
	<!-- En este fichero se muestran todas las opciones posibles, en sus valores por defecto -->
30

  
31
	<!-- Nombre base por defecto de los ficheros con las traducciones. En nuestro caso suele ser "text",
32
		de forma que los ficheros toman nombres como "text.properties", "text_en.properties". Nótese
33
		que sólo es el nombre por defecto. Cada proyecto puede especificar un baseName distinto -->
34
	<variable name="basename" value="text" />
35

  
36
	<!-- Directorio base. Las rutas relativas especificadas en otras variables (databaseDir, directorios
37
		de proyecto) tomarán este directorio como directorio base.  Por defecto es el directorio
38
		desde el que se llama a la aplicación -->
39
	<variable name="basedir" value="test-data" />
40

  
41
	<!-- Lista de idiomas que se tendrán en cuenta  -->
42
	<variable name="languages" value="ca;cs;de;en;es;eu;fr;gl;it;pt" />
43
	
44
	<!-- El directorio que contendrá la base de datos de traducciones por idioma. Por defecto es el
45
		directorio "database", relativo al directorio especificado en la variable "basedir".  -->
46
	<variable name="databaseDir" value="database" />
47
	
48
		<!-- El directorio por defecto que contendrá los property files que almacenan las claves de cada
49
	 proyecto". Esto se usa en los proyectos que no especifican un atributo "propertyDir". Si el
50
	 directorio no es absoluto, entonces es relativo al directorio de cada proyecto. -->
51
	<variable name="defaultPropertyDir" value="config" />
52
	
53
	<variable name="sourceKeys" value="sources" />
54
</config>
55
<projects>
56
	<!-- Los proyectos que se van a leer. Es necesario especificar un directorio (relativo o absoluto),
57
		y opcionalmente se puede incluir un atributo "basename" para especificar un nombre base
58
		distinto del nombre base por defecto -->
59
	<!-- The projects which are going to be read. An absolute or relative directory name must be specified,
60
		in which the property files are located. An optional "basename" attribute is also accepted,
61
		to override the default basename -->
62
	<project dir="src/appgvSIG" basename="otro"  sourceKeys="sources" propertyDir="config" />
63
	<project dir="src/_fwAndami" />
64
</projects>
0 65

  
tags/org.gvsig.desktop-2.0.72/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/test/src/org/gvsig/i18n/utils/TestProperties.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.FileOutputStream;
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.io.OutputStream;
33

  
34
import junit.framework.TestCase;
35

  
36
/**
37
 * @author cesar
38
 *
39
 */
40
public class TestProperties extends TestCase {
41
	static final String fileName = "TestProperties-file";
42
	InputStream is;
43
	OutputStream os;
44
	
45
	public void initOutputStream() {
46
		try {
47
			os = new FileOutputStream(fileName);
48
		} catch (FileNotFoundException e) {
49
			TestCase.fail(e.getLocalizedMessage());
50
		}
51
	}
52
	
53
	public void discardOutputStream() {
54
		try {
55
			os.close();
56
			File file = new File(fileName);
57
			file.delete();
58
		} catch (IOException e) {
59
			TestCase.fail(e.getLocalizedMessage());
60
		}
61
	}
62
	
63
	public void initInputStream() {
64
		try {
65
			is = new FileInputStream(fileName);
66
		} catch (FileNotFoundException e) {
67
			TestCase.fail(e.getLocalizedMessage());
68
		}
69
	}
70
	
71
	public void discardInputStream() {
72
		try {
73
			is.close();
74
		} catch (IOException e) {
75
			TestCase.fail(e.getLocalizedMessage());
76
		}
77
	}
78
	
79
	public void testOrderedPropertiesBasic() {
80
		// write file
81
		OrderedProperties props1 = new OrderedProperties();
82
		props1.setProperty("prueba", "hola");
83
		props1.setProperty("prueba2", "holas");
84
		props1.setProperty("abrir", "cerrar");
85
		props1.setProperty("puerta", "hembrilla");
86
		props1.setProperty("12libros", "quijote");
87
		props1.setProperty("ca?uto", "\u20acuropeo");
88
		props1.setProperty("confli=cto", "amigo");
89
		props1.setProperty("  confli =  :cto mayor ", " peque?o conflicto");
90
		initOutputStream();
91
		try {
92
			props1.store(os, "header");
93
		} catch (IOException e) {
94
			TestCase.fail(e.getLocalizedMessage());
95
		}
96
		
97
		// read file
98
		OrderedProperties props2 = new OrderedProperties();
99
		initInputStream();
100
		try {
101
			props2.load(is);
102
		} catch (IOException e) {
103
			TestCase.fail(e.getLocalizedMessage());
104
		}
105
		TestCase.assertEquals("\u20acuropeo", props2.getProperty("ca?uto"));
106
		TestCase.assertEquals("amigo", props2.getProperty("confli=cto"));
107
		TestCase.assertEquals(" peque?o conflicto", props2.getProperty("  confli =  :cto mayor "));
108
		TestCase.assertEquals("hola", props2.getProperty("prueba"));
109
		TestCase.assertEquals("holas", props2.getProperty("prueba2"));
110
		TestCase.assertEquals("cerrar", props2.getProperty("abrir"));
111
		TestCase.assertEquals("hembrilla", props2.getProperty("puerta"));
112
		TestCase.assertEquals("quijote", props2.getProperty("12libros"));
113
		discardInputStream();
114
		discardOutputStream();
115
	}
116

  
117
	
118
	public void testOrderedProperties() {
119
		// write file
120
		OrderedProperties props1 = new OrderedProperties();
121
		props1.setProperty("prueba", "hola");
122
		props1.setProperty("prueba2", "holas");
123
		props1.setProperty("ca?uto", "\u20acuropeo");
124
		props1.setProperty("confli=cto", "amigo");
125
		props1.setProperty("  conflis =  :cto mayor ", " peque?o conflicto");
126
		props1.setProperty("abrir", "cerrar");
127
		props1.setProperty("puerta", "hembrilla");
128
		props1.setProperty("12libros", "quijote");
129
		initOutputStream();
130
		try {
131
			props1.store(os, "header", "8859_15");
132
		} catch (IOException e) {
133
			TestCase.fail(e.getLocalizedMessage());
134
		}
135
		
136
		// read file
137
		OrderedProperties props2 = new OrderedProperties();
138
		initInputStream();
139
		try {
140
			props2.load(is, "8859_15");
141
		} catch (IOException e) {
142
			TestCase.fail(e.getLocalizedMessage());
143
		}
144
		// estos deber?an salir igual
145
		TestCase.assertEquals("hola", props2.getProperty("prueba"));
146
		TestCase.assertEquals("holas", props2.getProperty("prueba2"));
147
		TestCase.assertEquals("cerrar", props2.getProperty("abrir"));
148
		TestCase.assertEquals("hembrilla", props2.getProperty("puerta"));
149
		TestCase.assertEquals("quijote", props2.getProperty("12libros"));
150
		// con estos en cambio no obtenemos los mismos valores que escribimos anteriormente. Es normal, porque incluimos
151
		// caracteres especiales como ":" y "=". Para manejarlos correctamente necesitamos usas los m?todos load/store
152
		// sin encoding, los cuales s? escapan los caracteres especiales
153
		TestCase.assertEquals("\u20acuropeo", props2.getProperty("ca?uto"));
154
		TestCase.assertEquals("cto=amigo", props2.getProperty("confli"));
155
		TestCase.assertEquals(":cto mayor = peque?o conflicto", props2.getProperty("conflis"));
156

  
157
		discardInputStream();
158
		discardOutputStream();
159
		
160
		// write file
161
		props1 = new OrderedProperties();
162
		props1.setProperty("Prueba", "hola");
163
		props1.setProperty("prueba2", "holas");
164
		props1.setProperty("ca?uto", "\u20acuropeo");
165
		props1.setProperty("confli=cto", "amigo");
166
		props1.setProperty("  conflis =  :cto mayor ", " peque?o conflicto");
167
		props1.setProperty("abrir", "cerrar");
168
		props1.setProperty("puerta", "hembrilla");
169
		props1.setProperty("12libros", "quijote");
170
		initOutputStream();
171
		try {
172
			props1.store(os, "header", "UTF8");
173
		} catch (IOException e) {
174
			TestCase.fail(e.getLocalizedMessage());
175
		}
176
		
177
		// read file
178
		props2 = new OrderedProperties();
179
		initInputStream();
180
		try {
181
			props2.load(is, "UTF8");
182
		} catch (IOException e) {
183
			TestCase.fail(e.getLocalizedMessage());
184
		}
185
		// estos deber?an salir igual
186
		TestCase.assertEquals("hola", props2.getProperty("Prueba"));
187
		TestCase.assertEquals("holas", props2.getProperty("prueba2"));
188
		TestCase.assertEquals("cerrar", props2.getProperty("abrir"));
189
		TestCase.assertEquals("hembrilla", props2.getProperty("puerta"));
190
		TestCase.assertEquals("quijote", props2.getProperty("12libros"));
191
		// con estos en cambio no obtenemos los mismos valores que escribimos anteriormente. Es normal, porque incluimos
192
		// caracteres especiales como ":" y "=". Para manejarlos correctamente necesitamos usas los m?todos load/store
193
		// sin encoding, los cuales s? escapan los caracteres especiales
194
		TestCase.assertEquals("\u20acuropeo", props2.getProperty("ca?uto"));
195
		TestCase.assertEquals("cto=amigo", props2.getProperty("confli"));
196
		TestCase.assertEquals(":cto mayor = peque?o conflicto", props2.getProperty("conflis"));
197

  
198
		discardInputStream();
199
		discardOutputStream();
200
	}
201
	
202
}
0 203

  
tags/org.gvsig.desktop-2.0.72/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.72/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.72/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.72/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);*/
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff