equals and hashcode for robust identifiable.
[xmlrouter] / impl / src / main / java / org / wamblee / xmlrouter / impl / RobustIdentifiable.java
1 /*
2  * Copyright 2005-2011 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.xmlrouter.impl;
17
18 import static org.wamblee.xmlrouter.impl.MessageUtil.*;
19
20 import java.util.logging.Level;
21 import java.util.logging.Logger;
22
23 import org.wamblee.xmlrouter.common.Id;
24 import org.wamblee.xmlrouter.config.ConfigException;
25 import org.wamblee.xmlrouter.config.Identifiable;
26
27 /**
28  * Robust identifiable provides robustness for identifiable objects. It adds
29  * equality based on the id.
30  * 
31  * @author Erik Brakkee
32  * 
33  * @param <T>
34  */
35 public class RobustIdentifiable<T> implements Identifiable<T> {
36     private static final Logger LOGGER = Logger
37         .getLogger(RobustIdentifiable.class.getName());
38
39     private Id<T> id;
40
41     public RobustIdentifiable(String aPrefix, Identifiable<T> aIdentifiable) {
42         notNull("prefix", aPrefix);
43         notNull("identifiable", aIdentifiable);
44         try {
45             id = aIdentifiable.getId();
46             if (id == null) {
47                 throwConfigException("identifiable.getId() returned null", null);
48             }
49             id = new Id<T>(aPrefix + id.getId());
50         } catch (Exception e) {
51             throwConfigException("identifiable.getId() threw exception", e);
52         }
53
54     }
55
56     private void throwConfigException(String aMsg, Exception aException) {
57         LOGGER.log(Level.WARNING, aMsg, aException);
58         throw new ConfigException("id is null");
59     }
60
61     @Override
62     public Id<T> getId() {
63         return id;
64     }
65
66     // TODO test equals, hashcode.
67
68     @Override
69     public int hashCode() {
70         return id.hashCode();
71     }
72
73     @Override
74     public boolean equals(Object aObj) {
75         if (aObj == null) {
76             return false;
77         }
78         if (!getClass().isInstance(aObj)) {
79             return false;
80         }
81         RobustIdentifiable<T> obj = (RobustIdentifiable<T>) aObj;
82         return id.equals(obj.getId());
83     }
84 }