1 package se.citerus.dddsample.domain.model.handling;
2
3 import se.citerus.dddsample.domain.model.cargo.Cargo;
4 import se.citerus.dddsample.domain.model.cargo.CargoRepository;
5 import se.citerus.dddsample.domain.model.cargo.TrackingId;
6 import se.citerus.dddsample.domain.model.location.Location;
7 import se.citerus.dddsample.domain.model.location.LocationRepository;
8 import se.citerus.dddsample.domain.model.location.UnLocode;
9 import se.citerus.dddsample.domain.model.voyage.Voyage;
10 import se.citerus.dddsample.domain.model.voyage.VoyageNumber;
11 import se.citerus.dddsample.domain.model.voyage.VoyageRepository;
12
13 import java.util.Date;
14
15
16
17
18 public class HandlingEventFactory {
19
20 private final CargoRepository cargoRepository;
21 private final VoyageRepository voyageRepository;
22 private final LocationRepository locationRepository;
23
24 public HandlingEventFactory(final CargoRepository cargoRepository,
25 final VoyageRepository voyageRepository,
26 final LocationRepository locationRepository) {
27 this.cargoRepository = cargoRepository;
28 this.voyageRepository = voyageRepository;
29 this.locationRepository = locationRepository;
30 }
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public HandlingEvent createHandlingEvent(Date registrationTime, Date completionTime, TrackingId trackingId, VoyageNumber voyageNumber, UnLocode unlocode, HandlingEvent.Type type)
45 throws CannotCreateHandlingEventException {
46 final Cargo cargo = findCargo(trackingId);
47 final Voyage voyage = findVoyage(voyageNumber);
48 final Location location = findLocation(unlocode);
49
50 try {
51 if (voyage == null) {
52 return new HandlingEvent(cargo, completionTime, registrationTime, type, location);
53 } else {
54 return new HandlingEvent(cargo, completionTime, registrationTime, type, location, voyage);
55 }
56 } catch (Exception e) {
57 throw new CannotCreateHandlingEventException(e);
58 }
59 }
60
61 private Cargo findCargo(TrackingId trackingId) throws UnknownCargoException {
62 final Cargo cargo = cargoRepository.find(trackingId);
63 if (cargo == null) throw new UnknownCargoException(trackingId);
64 return cargo;
65 }
66
67 private Voyage findVoyage(VoyageNumber voyageNumber) throws UnknownVoyageException {
68 if (voyageNumber == null) {
69 return null;
70 }
71
72 final Voyage voyage = voyageRepository.find(voyageNumber);
73 if (voyage == null) {
74 throw new UnknownVoyageException(voyageNumber);
75 }
76
77 return voyage;
78 }
79
80 private Location findLocation(final UnLocode unlocode) throws UnknownLocationException {
81 final Location location = locationRepository.find(unlocode);
82 if (location == null) {
83 throw new UnknownLocationException(unlocode);
84 }
85
86 return location;
87 }
88
89 }