You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by df...@apache.org on 2005/05/06 12:36:42 UTC

svn commit: r168590 - in /jakarta/commons/sandbox/i18n/trunk: ./ src/examples/org/apache/i18n/examples/ src/java/org/apache/commons/i18n/ src/java/org/apache/commons/i18n/bundles/ src/test/org/apache/commons/i18n/ xdocs/

Author: dflorey
Date: Fri May  6 03:36:38 2005
New Revision: 168590

URL: http://svn.apache.org/viewcvs?rev=168590&view=rev
Log:
Incorporated changes proposed by Mattias J

Removed:
    jakarta/commons/sandbox/i18n/trunk/src/test/org/apache/commons/i18n/
    jakarta/commons/sandbox/i18n/trunk/xdocs/downloads.xml
Modified:
    jakarta/commons/sandbox/i18n/trunk/project.properties
    jakarta/commons/sandbox/i18n/trunk/project.xml
    jakarta/commons/sandbox/i18n/trunk/src/examples/org/apache/i18n/examples/LocalizedExceptionExample.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/LocalizedBundle.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/MessageManager.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/ResourceBundleMessageProvider.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/XMLMessageProvider.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/ErrorBundle.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/MessageBundle.java
    jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/TextBundle.java
    jakarta/commons/sandbox/i18n/trunk/xdocs/index.xml

Modified: jakarta/commons/sandbox/i18n/trunk/project.properties
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/project.properties?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/project.properties (original)
+++ jakarta/commons/sandbox/i18n/trunk/project.properties Fri May  6 03:36:38 2005
@@ -21,8 +21,9 @@
 maven.xdoc.version=${pom.currentVersion}
 maven.xdoc.developmentProcessUrl=http://jakarta.apache.org/commons/charter.html
 maven.xdoc.includeProjectDocumentation=yes
-maven.xdoc.distributionUrl=http://www.apache.org/dist/java-repository/commons-i18n/distributions
+maven.xdoc.distributionUrl=http://cvs.apache.org/repository/commons-i18n/distributions
 maven.xdoc.distributionType=zip
+
 # ------------------------------------------------------------------------
 # M A V E N  J A R  O V E R R I D E
 # ------------------------------------------------------------------------

Modified: jakarta/commons/sandbox/i18n/trunk/project.xml
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/project.xml?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/project.xml (original)
+++ jakarta/commons/sandbox/i18n/trunk/project.xml Fri May  6 03:36:38 2005
@@ -31,17 +31,10 @@
   <package>org.apache.commons.i18n</package>
   <shortDescription>Commons I18n</shortDescription>
   <description>Internationalization package</description>
+  <siteAddress>cvs.apache.org</siteAddress>
 
-  <currentVersion>0.4</currentVersion>
+  <currentVersion>20050221</currentVersion>
   <versions>
-	<version>
-		<id>1</id>
-		<name>0.4</name>
-	</version>
-	<version>
-		<id>2</id>
-		<name>0.3</name>
-	</version>
   </versions>
   <branches>
   </branches>
@@ -70,6 +63,10 @@
   </developers>
   
   <contributors>
+    <contributor>
+      <name>Mattias Jiderhamn</name>
+      <email>mattias.jiderhamn@expertsystem.se</email>
+    </contributor>
     <contributor>
       <name>Anaximandro (Woody)</name>
       <email>agodinhost@globo.com</email>

Modified: jakarta/commons/sandbox/i18n/trunk/src/examples/org/apache/i18n/examples/LocalizedExceptionExample.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/examples/org/apache/i18n/examples/LocalizedExceptionExample.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/examples/org/apache/i18n/examples/LocalizedExceptionExample.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/examples/org/apache/i18n/examples/LocalizedExceptionExample.java Fri May  6 03:36:38 2005
@@ -1,22 +1,22 @@
 /*
-*
-* ====================================================================
-*
-* Copyright 2004 The Apache Software Foundation 
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*     http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-*/
+ *
+ * ====================================================================
+ *
+ * Copyright 2004 The Apache Software Foundation 
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
 package org.apache.i18n.examples;
 
 import java.util.Locale;
@@ -29,30 +29,46 @@
 
 /**
  * @author Daniel Florey
- *
+ *  
  */
 public class LocalizedExceptionExample {
-    private static final Logger logger = Logger.getLogger(LocalizedExceptionExample.class.getName());
+    private static final Logger logger = Logger
+            .getLogger(LocalizedExceptionExample.class.getName());
 
     public static void main(String[] args) {
-        XMLMessageProvider.install("org.apache.commons-i18n.test", Thread.currentThread().getContextClassLoader().getResourceAsStream("testMessages.xml"));
+        // Install the file providing the required messages for this example
+        XMLMessageProvider.install("org.apache.commons-i18n.examples", Thread
+                .currentThread().getContextClassLoader().getResourceAsStream(
+                        "exampleMessages.xml"));
 
+        // Simulate the locale of the current user in a multi-user environment
+        // such as a web application
         Locale currentUsersLocale = Locale.GERMAN;
-        
-        // Dealing with localized exceptions
+
+        // This is the real part dealing with localized exceptions
         try {
             someMethodThrowingAnException();
-        } catch ( LocalizedException exception ) {
+        } catch (LocalizedException exception) {
+            // Retrieve the detailed localized error message
             ErrorBundle errorMessage = exception.getErrorMessage();
+
             // Print the summary of this error to the log with level SEVERE
             // using the VM default locale:
-            logger.log(Level.SEVERE, errorMessage.getSummary(Locale.getDefault()));
+            logger.log(Level.SEVERE, errorMessage.getSummary(Locale
+                    .getDefault()));
+
             // Print the details of this error to the log with level FINE
             // using the VM default locale:
-            logger.log(Level.FINE, errorMessage.getDetails(Locale.getDefault()));
-            // Provide the title of this error to the user in a highly visible way
+            logger
+                    .log(Level.FINE, errorMessage.getDetails(Locale
+                            .getDefault()));
+
+            // Provide the title of this error to the user in a highly visible
+            // way
             // using the current users locale:
-            System.out.println("#### "+errorMessage.getTitle(currentUsersLocale)+" ####");
+            System.out.println("#### "
+                    + errorMessage.getTitle(currentUsersLocale) + " ####");
+
             // Provide the text of this error to the user
             // using the current users locale:
             System.out.println(errorMessage.getText(currentUsersLocale));
@@ -60,12 +76,14 @@
     }
 
     /**
-     * @throws LocalizedException is thrown just to show the capabilities of LocalizedExceptions
+     * @throws LocalizedException
+     *             is thrown just to show the capabilities of
+     *             LocalizedExceptions
      */
-    private static void someMethodThrowingAnException() throws LocalizedException {
+    private static void someMethodThrowingAnException()
+            throws LocalizedException {
         String userCausingTheException = "Daniel";
-        throw new LocalizedException(
-                new ErrorBundle("theCauseOfThisException",
-                new String[] { userCausingTheException } ));
+        throw new LocalizedException(new ErrorBundle("theCauseOfThisException",
+                new String[]{userCausingTheException}));
     }
 }

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/LocalizedBundle.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/LocalizedBundle.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/LocalizedBundle.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/LocalizedBundle.java Fri May  6 03:36:38 2005
@@ -37,11 +37,10 @@
  * the key of the desired message entry.</p>  
  * This class should not be used directly in order to retrieve entries of a message bundle. It is recommended
  * to subclass the <code>LocalizedBundle</code> class in order to define a specific localized bundle. 
- * @see TextBundle, MessageBundle, ErrorBundle    
+ * @see org.apache.commons.i18n.bundles.TextBundle, MessageBundle, ErrorBundle
  */
 public class LocalizedBundle implements Serializable {
     public final static String ID = "id";
-    public final static String ARGUMENTS = "arguments";
 
     protected String id;
     protected Object[] arguments;
@@ -97,7 +96,7 @@
      * @param defaultText the text to be returned if no entry was found for the given key
      * @return returns the text of the desired message entry for the given locale  
      */
-    public String getEntry(String key, String defaultText, Locale locale) {
+    public String getEntry(String key, Locale locale, String defaultText) {
         return MessageManager.getText(id, key, arguments, locale, defaultText);
     }
 }

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/MessageManager.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/MessageManager.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/MessageManager.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/MessageManager.java Fri May  6 03:36:38 2005
@@ -20,12 +20,7 @@
 package org.apache.commons.i18n;
 
 import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.ResourceBundle;
+import java.util.*;
 
 /**
  * The <code>MessageManager</code> provides methods for retrieving localized
@@ -46,7 +41,7 @@
  * <p>
  * You can call {@link MessageManager#getText(String,String,Object[],Locale) getText} directly,
  * but if you do so, you have to ensure that the given entry key really
- * exists and to deal with the {@link MessageNotFound} exception that will 
+ * exists and to deal with the {@link MessageNotFoundException} exception that will
  * be thrown if you try to access a not existing entry.</p>
  * 
  */
@@ -61,28 +56,33 @@
 
     public static final ResourceBundle INTERNAL_MESSAGES = ResourceBundle.getBundle("messages", Locale.getDefault());
     
-    private static List messageProviders = new ArrayList();
-
-    static {
-        // Add default message providers
-        messageProviders.add(new XMLMessageProvider());
-        messageProviders.add(new ResourceBundleMessageProvider());
-    }
+    private static Map messageProviders = new LinkedHashMap();
 
     /**
      * Add a custom <code>{@link MessageProvider}</code> to the
      * <code>MessageManager</code>. It will be incorporated in later calls of
      * the {@link MessageManager#getText(String,String,Object[],Locale) getText}
      * or {@link #getEntries(String,Locale) getEntries}methods.
-     * 
+     *
+     * @param providerId Id of the provider used for uninstallation and
+     *          qualified naming.
      * @param messageProvider
      *            The <code>MessageProvider</code> to be added.
      */
-    public static void addMessageProvider(MessageProvider messageProvider) {
-        messageProviders.add(messageProvider);
+    public static void addMessageProvider(String providerId, MessageProvider messageProvider) {
+        messageProviders.put(providerId, messageProvider);
     }
 
     /**
+     * Remove custom <code>{@link MessageProvider}</code> from the
+     * <code>MessageManager</code>. Used for tearing down unit tests.
+     *
+     * @param providerId The ID of the provider to remove.
+     */
+    static void removeMessageProvider(String providerId) {
+        messageProviders.remove(providerId);
+    }
+    /**
      * Iterates over all registered message providers in order to find the given
      * entry in the requested message bundle.
      * 
@@ -104,8 +104,10 @@
      */
     public static String getText(String id, String entry, Object[] arguments,
             Locale locale) throws MessageNotFoundException {
+        if(messageProviders.isEmpty())
+            throw new MessageNotFoundException("No MessageProvider registered");
         MessageNotFoundException exception = null;
-        for (Iterator i = messageProviders.iterator(); i.hasNext();) {
+        for (Iterator i = messageProviders.values().iterator(); i.hasNext();) {
             try {
                 String text = ((MessageProvider) i.next()).getText(id, entry,
                         locale);
@@ -140,10 +142,9 @@
     public static String getText(String id, String entry, Object[] arguments,
             Locale locale, String defaultText) {
         try {
-            String text = getText(id, entry, arguments, locale);
-            return MessageFormat.format(text, arguments);
+            return getText(id, entry, arguments, locale);
         } catch (MessageNotFoundException e) {
-            return defaultText;
+            return MessageFormat.format(defaultText, arguments);
         }
     }
 
@@ -155,12 +156,12 @@
      */
     public static Map getEntries(String id, Locale locale)
             throws MessageNotFoundException {
+        if(messageProviders.isEmpty())
+            throw new MessageNotFoundException("No MessageProvider registered");
         MessageNotFoundException exception = null;
-        for (Iterator i = messageProviders.iterator(); i.hasNext();) {
+        for (Iterator i = messageProviders.values().iterator(); i.hasNext();) {
             try {
-                Map entries = ((MessageProvider) i.next()).getEntries(id,
-                        locale);
-                return entries;
+                return ((MessageProvider) i.next()).getEntries(id, locale);
             } catch (MessageNotFoundException e) {
                 exception = e;
             }

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/ResourceBundleMessageProvider.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/ResourceBundleMessageProvider.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/ResourceBundleMessageProvider.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/ResourceBundleMessageProvider.java Fri May  6 03:36:38 2005
@@ -20,11 +20,8 @@
 package org.apache.commons.i18n;
 
 import java.text.MessageFormat;
-import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.MissingResourceException;
@@ -40,35 +37,33 @@
 public class ResourceBundleMessageProvider implements MessageProvider {
     private static Logger logger = Logger.getLogger(ResourceBundleMessageProvider.class.getName());
 
-    private static List installedResourceBundles = new ArrayList();
+    private final String baseName;
+
+    public ResourceBundleMessageProvider(String baseName) {
+        this.baseName = baseName;
+    }
 
     /* (non-Javadoc)
      * @see org.apache.commons.i18n.MessageProvider#getText(java.lang.String, java.lang.String, java.util.Locale)
      */
     public String getText(String id, String entry, Locale locale) throws MessageNotFoundException {
-        for ( Iterator i = installedResourceBundles.iterator(); i.hasNext(); ) {
-            String baseName = (String)i.next();
-            try {
-                ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
-                try {
-                    return resourceBundle.getString(id+"."+entry);
-                } catch ( ClassCastException e ) {
-                    // ignore all entries that are not of type String
-                } catch ( MissingResourceException e ) {
-                    // skip resource bundle if it is not containing the desired entry
-                }
-            } catch ( MissingResourceException e ) {
-                logger.log(
-                        Level.WARNING, 
-                        MessageFormat.format(
-                                MessageManager.INTERNAL_MESSAGES.getString(MessageManager.RESOURCE_BUNDLE_NOT_FOUND),
-                                new String[] { baseName })); 
-                i.remove();
-            }
+        // TODO: Revise try/catch
+        try {
+            ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
+             return resourceBundle.getString(id+"."+entry);
+        } catch ( ClassCastException e ) {
+            // ignore all entries that are not of type String
+        }
+        catch ( MissingResourceException e ) {
+            logger.log(
+                    Level.WARNING,
+                    MessageFormat.format(
+                            MessageManager.INTERNAL_MESSAGES.getString(MessageManager.RESOURCE_BUNDLE_NOT_FOUND),
+                            new String[] { baseName }));
         }
         throw new MessageNotFoundException(MessageFormat.format(
-                MessageManager.INTERNAL_MESSAGES.getString(MessageManager.NO_MESSAGE_ENTRIES_FOUND),
-                new String[] { id })); 
+            MessageManager.INTERNAL_MESSAGES.getString(MessageManager.NO_MESSAGE_ENTRIES_FOUND),
+            new String[] { id }));
     }
 
     /* (non-Javadoc)
@@ -77,27 +72,25 @@
     public Map getEntries(String id, Locale locale) {
         String messageIdentifier = id+".";
         Map entries = null;
-        for ( Iterator i = installedResourceBundles.iterator(); i.hasNext(); ) {
-            String baseName = (String)i.next();
-            try {
-                ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
-                Enumeration keys = resourceBundle.getKeys();
-                while ( keys.hasMoreElements() ) {
-                    String key = (String)keys.nextElement();
-                    if ( key.startsWith(messageIdentifier) ) {
-                        if ( entries == null ) {
-                            entries = new HashMap(); 
-                        }
-                        entries.put(key.substring(messageIdentifier.length()), resourceBundle.getString(key));
+        try {
+            ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, locale);
+            Enumeration keys = resourceBundle.getKeys();
+            while ( keys.hasMoreElements() ) {
+                String key = (String)keys.nextElement();
+                if ( key.startsWith(messageIdentifier) ) {
+                    if ( entries == null ) {
+                        entries = new HashMap();
                     }
+                    entries.put(key.substring(messageIdentifier.length()), resourceBundle.getString(key));
                 }
-            } catch ( MissingResourceException e ) {
-                logger.log(
-                        Level.WARNING, 
-                        MessageFormat.format(
-                                MessageManager.INTERNAL_MESSAGES.getString(MessageManager.RESOURCE_BUNDLE_NOT_FOUND),
-                                new String[] { baseName })); 
             }
+        } catch ( MissingResourceException e ) {
+            logger.log(
+                    Level.WARNING,
+                    MessageFormat.format(
+                            MessageManager.INTERNAL_MESSAGES.getString(MessageManager.RESOURCE_BUNDLE_NOT_FOUND),
+                            new String[] { baseName }));
+            // TODO: Consider uninstalling
         }
         if ( entries == null ) {
             throw new MessageNotFoundException(MessageFormat.format(
@@ -117,15 +110,15 @@
      * 
      */
     public static void install(String baseName) {
-        if ( !installedResourceBundles.contains(baseName) ) 
-            installedResourceBundles.add(baseName); 
+        MessageManager.addMessageProvider(baseName,
+                new ResourceBundleMessageProvider(baseName));
     }
     
     /**
      * @param baseName unique identifier for the resource bundle to uninstall
      */
     public static void uninstall(String baseName) {
-        installedResourceBundles.remove(baseName);
+        MessageManager.removeMessageProvider(baseName); // TODO: Consider checkning type
     }
     
     /**

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/XMLMessageProvider.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/XMLMessageProvider.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/XMLMessageProvider.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/XMLMessageProvider.java Fri May  6 03:36:38 2005
@@ -21,9 +21,7 @@
 
 import java.io.InputStream;
 import java.text.MessageFormat;
-import java.util.Collection;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Locale;
 import java.util.Map;
 import java.util.logging.Level;
@@ -41,13 +39,32 @@
  *  
  */
 public class XMLMessageProvider implements MessageProvider {
-    private static Logger logger = Logger.getLogger(XMLMessageProvider.class.getName());
+    private static final Logger logger = Logger.getLogger(XMLMessageProvider.class.getName());
 
     private static SAXParserFactory factory = SAXParserFactory.newInstance();
     
-    private static Map installedMessages = new HashMap();
-    private static Map messages = new HashMap();
-    
+    private final String id;
+
+    private Map messages = new HashMap();
+
+    public XMLMessageProvider(String id, InputStream inputStream) {
+        this.id = id;
+        try {
+            Map applicationMessages = new HashMap();
+            SAXParser parser = factory.newSAXParser();
+            ConfigurationHandler handler = new ConfigurationHandler();
+            parser.parse(new InputSource(inputStream), handler);
+            Map parsedMessages = handler.getMessages();
+            applicationMessages.putAll(parsedMessages);
+            messages.putAll(applicationMessages);
+        } catch (Exception exception) {
+            logger.log(Level.SEVERE,
+                    MessageFormat.format(
+                    MessageManager.INTERNAL_MESSAGES.getString(MessageManager.MESSAGE_PARSING_ERROR),
+                    new String[] { id }), exception);
+        }
+    }
+
     /* (non-Javadoc)
      * @see org.apache.commons.i18n.MessageProvider#getText(java.lang.String, java.lang.String, java.util.Locale)
      */
@@ -72,33 +89,14 @@
      * @param inputStream providing the messages in the required XML format 
      */
     public static void install(String id, InputStream inputStream) {
-        try {
-            Map applicationMessages = new HashMap();
-            SAXParser parser = factory.newSAXParser();
-            ConfigurationHandler handler = new ConfigurationHandler();
-            parser.parse(new InputSource(inputStream), handler);
-            Map parsedMessages = handler.getMessages();
-            applicationMessages.putAll(parsedMessages);
-            messages.putAll(applicationMessages);
-            installedMessages.put(id, applicationMessages.keySet());
-        } catch (Exception exception) {
-            logger.log(Level.SEVERE, 
-                    MessageFormat.format(
-                    MessageManager.INTERNAL_MESSAGES.getString(MessageManager.MESSAGE_PARSING_ERROR),
-                    new String[] { id }), exception); 
-        }
+        MessageManager.addMessageProvider(id, new XMLMessageProvider(id, inputStream));
     }
     
     /**
      * @param id unique identifier for the messages to uninstall
      */
     public static void uninstall(String id) {
-        Collection messageKeys = (Collection)installedMessages.get(id);
-        for ( Iterator i = messageKeys.iterator(); i.hasNext(); ) {
-            String messageKey = (String)i.next();
-            messages.remove(messageKey);
-        }
-        installedMessages.remove(id);
+        MessageManager.removeMessageProvider(id);
     }
     
     /**
@@ -110,7 +108,7 @@
         install(id, inputStream);
     }
         
-    private static Message findMessage(String id, Locale locale) {
+    private Message findMessage(String id, Locale locale) {
         Message message = lookupMessage(id, locale);
         if (message == null) {
             message = lookupMessage(id, Locale.getDefault());
@@ -122,13 +120,8 @@
         return message;
     }
 
-    private static Message lookupMessage(String id, Locale locale) {
-        StringBuffer keyBuffer = new StringBuffer(64);
-        keyBuffer.append(id);
-        if (locale.getLanguage() != null) keyBuffer.append("_" + locale.getLanguage());
-        if (locale.getCountry() != null) keyBuffer.append("_" + locale.getCountry());
-        if (locale.getVariant() != null) keyBuffer.append("_" + locale.getVariant());
-        String key = keyBuffer.toString();
+    private Message lookupMessage(String id, Locale locale) {
+        String key = id + '_' + locale.toString();
         if (messages.containsKey(key)) return (Message)messages.get(key);
         while (key.lastIndexOf('_') > 0) {
             key = key.substring(0, key.lastIndexOf('_'));
@@ -137,7 +130,7 @@
         return null;
     }
 
-    static class ConfigurationHandler extends DefaultHandler {
+    class ConfigurationHandler extends DefaultHandler {
         private String id, key;
         private Message message;
         private StringBuffer cData;
@@ -178,7 +171,8 @@
     }
 
     static class Message {
-        private String id, language, country, variant;
+        private final String id;
+        private String language, country, variant;
         private Map entries = new HashMap();
 
         public Message(String id) {
@@ -210,12 +204,9 @@
         }
 
         public String getKey() {
-            StringBuffer key = new StringBuffer(64);
-            key.append(id);
-            if (language != null) key.append("_" + language);
-            if (country != null) key.append("_" + country);
-            if (variant != null) key.append("_" + variant);
-            return key.toString();
+            return id + '_' + new Locale((language != null) ? language : "",
+                    (country != null) ? country : "",
+                    (variant != null) ? variant : "").toString();
         }
     }
 }

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/ErrorBundle.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/ErrorBundle.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/ErrorBundle.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/ErrorBundle.java Fri May  6 03:36:38 2005
@@ -64,11 +64,11 @@
 
     /**
      * @param locale The locale that is used to find the appropriate localized text 
-     * @param defaultText The default text will be returned, if no entry with key <code>summary</code> could be found in the message bundle identified by the given message identifier
+     * @param defaultSummary The default text will be returned, if no entry with key <code>summary</code> could be found in the message bundle identified by the given message identifier
      * @return returns the localized message entry with the key <code>summary</code>
      */
     public String getSummary(Locale locale, String defaultSummary) {
-        return getEntry(SUMMARY, defaultSummary, locale);
+        return getEntry(SUMMARY, locale, defaultSummary);
     }
 
 
@@ -83,10 +83,10 @@
 
     /**
      * @param locale The locale that is used to find the appropriate localized text 
-     * @param defaultText The default text will be returned, if no entry with key <code>details</code> could be found in the message bundle identified by the given message identifier
+     * @param defaultDetails The default text will be returned, if no entry with key <code>details</code> could be found in the message bundle identified by the given message identifier
      * @return returns the localized message entry with the key <code>details</code>
      */
     public String getDetails(Locale locale, String defaultDetails) {
-        return getEntry(DETAILS, defaultDetails, locale);
+        return getEntry(DETAILS, locale, defaultDetails);
     }
 }

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/MessageBundle.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/MessageBundle.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/MessageBundle.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/MessageBundle.java Fri May  6 03:36:38 2005
@@ -62,10 +62,10 @@
 
     /**
      * @param locale The locale that is used to find the appropriate localized text 
-     * @param defaultText The default text will be returned, if no entry with key <code>title</code> could be found in the message bundle identified by the given message identifier
+     * @param defaultTitle The default text will be returned, if no entry with key <code>title</code> could be found in the message bundle identified by the given message identifier
      * @return returns the localized message entry with the key <code>title</code>
      */
-    public String getTitle(Locale locale, String defaultSummary) {
-        return getEntry(TITLE, defaultSummary, locale);
+    public String getTitle(Locale locale, String defaultTitle) {
+        return getEntry(TITLE, locale, defaultTitle);
     }
 }

Modified: jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/TextBundle.java
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/TextBundle.java?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/TextBundle.java (original)
+++ jakarta/commons/sandbox/i18n/trunk/src/java/org/apache/commons/i18n/bundles/TextBundle.java Fri May  6 03:36:38 2005
@@ -67,6 +67,6 @@
      * @return returns the localized message entry with the key <code>text</code>
      */
     public String getText(Locale locale, String defaultText) {
-        return getEntry(TEXT, defaultText, locale);
+        return getEntry(TEXT, locale, defaultText);
     }
 }

Modified: jakarta/commons/sandbox/i18n/trunk/xdocs/index.xml
URL: http://svn.apache.org/viewcvs/jakarta/commons/sandbox/i18n/trunk/xdocs/index.xml?rev=168590&r1=168589&r2=168590&view=diff
==============================================================================
--- jakarta/commons/sandbox/i18n/trunk/xdocs/index.xml (original)
+++ jakarta/commons/sandbox/i18n/trunk/xdocs/index.xml Fri May  6 03:36:38 2005
@@ -43,9 +43,6 @@
 <p>
 None. This is a <i>sandbox</i> component.
 </p>
-    <p>
-       See the <a href="downloads.html">downloads</a> page for information on obtaining snapshop builds.
-    </p>
 <p>
  <ul>
   <li>The code is unreleased</li>
@@ -53,7 +50,9 @@
   <li>If you like the code and want to push it towards a release, join the mailing list!</li>
  </ul>
 </p>
-    
+<p>
+You can obtain snapshot builds <a href="http://cvs.apache.org/repository/commons-i18n/distributions/">here</a>.
+</p>
 </section>
 
 <section name="Documentation">



---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


[i18n] Continued development

Posted by Mattias J <mj...@expertsystem.se>.
Daniel, I see you checked in my refactorings now. Thanks.

To solve one of the issues previously discussed - with one provider 
throwing an exception and another one returning null for a particular case 
- I have the following idea:
Let's extend the MessageProvider interface to include both getText() - 
which throws an exception if not found - and findText() - which returns 
null if not found. (Something like the difference between Hibernates 
Session.load() and .find()).
Then for the MessageProvider implementations, you will only actually 
implement one of these - which should be clear by the documentation. Either 
you implement findText() and have getText() throw an exception if the call 
to findText() returns null, OR you implement getText() and have findText() 
return null if the call to getText() throws and exception.

This way we will not only solve the inconsequence problems; we will also 
increase performance by using findText() in MessageManager and thus 
avoiding throwing and catching exceptions while looping (assuming the 
MessageProvider implements findText() that does not throw, that is).

Therefore, if we only want findText() OR getText(), I would suggest findText().


As to the other issue, that ResouceBundles returns the entry of the default 
locale if not found for the specific locale while XML does not, I assume 
the most straight forward would be to have XML behave the same way 
ResourceBundles does. AFAIK there is no way to change the behaivor of 
java.util.ResourceBundle and providing our own implementation would not 
only cost a lot of time, but feel just "wrong".

(B.t.w. I have started working on naming/qualifying provider and will post 
a diff when I'm done)

   /Mattias J


---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org