View Javadoc

1   package org.kite9.diagram.builders;
2   
3   import java.lang.reflect.Field;
4   import java.lang.reflect.Method;
5   import java.util.HashSet;
6   import java.util.Set;
7   
8   import org.kite9.framework.common.Kite9ProcessingException;
9   
10  /***
11   * Ensures that IDs for elements are unique within the diagram.
12   * 
13   * @author robmoffat
14   * 
15   */
16  public class IdHelper {
17  
18  	Set<String> used = new HashSet<String>();
19  
20  	public synchronized String getId(Object o) {
21  		if (o instanceof Class<?>) {
22  			return getProjectClassId((Class<?>) o);
23  		} else if (o instanceof String) {
24  			return getDiagramEntityId((String) o);
25  		} else if (o instanceof Method) {
26  			return getProjectMethodId((Method) o);
27  		} else if (o instanceof Package) {
28  			return getProjectPackageId((Package) o);
29  		} else if (o instanceof Field) {
30  			return getProjectFieldId((Field) o);
31  		} else if (o instanceof SubjectBinding<?>) {
32  			return getSubjectBindingId((SubjectBinding<?>) o);
33  		} else if (o instanceof Relationship) {
34  		    	return getRelationshipId((Relationship) o);
35  		} else {
36  			throw new Kite9ProcessingException("Could not get id for " + o.getClass().toString());
37  		}
38  	}
39  
40  	private String getSubjectBindingId(SubjectBinding<?> o) {
41  		return getId(o.getSubject())+"/"+getId(o.getRelationship());
42  	}
43  
44  	protected String getRelationshipId(Relationship o) {
45  	    return "rel_"+o.getName();
46  	}
47  	
48  
49  	protected String getProjectMethodId(Method o) {
50  		return getProjectClassId(o.getDeclaringClass()) + "/" + o.getName()+"()";
51  	}
52  	
53  
54  	protected String getProjectFieldId(Field o) {
55  		return getProjectClassId(o.getDeclaringClass()) + "/" + o.getName();
56  	}
57  
58  	protected String getDiagramEntityId(String o) {
59  		int index = 0;
60  		while (used.contains(o + index)) {
61  			index++;
62  		}
63  
64  		used.add(o + index);
65  		return o + index;
66  	}
67  
68  	protected String getProjectClassId(Class<?> o) {
69  		return "project:" + o.getCanonicalName();
70  	}
71  	
72  	protected String getProjectPackageId(Package p) {
73  		return "project:" + p.getName();
74  	}
75  
76  }