Class StringResourceModel

java.lang.Object
org.apache.wicket.model.LoadableDetachableModel<String>
org.apache.wicket.model.StringResourceModel
All Implemented Interfaces:
Serializable, IComponentAssignedModel<String>, IDetachable, IModel<String>, IClusterable

This model class encapsulates the full power of localization support within the Wicket framework. It combines the flexible Wicket resource loading mechanism with property expressions, property models and standard Java MessageFormat substitutions. This combination should be able to solve any dynamic localization requirement that a project has.

The model should be created with four parameters, which are described in detail below:

  • resourceKey - This is the most important parameter as it contains the key that should be used to obtain resources from any string resource loaders. This parameter is mandatory: a null value will throw an exception. Typically it will contain an ordinary string such as "label.username". To add extra power to the key functionality the key may also contain a property expression which will be evaluated if the model parameter (see below) is not null. This allows keys to be changed dynamically as the application is running. For example, the key could be "product.${product.id}" which prior to rendering will call model.getObject().getProduct().getId() and substitute this value into the resource key before is is passed to the loader.
  • component - This parameter should be a component that the string resource is relative to. In a simple application this will usually be the Page on which the component resides. For reusable components/containers that are packaged with their own string resource bundles it should be the actual component/container rather than the page. For more information on this please see ComponentStringResourceLoader. The relative component may actually be null if this model is wrapped on assignment ( IComponentAssignedModel) or when all resource loading is to be done from a global resource loader. However, we recommend that a relative component is still supplied even in the latter case in order to 'future proof' your application with regards to changing resource loading strategies.
  • model - This parameter is mandatory if either the resourceKey, the found string resource (see below) or any of the substitution parameters (see below) contain property expressions. Where property expressions are present they will all be evaluated relative to this model object. If there are no property expressions present then this model parameter may be null
  • parameters - This parameter allows an array of objects to be passed for substitution on the found string resource (see below) using a standard java.text.MessageFormat object. Each parameter may be an ordinary Object, in which case it will be processed by the standard formatting rules associated with java.text.MessageFormat. Alternatively, the parameter may be an instance of IModel in which case the getObject() method will be applied prior to the parameter being passed to the java.text.MessageFormat. This allows such features dynamic parameters that are obtained using a PropertyModel object or even nested string resource models. Unlike the other parameters listed above this one can not be provided as constructor parameter but rather using method setParameters(Object...).
As well as the supplied parameters, the found string resource can contain formatting information. It may contain property expressions in which case these are evaluated using the model object supplied when the string resource model is created. The string resource may also contain java.text.MessageFormat style markup for replacement of parameters. Where a string resource contains both types of formatting information then the property expression will be applied first.

Example Bean

In the next examples we will use the following class as bundle model:

 public class WeatherStation implements Serializable
  {
    private final String name = "Europe's main weather station";

    private String currentStatus = "sunny";

    private double currentTemperature = 25.7;

    private String units = "°C";
  }
 

Example 1

In its simplest form, the model can be used as follows:

 public class MyPage extends WebPage<Void>
 {
    public MyPage(final PageParameters parameters)
    {
        add(new Label("username", new StringResourceModel("label.username", this)));
    }
 }
 
Where the resource bundle for the page contains the entry label.username=Username

Example 2

In this example, the resource key is selected based on the evaluation of a property expression:

 public class MyPage extends WebPage<Void>
 {
     public MyPage(final PageParameters parameters)
     {
         WeatherStation ws = new WeatherStation();
         add(new Label("weatherMessage",
             new StringResourceModel("weather.${currentStatus}", this, new Model<WeatherStation>(ws)));
     }
 }
 
Which will call the WeatherStation.getCurrentStatus() method each time the string resource model is used and where the resource bundle for the page contains the entries:
 weather.sunny=Don't forget sunscreen!
 weather.raining=You might need an umbrella
 weather.snowing=Got your skis?
 weather.overcast=Best take a coat to be safe
 

Example 3

In this example the found resource string contains a property expression that is substituted via the model:

 public class MyPage extends WebPage<Void>
 {
     public MyPage(final PageParameters parameters)
     {
         WeatherStation ws = new WeatherStation();
         add(new Label("weatherMessage",
             new StringResourceModel("weather.message", this, new Model<WeatherStation>(ws)));
     }
 }
 
Where the resource bundle contains the entry weather.message=Weather station reports that the temperature is ${currentTemperature} ${units}

Example 4

In this example, the use of substitution parameters is employed to format a quite complex message string. This is an example of the most complex and powerful use of the string resource model:

 public class MyPage extends WebPage<Void>
 {
     public MyPage(final PageParameters parameters)
     {
         WeatherStation ws = new WeatherStation();
         IModel<WeatherStation> model = new Model<WeatherStation>(ws);
         add(new Label("weatherMessage",
             new StringResourceModel("weather.detail", this)
                     .setParameters(
                         new Date(),
                         new PropertyModel<?>(model, "currentStatus"),
                         new PropertyModel<?>(model, "currentTemperature"),
                         new PropertyModel<?>(model, "units")
                      )
         }));
     }
 }
 
And where the resource bundle entry is:
 weather.detail=The report for {0,date}, shows the temperature as {2,number,###.##} {3} \
     and the weather to be {1}
 
Author:
Chris Turner
See Also:
  • Constructor Details

    • StringResourceModel

      public StringResourceModel(String resourceKey, Component component, IModel<?> model)
      Creates a new string resource model using the supplied parameters.

      The relative component parameter should generally be supplied, as without it resources can not be obtained from resource bundles that are held relative to a particular component or page. However, for application that use only global resources then this parameter may be null.

      Parameters:
      resourceKey - The resource key for this string resource
      component - The component that the resource is relative to
      model - The model to use for property substitutions
    • StringResourceModel

      public StringResourceModel(String resourceKey, Component component)
      Creates a new string resource model using the supplied parameters.

      The relative component parameter should generally be supplied, as without it resources can not be obtained from resource bundles that are held relative to a particular component or page. However, for application that use only global resources then this parameter may be null.

      Parameters:
      resourceKey - The resource key for this string resource
      component - The component that the resource is relative to
    • StringResourceModel

      public StringResourceModel(String resourceKey, IModel<?> model)
      Creates a new string resource model using the supplied parameter.
      Parameters:
      resourceKey - The resource key for this string resource
      model - The model to use for property substitutions
    • StringResourceModel

      public StringResourceModel(String resourceKey)
      Creates a new string resource model using the supplied parameter.
      Parameters:
      resourceKey - The resource key for this string resource
  • Method Details

    • wrapOnAssignment

      Description copied from interface: IComponentAssignedModel
      This method is called when the component gets its model assigned. WARNING: Because the model can be assigned in the constructor of component this method can also be called with a 'this' of a component that is not fully constructed yet.
      Specified by:
      wrapOnAssignment in interface IComponentAssignedModel<String>
      Returns:
      The WrapModel that wraps this model
    • setDefaultValue

      Sets the default value if the resource key is not found.
      Parameters:
      defaultValue - The default value if the resource key is not found.
      Returns:
      this for chaining
    • setDefaultValue

      Sets the default value if the resource key is not found.
      Parameters:
      defaultValue - The default value as string if the resource key is not found.
      Returns:
      this for chaining
    • setModel

      public StringResourceModel setModel(IModel<?> model)
      Sets the model used for property substitutions.
      Parameters:
      model - The model to use for property substitutions
      Returns:
      this for chaining
    • setParameters

      public StringResourceModel setParameters(Object... parameters)
      Sets the parameters used for substitution.
      Parameters:
      parameters - The parameters to substitute using a Java MessageFormat object
      Returns:
      this for chaining
    • getLocalizer

      Gets the localizer that is being used by this string resource model.
      Returns:
      The localizer
    • getString

      public final String getString()
      Gets the string currently represented by this model. The string that is returned may vary for each call to this method depending on the values contained in the model and an the parameters that were passed when this string resource model was created.
      Returns:
      The string
    • getString

      protected String getString(Component component)
    • getLocale

      protected Locale getLocale()
      Returns:
      The locale to use when formatting the resource value
    • toString

      public String toString()
      This method just returns debug information, so it won't return the localized string. Please use getString() for that.
      Overrides:
      toString in class LoadableDetachableModel<String>
      Returns:
      The string for this model object
    • getParameters

      protected Object[] getParameters()
      Gets the Java MessageFormat substitution parameters.
      Returns:
      The substitution parameters
    • getResourceKey

      protected final String getResourceKey()
      Gets the resource key for this string resource. If the resource key contains property expressions and the model is not null then the returned value is the actual resource key with all substitutions undertaken.
      Returns:
      The (possibly substituted) resource key
    • load

      protected final String load()
      Gets the string that this string resource model currently represents.

      Note: This method is used only if this model is used directly without assignment to a component, it is not called by the assignment wrapper returned from wrapOnAssignment(Component).

      Specified by:
      load in class LoadableDetachableModel<String>
      Returns:
      the (temporary) model object
    • detach

      public final void detach()
      Description copied from interface: IDetachable
      Detaches model after use. This is generally used to null out transient references that can be re-attached later.
      Specified by:
      detach in interface IDetachable
      Specified by:
      detach in interface IModel<String>
      Overrides:
      detach in class LoadableDetachableModel<String>
    • setObject

      public void setObject(String object)
      Description copied from class: LoadableDetachableModel
      Manually loads the model with the specified object. Subsequent calls to LoadableDetachableModel.getObject() will return object until LoadableDetachableModel.detach() is called.
      Specified by:
      setObject in interface IModel<String>
      Overrides:
      setObject in class LoadableDetachableModel<String>
      Parameters:
      object - The object to set into the model