Revision 41390

View differences:

trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.i18n/src/main/java/org/gvsig/i18n/Messages.java
543 543
        public static Locale getCurrentLocale() {
544 544
            return currentLocale;
545 545
        }
546

  
547
        /**
548
         * 
549
         * @deprecated  use setCurrentLocale(Locale locale, Locale alternatives[]) or LocaleManager.setCurrentLocale
550
         */
551
        public static void setCurrentLocale(Locale locale) {
552
            Locale alternatives[] = null;
553

  
554
            String localeStr = locale.getLanguage();
555
            if ( localeStr.equals("es") || 
556
                 localeStr.equals("ca") ||
557
                 localeStr.equals("gl") || 
558
                 localeStr.equals("eu") ||
559
                 localeStr.equals("vl") ) {
560
                alternatives = new Locale[2];
561
                alternatives[0] = new Locale("es");
562
                alternatives[1] = new Locale("en");
563
            } else {
564
                // prefer English for the rest
565
                alternatives = new Locale[2];
566
                alternatives[0] = new Locale("en");
567
                alternatives[1] = new Locale("es");
568
            }
569
            setCurrentLocale(locale, alternatives);
570
        }
546 571
        
547
        public static void setCurrentLocale(Locale locale) {
572
        public static void setCurrentLocale(Locale locale, Locale alternatives[]) {
548 573
            logger.info("setCurrentLocale "+locale.toString());
549 574
            
550 575
            resourceFamilies = new HashSet();
......
554 579
            notTranslatedKeys = new HashSet();            
555 580
            
556 581
            addLocale(locale);
557
            String localeStr = locale.getLanguage();
558
            if ( localeStr.equals("es") || localeStr.equals("ca")
559
                    || localeStr.equals("gl") || localeStr.equals("eu")
560
                    || localeStr.equals("va") ) {
561
                // prefer Spanish for languages spoken in Spain
562
                addLocale(new Locale("es"));
563
                addLocale(new Locale("en"));
564
            } else {
565
                // prefer English for the rest
566
                addLocale(new Locale("en"));
567
                addLocale(new Locale("es"));
582
            for( int i=0 ; i<alternatives.length; i++ ) {
583
                addLocale(alternatives[i]);
568 584
            }
569
            
570 585
            for( int curlocale=0; curlocale<preferredLocales.size(); curlocale++) {
571 586
                for( int curfamily=0; curfamily<familyDescriptors.size(); curfamily++) {
572 587
                     FamilyDescriptor family = (FamilyDescriptor) familyDescriptors.get(curfamily);
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/resources-application/i18n/locale.config
1
#
2
# Default locales
3
#
4
locale=es
5
locale=en        
6
locale=en_US
7
locale=ca
8
locale=gl
9
locale=eu
10
locale=de
11
locale=cs
12
locale=fr
13
locale=it
14
locale=pl
15
locale=pt
16
locale=pt_BR
17
locale=ro
18
locale=zh
19
locale=ru
20
locale=el
21
locale=ro
22
locale=ro
23
locale=pl
24
locale=tr
25
locale=sr
26
locale=sw
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/PluginsLocator.java
39 39
     */
40 40
    public static final String PLUGINS_MANAGER_NAME = "PluginsManager";
41 41
    public static final String PLUGINS_ACTIONINFO_MANAGER_NAME = "PluginsActionInfoManager";
42
    public static final String PLUGINS_LOCALE_MANAGER_NAME = "LocaleManager";
42 43

  
43 44
    private static final String PLUGINS_MANAGER_DESCRIPTION = "PluginsManager of Andami framework";
44 45
    private static final String PLUGINS_ACTIONINFO_MANAGER_DESCRIPTION = "PluginsActionInfoManager";
46
    private static final String PLUGINS_LOCALE_MANAGER_DESCRIPTION = "LocaleManager";
45 47

  
46 48
    /**
47 49
     * Unique instance.
......
114 116
    public static MainFrame getMainFrame() {
115 117
        return Launcher.getFrame();
116 118
    }
119
    
120
    public static LocaleManager getLocaleManager() throws LocatorException {
121
        return (LocaleManager) getInstance().get(PLUGINS_LOCALE_MANAGER_NAME);
122
    }
123

  
124
    public static void registerLocaleManager(Class clazz) {
125
        getInstance().register(PLUGINS_LOCALE_MANAGER_NAME, PLUGINS_LOCALE_MANAGER_DESCRIPTION,
126
                clazz);
127
    }
128

  
117 129
}
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/PluginsLibrary.java
24 24
package org.gvsig.andami;
25 25

  
26 26
import org.gvsig.andami.actioninfo.impl.DefaultActionInfoManager;
27
import org.gvsig.andami.impl.DefaultLocaleManager;
27 28
import org.gvsig.andami.impl.DefaultPluginsManager;
28 29
import org.gvsig.andami.installer.translations.TranslationsInstallerFactory.RegisterTranslationsInstaller;
29 30
import org.gvsig.andami.ui.mdiManager.WindowInfo;
......
43 44
    protected void doInitialize() throws LibraryException {
44 45
        PluginsLocator.registerDefaultManager(DefaultPluginsManager.class);
45 46
        PluginsLocator.registerActionInfoManager(DefaultActionInfoManager.class);
47
        PluginsLocator.registerLocaleManager(DefaultLocaleManager.class);
48
        
49
        // Force initialize of the LocaleManager
50
        PluginsLocator.getLocaleManager();
46 51
    }
47 52

  
48 53
    protected void doPostInitialize() throws LibraryException {
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/PluginsManager.java
229 229
     */
230 230
    public void executeShutdownTasks();
231 231

  
232
    public Locale getCurrentLocale();
233 232
    
234
    public void setCurrentLocale(Locale locale);
235
    
236 233
    public FirewallConfiguration getFirewallConfiguration();
237 234
    
238 235
}
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/installer/translations/TranslationsInstaller.java
28 28
import java.io.FileOutputStream;
29 29
import java.io.IOException;
30 30
import java.io.InputStream;
31
import java.net.MalformedURLException;
31 32
import java.util.zip.ZipEntry;
32 33
import java.util.zip.ZipException;
33 34
import java.util.zip.ZipInputStream;
34 35
import org.apache.commons.io.FileUtils;
35 36
import org.apache.commons.io.FilenameUtils;
37
import org.gvsig.andami.LocaleManager;
36 38
import org.gvsig.andami.PluginsLocator;
37 39
import org.gvsig.andami.PluginsManager;
38 40
import org.gvsig.installer.lib.api.PackageInfo;
......
69 71
		throw new TranslationsIntallerFolderNotFoundException();
70 72
            }
71 73
            decompress(inputStream, i18nFolder);
74
            installLocales(i18nFolder, packageInfo);
72 75
        } catch (Exception e) {
73 76
            try {
74 77
                logger.warn("Can install package '"+packageInfo.getCode()+"'.", e);
......
142 145
    public void installLater(File applicationDirectory, InputStream inputStream, PackageInfo packageInfo) throws InstallPackageServiceException, IOException {
143 146
        logger.warn("installLater is not implementes.");
144 147
    }
148

  
149
    private void installLocales(File i18nFolder, PackageInfo packageInfo) throws MalformedURLException {
150
        LocaleManager localeManager = PluginsLocator.getLocaleManager();
151
        
152
        File folder = new File(i18nFolder, packageInfo.getCode());
153
        File localeConfig = new File(folder,"locale.config");
154
        localeManager.installLocales(localeConfig.toURI().toURL());
155
    }
145 156
    
146 157
    
147 158
    public class TranslationsIntallerFolderNotFoundException extends
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/impl/DefaultLocaleManager.java
1
package org.gvsig.andami.impl;
2

  
3
import java.io.File;
4
import java.net.URL;
5
import java.security.AccessController;
6
import java.security.PrivilegedAction;
7
import java.util.Collections;
8
import java.util.Comparator;
9
import java.util.HashSet;
10
import java.util.Iterator;
11
import java.util.List;
12
import java.util.Locale;
13
import java.util.Set;
14
import java.util.TreeSet;
15
import javax.swing.JComponent;
16
import javax.swing.SwingUtilities;
17
import org.apache.commons.configuration.PropertiesConfiguration;
18
import org.apache.commons.lang3.LocaleUtils;
19
import org.apache.commons.lang3.StringUtils;
20
import org.gvsig.andami.Launcher;
21
import org.gvsig.andami.LocaleManager;
22
import org.gvsig.andami.PluginServices;
23
import org.gvsig.andami.PluginsLocator;
24
import org.gvsig.andami.PluginsManager;
25
import org.gvsig.andami.config.generate.AndamiConfig;
26
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
27
import org.gvsig.utils.XMLEntity;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

  
31

  
32
public class DefaultLocaleManager implements LocaleManager {
33

  
34
    private static final Logger logger
35
            = LoggerFactory.getLogger(DefaultLocaleManager.class);
36

  
37
    private static final String LOCALE_CODE_VALENCIANO = "vl";
38
    
39
    private static final String I18N_EXTENSION = "org.gvsig.i18n.extension";
40
    private static final String INSTALLED_TRANSLATIONS_HOME_FOLDER = "i18n";
41
    private static final String VARIANT = "variant";
42
    private static final String COUNTRY = "country";
43
    private static final String LANGUAGE = "language";
44
    private static final String REGISTERED_LOCALES_PERSISTENCE = "RegisteredLocales";
45

  
46
    private final Locale[] hardcoredLocales = new Locale[]{
47
        // Default supported locales
48
        SPANISH, // Spanish
49
        ENGLISH, // English
50
        new Locale("en", "US"), // English US
51
        new Locale("ca"), // Catalan
52
        new Locale("gl"), // Galician
53
        new Locale("eu"), // Basque
54
        new Locale("de"), // German
55
        new Locale("cs"), // Czech
56
        new Locale("fr"), // French
57
        new Locale("it"), // Italian
58
        new Locale("pl"), // Polish
59
        new Locale("pt"), // Portuguese
60
        new Locale("pt", "BR"), // Portuguese Brazil
61
        new Locale("ro"), // Romanian
62
        new Locale("zh"), // Chinese
63
        new Locale("ru"), // Russian
64
        new Locale("el"), // Greek
65
        new Locale("ro"), // Romanian
66
        new Locale("pl"), // Polish
67
        new Locale("tr"), // Turkish
68
        new Locale("sr"), // Serbio
69
        new Locale("sw") // Swahili
70
    };
71

  
72
    private Set installedLocales = null;
73
    private Set defaultLocales = null;
74

  
75
    public DefaultLocaleManager() {
76
        Locale currentLocale = org.gvsig.i18n.Messages.getCurrentLocale();
77
        this.setCurrentLocale(currentLocale);
78
    }
79
    
80
    public Locale getCurrentLocale() {
81
        return org.gvsig.i18n.Messages.getCurrentLocale();
82
    }
83

  
84
    public void setCurrentLocale(final Locale locale) {
85
        org.gvsig.i18n.Messages.setCurrentLocale(locale, this.getLocaleAlternatives(locale));
86

  
87
        String localeStr = locale.getLanguage();
88
        if ( localeStr.equalsIgnoreCase(LOCALE_CODE_VALENCIANO) ) {
89
            Locale.setDefault(new Locale("ca"));
90
        } else {
91
            Locale.setDefault(locale);
92
        }
93

  
94
        AndamiConfig config = Launcher.getAndamiConfig();
95
        config.setLocaleLanguage(locale.getLanguage());
96
        config.setLocaleCountry(locale.getCountry());
97
        config.setLocaleVariant(locale.getVariant());
98

  
99
        setCurrentLocaleUI(locale);
100
    }
101

  
102
    public Locale getDefaultSystemLocale() {
103
        String language, region, country, variant;
104
        language = getSystemProperty("user.language", "en");
105
        // for compatibility, check for old user.region property
106
        region = getSystemProperty("user.region", null);
107

  
108
        if ( region != null ) {
109
            // region can be of form country, country_variant, or _variant
110
            int i = region.indexOf('_');
111
            if ( i >= 0 ) {
112
                country = region.substring(0, i);
113
                variant = region.substring(i + 1);
114
            } else {
115
                country = region;
116
                variant = "";
117
            }
118
        } else {
119
            country = getSystemProperty("user.country", "");
120
            variant = getSystemProperty("user.variant", "");
121
        }
122
        return new Locale(language, country, variant);
123
    }
124

  
125
    public Set<Locale> getDefaultLocales() {
126
        if ( this.defaultLocales == null ) {
127
            PluginsManager pluginsManager = PluginsLocator.getManager();
128
            File localesFile = new File(pluginsManager.getApplicationI18nFolder(), "locale.config");
129

  
130
            PropertiesConfiguration config = null;
131
            if ( localesFile.canRead() ) {
132
                try {
133
                    config = new PropertiesConfiguration(localesFile);
134
                } catch (Exception ex) {
135
                    logger.warn("Can't open configuration '" + localesFile + "'.", ex);
136
                }
137
            }
138
            defaultLocales = new HashSet<Locale>();
139
            if ( config == null ) {
140
                for ( int i = 0; i < hardcoredLocales.length; i++ ) {
141
                    defaultLocales.add(hardcoredLocales[i]);
142
                }
143
            } else {
144
                List localeCodes = config.getList("locale");
145
                for ( Object localeCode : localeCodes ) {
146
                    Locale locale = LocaleUtils.toLocale((String) localeCode);
147
                    defaultLocales.add(locale);
148
                }
149
            }
150

  
151
        }
152
        return this.defaultLocales;
153
    }
154

  
155
    public boolean installLocales(URL localesFile) {
156
        PluginsManager pluginsManager = PluginsLocator.getManager();
157
        PropertiesConfiguration config = null;
158
        try {
159
            config = new PropertiesConfiguration(localesFile);
160
        } catch (Exception ex) {
161
            logger.warn("Can't open configuration '" + localesFile + "'.", ex);
162
        }
163
        if ( config == null ) {
164
            return false;
165
        }
166
        List localeCodes = config.getList("locale");
167
        for ( Object localeCode : localeCodes ) {
168
            Locale locale = LocaleUtils.toLocale((String) localeCode);
169
            if ( !getInstalledLocales().contains(locale) ) {
170
                this.installedLocales.add(locale);
171
            }
172
        }
173
        storeInstalledLocales();
174
        return true;
175
    }
176

  
177
    public Set<Locale> getInstalledLocales() {
178
        if ( installedLocales == null ) {
179
            installedLocales = new TreeSet<Locale>(new Comparator<Locale>() {
180
                public int compare(Locale t0, Locale t1) {
181
                    if( t1 == null || t0 == null ) {
182
                        return 0;
183
                    }
184
                    return getLanguageDisplayName(t0).compareToIgnoreCase(getLanguageDisplayName(t1));
185
                }
186
            });
187

  
188
            XMLEntity child = getRegisteredLocalesPersistence();
189

  
190
            // If the list of registered locales is not already persisted,
191
            // this should be the first time gvSIG is run with the I18nPlugin
192
            // so we will take the list of default locales
193
            if ( child == null ) {
194
                installedLocales.addAll(getDefaultLocales());
195
                storeInstalledLocales();
196
            } else {
197
                XMLEntity localesEntity = getRegisteredLocalesPersistence();
198
                for ( int i = 0; i < localesEntity.getChildrenCount(); i++ ) {
199
                    XMLEntity localeEntity = localesEntity.getChild(i);
200
                    String language = localeEntity.getStringProperty(LANGUAGE);
201
                    String country = localeEntity.getStringProperty(COUNTRY);
202
                    String variant = localeEntity.getStringProperty(VARIANT);
203
                    Locale locale = new Locale(language, country, variant);
204
                    installedLocales.add(locale);
205
                }
206
            }
207
        }
208
        return Collections.unmodifiableSet(installedLocales);
209
    }
210

  
211
    public boolean installLocale(Locale locale) {
212
        // Add the locale to the list of installed ones, if it
213
        // is new, otherwise, update the texts.
214
        if ( !getInstalledLocales().contains(locale) ) {
215
            getInstalledLocales().add(locale);
216
            storeInstalledLocales();
217
        }
218
        return true;
219
    }
220

  
221
    public boolean uninstallLocale(Locale locale) {
222
        if ( !getInstalledLocales().remove(locale) ) {
223
            return false;
224
        }
225
        storeInstalledLocales();
226
        return true;
227
    }
228

  
229
    public String getLanguageDisplayName(Locale locale) {
230

  
231
        String displayName;
232

  
233
        if ( "eu".equals(locale.getLanguage())
234
                && "vascuence".equals(locale.getDisplayLanguage()) ) {
235
            // Correction for the Basque language display name,
236
            // show it in Basque, not in Spanish
237
            displayName = "Euskera";
238
        } else if ( LOCALE_CODE_VALENCIANO.equals(locale.getLanguage()) ) {
239
            // Patch for Valencian/Catalan
240
            displayName = "Valenci?";
241
        } else {
242
            displayName = locale.getDisplayLanguage(locale);
243
        }
244

  
245
        return StringUtils.capitalize(displayName);
246
    }
247
    
248
    public Locale[] getLocaleAlternatives(Locale locale) {
249
        Locale alternatives[] = null;
250

  
251
        String localeStr = locale.getLanguage();
252
        if ( localeStr.equals("es") || 
253
             localeStr.equals("ca") ||
254
             localeStr.equals("gl") || 
255
             localeStr.equals("eu") ||
256
             localeStr.equals(LOCALE_CODE_VALENCIANO) ) {
257
            alternatives = new Locale[2];
258
            alternatives[0] = new Locale("es");
259
            alternatives[1] = new Locale("en");
260
        } else {
261
            // prefer English for the rest
262
            alternatives = new Locale[2];
263
            alternatives[0] = new Locale("en");
264
            alternatives[1] = new Locale("es");
265
        }
266
        return alternatives;
267
    }
268

  
269
    private void setCurrentLocaleUI(final Locale locale) {
270
        if ( !SwingUtilities.isEventDispatchThread() ) {
271
            try {
272
                SwingUtilities.invokeAndWait(new Runnable() {
273
                    public void run() {
274
                        setCurrentLocaleUI(locale);
275
                    }
276
                });
277
            } catch (Exception ex) {
278
                // Ignore
279
            }
280
        }
281
        try {
282
            JComponent.setDefaultLocale(locale);
283
        } catch (Exception ex) {
284
            logger.warn("Problems setting locale to JComponent.", ex);
285
        }
286
        try {
287
            MDIFrame.getInstance().setLocale(locale);
288
        } catch (Exception ex) {
289
            logger.warn("Problems settings locale to MDIFrame.", ex);
290
        }
291
    }
292

  
293
    public File getResourcesFolder() {
294
        File i18nFolder = new File(
295
                PluginsLocator.getManager().getApplicationHomeFolder(),
296
                INSTALLED_TRANSLATIONS_HOME_FOLDER
297
        );
298
        if ( !i18nFolder.exists() ) {
299
            i18nFolder.mkdirs();
300
        }
301
        return i18nFolder;
302
    }
303

  
304
    /**
305
     * Returns the child XMLEntity with the RegisteredLocales.
306
     */
307
    private XMLEntity getRegisteredLocalesPersistence() {
308
        XMLEntity entity = getI18nPersistence();
309
        XMLEntity child = null;
310
        for ( int i = entity.getChildrenCount() - 1; i >= 0; i-- ) {
311
            XMLEntity tmpchild = entity.getChild(i);
312
            if ( tmpchild.getName().equals(REGISTERED_LOCALES_PERSISTENCE) ) {
313
                child = tmpchild;
314
                break;
315
            }
316
        }
317
        return child;
318
    }
319

  
320
    /**
321
     * Stores the list of installed locales into the plugin persistence.
322
     */
323
    private void storeInstalledLocales() {
324
        XMLEntity localesEntity = getRegisteredLocalesPersistence();
325

  
326
        // Remove the previous list of registered languages
327
        if ( localesEntity != null ) {
328
            XMLEntity i18nPersistence = getI18nPersistence();
329
            for ( int i = i18nPersistence.getChildrenCount() - 1; i >= 0; i-- ) {
330
                XMLEntity child = i18nPersistence.getChild(i);
331
                if ( child.getName().equals(REGISTERED_LOCALES_PERSISTENCE) ) {
332
                    i18nPersistence.removeChild(i);
333
                    break;
334
                }
335
            }
336
        }
337

  
338
        // Create the new persistence for the registered languages
339
        localesEntity = new XMLEntity();
340

  
341
        localesEntity.setName(REGISTERED_LOCALES_PERSISTENCE);
342

  
343
        Set<Locale> locales = getInstalledLocales();
344
        for ( Iterator iterator = locales.iterator(); iterator.hasNext(); ) {
345
            Locale locale = (Locale) iterator.next();
346
            XMLEntity localeEntity = new XMLEntity();
347
            localeEntity.setName(locale.getDisplayName());
348
            localeEntity.putProperty(LANGUAGE, locale.getLanguage());
349
            localeEntity.putProperty(COUNTRY, locale.getCountry());
350
            localeEntity.putProperty(VARIANT, locale.getVariant());
351

  
352
            localesEntity.addChild(localeEntity);
353
        }
354

  
355
        getI18nPersistence().addChild(localesEntity);
356
    }
357

  
358
    /**
359
     * Returns the I18n Plugin persistence.
360
     */
361
    private XMLEntity getI18nPersistence() {
362
        XMLEntity entity
363
                = PluginServices.getPluginServices(I18N_EXTENSION).getPersistentXML();
364
        return entity;
365
    }
366

  
367
    @SuppressWarnings("unchecked")
368
    private String getSystemProperty(final String property, String defaultValue) {
369
        String value
370
                = (String) AccessController.doPrivileged(new PrivilegedAction() {
371
                    public Object run() {
372
                        return System.getProperty(property);
373
                    }
374
                });
375
        return value == null ? defaultValue : value;
376
    }
377
}
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/impl/DefaultPluginsManager.java
300 300
    public File getApplicationI18nFolder() {
301 301
        return new File(this.getApplicationFolder(), "i18n");
302 302
    }
303

  
304
    public Locale getCurrentLocale() {
305
        return org.gvsig.i18n.Messages.getCurrentLocale();
306
    }
307

  
308
    public void setCurrentLocale(final Locale locale) {
309
        org.gvsig.i18n.Messages.setCurrentLocale(locale);
310

  
311
        AndamiConfig config = Launcher.getAndamiConfig();
312
        config.setLocaleLanguage(locale.getLanguage());
313
        config.setLocaleCountry(locale.getCountry());
314
        config.setLocaleVariant(locale.getVariant());
315
        
316
        setCurrentLocaleUI(locale);
317
    }
318
    
319
    private void setCurrentLocaleUI(final Locale locale) {
320
        if( !SwingUtilities.isEventDispatchThread() ) {
321
            try {
322
                SwingUtilities.invokeAndWait(new Runnable() {
323
                    public void run() {
324
                        setCurrentLocaleUI(locale);
325
                    }
326
                });
327
            } catch (Exception ex) {
328
                // Ignore
329
            }
330
        }
331
        try {
332
            JComponent.setDefaultLocale(locale);
333
        } catch (Exception ex) {
334
            logger.warn("Problems setting locale to JComponent.",ex);
335
        }
336
        try {
337
            MDIFrame.getInstance().setLocale(locale);
338
        } catch(Exception ex) {
339
            logger.warn("Problems settings locale to MDIFrame.",ex);
340
        }
341
    }
342

  
343 303
    public FirewallConfiguration getFirewallConfiguration() {
344 304
        return new DefaultFirewallConfiguration();
345 305
    }
trunk/org.gvsig.desktop/org.gvsig.desktop.framework/org.gvsig.andami/src/main/java/org/gvsig/andami/LocaleManager.java
1
package org.gvsig.andami;
2

  
3
import java.io.File;
4
import java.net.URL;
5
import java.util.Locale;
6
import java.util.Set;
7

  
8
public interface LocaleManager {
9

  
10
    public static final Locale SPANISH = new Locale("es");
11

  
12
    public static final Locale ENGLISH = new Locale("en");
13

  
14
    public Set<Locale> getDefaultLocales();
15

  
16
    public Set<Locale> getInstalledLocales();
17

  
18
    public Locale getDefaultSystemLocale();
19

  
20
    public Locale getCurrentLocale();
21

  
22
    public void setCurrentLocale(Locale locale);
23

  
24
    public boolean installLocale(Locale locale);
25

  
26
    public boolean uninstallLocale(Locale locale);
27
    
28
    public boolean installLocales(URL localesFile);
29

  
30
    public File getResourcesFolder();
31
    
32
    public Locale[] getLocaleAlternatives(Locale locale);
33
    
34
    public String getLanguageDisplayName(Locale locale);
35
}
trunk/org.gvsig.desktop/org.gvsig.desktop.plugin/org.gvsig.i18n.app/org.gvsig.i18n.app.mainplugin/src/main/java/org/gvsig/i18n/I18nManager.java
229 229
     * @param defaultLocales
230 230
     */
231 231
    void setDefaultLocales(Locale[] defaultLocales);
232
    
233
    /**
234
     * Install a new locale in the framework of andami.
235
     * 
236
     * If the locale already exists update it.
237
     * 
238
     * @param locale to install
239
     */
240
    public void installLocale(Locale locale);
232 241
}
trunk/org.gvsig.desktop/org.gvsig.desktop.plugin/org.gvsig.i18n.app/org.gvsig.i18n.app.mainplugin/src/main/java/org/gvsig/i18n/impl/I18nManagerImpl.java
10 10
 *
11 11
 * This program is distributed in the hope that it will be useful,
12 12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 14
 * GNU General Public License for more details.
15 15
 *
16 16
 * You should have received a copy of the GNU General Public License
17 17
 * along with this program; if not, write to the Free Software
18 18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
19
 * MA 02110-1301, USA.
20 20
 *
21 21
 * For any additional information, do not hesitate to contact us
22 22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
......
37 37
import java.io.InputStreamReader;
38 38
import java.io.OutputStreamWriter;
39 39
import java.io.PrintStream;
40
import java.security.AccessController;
41
import java.security.PrivilegedAction;
42 40
import java.util.ArrayList;
43 41
import java.util.HashMap;
44 42
import java.util.HashSet;
......
52 50
import java.util.zip.ZipEntry;
53 51
import java.util.zip.ZipFile;
54 52
import java.util.zip.ZipOutputStream;
55
import javax.swing.JComponent;
56

  
57
import org.gvsig.andami.Launcher;
58
import org.gvsig.andami.PluginServices;
53
import org.gvsig.andami.LocaleManager;
59 54
import org.gvsig.andami.PluginsLocator;
60
import org.gvsig.andami.PluginsManager;
61
import org.gvsig.andami.config.generate.AndamiConfig;
62
import org.gvsig.app.ApplicationLocator;
63
import org.gvsig.app.ApplicationManager;
64 55
import org.gvsig.i18n.I18nException;
65 56
import org.gvsig.i18n.I18nManager;
66 57
import org.gvsig.i18n.Messages;
67 58
import org.gvsig.utils.StringUtilities;
68
import org.gvsig.utils.XMLEntity;
59
import org.slf4j.Logger;
60
import org.slf4j.LoggerFactory;
69 61

  
70 62
/**
71 63
 * Implementation of the I18nManager interface.
72
 * 
64
 *
73 65
 * @author <a href="mailto:dcervera@disid.com">David Cervera</a>
74 66
 * @author <a href="mailto:cordin@disid.com">C?sar Ordi?ana</a>
75 67
 */
76 68
public class I18nManagerImpl implements I18nManager {
77 69

  
78
    private static final String INSTALLED_TRANSLATIONS_HOME_FOLDER = "i18n";
79

  
70
    private static final Logger logger = LoggerFactory.getLogger(I18nManagerImpl.class);
71
    
80 72
    private static final String LOCALES_FILE_NAME = "locales.csv";
81 73

  
82
	private static final String CSV_SEPARATOR = ",";
74
    private static final String CSV_SEPARATOR = ",";
83 75

  
84
	private static final String I18N_EXTENSION = "org.gvsig.i18n.extension";
76
    private static final I18nManager DEFAULT = new I18nManagerImpl();
85 77

  
86
	private static final String VARIANT = "variant";
78
    /**
79
     * The list of default reference locales. The last one will be used to get
80
     * all the keys when translating to a new locale.
81
     */
82
    private Locale[] referenceLocales = new Locale[]{ENGLISH, SPANISH};
87 83

  
88
	private static final String COUNTRY = "country";
84
    LocaleManager localeManager = null;
89 85

  
90
	private static final String LANGUAGE = "language";
86
    private LocaleManager getLocaleManager() {
87
        if ( localeManager == null ) {
88
            localeManager = PluginsLocator.getLocaleManager();
89
        }
90
        return localeManager;
91
    }
91 92

  
92
	private static final String REGISTERED_LOCALES_PERSISTENCE =
93
			"RegisteredLocales";
93
    /**
94
     * Returns the unique instance of the I18nManager.
95
     *
96
     * @return the unique instance
97
     */
98
    public static I18nManager getInstance() {
99
        return DEFAULT;
100
    }
94 101

  
95
	private static final I18nManager DEFAULT = new I18nManagerImpl();
102
    public static String capitalize(String text) {
103
        // Convert the first letter to uppercase
104
        String capitalLetter
105
                = new String(new char[]{Character.toUpperCase(text.charAt(0))});
106
        return capitalLetter.concat(text.substring(1));
107
    }
96 108

  
97
	private Set registeredLocales;
109
    private Set<Locale> getRegisteredLocales() {
110
        return getLocaleManager().getInstalledLocales();
111
    }
98 112

  
99
	/**
100
	 * The list of default reference locales. The last one will be used to get
101
	 * all the keys when translating to a new locale.
102
	 */
103
	private Locale[] referenceLocales = new Locale[] { ENGLISH, SPANISH };
113
    public Locale getCurrentLocale() {
114
        return getLocaleManager().getCurrentLocale();
115
    }
104 116

  
105
	private Locale[] defaultLocales = new Locale[] {
106
	// Default supported locales
107
			SPANISH, // Spanish
108
			ENGLISH, // English
109
			new Locale("en", "US"), // English US
110
			new Locale("ca"), // Catalan
111
			new Locale("gl"), // Galician
112
			new Locale("eu"), // Basque
113
			new Locale("de"), // German
114
			new Locale("cs"), // Czech
115
			new Locale("fr"), // French
116
			new Locale("it"), // Italian
117
			new Locale("pl"), // Polish
118
			new Locale("pt"), // Portuguese
119
			new Locale("pt", "BR"), // Portuguese Brazil
120
			new Locale("ro"), // Romanian
121
			new Locale("zh"), // Chinese
122
			new Locale("ru"), // Russian
123
			new Locale("el"), // Greek
124
			new Locale("ro"), // Romanian
125
			new Locale("pl"), // Polish
126
			new Locale("tr"), // Turkish
127
			new Locale("sr"), // Serbio
128
			new Locale("sw") // Swahili
129
			};
117
    public Locale[] getInstalledLocales() {
118
        Set<Locale> locales = getRegisteredLocales();
119
        return (Locale[]) locales.toArray(new Locale[locales.size()]);
120
    }
130 121

  
131
	/**
132
	 * Returns the unique instance of the I18nManager.
133
	 * 
134
	 * @return the unique instance
135
	 */
136
	public static I18nManager getInstance() {
137
		return DEFAULT;
138
	}
122
    private File getResourcesFolder() {
123
        return getLocaleManager().getResourcesFolder();
124
    }
139 125

  
140
	public static String capitalize(String text) {
141
		// Convert the first letter to uppercase
142
		String capitalLetter =
143
				new String(new char[] { Character.toUpperCase(text.charAt(0)) });
144
		return capitalLetter.concat(text.substring(1));
145
	}
126
    public void setCurrentLocale(Locale locale) {
127
        getLocaleManager().setCurrentLocale(locale);
128
    }
146 129

  
147
	public Locale[] getInstalledLocales() {
148
		if (registeredLocales == null) {
130
    public Locale getDefaultSystemLocale() {
131
        return getLocaleManager().getDefaultSystemLocale();
132
    }
149 133

  
150
			XMLEntity child = getRegisteredLocalesPersistence();
134
    public void installLocale(Locale locale) {
135
        getLocaleManager().uninstallLocale(locale);
136
    }
151 137

  
152
			// If the list of registered locales is not already persisted,
153
			// this should be the first time gvSIG is run with the I18nPlugin
154
			// so we will take the list of default locales
155
			if (child == null) {
156
				Locale[] defaultLocales = getDefaultLocales();
157
				registeredLocales = new HashSet(defaultLocales.length);
158
				for (int i = 0; i < defaultLocales.length; i++) {
159
					registeredLocales.add(defaultLocales[i]);
160
				}
161
				storeInstalledLocales();
162
			} else {
163
				XMLEntity localesEntity = getRegisteredLocalesPersistence();
164
				registeredLocales =
165
						new HashSet(localesEntity.getChildrenCount());
166
				for (int i = 0; i < localesEntity.getChildrenCount(); i++) {
167
					XMLEntity localeEntity = localesEntity.getChild(i);
168
					String language = localeEntity.getStringProperty(LANGUAGE);
169
					String country = localeEntity.getStringProperty(COUNTRY);
170
					String variant = localeEntity.getStringProperty(VARIANT);
171
					Locale locale = new Locale(language, country, variant);
172
					registeredLocales.add(locale);
173
				}
174
			}
175
		}
138
    public void uninstallLocale(Locale locale) throws I18nException {
139
        if ( getCurrentLocale().equals(locale) || isReferenceLocale(locale) ) {
140
            throw new UninstallLocaleException(locale);
141
        }
142
        if ( getLocaleManager().uninstallLocale(locale) ) {
143
            // Remove the resource bundle file
144
            File bundleFile
145
                    = new File(getResourcesFolder(), getResourceFileName(locale));
176 146

  
177
		return (Locale[]) registeredLocales.toArray(new Locale[registeredLocales.size()]);
178
	}
147
            if ( bundleFile.exists() ) {
148
                bundleFile.delete();
149
            }
150
        }
151
    }
179 152

  
180
	public void uninstallLocale(Locale locale) throws I18nException {
181
		if (getCurrentLocale().equals(locale) || isReferenceLocale(locale)) {
182
			throw new UninstallLocaleException(locale);
183
		}
153
    public String getDisplayName(Locale locale) {
154
        return getDisplayName(locale, locale);
155
    }
184 156

  
185
		if (registeredLocales.remove(locale)) {
186
			// Remove from the configured locale list
187
			storeInstalledLocales();
157
    public String getDisplayName(Locale locale, Locale displayLocale) {
158
        StringBuffer name
159
                = new StringBuffer(getLanguageDisplayName(locale, displayLocale));
188 160

  
189
			// Remove the resource bundle file
190
			File bundleFile =
191
					new File(getResourcesFolder(), getResourceFileName(locale));
161
        if ( !isEmpty(locale.getCountry()) ) {
162
            name.append(" - ");
163
            name.append(locale.getDisplayCountry(displayLocale));
164
        }
192 165

  
193
			if (bundleFile.exists()) {
194
				bundleFile.delete();
195
			}
196
		}
197
	}
166
        if ( !isEmpty(locale.getVariant()) ) {
167
            name.append(" - ");
168
            name.append(locale.getDisplayVariant(displayLocale));
169
        }
198 170

  
199
	public String getDisplayName(Locale locale) {
200
		return getDisplayName(locale, locale);
201
	}
171
        name.append(" (").append(locale.toString()).append(")");
202 172

  
203
	public String getDisplayName(Locale locale, Locale displayLocale) {
204
		StringBuffer name =
205
				new StringBuffer(getLanguageDisplayName(locale, displayLocale));
173
        return name.toString();
174
    }
206 175

  
207
		if (!isEmpty(locale.getCountry())) {
208
			name.append(" - ");
209
			name.append(locale.getDisplayCountry(displayLocale));
210
		}
176
    private boolean isEmpty(String text) {
177
        return text == null || text.trim().length() == 0;
178
    }
211 179

  
212
		if (!isEmpty(locale.getVariant())) {
213
			name.append(" - ");
214
			name.append(locale.getDisplayVariant(displayLocale));
215
		}
180
    public String getLanguageDisplayName(Locale locale) {
181
        return this.getLocaleManager().getLanguageDisplayName(locale);
182
    }
216 183

  
217
		name.append(" (").append(locale.toString()).append(")");
184
    public String getLanguageDisplayName(Locale locale, Locale displayLocale) {
185
        return this.getLocaleManager().getLanguageDisplayName(locale);
186
        /*
187
        String displayName;
218 188

  
219
		return name.toString();
220
	}
221

  
222
	private boolean isEmpty(String text) {
223
		return text == null || text.trim().length() == 0;
224
	}
225

  
226
	public String getLanguageDisplayName(Locale locale) {
227
		return getLanguageDisplayName(locale, locale);
228
	}
229

  
230
	public String getLanguageDisplayName(Locale locale, Locale displayLocale) {
231

  
232
		String displayName;
233

  
234
		// Correction for the Basque language display name,
235
		// show it in Basque, not in Spanish
236
		if ("eu".equals(locale.getLanguage())
237
				&& "vascuence".equals(locale.getDisplayLanguage())) {
238
			displayName = "Euskera";
239
		}
240
		// Patch for Valencian/Catalan
241
		else if ("ca".equals(locale.getLanguage())) {
242
			// displayName = Messages.getText("__valenciano");
243
			// if ("__valenciano".equals(displayName)) {
244
			// displayName = Messages.getText("__catalan");
245
			// }
246
			displayName = "Valenci?";
247
		} else {
248
			displayName = locale.getDisplayLanguage(displayLocale);
249
		}
250

  
251
		return capitalize(displayName);
252
	}
253

  
254
	public Locale getCurrentLocale() {
255
		return Locale.getDefault();
256
	}
257

  
258
	public Locale getDefaultSystemLocale() {
259
		String language, region, country, variant;
260
		language = getSystemProperty("user.language", "en");
261
		// for compatibility, check for old user.region property
262
		region = getSystemProperty("user.region", null);
263

  
264
		if (region != null) {
265
			// region can be of form country, country_variant, or _variant
266
			int i = region.indexOf('_');
267
			if (i >= 0) {
268
				country = region.substring(0, i);
269
				variant = region.substring(i + 1);
270
			} else {
271
				country = region;
272
				variant = "";
273
			}
274
		} else {
275
			country = getSystemProperty("user.country", "");
276
			variant = getSystemProperty("user.variant", "");
277
		}
278
		return new Locale(language, country, variant);
279
	}
280

  
281
        public void setCurrentLocale(Locale locale) {
282
            PluginsManager pluginsManager = PluginsLocator.getManager();
283
            pluginsManager.setCurrentLocale(locale);
189
	// Correction for the Basque language display name,
190
        // show it in Basque, not in Spanish
191
        if ( "eu".equals(locale.getLanguage())
192
                && "vascuence".equals(locale.getDisplayLanguage()) ) {
193
            displayName = "Euskera";
194
        } // Patch for Valencian/Catalan
195
        else if ( "ca".equals(locale.getLanguage()) ) {
196
	    // displayName = Messages.getText("__valenciano");
197
            // if ("__valenciano".equals(displayName)) {
198
            // displayName = Messages.getText("__catalan");
199
            // }
200
            displayName = "Valenci?";
201
        } else {
202
            displayName = locale.getDisplayLanguage(displayLocale);
284 203
        }
285 204

  
286
	public Locale[] installLocales(File importFile) throws I18nException {
287
		List importLocales = new ArrayList();
205
        return capitalize(displayName);
206
        */
207
    }
288 208

  
289
		try {
290
			ZipFile zipFile = new ZipFile(importFile);
209
    public Locale[] installLocales(File importFile) throws I18nException {
210
        List importLocales = new ArrayList();
291 211

  
292
			Map locales = getZipFileNonReferenceLocales(zipFile);
212
        try {
213
            ZipFile zipFile = new ZipFile(importFile);
293 214

  
294
			if (locales == null || locales.size() == 0) {
295
				return null;
296
			}
215
            Map locales = getZipFileNonReferenceLocales(zipFile);
297 216

  
298
			for (Iterator iterator = locales.entrySet().iterator(); iterator.hasNext();) {
299
				Entry entry = (Entry) iterator.next();
217
            if ( locales == null || locales.size() == 0 ) {
218
                return null;
219
            }
300 220

  
301
				String fileName = (String) entry.getKey();
302
				Locale locale = (Locale) entry.getValue();
303
				importLocales.add(locale);
221
            for ( Iterator iterator = locales.entrySet().iterator(); iterator.hasNext(); ) {
222
                Entry entry = (Entry) iterator.next();
304 223

  
305
				// Add the locale to the list of installed ones, if it
306
				// is new, otherwise, update the texts.
307
				if (!registeredLocales.contains(locale)) {
308
					registeredLocales.add(locale);
309
					storeInstalledLocales();
310
				}
224
                String fileName = (String) entry.getKey();
225
                Locale locale = (Locale) entry.getValue();
226
                importLocales.add(locale);
311 227

  
312
				// Replace the old bundle with the new one
313
				ZipEntry zipEntry = zipFile.getEntry(fileName);
314
				InputStream is = zipFile.getInputStream(zipEntry);
315
				BufferedReader reader =
316
						new BufferedReader(new InputStreamReader(is));
228
                getLocaleManager().installLocale(locale);
317 229

  
318
				File bundleFile = getResourceFile(locale);
319
				FileWriter fileWriter = new FileWriter(bundleFile);
320
				BufferedWriter writer = new BufferedWriter(fileWriter);
230
                // Replace the old bundle with the new one
231
                ZipEntry zipEntry = zipFile.getEntry(fileName);
232
                InputStream is = zipFile.getInputStream(zipEntry);
233
                BufferedReader reader
234
                        = new BufferedReader(new InputStreamReader(is));
321 235

  
322
				String line;
323
				while ((line = reader.readLine()) != null) {
324
					writer.write(line);
325
					writer.write('\n');
326
				}
327
				writer.flush();
328
				writer.close();
329
				fileWriter.close();
330
				reader.close();
331
				is.close();
332
			}
236
                File bundleFile = getResourceFile(locale);
237
                FileWriter fileWriter = new FileWriter(bundleFile);
238
                BufferedWriter writer = new BufferedWriter(fileWriter);
333 239

  
334
		} catch (Exception ex) {
335
			throw new InstallLocalesException(importFile, ex);
336
		}
240
                String line;
241
                while ( (line = reader.readLine()) != null ) {
242
                    writer.write(line);
243
                    writer.write('\n');
244
                }
245
                writer.flush();
246
                writer.close();
247
                fileWriter.close();
248
                reader.close();
249
                is.close();
250
            }
337 251

  
338
		return (Locale[]) importLocales.toArray(new Locale[importLocales.size()]);
339
	}
252
        } catch (Exception ex) {
253
            throw new InstallLocalesException(importFile, ex);
254
        }
340 255

  
341
	public void exportLocaleForUpdate(Locale locale, Locale referenceLocale,
342
			File exportFile) throws I18nException {
256
        return (Locale[]) importLocales.toArray(new Locale[importLocales.size()]);
257
    }
343 258

  
344
		exportLocalesForUpdate(new Locale[] { locale }, referenceLocale,
345
				exportFile);
346
	}
259
    public void exportLocaleForUpdate(Locale locale, Locale referenceLocale,
260
            File exportFile) throws I18nException {
347 261

  
348
	public void exportLocalesForUpdate(Locale[] locales,
349
			Locale referenceLocale, File exportFile) throws I18nException {
262
        exportLocalesForUpdate(new Locale[]{locale}, referenceLocale,
263
                exportFile);
264
    }
350 265

  
351
		exportLocale(locales, new Locale[] { referenceLocale }, exportFile,
352
				true);
353
	}
266
    public void exportLocalesForUpdate(Locale[] locales,
267
            Locale referenceLocale, File exportFile) throws I18nException {
354 268

  
355
	public void exportLocaleForTranslation(Locale locale,
356
			Locale referenceLocale, File exportFile) throws I18nException {
269
        exportLocale(locales, new Locale[]{referenceLocale}, exportFile,
270
                true);
271
    }
357 272

  
358
		exportLocaleForTranslation(locale, new Locale[] { referenceLocale },
359
				exportFile);
360
	}
273
    public void exportLocaleForTranslation(Locale locale,
274
            Locale referenceLocale, File exportFile) throws I18nException {
361 275

  
362
	public void exportLocaleForTranslation(Locale locale,
363
			Locale[] referenceLocales, File exportFile) throws I18nException {
276
        exportLocaleForTranslation(locale, new Locale[]{referenceLocale},
277
                exportFile);
278
    }
364 279

  
365
		exportLocale(new Locale[] { locale }, referenceLocales, exportFile,
366
				false);
367
	}
280
    public void exportLocaleForTranslation(Locale locale,
281
            Locale[] referenceLocales, File exportFile) throws I18nException {
368 282

  
369
	public Locale[] getReferenceLocales() {
370
		return referenceLocales;
371
	}
283
        exportLocale(new Locale[]{locale}, referenceLocales, exportFile,
284
                false);
285
    }
372 286

  
373
	public void setReferenceLocales(Locale[] referenceLocales) {
374
		this.referenceLocales = referenceLocales;
375
	}
287
    public Locale[] getReferenceLocales() {
288
        return referenceLocales;
289
    }
376 290

  
377
	public void setDefaultLocales(Locale[] defaultLocales) {
378
		this.defaultLocales = defaultLocales;
379
	}
291
    public void setReferenceLocales(Locale[] referenceLocales) {
292
        this.referenceLocales = referenceLocales;
293
    }
380 294

  
381
	private void exportLocale(Locale[] locales, Locale[] referenceLocales,
382
			File exportFile, boolean update) throws I18nException {
295
    public void setDefaultLocales(Locale[] defaultLocales) {
296
        logger.warn("This operation (setDefaultLocales) is not supported.");
297
    }
383 298

  
384
		Locale[] refArray =
385
				getReferenceLocalesToExport(locales, referenceLocales);
299
    private void exportLocale(Locale[] locales, Locale[] referenceLocales,
300
            File exportFile, boolean update) throws I18nException {
386 301

  
387
		Set allReferenceKeys = new HashSet();
388
		Map referenceTexts = new HashMap(refArray.length);
389
		for (int i = 0; i < refArray.length; i++) {
390
			Map texts = getAllTexts(refArray[i]);
391
			referenceTexts.put(refArray[i], texts);
392
			allReferenceKeys.addAll(texts.keySet());
393
		}
302
        Locale[] refArray
303
                = getReferenceLocalesToExport(locales, referenceLocales);
394 304

  
395
		try {
396
			FileOutputStream fos = new FileOutputStream(exportFile);
397
			ZipOutputStream zipos = new ZipOutputStream(fos);
305
        Set allReferenceKeys = new HashSet();
306
        Map referenceTexts = new HashMap(refArray.length);
307
        for ( int i = 0; i < refArray.length; i++ ) {
308
            Map texts = getAllTexts(refArray[i]);
309
            referenceTexts.put(refArray[i], texts);
310
            allReferenceKeys.addAll(texts.keySet());
311
        }
398 312

  
399
			// Create the index file
400
			writeZipFileLocales(zipos, locales, refArray);
313
        try {
314
            FileOutputStream fos = new FileOutputStream(exportFile);
315
            ZipOutputStream zipos = new ZipOutputStream(fos);
401 316

  
402
			PrintStream ps = new PrintStream(zipos);
403
			Map texts = null;
317
            // Create the index file
318
            writeZipFileLocales(zipos, locales, refArray);
404 319

  
405
			if (update) {
406
				// First, export the locales to update
407
				if (locales != null) {
408
					for (int i = 0; i < locales.length; i++) {
409
						texts = getAllTexts(locales[i]);
410
						addPendingKeys(texts, allReferenceKeys);
411
						putResourceInZip(zipos, ps, texts,
412
								getResourceFileName(locales[i]));
413
					}
414
				}
415
			} else { // translate
416
				// First, export the locales to translate, taking the keys from
417
				// the reference locales, but without values
418
				if (locales != null) {
419
					for (int i = 0; i < locales.length; i++) {
420
						putResourceInZip(zipos, ps, allReferenceKeys,
421
								getResourceFileName(locales[i]));
422
					}
423
				}
424
			}
320
            PrintStream ps = new PrintStream(zipos);
321
            Map texts = null;
425 322

  
426
			// Next, export the reference locales
427
			if (refArray != null) {
428
				for (int i = 0; i < refArray.length; i++) {
429
					texts = getAllTexts(refArray[i]);
430
					putResourceInZip(zipos, ps, texts,
431
							getResourceFileName(refArray[i]));
432
				}
433
			}
323
            if ( update ) {
324
                // First, export the locales to update
325
                if ( locales != null ) {
326
                    for ( int i = 0; i < locales.length; i++ ) {
327
                        texts = getAllTexts(locales[i]);
328
                        addPendingKeys(texts, allReferenceKeys);
329
                        putResourceInZip(zipos, ps, texts,
330
                                getResourceFileName(locales[i]));
331
                    }
332
                }
333
            } else { // translate
334
                // First, export the locales to translate, taking the keys from
335
                // the reference locales, but without values
336
                if ( locales != null ) {
337
                    for ( int i = 0; i < locales.length; i++ ) {
338
                        putResourceInZip(zipos, ps, allReferenceKeys,
339
                                getResourceFileName(locales[i]));
340
                    }
341
                }
342
            }
434 343

  
435
			ps.flush();
436
			ps.close();
437
			zipos.close();
438
			fos.close();
439
		} catch (IOException ex) {
440
			throw new ExportLocaleException(locales, ex);
441
		}
442
	}
344
            // Next, export the reference locales
345
            if ( refArray != null ) {
346
                for ( int i = 0; i < refArray.length; i++ ) {
347
                    texts = getAllTexts(refArray[i]);
348
                    putResourceInZip(zipos, ps, texts,
349
                            getResourceFileName(refArray[i]));
350
                }
351
            }
443 352

  
444
	/**
445
	 * Adds the keys of the set to the map that aren't still contained in it
446
	 * with a related empty String.
447
	 * 
448
	 * @param texts
449
	 *            the map to complete with the keys
450
	 * @param allReferenceKeys
451
	 *            the complete key set
452
	 */
453
	private void addPendingKeys(Map texts, Set allReferenceKeys) {
454
		for (Iterator iterator = allReferenceKeys.iterator(); iterator.hasNext();) {
455
			Object key = (Object) iterator.next();
456
			if (!texts.containsKey(key)) {
457
				texts.put(key, "");
458
			}
459
		}
460
	}
353
            ps.flush();
354
            ps.close();
355
            zipos.close();
356
            fos.close();
357
        } catch (IOException ex) {
358
            throw new ExportLocaleException(locales, ex);
359
        }
360
    }
461 361

  
462
	/**
463
	 * Returns the list of reference locales to export, as the union of the
464
	 * default reference locales list and the one selected as reference. The
465
	 * locales to translate or update are extracted from the list.
466
	 */
467
	private Locale[] getReferenceLocalesToExport(Locale[] locales,
468
			Locale[] referenceLocalesSelected) {
362
    /**
363
     * Adds the keys of the set to the map that aren't still contained in it
364
     * with a related empty String.
365
     *
366
     * @param texts
367
     * the map to complete with the keys
368
     * @param allReferenceKeys
369
     * the complete key set
370
     */
371
    private void addPendingKeys(Map texts, Set allReferenceKeys) {
372
        for ( Iterator iterator = allReferenceKeys.iterator(); iterator.hasNext(); ) {
373
            Object key = (Object) iterator.next();
374
            if ( !texts.containsKey(key) ) {
375
                texts.put(key, "");
376
            }
377
        }
378
    }
379

  
380
    /**
381
     * Returns the list of reference locales to export, as the union of the
382
     * default reference locales list and the one selected as reference. The
383
     * locales to translate or update are extracted from the list.
384
     */
385
    private Locale[] getReferenceLocalesToExport(Locale[] locales,
386
            Locale[] referenceLocalesSelected) {
469 387
		// The reference locales to export are the default ones plus the
470
		// selected by the user.
471
		Set exportRefLocales = new HashSet(referenceLocales.length);
472
		for (int i = 0; i < referenceLocales.length; i++) {
473
			exportRefLocales.add(referenceLocales[i]);
474
		}
475
		if (referenceLocalesSelected != null) {
476
			for (int i = 0; i < referenceLocalesSelected.length; i++) {
477
				exportRefLocales.add(referenceLocalesSelected[i]);
478
			}
479
		}
480
		if (locales != null) {
481
			for (int i = 0; i < locales.length; i++) {
482
				exportRefLocales.remove(locales[i]);
483
			}
484
		}
485
		Locale[] refArray =
486
				(Locale[]) exportRefLocales.toArray(new Locale[exportRefLocales.size()]);
487
		return refArray;
488
	}
388
        // selected by the user.
389
        Set exportRefLocales = new HashSet(referenceLocales.length);
390
        for ( int i = 0; i < referenceLocales.length; i++ ) {
391
            exportRefLocales.add(referenceLocales[i]);
392
        }
393
        if ( referenceLocalesSelected != null ) {
394
            for ( int i = 0; i < referenceLocalesSelected.length; i++ ) {
395
                exportRefLocales.add(referenceLocalesSelected[i]);
396
            }
397
        }
398
        if ( locales != null ) {
399
            for ( int i = 0; i < locales.length; i++ ) {
400
                exportRefLocales.remove(locales[i]);
401
            }
402
        }
403
        Locale[] refArray
404
                = (Locale[]) exportRefLocales.toArray(new Locale[exportRefLocales.size()]);
405
        return refArray;
406
    }
489 407

  
490
	/**
491
	 * Returns all the localized texts and its keys for a locale.
492
	 */
493
	private Map getAllTexts(Locale locale) {
494
		return Messages.getAllTexts(locale);
495
	}
408
    /**
409
     * Returns all the localized texts and its keys for a locale.
410
     */
411
    private Map getAllTexts(Locale locale) {
412
        return Messages.getAllTexts(locale);
413
    }
496 414

  
497
	private Map getZipFileNonReferenceLocales(ZipFile zipFile)
498
			throws I18nException {
499
		ZipEntry zipEntry = zipFile.getEntry(LOCALES_FILE_NAME);
415
    private Map getZipFileNonReferenceLocales(ZipFile zipFile)
416
            throws I18nException {
417
        ZipEntry zipEntry = zipFile.getEntry(LOCALES_FILE_NAME);
500 418

  
501
		if (zipEntry == null) {
502
			return null;
503
		}
419
        if ( zipEntry == null ) {
420
            return null;
421
        }
504 422

  
505
		Map locales;
506
		try {
507
			InputStream is = zipFile.getInputStream(zipEntry);
508
			BufferedReader reader =
509
					new BufferedReader(new InputStreamReader(is));
423
        Map locales;
424
        try {
425
            InputStream is = zipFile.getInputStream(zipEntry);
426
            BufferedReader reader
427
                    = new BufferedReader(new InputStreamReader(is));
510 428

  
511
			locales = new HashMap(2);
512
			String line;
513
			while ((line = reader.readLine()) != null) {
429
            locales = new HashMap(2);
430
            String line;
431
            while ( (line = reader.readLine()) != null ) {
514 432
				// The excepted format is:
515
				// FILENAME,LANGUAGE,COUNTRY,VARIANT,IS_REFERENCE
516
				StringTokenizer st =
517
						new StringTokenizer(line, CSV_SEPARATOR, true);
518
				// First: locale file name (required)
519
				String fileName = st.nextToken();
520
				if (CSV_SEPARATOR.equals(fileName)) {
521
					throw new LocaleFileNameRequiredException(line);
522
				} else {
523
					// Read the next separator
524
					st.nextToken();
525
				}
526
				// Second: the locale language (required)
527
				String language = st.nextToken();
528
				if (CSV_SEPARATOR.equals(language)) {
529
					throw new LocaleLanguageRequiredException(line);
530
				} else {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff