Revision 46321

View differences:

tags/org.gvsig.desktop-2.0.366/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
    <modelVersion>4.0.0</modelVersion>
6
    <artifactId>org.gvsig.i18n</artifactId>
7
    <packaging>jar</packaging>
8
    <name>${project.artifactId}</name>
9
    <description>Management of texts related to a locale:  loading from resource bundles and getting the text value for the current locale</description>
10

  
11
    <parent>
12
        <groupId>org.gvsig</groupId>
13
        <artifactId>org.gvsig.desktop.compat.cdc</artifactId>
14
        <version>2.0.366</version>
15
    </parent>
16
            
17
    <dependencies>
18
        <dependency>
19
            <groupId>org.slf4j</groupId>
20
            <artifactId>slf4j-api</artifactId>
21
            <scope>compile</scope>
22
        </dependency>
23
        <dependency>
24
            <groupId>org.slf4j</groupId>
25
            <artifactId>slf4j-log4j12</artifactId>
26
            <scope>runtime</scope>
27
        </dependency>
28
        <dependency>
29
          <groupId>org.gvsig</groupId>
30
          <artifactId>org.gvsig.tools.lib</artifactId>
31
          <scope>compile</scope>  
32
        </dependency>
33
    </dependencies>
34

  
35
</project>
0 36

  
tags/org.gvsig.desktop-2.0.366/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/TranslationDatabase.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.util.ArrayList;
32
import java.util.HashMap;
33
import java.util.Iterator;
34
import java.util.Set;
35

  
36
/**
37
 * @author cesar
38
 *
39
 */
40
public class TranslationDatabase {
41
	
42
	public TranslationDatabase(ConfigOptions config){
43
		this.config = config; 
44
	}
45
	
46
	private ConfigOptions config;
47
	private HashMap dictionaries;
48
	
49
	public void load() {
50
		// always start with an empty HashMap when loading
51
		dictionaries = new HashMap();
52
		String lang;
53
		DoubleProperties dictionary;
54
		
55
		FileInputStream stream=null;
56
		
57
		for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
58
			lang = config.languages[currentLang];
59
			dictionary = new DoubleProperties();
60
			try {
61
				stream = new FileInputStream(config.databaseDir+File.separator+config.defaultBaseName+"_"+lang+".properties");
62
				try {
63
					dictionary.load(stream);
64
				} catch (IOException e) {
65
					System.err.println("Error cargando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
66
				}
67
			} catch (FileNotFoundException e) {
68
				System.err.println("Error cargando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
69
			}
70
			dictionaries.put(lang, dictionary);
71
		}
72
	}
73
	
74
	public void save() {
75
		String lang;
76
		DoubleProperties dictionary;
77
		
78
		FileOutputStream stream=null;
79

  
80
		for (int currentLang=0; currentLang<config.languages.length; currentLang++) {
81
			lang = config.languages[currentLang];
82
			
83
			dictionary = ((DoubleProperties)dictionaries.get(lang));
84
			
85
			try {
86
				stream = new FileOutputStream(config.databaseDir+File.separator+config.defaultBaseName+"_"+lang+".properties");
87
				try {
88
					dictionary.store(stream, "Translations for language: " + lang);
89
				} catch (IOException e) {
90
					System.err.println("Error guardando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
91
				}
92
			} catch (FileNotFoundException e) {
93
				System.err.println("Error guardando la base de datos para el idioma: ["+lang+"]. "+e.getLocalizedMessage());
94
			}
95
		}
96
	}
97
	
98
	public String getTranslation(String lang, String key) {
99
		if (lang==null || key==null) return null;
100
		
101
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
102
		if (dictionary==null) return null;
103
		return (String) dictionary.get(key);
104
	}
105
	
106
	public String setTranslation(String lang, String key, String translation) {
107
		if (lang==null || key==null) return null;
108

  
109
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
110
		if (dictionary==null) return null;
111
		String oldvalue = (String) dictionary.get(key);
112
		dictionary.put(key, translation);
113
		return oldvalue;
114
	}
115
	
116
	/**
117
	 * Removes the key from the specified dictionary, and its associated translation.
118
	 * It has no effect if the key was not present in the dictionary.
119
	 * 
120
	 * @param lang The language from which the key should be removed.
121
	 * @param key  The key to be removed.
122
	 * @return The translation associated with the key, or null if the
123
	 * key was not present in the dictionary. It also returns null if any of the parameters is
124
	 * null, or if there was no dictionary for the specified language.
125
	 */
126
	public String removeTranslation(String lang, String key) {
127
		if (lang==null || key==null) return null;
128

  
129
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
130
		if (dictionary==null) return null;
131
		String oldvalue = (String) dictionary.get(key);
132
		dictionary.remove(key);
133
		return oldvalue;
134
	}
135
	
136
	/**
137
	 * Removes the key and its associated translation from all the dictionaries.
138
	 * The key will be deleted from the dictionaries in which it is present (if any).
139
	 * 
140
	 * @param key  The key to be removed.
141
	 * @return True if the key was removed from any dictionary, or false if the key
142
	 * was not present in any dictionary.
143
	 * @throws NullPointerException if the key is null.
144
	 */
145
	public boolean removeTranslation(String key) throws NullPointerException {
146
		DoubleProperties dictionary;
147
		String lang;
148
		boolean present=false;
149
		
150
		Set keys = dictionaries.keySet();
151
		Iterator langIterator = keys.iterator();
152
		while (langIterator.hasNext()) {
153
			lang = (String) langIterator.next();
154
			dictionary = (DoubleProperties) dictionaries.get(lang);
155
			if (dictionary.containsKey(key)) {
156
				present=true;
157
				dictionary.remove(key);
158
			}
159
		}
160
		return present;
161
	}
162
	
163
	public boolean containsLanguage(String lang) {
164
		return dictionaries.containsKey(lang);
165
	}
166

  
167
	public boolean containsKey(String lang, String key) {
168
		if (lang==null || key==null) return false;
169

  
170
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
171
		return dictionary.containsKey(key);
172
	}
173
	
174
	public String getAssociatedKey(String lang, String value) {
175
		if (lang==null || value==null) return null;
176

  
177
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
178
		return dictionary.getAssociatedKey(value);
179
	}
180
	
181
	public ArrayList getAssociatedKeys(String lang, String value) {
182
		if (lang==null || value==null) return null;
183

  
184
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
185
		return dictionary.getAssociatedKeys(value);
186
	}
187

  
188
	public boolean containsTranslation(String lang, String translation) {
189
		if (lang==null || translation==null) return false;
190

  
191
		DoubleProperties dictionary = (DoubleProperties) dictionaries.get(lang);
192
		return dictionary.containsValue(translation);
193
	}
194
}
0 195

  
tags/org.gvsig.desktop-2.0.366/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/src/org/gvsig/i18n/utils/AddNewTranslations.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.IOException;
31
import java.io.InputStreamReader;
32
import java.io.UnsupportedEncodingException;
33
import java.util.Enumeration;
34
import java.util.Properties;
35

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

  
49
	/**
50
	 * @param args
51
	 */
52
	public static void main(String[] args) {
53
		AddNewTranslations process = new AddNewTranslations();
54
		
55
		// load command line parameters
56
		if (!process.readParameters(args)) {
57
			usage();
58
			System.exit(-1);
59
		}
60
		
61
		// transfer control to the program's main loop
62
		process.start();
63
	}
64
	
65
	private void start() {
66
		// load config options from the config file
67
		if (!loadConfig()) {
68
			System.out.println("Error leyendo el fichero de configuraci?n.");
69
			usage();
70
			System.exit(-1);
71
		}
72
		
73
		loadDataBase();
74
		
75
		readNewTranslations();
76
		
77
		database.save();
78
	}
79

  
80
	/**
81
	 *  Reads the command line parameters */
82
	private boolean readParameters(String[] args) {
83
		String configPair[];
84

  
85
		for (int i=0; i<args.length; i++) {
86
			configPair = args[i].split("=",2);
87
			if ( (configPair[0].equals("-c") || configPair[0].equals("--config"))
88
					&& configPair.length==2) {
89
				configFileName = configPair[1];
90
			}
91
			else {
92
				return false;
93
			}
94
		}
95
		return true;
96
	}
97
	
98
	private boolean loadConfig() {
99
		config = new ConfigOptions(configFileName);
100
		config.load();
101
		return true;
102
	}
103
	
104
	private static void usage() {
105
		System.out.println("Uso: AddNewTranslations [OPCION]");
106
		System.out.println("\t-c\t--config=configFile");
107
	}
108
	
109
	private void loadDataBase() {
110
		database = new TranslationDatabase(config);
111
		database.load();
112
	}
113
	
114
	private void readNewTranslations() {
115
		String lang, key, value, oldValue;
116
		
117
		for (int i=0; i<config.languages.length; i++) {
118
			lang = config.languages[i];
119
			try {
120
				FileInputStream fisProp = new FileInputStream(config.inputDir+File.separator+config.defaultBaseName+"_"+lang+".properties");
121
				Properties prop = new Properties();
122
				try {
123
					prop.load(fisProp);
124
					Enumeration keysEnum  = prop.keys();
125
					while (keysEnum.hasMoreElements()){
126
						key = (String) keysEnum.nextElement();
127
						value = prop.getProperty(key);
128
						if (value!=null && !value.equals("")) {
129
							if (!database.containsKey(lang, key)) {
130
								System.out.println("["+lang+"] Traducci?n a?adida -- "+key+"="+value);
131
								database.setTranslation(lang, key, value);
132
							}
133
							else {
134
								oldValue = database.setTranslation(lang, key, value);
135
								if (!oldValue.equals(value)) {
136
									System.out.println("["+lang+"] Traducci?n actualizada -- "+key+"="+value);
137
									System.out.println("Valor anterior: "+database.getTranslation(lang, key));
138
								}
139
							}
140
						}
141
					}
142
				} catch (IOException e) {
143
					System.err.println("Error leyendo traducciones para idioma ["+lang+"]. "+e.getLocalizedMessage());
144
				}
145
				
146
			} catch (FileNotFoundException e) {
147
				try {
148
					FileInputStream fis = new FileInputStream(config.inputDir+File.separator+config.defaultBaseName+"_"+lang+".properties-"+config.outputEncoding);
149
					
150
					BufferedReader currentFile=null;
151
					try {
152
						currentFile = new BufferedReader(new InputStreamReader(fis, config.outputEncoding));
153
					} catch (UnsupportedEncodingException e1) {
154
						// TODO Auto-generated catch block
155
						e1.printStackTrace();
156
					}
157
					
158
				    String line = null;
159
				    try {
160
						while((line = currentFile.readLine()) != null) {
161
							String[] parts = line.split("=");
162
							if (parts.length == 2) {
163
								key = parts[0];
164
								value = parts[1];
165
								if (value!=null && !value.equals("")) {
166
									if (!database.containsKey(lang, key)) {
167
										System.out.println("["+lang+"] Traducci?n a?adida -- "+key+"="+value);
168
										database.setTranslation(lang, key, value);
169
									}
170
									else {
171
										oldValue = database.setTranslation(lang, key, value);
172
										if (!oldValue.equals(value)) {
173
											System.out.println("["+lang+"] Traducci?n actualizada -- "+key+"="+value);
174
											System.out.println("Valor anterior: "+database.getTranslation(lang, key));
175
										}
176
									}
177
								}
178
							}
179
							else {
180
								System.err.println("Error leyendo traducciones para idioma ["+lang+"].");
181
								System.err.println("L?nea: "+line);
182
							}
183
						}
184
					    currentFile.close();
185
					} catch (IOException ex) {
186
						System.err.println("Error leyendo traducciones para idioma ["+lang+"]. "+ex.getLocalizedMessage());
187
					}
188
					
189
				} catch (FileNotFoundException e1) {
190
					System.out.println("Aviso -- no se encontraron nuevas traducciones para el idioma ["+lang+"].");
191
				}
192
			}
193
			
194
		}
195
		
196
	}
197
	
198
}
0 199

  
tags/org.gvsig.desktop-2.0.366/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/utils/java/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="../" />
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;nl;pt;pt_BR;pl;ro;sr;sw;zh;en_US" />
43
	<!-- El directorio que contendrá la base de datos general de traducciones por idioma. Por defecto es el
44
		directorio "database", relativo al directorio especificado en la variable "basedir".  -->
45
	<variable name="databaseDir" value="libInternationalization/utils-data/database" />
46
	
47
	<!-- El directorio por defecto que contendrá los property files que almacenan las claves de cada
48
	 proyecto". Esto se usa en los proyectos que no especifican un atributo "propertyDir". Si el
49
	 directorio no es absoluto, entonces es relativo al directorio de cada proyecto. -->
50
	<variable name="defaultPropertyDir" value="config" />
51
	
52
	<!-- El directorio en el que se escribirán las cadenas para enviar a traducir. -->
53
	<variable name="outputDir" value="libInternationalization/utils-data/output" />
54

  
55
	<!-- El directorio del que se leerán las nuevas cadenas traducidas, que se van a integrar
56
	a la base de datos. -->
57
	<variable name="inputDir" value="libInternationalization/utils-data/input" />
58
	
59
	<!-- Los subdirectorios que contienen fuentes, relativos a cada directorio de
60
	proyecto. Si se especifican varios subdirectorios,  deben ir separado por
61
	 punto y coma (;).  -->
62
	<variable name="srcDirs" value="src;config" />
63

  
64
	
65
	<!-- 	Esta variable especifica el origen de las claves. Los valores posibles son "sources" y "properties".
66
	     	Con esta variable se define el conjunto de valores válidos (esto es, el conjunto de claves que
67
		o bien deben estar traducidas o bien debemos enviar a traducir). El valor por defecto es "sources".
68

  
69
              - "properties" significa que el conjunto de claves válido se determinará tomando las claves
70
		presentes en el fichero .properties del idioma principal de cada proyecto. El idioma
71
		principal de un proyecto se define con el atributo "mainLang" de cada proyecto (si existe),
72
		o con la variable general "mainLang" en caso contrario.
73
	      - "sources" significa que el conjunto de claves válido se determina buscando en el código fuente del
74
		programa. Se buscarán llamadas a las funciones getText y getString y se tomarán las claves de la
75
		llamada, también se buscarán las claves presentes en el config.xml de cada extensión.
76

  
77
		Cada proyecto puede especificar un sourceKeys distinto.
78
	-->
79
	<variable name="sourceKeys" value="sources" />
80

  
81
</config>
82
<projects>
83
	<!-- Los proyectos que se van a leer. Es necesario especificar un directorio (relativo o absoluto),
84
		y opcionalmente se puede incluir un atributo "basename" para especificar un nombre base
85
		distinto del nombre base por defecto -->
86
	<!-- The projects which are going to be read. An absolute or relative directory name must be specified,
87
		in which the property files are located. An optional "basename" attribute is also accepted,
88
		to override the default basename -->
89
	<project dir="appgvSIG" basename="text" sourceKeys="sources" propertyDir="config"/>
90
	<project dir="_fwAndami" />
91
	<project dir="extAddEventTheme" />
92
	<project dir="extCAD" />
93
	<project dir="extCatalogYNomenclator" />
94
	<project dir="extCenterViewToPoint" />
95
	<project dir="extDataLocator" />
96
	<project dir="extGeoProcessing" />
97
	<project dir="extGeoprocessingExtensions" />
98
	<project dir="extGeoreferencing" />
99
	<project dir="extJDBC" />
100
	<project dir="extRasterTools" />
101
	<project dir="extScripting" />
102
	<project dir="extWCS" />
103
	<project dir="extWFS2" />
104
	<project dir="extWMS" />
105
	<project dir="libCorePlugin" />
106
	<project dir="libCq CMS for java" />
107
<!--	<project dir="libDriverManager" /> -->
108
<!--	<project dir="libDwg" /> -->
109
	<!-- <project dir="libFMap" /> -->
110
	<project dir="libInternationalization" />
111
	<project dir="libUI" />
112
	<!-- <project dir="libIverUtiles" /> -->
113
	<!-- <project dir="libRemoteServices" /> -->
114
	<project dir="extArcims" />
115
	<project dir="libArcIMS" />
116
</projects>
0 117

  
tags/org.gvsig.desktop-2.0.366/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.366/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.366/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.366/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()) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff