View Javadoc

1   // Copyright 2008 Thiago H. de Paula Figueiredo
2   //
3   // Licensed under the Apache License, Version 2.0 (the "License");
4   // you may not use this file except in compliance with the License.
5   // You may obtain a copy of the License at
6   //
7   //     http://www.apache.org/licenses/LICENSE-2.0
8   //
9   // Unless required by applicable law or agreed to in writing, software
10  // distributed under the License is distributed on an "AS IS" BASIS,
11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  // See the License for the specific language governing permissions and
13  // limitations under the License.
14  
15  package br.com.arsmachina.tapestrycrud.services.impl;
16  
17  import java.util.Map;
18  
19  
20  import org.apache.tapestry5.ioc.util.StrategyRegistry;
21  
22  import br.com.arsmachina.tapestrycrud.encoder.LabelEncoder;
23  import br.com.arsmachina.tapestrycrud.services.EncoderSource;
24  import br.com.arsmachina.tapestrycrud.services.LabelEncoderSource;
25  
26  /**
27   * {@link LabelEncoderSource} implementation.
28   * 
29   * @author Thiago H. de Paula Figueiredo
30   */
31  public class LabelEncoderSourceImpl implements LabelEncoderSource {
32  	
33  	final private static LabelEncoder<Object> DEFAULT_ENCODER = new ToStringEncoder();
34  
35  	@SuppressWarnings("unchecked")
36  	final private StrategyRegistry<LabelEncoder> registry;
37  
38  	final private EncoderSource encoderSource;
39  
40  	/**
41  	 * Single constructor.
42  	 * 
43  	 * @param registrations
44  	 */
45  	@SuppressWarnings("unchecked")
46  	public LabelEncoderSourceImpl(Map<Class, LabelEncoder> registrations,
47  			EncoderSource encoderSource) {
48  
49  		if (registrations == null) {
50  			throw new IllegalArgumentException("Parameter registrations cannot be null");
51  		}
52  
53  		if (encoderSource == null) {
54  			throw new IllegalArgumentException("Parameter encoderSource cannot be null");
55  		}
56  
57  		registry = StrategyRegistry.newInstance(LabelEncoder.class, registrations, true);
58  
59  		this.encoderSource = encoderSource;
60  
61  	}
62  
63  	/**
64  	 * @see br.com.arsmachina.tapestrycrud.services.LabelEncoderSource#get(java.lang.Class)
65  	 */
66  	@SuppressWarnings("unchecked")
67  	public <T> LabelEncoder<T> get(Class<T> clasz) {
68  
69  		LabelEncoder<T> encoder = registry.get(clasz);
70  
71  		if (encoder == null) {
72  			encoder = encoderSource.get(clasz);
73  		}
74  
75  		if (encoder == null) {
76  			encoder = (LabelEncoder<T>) DEFAULT_ENCODER;
77  		}
78  
79  		return encoder;
80  
81  	}
82  	
83  	final private static class ToStringEncoder implements LabelEncoder<Object> {
84  
85  		public String toLabel(Object object) {
86  			return object.toString();
87  		}
88  		
89  	}
90  
91  }