(no commit message)
[utils] / wicket / components / src / main / java / org / wamblee / wicket / behavior / LocalizedCompositeBehavior.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.wicket.behavior;
17
18 import org.apache.wicket.Component;
19 import org.apache.wicket.behavior.IBehavior;
20 import org.apache.wicket.model.Model;
21 import org.apache.wicket.model.StringResourceModel;
22
23
24 /**
25  * Composite behavior that deals with (optional) localization of 
26  * the behavior. It does this by creating localized behaviors in the bind callback.
27  * This is required because the component is need in order to obtain the resources to use 
28  * for localization. 
29  */
30 public abstract class LocalizedCompositeBehavior extends CompositeBehavior {
31         private boolean localize; 
32         
33         public LocalizedCompositeBehavior(IBehavior[] aBehaviors, boolean aLocalize) {
34                 super(aBehaviors);
35                 localize = aLocalize; 
36         }
37         
38         @Override
39         public void bind(Component aComponent) {
40                 super.bind(aComponent);
41                 for (IBehavior behavior: createLocalizedBehaviors(aComponent) ) { 
42                         behavior.bind(aComponent); 
43                         add(behavior);
44                 }
45         }
46         
47         public boolean isLocalized() {
48                 return localize;
49         }
50         
51         /**
52          * Utility method to obtain a localized message for a given component. 
53          * @param aComponent Component.
54          * @param aMessage Message or message key in case localization is used.
55          * @return Localized message.
56          */
57         protected String getLocalizedMessage(Component aComponent, String aMessage) { 
58                 if ( !localize ) { 
59                         return aMessage;
60                 }
61                 return new StringResourceModel(aMessage, aComponent, new Model(aMessage)).toString();
62         }
63
64         /**
65          * Callback to create further localized components. 
66          * @param aLocalize True iff localization must be used.
67          * @return Array of behaviors. 
68          */
69         protected abstract IBehavior[] createLocalizedBehaviors(Component aComponent);
70 }