Consolidating some to String methods in RocketScieence
[sw/motorsim] / src / com / billkuker / rocketry / motorsim / QuantityChecking.aj
1 package com.billkuker.rocketry.motorsim;
2
3 import java.beans.BeanInfo;
4 import java.beans.Introspector;
5 import java.beans.PropertyDescriptor;
6 import java.lang.reflect.Field;
7 import java.lang.reflect.ParameterizedType;
8 import java.lang.reflect.Type;
9
10 import javax.measure.unit.Unit;
11
12 import org.apache.log4j.Logger;
13 import org.jscience.physics.amount.Amount;
14
15 public aspect QuantityChecking {
16
17         private static Logger log = Logger.getLogger(QuantityChecking.class);
18         public interface Checked {
19         };
20
21         declare parents: Motor || Grain || Chamber || Nozzle || Fuel extends Checked;
22
23         @SuppressWarnings("unchecked")
24         void around(Checked c, Amount amt):
25                 execution(void Checked+.set*(Amount)) && target(c) && args(amt) {
26                 try {
27                         BeanInfo b = Introspector.getBeanInfo(c.getClass());
28                         PropertyDescriptor ps[] = b.getPropertyDescriptors();
29                         String name = thisJoinPointStaticPart.getSignature().getName();
30                         name = name.replaceFirst("set", "");
31                         for (int i = 0; i < ps.length; i++) {
32                                 if (ps[i].getName().equals(name)) {
33                                         Type t = ps[i].getReadMethod().getGenericReturnType();
34                                         ParameterizedType p = (ParameterizedType) t;
35                                         Class expected = (Class) p.getActualTypeArguments()[0];
36                                         Field f = expected.getDeclaredField("UNIT");
37                                         Unit u = (Unit) f.get(null);
38
39                                         Amount a = amt;
40                                         if (!a.getUnit().isCompatible(u)) {
41                                                 log.warn("Aspect Expected " + expected
42                                                                 + " got " + u);
43
44                                                 throw new Error(ps[i].getShortDescription()
45                                                                 + " must be in units of "
46                                                                 + expected.getSimpleName());
47                                         }
48                                 }
49                         }
50                 } catch (Exception e) {
51                         e.printStackTrace();
52                 }
53                 proceed(c, amt);
54         }
55 }