1d969222da7dcce8d1f5ba933880e6d58f31307d
[mir.git] / source / mir / entity / adapter / EntityAdapterDefinition.java
1 package mir.entity.adapter;
2
3 import java.util.*;
4 import mir.entity.*;
5 import mir.storage.*;
6
7 public class EntityAdapterDefinition {
8   Map calculatedFields;
9
10   public EntityAdapterDefinition() {
11     calculatedFields = new HashMap();
12   }
13
14   public EntityAdapter makeEntityAdapter(Entity anEntity) {
15     return new EntityAdapter(anEntity, this);
16   }
17
18   public CalculatedField getCalculatedField(String aFieldName) {
19     return (CalculatedField) calculatedFields.get(aFieldName);
20   }
21
22   public boolean hasCalculatedField(String aFieldName) {
23     return calculatedFields.containsKey(aFieldName);
24   }
25
26   public void addCalculatedField(String aFieldName, CalculatedField aField) {
27     calculatedFields.put(aFieldName, aField);
28   }
29
30   public void addDateField(String aDestinationFieldName, String aSourceFieldName) {
31     addCalculatedField(aDestinationFieldName, new DateField(aSourceFieldName));
32   }
33
34   public interface CalculatedField {
35     public Object getValue(EntityAdapter anEntityAdapter);
36   }
37
38   private class DateField implements CalculatedField {
39     private String fieldName;
40
41     public DateField(String aFieldName) {
42       fieldName = aFieldName;
43     }
44
45     public Object getValue(EntityAdapter anEntityAdapter) {
46       Map result = new HashMap();
47       String textValue = anEntityAdapter.getEntity().getValue(fieldName);
48       Calendar calendar = GregorianCalendar.getInstance();
49       int year;
50       int month;
51       int day;
52       Date date;
53
54       if (textValue!=null) {
55         try {
56           year = Integer.parseInt(textValue.substring(0,4));
57           month = Integer.parseInt(textValue.substring(4,6));
58           day = Integer.parseInt(textValue.substring(6,8));
59
60           calendar.set(year, month, day);
61           date = calendar.getTime();
62
63           result.put("date", date);
64           result.put("year", textValue.substring(0,4));
65           result.put("month", textValue.substring(4,6));
66           result.put("day", textValue.substring(6,8));
67         }
68         catch (Throwable t) {
69           result.put("date", null);
70           result.put("year", null);
71           result.put("month", null);
72           result.put("day", null);
73         }
74       }
75
76       return result;
77     }
78   }
79
80   static protected Object getRelation(StorageObject aStorageObject, String aWhereClause, String anOrderByClause, EntityAdapterDefinition aDefinition) {
81     try {
82       return
83           new EntityIteratorAdapter(
84               new EntityBrowser( aStorageObject, aWhereClause, anOrderByClause, -1),
85               aDefinition);
86     }
87     catch (Throwable t) {
88       throw new RuntimeException(t.getMessage());
89     }
90   }
91 }