01 package trail.entity.basic;
02
03 import trail.entity.beans.*;
04 import javax.ejb.*;
05 import javax.persistence.*;
06 import java.sql.Timestamp;
07 import java.util.Collection;
08
09 @Stateless
10 public class EntityCalculator implements Calculator {
11
12 @PersistenceContext // (unitName="cal")
13 protected EntityManager em;
14
15 public void addFund (String name, double growthrate) {
16 Fund fund = new Fund (name, growthrate);
17 em.persist (fund);
18 }
19
20 public void addInvestor (String name, int start, int end) {
21 Investor investor = new Investor (name, start, end);
22 em.persist (investor);
23 }
24
25 public double calculate (int fundId, int investorId, double saving) {
26
27 Investor investor =
28 em.find(Investor.class,
29 Integer.valueOf(investorId));
30 Fund fund =
31 em.find(Fund.class,
32 Integer.valueOf(fundId));
33
34 int start = investor.getStartAge();
35 int end = investor.getEndAge();
36 double growthrate = fund.getGrowthrate();
37
38 double tmp = Math.pow(1. + growthrate / 12., 12. * (end - start) + 1);
39 double result = saving * 12. * (tmp - 1) / growthrate;
40 Timestamp ts = new Timestamp (System.currentTimeMillis());
41
42 TimedRecord rec =
43 new TimedRecord (fund, investor, saving, result, ts);
44 em.persist (rec);
45
46 return result;
47 }
48
49 public Collection<Fund> getFunds () {
50 return em.createQuery("from Fund f").getResultList();
51 }
52 public Collection <Investor> getInvestors () {
53 return em.createQuery("from Investor p").getResultList();
54 }
55 public Collection <TimedRecord> getRecords () {
56 return em.createQuery("from TimedRecord r order by r.ts desc").getResultList();
57 }
58
59 }
|