Wednesday, August 4, 2010

Parameters for resource messages

Spent a lot of time thinking/recollecting to do this.
Here it goes



import java.util.ListResourceBundle;
/*
** Resource bundle test
*/
public class AppMessageBundle extends ListResourceBundle
{
 
    static final Object[][] m_contents =
    {
    // KEY                  , MESSAGE

    // Messages for the migration exception log
     {"HELLO"         , "Hello without parameter."
     }
    ,{"HELLO_ARG1"    , "Hello {0}."
     }
    ,{"HELLO_ARG2"    , "Hello {0} and {1}."
     }


    // Errors and Exceptions
   

    // Genric Messages
    // To add as and when requirements arise

    // Command line usage
    // To add if requirements arise.

   
  };


  public Object[][] getContents()
  {
    return (m_contents);
  }
}




import java.text.MessageFormat;
import java.util.*;

/*
** Test program to understand 
** passing arguments to construct
** resource messages of more meaning.
*/

public class AppMessageBundleTester
{
  private static final String RESOURCE_BUNDLE = "AppMessageBundle";
 
  public static void main ( String[] args )
  {
      String name1 = "Test string";
      int num = 734;
      printResourceMessage("HELLO");
      printResourceMessage("HELLO_ARG1",new Object[]{name1});
      printResourceMessage("HELLO_ARG2",new Object[]{name1,name1});
      printResourceMessage("HELLO_ARG2",new Object[]{name1,num});
     
     
  } 
   private static ResourceBundle s_resBund = ResourceBundle.getBundle(
                                              RESOURCE_BUNDLE, Locale.getDefault());
    public static ResourceBundle getResourceBundle()
  {
    return s_resBund;
  }

  
  static void printResourceMessage(String message, Object[] names)
  {
    println(MessageFormat.format(s_resBund.getString(message), names));
  }

  static void printResourceMessage(String message)
  {
    println(s_resBund.getString(message));
  }
    static void println(Object o)
  {
    System.out.println(o);
  }

   
   
} //  end of class
This is all java and you need not have to go through hassle of having properties file. Specially useful in a web application.

Followers