Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.i18n.app / org.gvsig.i18n.app.mainplugin / src / main / java / org / gvsig / i18n / impl / TranslationsConsolider.java @ 41284

History | View | Annotate | Download (13 KB)

1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package org.gvsig.i18n.impl;
7

    
8
import java.io.File;
9
import java.io.FileFilter;
10
import java.io.FileInputStream;
11
import java.io.FileOutputStream;
12
import java.io.IOException;
13
import java.util.ArrayList;
14
import java.util.Collections;
15
import java.util.Enumeration;
16
import java.util.HashMap;
17
import java.util.Iterator;
18
import java.util.List;
19
import java.util.Locale;
20
import java.util.Map;
21
import java.util.Properties;
22
import org.apache.commons.io.FileUtils;
23
import org.apache.commons.io.IOUtils;
24
import org.apache.commons.lang3.StringUtils;
25
import org.gvsig.andami.PluginServices;
26
import org.gvsig.andami.PluginsLocator;
27
import org.gvsig.andami.PluginsManager;
28
import org.gvsig.i18n.I18nManager;
29
import org.gvsig.tools.ToolsLocator;
30
import org.gvsig.tools.task.SimpleTaskStatus;
31
import org.gvsig.tools.task.TaskStatus;
32
import org.slf4j.Logger;
33
import org.slf4j.LoggerFactory;
34

    
35
/**
36
 *
37
 * @author usuario
38
 */
39
public class TranslationsConsolider {
40

    
41
    private static final Logger logger = LoggerFactory.getLogger(TranslationsConsolider.class);
42

    
43
    private I18nManager i18nManager = null;
44
    private PluginsManager pluginsManager = null;
45
    private Map<String, Map<String, String>> allTranslations = null;
46
    private Locale currentLocale = null;
47
    private Map<String, List<String>> keysInPlugins = null;
48

    
49
    public TranslationsConsolider() {
50
        this.pluginsManager = PluginsLocator.getManager();
51
        this.allTranslations = new HashMap<String, Map<String, String>>();
52
        this.currentLocale = this.getI18nManager().getCurrentLocale();
53
        this.keysInPlugins = new HashMap<String, List<String>>();
54
    }
55

    
56
    public void setCurrentLocale(Locale locale) {
57
        this.currentLocale = locale;
58
    }
59

    
60
    public Locale getCurrentLocale() {
61
        return this.currentLocale;
62
    }
63

    
64
    public I18nManager getI18nManager() {
65
        if ( this.i18nManager == null ) {
66
            this.i18nManager = I18nManagerImpl.getInstance();
67
        }
68
        return this.i18nManager;
69
    }
70

    
71
    public void addKey(String key, String pluginCode) {
72
        List<String> pluginCodes = this.keysInPlugins.get(key);
73
        if ( pluginCodes == null ) {
74
            pluginCodes = new ArrayList<String>();
75
            this.keysInPlugins.put(key, pluginCodes);
76
        }
77
        if ( !StringUtils.isBlank(pluginCode) ) {
78
            if ( !pluginCodes.contains(pluginCode) ) {
79
                pluginCodes.add(pluginCode);
80
            }
81
        }
82
    }
83

    
84
    public void addLocale(Locale locale) {
85
        if ( this.allTranslations.get(locale.toString()) == null ) {
86
            this.allTranslations.put(locale.toString().toLowerCase(), new HashMap<String, String>());
87
        }
88
    }
89

    
90
    public List<String> getPluginCodesOfKey(String key) {
91
        List<String> pluginCodes = this.keysInPlugins.get(key);
92
        return pluginCodes;
93
    }
94

    
95
    public Map<String, String> getTranslations(String locale) {
96
        Map<String, String> translations = this.allTranslations.get(locale.toString().toLowerCase());
97
        return translations;
98
    }
99

    
100
    public Map<String, String> getTranslations(Locale locale) {
101
        return this.getTranslations(locale.toString());
102
    }
103

    
104
    public void add(Locale locale, String key, String value, String pluginCode) {
105
        Map<String, String> translations = this.getTranslations(locale);
106
        if ( !translations.containsKey(key) ) {
107
            translations.put(key, value);
108
            this.addKey(key, pluginCode);
109
        }
110
    }
111

    
112
    public void add(Locale locale, Properties properties, String pluginCode) {
113
        this.addLocale(locale);
114
        Enumeration enumKeys = properties.keys();
115
        while ( enumKeys.hasMoreElements() ) {
116
            String key = (String) enumKeys.nextElement();
117
            String value = properties.getProperty(key);
118
            this.add(locale, key, value, pluginCode);
119
        }
120
    }
121

    
122
    public List<Locale> getLocales() {
123
        List<Locale> locales = new ArrayList<Locale>(this.allTranslations.size());
124
        Iterator<String> itLocales = this.allTranslations.keySet().iterator();
125
        while ( itLocales.hasNext() ) {
126
            Locale locale = new Locale(itLocales.next().toString());
127
            locales.add(locale);
128
        }
129
        return locales;
130
    }
131

    
132
    public List<String> getKeys() {
133
        List<String> keys = new ArrayList<String>(this.keysInPlugins.size());
134
        keys.addAll(this.keysInPlugins.keySet());
135
        Collections.sort(keys);
136
        return keys;
137
    }
138

    
139
    private String getResourceFileName(Locale locale) {
140
        StringBuilder fileName = new StringBuilder();
141
        fileName.append("text");
142
        if ( !StringUtils.isBlank(locale.getLanguage()) ) {
143
            fileName.append("_");
144
            fileName.append(locale.getLanguage());
145
        }
146
        if ( !StringUtils.isBlank(locale.getCountry()) ) {
147
            fileName.append("_");
148
            fileName.append(locale.getCountry());
149
        }
150
        if ( !StringUtils.isBlank(locale.getVariant()) ) {
151
            fileName.append("_");
152
            fileName.append(locale.getVariant());
153
        }
154
        fileName.append(".properties");
155
        return fileName.toString();
156
    }
157

    
158
    public String getTranslation(String locale, String key) {
159
        Map<String, String> translations = this.getTranslations(locale);
160
        if ( translations == null ) {
161
            logger.warn("Can't locate the translations for locale '" + locale + "'.");
162
            return null;
163
        }
164
        return translations.get(key);
165
    }
166

    
167
    public String getTranslation(Locale locale, String key) {
168
        return this.getTranslation(locale.toString(), key);
169
    }
170

    
171
    public String get(String key) {
172
        return this.getTranslation(currentLocale, key);
173
    }
174

    
175
    public void put(String key, String value) {
176
        this.add(currentLocale, key, value, null);
177
    }
178

    
179
    public void consolide() throws IOException {
180
        SimpleTaskStatus task = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("Consolide translations");
181
        task.setAutoremove(true);
182
        task.add();
183
        try {
184
            task.setTitle("Consolide translations");
185
            int n = this.loadAllTranslations(task);
186
            if( !task.isCancellationRequested() ) {
187
                this.storeAsProperties(task, n);
188
            }
189
        } finally {
190
            task.terminate();
191
        }
192
    }
193
    
194
    private int loadAllTranslations(SimpleTaskStatus task) {
195
        task.message("searching locales");
196
        Locale[] locales = this.getI18nManager().getInstalledLocales();
197

    
198
        List<PluginServices> plugins = this.pluginsManager.getPlugins();
199
        File appI18nFolder = pluginsManager.getApplicationI18nFolder();
200
        File[] subfolders = appI18nFolder.listFiles(new FileFilter() {
201
            public boolean accept(File file) {
202
                return file.isDirectory();
203
            }
204
        });
205
        int n = 1;
206
        task.setRangeOfValues(0, plugins.size() + subfolders.length + locales.length + 1);
207

    
208
        task.message("loading from andami.");
209
        task.setCurValue(n++);
210
        loadTranslation(locales, appI18nFolder, null);
211

    
212
        for ( File subfolder : subfolders ) {
213
            if( task.isCancellationRequested() ) {
214
                return n;
215
            }
216
            task.setCurValue(n++);
217
            if ( subfolder.isDirectory() ) {
218
                task.message("loading " + subfolder.getName());
219
                if ( "andami".equals(subfolder.getName()) ) {
220
                    loadTranslation(locales, appI18nFolder, "org.gvsig.andami");
221
                } else {
222
                    loadTranslation(locales, appI18nFolder, null);
223
                }
224
            }
225
        }
226

    
227
        for ( PluginServices plugin : plugins ) {
228
            if( task.isCancellationRequested() ) {
229
                return n;
230
            }
231
            if ( plugin != null ) {
232
                task.message("loading " + plugin.getPluginName());
233
                task.setCurValue(n++);
234
                loadTranslation(locales, plugin.getPluginDirectory(), plugin.getPluginName());
235
            }
236
        }
237
        return n;
238
    }
239

    
240
    private void loadTranslation(Locale[] locales, File folder, String pluginCode) {
241
        for ( Locale locale : locales ) {
242
            File f1 = new File(folder, getResourceFileName(locale));
243
            File f2 = new File(folder, "i18n/" + getResourceFileName(locale));
244
            if ( !f1.exists() && !f2.exists() ) {
245
                if ( "es".equals(locale.getLanguage()) ) {
246
                    f1 = new File(folder, "text.properties");
247
                    f2 = new File(folder, "i18n/text.properties");
248
                }
249
            }
250
            if ( f1.exists() ) {
251
                loadTranslation(locale, f1, pluginCode);
252
            }
253
            if ( f2.exists() ) {
254
                loadTranslation(locale, f2, pluginCode);
255
            }
256
        }
257
    }
258

    
259
    private void loadTranslation(Locale locale, File f, String pluginCode) {
260
        FileInputStream fins = null;
261
        try {
262
            Properties properties = new Properties();
263
            fins = new FileInputStream(f);
264
            properties.load(fins);
265
            this.add(locale, properties, pluginCode);
266
        } catch (IOException ex) {
267
            logger.warn("Error processing property file '" + f.getAbsolutePath() + "'.", ex);
268
        } finally {
269
            IOUtils.closeQuietly(fins);
270
        }
271
    }
272

    
273
    private void storeAsProperties(SimpleTaskStatus task, int pos) throws IOException {
274
        task.message("Prepraring to store");
275
        File folder = new File(this.pluginsManager.getApplicationI18nFolder(), "translations.all");
276
        if( !folder.exists() ) {
277
            FileUtils.forceMkdir(folder);
278
        }
279
        List<String> keys = this.getKeys();
280
        List<Locale> locales = this.getLocales();
281
        for ( Locale locale : locales ) {
282
            task.setCurValue(pos++);
283
            task.message("Storing "+locale.toString());
284
            Map<String, String> translations = this.getTranslations(locale);
285
            Properties properties = new Properties();
286
            for ( String key : keys ) {
287
                String value = this.getTranslation(locale, key);
288
                if( value == null ) {
289
                    value = "";
290
                }
291
                properties.setProperty(key, value);
292
            }
293
            File f = new File(folder, this.getResourceFileName(locale));
294
            FileOutputStream fos = null;
295
            try {
296
                fos = new FileOutputStream(f);
297
                properties.store(fos, null);
298
            } catch (Exception ex) {
299
                logger.warn("Can't write properties '" + f.getAbsolutePath() + "'.", ex);
300
            } finally {
301
                IOUtils.closeQuietly(fos);
302
            }
303

    
304
        }
305
        task.message("Storing plugin information");
306
        Properties properties = new Properties();
307
        for ( String key : keys ) {
308
            List<String> pluginCodes = this.keysInPlugins.get(key);
309
            StringBuilder ss = null;
310
            for ( String pluginCode : pluginCodes ) {
311
                if ( ss == null ) {
312
                    ss = new StringBuilder();
313
                } else {
314
                    ss.append(", ");
315
                }
316
                ss.append(pluginCode);
317
            }
318
            if ( ss == null ) {
319
                properties.setProperty(key, "");
320
            } else {
321
                properties.setProperty(key, ss.toString());
322
            }
323
        }
324
        FileOutputStream fos = null;
325
        File f = new File(folder, "keysbyplugin.properties");
326
        try {
327
            fos = new FileOutputStream(f);
328
            properties.store(fos, null);
329
        } catch (Exception ex) {
330
            logger.warn("Can't write properties '" + f.getAbsolutePath() + "'.", ex);
331
        } finally {
332
            IOUtils.closeQuietly(fos);
333
        }
334
        task.message("");
335
    }
336

    
337
    /*
338
     def storeAsDBF(self):
339
     maxl = 100
340
     for k in self.keys():
341
     if len(k) > maxl:
342
     maxl = len(k)
343
     #print "max key len: ", maxl
344
        
345
     folder = File(self.__pluginsManager.getApplicationFolder(),"i18n")
346
     f = File(folder,"translations.dbf")
347
     try:
348
     f.delete()
349
     except:
350
     print "Can't delete file "+f.getAbsolutePath()
351
     schema = createSchema() 
352
     schema.append( "ID" , "Integer" , 7)
353
     schema.append( "key" , "String" , maxl)
354
     schema.append( "locale" , "String" , 30)
355
     schema.append( "translation" , "String" , 200)
356
     schema.append( "plugins" , "String" , 200)
357

358
     table = createDBF( schema, File(folder,"translations.dbf"))
359

360
     locales = self.getI18nManager().getInstalledLocales()
361
     idCounter = 1
362
     for key in self.keys():
363
     for locale in locales:
364
     pluginCodes = ""
365
     for pluginCode in self.getPluginCodesOfKey(key):
366
     pluginCodes += pluginCode + " "
367
     pluginCodes = str(pluginCodes).strip()
368
        
369
     table.append(ID=idCounter, 
370
     key=key, 
371
     locale=locale.toString(), 
372
     translation=self.getTranslation(locale, key),
373
     plugins=pluginCodes
374
     )
375
     idCounter +=1
376
     table.commit()
377
  
378
     */
379
}