Przeglądaj źródła

Merge branch 'bump-java-and-spring'

Dan Eidmark 11 lat temu
rodzic
commit
3775b7625e
17 zmienionych plików z 625 dodań i 670 usunięć
  1. 30
    21
      pom.xml
  2. 0
    71
      src/main/java/se/citerus/dddsample/domain/shared/experimental/EntitySupport.java
  3. 23
    16
      src/main/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingController.java
  4. 25
    9
      src/main/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingViewAdapter.java
  5. 63
    73
      src/main/resources/context-interfaces.xml
  6. 1
    5
      src/main/webapp/WEB-INF/tracking-servlet.xml
  7. 1
    1
      src/main/webapp/index.jsp
  8. 0
    62
      src/test/java/se/citerus/dddsample/domain/shared/experimental/EntitySupportTest.java
  9. 0
    78
      src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/AbstractRepositoryTest.java
  10. 178
    118
      src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/CargoRepositoryTest.java
  11. 64
    27
      src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/CarrierMovementRepositoryTest.java
  12. 86
    33
      src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/HandlingEventRepositoryTest.java
  13. 49
    18
      src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/LocationRepositoryTest.java
  14. 12
    19
      src/test/java/se/citerus/dddsample/interfaces/booking/web/CargoAdminControllerTest.java
  15. 31
    29
      src/test/java/se/citerus/dddsample/interfaces/booking/web/ItinerarySelectionCommandTest.java
  16. 61
    89
      src/test/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingControllerTest.java
  17. 1
    1
      src/test/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingViewAdapterTest.java

+ 30
- 21
pom.xml Wyświetl plik

@@ -4,7 +4,7 @@
4 4
   <artifactId>dddsample</artifactId>
5 5
   <packaging>war</packaging>
6 6
   <name>DDDSample</name>
7
-  <version>1.1.1-SNAPSHOT</version>
7
+  <version>2.0-SNAPSHOT</version>
8 8
   <description>This application shows a few key concepts of
9 9
     Domain Driven Design implemented in Enterprise Java.
10 10
   </description>
@@ -65,8 +65,8 @@
65 65
     <url>https://github.com/citerus/dddsample-core</url>
66 66
   </scm>
67 67
   <properties>
68
-    <spring.version>2.5.6</spring.version>
69
-    <cxf.version>2.1.3</cxf.version>
68
+    <spring.version>4.1.4.RELEASE</spring.version>
69
+    <cxf.version>3.0.3</cxf.version>
70 70
   </properties>
71 71
   <build>
72 72
     <plugins>
@@ -74,8 +74,8 @@
74 74
       <plugin>
75 75
         <artifactId>maven-compiler-plugin</artifactId>
76 76
         <configuration>
77
-          <source>1.6</source>
78
-          <target>1.6</target>
77
+          <source>1.8</source>
78
+          <target>1.8</target>
79 79
           <encoding>UTF-8</encoding>
80 80
         </configuration>
81 81
       </plugin>
@@ -127,7 +127,7 @@
127 127
     <dependency>
128 128
       <groupId>junit</groupId>
129 129
       <artifactId>junit</artifactId>
130
-      <version>4.4</version>
130
+      <version>4.12</version>
131 131
       <scope>test</scope>
132 132
     </dependency>
133 133
     <dependency>
@@ -137,19 +137,28 @@
137 137
     </dependency>
138 138
     <dependency>
139 139
       <groupId>org.springframework</groupId>
140
-      <artifactId>spring-web</artifactId>
140
+      <artifactId>spring-tx</artifactId>
141 141
       <version>${spring.version}</version>
142 142
     </dependency>
143 143
     <dependency>
144 144
       <groupId>org.springframework</groupId>
145
-      <artifactId>spring</artifactId>
145
+      <artifactId>spring-jdbc</artifactId>
146
+      <version>${spring.version}</version>
147
+    </dependency>
148
+    <dependency>
149
+      <groupId>org.springframework</groupId>
150
+      <artifactId>spring-jms</artifactId>
151
+      <version>${spring.version}</version>
152
+    </dependency>
153
+    <dependency>
154
+      <groupId>org.springframework</groupId>
155
+      <artifactId>spring-orm</artifactId>
156
+      <version>${spring.version}</version>
157
+    </dependency>
158
+    <dependency>
159
+      <groupId>org.springframework</groupId>
160
+      <artifactId>spring-web</artifactId>
146 161
       <version>${spring.version}</version>
147
-      <exclusions>
148
-        <exclusion>
149
-          <groupId>commons-logging</groupId>
150
-          <artifactId>commons-logging</artifactId>
151
-        </exclusion>
152
-      </exclusions>
153 162
     </dependency>
154 163
     <dependency>
155 164
       <groupId>org.springframework</groupId>
@@ -214,13 +223,13 @@
214 223
       <artifactId>hsqldb</artifactId>
215 224
       <version>1.8.0.7</version>
216 225
     </dependency>
217
-    <dependency>
218
-      <groupId>javax.servlet</groupId>
219
-      <artifactId>servlet-api</artifactId>
220
-      <version>2.5</version>
221
-      <scope>provided</scope>
222
-    </dependency>
223
-    <dependency>
226
+      <dependency>
227
+          <groupId>javax.servlet</groupId>
228
+          <artifactId>javax.servlet-api</artifactId>
229
+          <version>3.1.0</version>
230
+          <scope>provided</scope>
231
+      </dependency>
232
+      <dependency>
224 233
       <groupId>taglibs</groupId>
225 234
       <artifactId>standard</artifactId>
226 235
       <version>1.1.2</version>

+ 0
- 71
src/main/java/se/citerus/dddsample/domain/shared/experimental/EntitySupport.java Wyświetl plik

@@ -1,71 +0,0 @@
1
-package se.citerus.dddsample.domain.shared.experimental;
2
-
3
-import java.lang.reflect.Field;
4
-
5
-/**
6
- * Base class for entities.
7
- *
8
- */
9
-public abstract class EntitySupport<T extends Entity, ID> implements Entity<T, ID> {
10
-
11
-    private static Field identityField;
12
-
13
-    @Override
14
-    public final boolean sameIdentityAs(final T other) {
15
-        return other != null && this.identity().equals(other.identity());
16
-    }
17
-
18
-    @Override
19
-    public final ID identity() {
20
-        if (identityField == null) {
21
-            identityField = identityFieldLazyDetermination(this.getClass());
22
-        }
23
-
24
-        try {
25
-            return (ID) identityField.get(this);
26
-        } catch (IllegalAccessException e) {
27
-            throw new RuntimeException(e);
28
-        }
29
-    }
30
-
31
-    private static Field identityFieldLazyDetermination(final Class cls) {
32
-        Field identityField = null;
33
-
34
-        for (Field field : cls.getDeclaredFields()) {
35
-            if (field.getAnnotation(Identity.class) != null) {
36
-                field.setAccessible(true);
37
-                if (identityField != null) {
38
-                    throw new IllegalStateException("Only one field can be annotated with " + Identity.class);
39
-                } else {
40
-                    identityField = field;
41
-                }
42
-            }
43
-        }
44
-
45
-        if (identityField == null) {
46
-            if (cls == Object.class) {
47
-                throw new IllegalStateException(
48
-                  "This class, or one of its superclasses, " +
49
-                  "must have a unique field annotated with " + Identity.class);
50
-            } else {
51
-                return identityFieldLazyDetermination(cls.getSuperclass());
52
-            }
53
-        }
54
-
55
-        return identityField;
56
-    }
57
-
58
-    @Override
59
-    public final int hashCode() {
60
-        return identity().hashCode();
61
-    }
62
-
63
-    @Override
64
-    public final boolean equals(final Object o) {
65
-        if (this == o) return true;
66
-        if (o == null || getClass() != o.getClass()) return false;
67
-
68
-        return sameIdentityAs((T) o);
69
-    }
70
-
71
-}

+ 23
- 16
src/main/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingController.java Wyświetl plik

@@ -1,9 +1,12 @@
1 1
 package se.citerus.dddsample.interfaces.tracking;
2 2
 
3 3
 import org.springframework.context.MessageSource;
4
+import org.springframework.stereotype.Controller;
4 5
 import org.springframework.validation.BindException;
5
-import org.springframework.web.servlet.ModelAndView;
6
-import org.springframework.web.servlet.mvc.SimpleFormController;
6
+import org.springframework.validation.BindingResult;
7
+import org.springframework.validation.Errors;
8
+import org.springframework.web.bind.WebDataBinder;
9
+import org.springframework.web.bind.annotation.*;
7 10
 import org.springframework.web.servlet.support.RequestContextUtils;
8 11
 import se.citerus.dddsample.domain.model.cargo.Cargo;
9 12
 import se.citerus.dddsample.domain.model.cargo.CargoRepository;
@@ -12,7 +15,6 @@ import se.citerus.dddsample.domain.model.handling.HandlingEvent;
12 15
 import se.citerus.dddsample.domain.model.handling.HandlingEventRepository;
13 16
 
14 17
 import javax.servlet.http.HttpServletRequest;
15
-import javax.servlet.http.HttpServletResponse;
16 18
 import java.util.HashMap;
17 19
 import java.util.List;
18 20
 import java.util.Locale;
@@ -33,35 +35,36 @@ import java.util.Map;
33 35
  * @see se.citerus.dddsample.interfaces.booking.web.CargoAdminController
34 36
  *
35 37
  */
36
-public final class CargoTrackingController extends SimpleFormController {
38
+@Controller
39
+public final class CargoTrackingController {
37 40
 
38 41
   private CargoRepository cargoRepository;
39 42
   private HandlingEventRepository handlingEventRepository;
43
+  private MessageSource messageSource;
40 44
 
41
-  public CargoTrackingController() {
42
-    setCommandClass(TrackCommand.class);
45
+  @RequestMapping(method = RequestMethod.GET)
46
+  public Map<String, CargoTrackingViewAdapter> get(final TrackCommand trackCommand) {
47
+      return new HashMap<>();
43 48
   }
44 49
 
45
-  @Override
46
-  protected ModelAndView onSubmit(final HttpServletRequest request, final HttpServletResponse response,
47
-                                  final Object command, final BindException errors) throws Exception {
50
+  @RequestMapping(method = RequestMethod.POST)
51
+  protected Map<String, CargoTrackingViewAdapter> onSubmit(final HttpServletRequest request,
52
+                                                           final TrackCommand command,
53
+                                                           final BindingResult bindingResult) {
54
+    new TrackCommandValidator().validate(command, bindingResult);
48 55
 
49
-    final TrackCommand trackCommand = (TrackCommand) command;
50
-    final String trackingIdString = trackCommand.getTrackingId();
51
-
52
-    final TrackingId trackingId = new TrackingId(trackingIdString);
56
+    final TrackingId trackingId = new TrackingId(command.getTrackingId());
53 57
     final Cargo cargo = cargoRepository.find(trackingId);
54 58
 
55 59
     final Map<String, CargoTrackingViewAdapter> model = new HashMap<String, CargoTrackingViewAdapter>();
56 60
     if (cargo != null) {
57
-      final MessageSource messageSource = getApplicationContext();
58 61
       final Locale locale = RequestContextUtils.getLocale(request);
59 62
       final List<HandlingEvent> handlingEvents = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
60 63
       model.put("cargo", new CargoTrackingViewAdapter(cargo, messageSource, locale, handlingEvents));
61 64
     } else {
62
-      errors.rejectValue("trackingId", "cargo.unknown_id", new Object[]{trackCommand.getTrackingId()}, "Unknown tracking id");
65
+      bindingResult.rejectValue("trackingId", "cargo.unknown_id", new Object[]{command.getTrackingId()}, "Unknown tracking id");
63 66
     }
64
-    return showForm(request, response, errors, model);
67
+    return model;
65 68
   }
66 69
 
67 70
   public void setCargoRepository(CargoRepository cargoRepository) {
@@ -72,4 +75,8 @@ public final class CargoTrackingController extends SimpleFormController {
72 75
     this.handlingEventRepository = handlingEventRepository;
73 76
   }
74 77
 
78
+  public void setMessageSource(MessageSource messageSource) {
79
+      this.messageSource = messageSource;
80
+  }
81
+
75 82
 }

+ 25
- 9
src/main/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingViewAdapter.java Wyświetl plik

@@ -21,8 +21,9 @@ public final class CargoTrackingViewAdapter {
21 21
   private final Locale locale;
22 22
   private final List<HandlingEventViewAdapter> events;
23 23
   private final String FORMAT = "yyyy-MM-dd hh:mm";
24
+  private final TimeZone timeZone;
24 25
 
25
-  /**
26
+    /**
26 27
    * Constructor.
27 28
    *
28 29
    * @param cargo
@@ -31,15 +32,28 @@ public final class CargoTrackingViewAdapter {
31 32
    * @param handlingEvents
32 33
    */
33 34
   public CargoTrackingViewAdapter(Cargo cargo, MessageSource messageSource, Locale locale, List<HandlingEvent> handlingEvents) {
34
-    this.messageSource = messageSource;
35
-    this.locale = locale;
36
-    this.cargo = cargo;
35
+    this(cargo, messageSource, locale, handlingEvents, TimeZone.getDefault());
36
+  }
37 37
 
38
-    this.events = new ArrayList<HandlingEventViewAdapter>(handlingEvents.size());
39
-    for (HandlingEvent handlingEvent : handlingEvents) {
40
-      events.add(new HandlingEventViewAdapter(handlingEvent));
38
+    /**
39
+     * Constructor.
40
+     *
41
+     * @param cargo
42
+     * @param messageSource
43
+     * @param locale
44
+     * @param handlingEvents
45
+     */
46
+    public CargoTrackingViewAdapter(Cargo cargo, MessageSource messageSource, Locale locale, List<HandlingEvent> handlingEvents, TimeZone tz) {
47
+      this.messageSource = messageSource;
48
+      this.locale = locale;
49
+      this.cargo = cargo;
50
+      this.timeZone = tz;
51
+
52
+      this.events = new ArrayList<HandlingEventViewAdapter>(handlingEvents.size());
53
+        for (HandlingEvent handlingEvent : handlingEvents) {
54
+          events.add(new HandlingEventViewAdapter(handlingEvent));
55
+        }
41 56
     }
42
-  }
43 57
 
44 58
   /**
45 59
    * @param location a location
@@ -165,7 +179,9 @@ public final class CargoTrackingViewAdapter {
165 179
      * @return Time when the event was completed.
166 180
      */
167 181
     public String getTime() {
168
-      return new SimpleDateFormat(FORMAT).format(handlingEvent.completionTime());
182
+      final SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
183
+      sdf.setTimeZone(timeZone);
184
+      return sdf.format(handlingEvent.completionTime());
169 185
     }
170 186
 
171 187
     /**

+ 63
- 73
src/main/resources/context-interfaces.xml Wyświetl plik

@@ -1,104 +1,94 @@
1 1
 <?xml version="1.0"?>
2 2
 
3 3
 <beans xmlns="http://www.springframework.org/schema/beans"
4
+       xmlns:task="http://www.springframework.org/schema/task"
4 5
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
-	     xmlns:jaxws="http://cxf.apache.org/jaxws"
6
+       xmlns:jaxws="http://cxf.apache.org/jaxws"
6 7
        xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
7
-                           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
8
+                           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
9
+                           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
8 10
 
9
-  <import resource="classpath:META-INF/cxf/cxf.xml"/>
10
-  <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
11
-  <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
12
-  <import resource="classpath:META-INF/cxf/cxf-extension-jaxws.xml"/>
11
+    <import resource="classpath:META-INF/cxf/cxf.xml"/>
13 12
 
14 13
 
15
-  <!-- Handling report web service -->
14
+    <!-- Handling report web service -->
16 15
 
16
+    <jaxws:endpoint id="jax-ws.http" implementor="#handlingReportService" address="/RegisterEvent"/>
17 17
 
18
-  <jaxws:endpoint id="jax-ws.http" implementor="#handlingReportService" address="/RegisterEvent"/>
18
+    <bean id="handlingReportService" class="se.citerus.dddsample.interfaces.handling.ws.HandlingReportServiceImpl">
19
+        <property name="applicationEvents" ref="applicationEvents"/>
20
+    </bean>
19 21
 
20
-  <bean id="handlingReportService" class="se.citerus.dddsample.interfaces.handling.ws.HandlingReportServiceImpl">
21
-    <property name="applicationEvents" ref="applicationEvents"/>
22
-  </bean>
23 22
 
23
+    <!-- File upload directory scanner -->
24 24
 
25
-  <!-- File upload directory scanner -->
25
+    <task:scheduled-tasks scheduler="myScheduler">
26
+        <task:scheduled ref="uploadDirectoryScanner" method="run" fixed-delay="5000"/>
27
+    </task:scheduled-tasks>
26 28
 
29
+    <task:scheduler id="myScheduler" pool-size="10"/>
27 30
 
28
-  <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
29
-    <property name="period" value="5000"/>
30
-    <property name="delay" value="5000"/>
31
-    <property name="timerTask" ref="uploadDirectoryScanner"/>
32
-  </bean>
31
+    <bean id="uploadDirectoryScanner" class="se.citerus.dddsample.interfaces.handling.file.UploadDirectoryScanner">
32
+        <property name="uploadDirectory" value="/tmp/upload"/>
33
+        <property name="parseFailureDirectory" value="/tmp/failed"/>
34
+        <property name="applicationEvents" ref="applicationEvents"/>
35
+    </bean>
33 36
 
34
-  <bean id="uploadDirectoryScanner" class="se.citerus.dddsample.interfaces.handling.file.UploadDirectoryScanner">
35
-    <property name="uploadDirectory" value="/tmp/upload"/>
36
-    <property name="parseFailureDirectory" value="/tmp/failed"/>
37
-    <property name="applicationEvents" ref="applicationEvents"/>
38
-  </bean>
37
+    <bean id="handlingReportConsumptionSupport" class="se.citerus.dddsample.interfaces.handling.HandlingReportParser"/>
39 38
 
40
-  <bean id="handlingReportConsumptionSupport" class="se.citerus.dddsample.interfaces.handling.HandlingReportParser"/>
39
+    <!-- RMI exposed booking service facade, which operates in an open Hibernate session -->
41 40
 
42
-  <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
43
-    <property name="scheduledTimerTasks">
44
-      <list>
45
-        <ref bean="scheduledTask"/>
46
-      </list>
47
-    </property>
48
-  </bean>
49 41
 
42
+    <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
43
+        <property name="sessionFactory" ref="sessionFactory"/>
44
+    </bean>
50 45
 
51
-  <!-- RMI exposed booking service facade, which operates in an open Hibernate session -->
46
+    <bean id="bookingServiceFacade" class="org.springframework.aop.framework.ProxyFactoryBean">
47
+        <property name="target" ref="bookingServiceFacadeTarget"/>
48
+        <property name="interceptorNames">
49
+            <list>
50
+                <value>hibernateInterceptor</value>
51
+            </list>
52
+        </property>
53
+    </bean>
52 54
 
55
+    <bean id="bookingServiceFacadeTarget"
56
+          class="se.citerus.dddsample.interfaces.booking.facade.internal.BookingServiceFacadeImpl">
57
+        <property name="bookingService" ref="bookingService"/>
58
+        <property name="cargoRepository" ref="cargoRepository"/>
59
+        <property name="locationRepository" ref="locationRepository"/>
60
+        <property name="voyageRepository" ref="voyageRepository"/>
61
+    </bean>
53 62
 
54
-  <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
55
-    <property name="sessionFactory" ref="sessionFactory"/>
56
-  </bean>
63
+    <bean class="org.springframework.remoting.rmi.RmiServiceExporter">
64
+        <property name="serviceInterface" value="se.citerus.dddsample.interfaces.booking.facade.BookingServiceFacade"/>
65
+        <property name="service" ref="bookingServiceFacade"/>
66
+        <property name="serviceName" value="BookingService"/>
67
+    </bean>
57 68
 
58
-  <bean id="bookingServiceFacade" class="org.springframework.aop.framework.ProxyFactoryBean">
59
-    <property name="target" ref="bookingServiceFacadeTarget"/>
60
-    <property name="interceptorNames">
61
-      <list>
62
-        <value>hibernateInterceptor</value>
63
-      </list>
64
-    </property>
65
-  </bean>
66 69
 
67
-  <bean id="bookingServiceFacadeTarget" class="se.citerus.dddsample.interfaces.booking.facade.internal.BookingServiceFacadeImpl">
68
-    <property name="bookingService" ref="bookingService"/>
69
-    <property name="cargoRepository" ref="cargoRepository"/>
70
-    <property name="locationRepository" ref="locationRepository"/>
71
-    <property name="voyageRepository" ref="voyageRepository"/>
72
-  </bean>
73
-  
74
-  <bean class="org.springframework.remoting.rmi.RmiServiceExporter">
75
-    <property name="serviceInterface" value="se.citerus.dddsample.interfaces.booking.facade.BookingServiceFacade"/>
76
-    <property name="service" ref="bookingServiceFacade"/>
77
-    <property name="serviceName" value="BookingService"/>
78
-  </bean>
70
+    <!-- Tracking web application support -->
79 71
 
80 72
 
81
-  <!-- Tracking web application support -->
73
+    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
74
+        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
75
+        <property name="prefix" value="/WEB-INF/jsp/pub/"/>
76
+        <property name="suffix" value=".jsp"/>
77
+        <property name="requestContextAttribute" value="rc"/>
78
+        <property name="cache" value="false"/>
79
+    </bean>
82 80
 
81
+    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
82
+        <property name="basename" value="messages"/>
83
+    </bean>
83 84
 
84
-  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
85
-    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
86
-    <property name="prefix" value="/WEB-INF/jsp/pub/"/>
87
-    <property name="suffix" value=".jsp"/>
88
-    <property name="requestContextAttribute" value="rc"/>
89
-    <property name="cache" value="false"/>
90
-  </bean>
85
+    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
86
+        <property name="defaultLocale" value="en"/>
87
+    </bean>
91 88
 
92
-  <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
93
-    <property name="basename" value="messages"/>
94
-  </bean>
95
-
96
-  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
97
-    <property name="defaultLocale" value="en"/>
98
-  </bean>
99
-
100
-  <bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
101
-    <property name="sessionFactory" ref="sessionFactory"/>
102
-  </bean>
89
+    <bean id="openSessionInViewInterceptor"
90
+          class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
91
+        <property name="sessionFactory" ref="sessionFactory"/>
92
+    </bean>
103 93
 
104 94
 </beans>

+ 1
- 5
src/main/webapp/WEB-INF/tracking-servlet.xml Wyświetl plik

@@ -12,13 +12,9 @@
12 12
   </bean>
13 13
 
14 14
   <bean name="/track" class="se.citerus.dddsample.interfaces.tracking.CargoTrackingController">
15
-    <property name="sessionForm" value="true"/>
16
-    <property name="commandName" value="trackCommand"/>
17
-    <property name="formView" value="track"/>
18
-    <property name="successView" value="start"/>
19
-    <property name="validator" ref="trackCommandValidator"/>
20 15
     <property name="cargoRepository" ref="cargoRepository"/>
21 16
     <property name="handlingEventRepository" ref="handlingEventRepository"/>
17
+    <property name="messageSource" ref="messageSource"/>
22 18
   </bean>
23 19
 
24 20
   <bean id="trackCommandValidator" class="se.citerus.dddsample.interfaces.tracking.TrackCommandValidator"/>

+ 1
- 1
src/main/webapp/index.jsp Wyświetl plik

@@ -17,7 +17,7 @@
17 17
 <li>Administration of <a href="admin/list">booking and routing</a>.</li>
18 18
 </ul>
19 19
 <p>The Incident Logging application, that is used to register handling events, is a stand-alone application and a separate download.</p>
20
-<p>Please visit the <a href="http://dddsample.sf.net">project website</a> for more information and a screencast demonstration of how the application works.</p>
20
+<p>Please visit the <a href="https://github.com/citerus/dddsample-core/">project website</a> for more information and a screencast demonstration of how the application works.</p>
21 21
 <p><i>This project is a joint effort by Eric Evans' company <a href="http://www.domainlanguage.com" class="externalLink">Domain Language</a>
22 22
  and the Swedish software consulting company <a href="http://www.citerus.se" class="externalLink">Citerus</a>.</i></p>
23 23
 </body>

+ 0
- 62
src/test/java/se/citerus/dddsample/domain/shared/experimental/EntitySupportTest.java Wyświetl plik

@@ -1,62 +0,0 @@
1
-package se.citerus.dddsample.domain.shared.experimental;
2
-
3
-import junit.framework.TestCase;
4
-
5
-public class EntitySupportTest extends TestCase {
6
-
7
-    public void testNoIdentityAnnotationFail() {
8
-        NoAnnotationEntity entity = new NoAnnotationEntity();
9
-
10
-        try {
11
-            entity.identity();
12
-            fail("Entity must have a unique identity");
13
-        } catch (IllegalStateException expected) {
14
-        }
15
-    }
16
-
17
-    public void testTwoIdentityAnnotationsFail() {
18
-        TwoAnnotationsEntity entity = new TwoAnnotationsEntity();
19
-        try {
20
-            entity.identity();
21
-            fail("Entity must have a unique identity");
22
-        } catch (IllegalStateException expected) {
23
-        }
24
-    }
25
-
26
-    public void testOneAnnotationSuccess() {
27
-        OneAnnotationEntity entity = new OneAnnotationEntity("id");
28
-        assertEquals("id", entity.identity());
29
-    }
30
-
31
-    public void testSameIdentityEqualsHashcode() {
32
-        OneAnnotationEntity entity1 = new OneAnnotationEntity("A");
33
-        OneAnnotationEntity entity2 = new OneAnnotationEntity("A");
34
-        OneAnnotationEntity entity3 = new OneAnnotationEntity("B");
35
-
36
-        assertTrue(entity1.sameIdentityAs(entity2));
37
-        assertFalse(entity2.sameIdentityAs(entity3));
38
-
39
-        assertTrue(entity1.equals(entity2));
40
-        assertFalse(entity2.equals(entity3));
41
-
42
-        assertTrue(entity1.hashCode() == entity2.hashCode());
43
-        assertFalse(entity2.hashCode() == entity3.hashCode());
44
-    }
45
-
46
-    class NoAnnotationEntity extends EntitySupport<NoAnnotationEntity, String> {
47
-    }
48
-
49
-    class OneAnnotationEntity extends EntitySupport<OneAnnotationEntity, String> {
50
-        private @Identity String id;
51
-
52
-        OneAnnotationEntity(String id) {
53
-            this.id = id;
54
-        }
55
-    }
56
-
57
-    class TwoAnnotationsEntity extends EntitySupport<TwoAnnotationsEntity, String> {
58
-        private @Identity String id1 = "id1";
59
-        private @Identity String id2 = "id2";
60
-    }
61
-
62
-}

+ 0
- 78
src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/AbstractRepositoryTest.java Wyświetl plik

@@ -1,78 +0,0 @@
1
-package se.citerus.dddsample.infrastructure.persistence.hibernate;
2
-
3
-import org.hibernate.SessionFactory;
4
-import org.hibernate.classic.Session;
5
-import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
6
-import org.springframework.orm.hibernate3.HibernateTransactionManager;
7
-import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
8
-import org.springframework.transaction.support.TransactionTemplate;
9
-import se.citerus.dddsample.application.util.SampleDataGenerator;
10
-import se.citerus.dddsample.domain.model.handling.HandlingEventFactory;
11
-import se.citerus.dddsample.domain.model.handling.HandlingEventRepository;
12
-
13
-import java.lang.reflect.Field;
14
-
15
-public abstract class AbstractRepositoryTest extends AbstractTransactionalDataSourceSpringContextTests {
16
-
17
-  SessionFactory sessionFactory;
18
-  SimpleJdbcTemplate sjt;
19
-  HandlingEventFactory handlingEventFactory;
20
-  HandlingEventRepository handlingEventRepository;
21
-
22
-  public void setHandlingEventFactory(HandlingEventFactory handlingEventFactory) {
23
-    this.handlingEventFactory = handlingEventFactory;
24
-  }
25
-
26
-  public void setHandlingEventRepository(HandlingEventRepository handlingEventRepository) {
27
-    this.handlingEventRepository = handlingEventRepository;
28
-  }
29
-
30
-  protected AbstractRepositoryTest() {
31
-    setAutowireMode(AUTOWIRE_BY_NAME);
32
-    setDependencyCheck(false);
33
-  }
34
-
35
-  public void setSessionFactory(SessionFactory sessionFactory) {
36
-    this.sessionFactory = sessionFactory;
37
-    transactionManager = new HibernateTransactionManager(sessionFactory);
38
-  }
39
-
40
-  public SessionFactory getSessionFactory() {
41
-    return sessionFactory;
42
-  }
43
-
44
-  protected void flush() {
45
-    sessionFactory.getCurrentSession().flush();
46
-  }
47
-
48
-  @Override
49
-  protected String[] getConfigLocations() {
50
-    return new String[] {"/context-infrastructure-persistence.xml", "context-domain.xml"};
51
-  }
52
-
53
-  @Override
54
-  protected void onSetUpInTransaction() throws Exception {
55
-    // TODO store Sample* and object instances here instead of handwritten SQL
56
-    SampleDataGenerator.loadSampleData(jdbcTemplate, new TransactionTemplate(transactionManager));
57
-    sjt = new SimpleJdbcTemplate(jdbcTemplate);
58
-  }
59
-
60
-  protected Session getSession() {
61
-    return sessionFactory.getCurrentSession();
62
-  }
63
-
64
-  // Instead of exposing a getId() on persistent classes
65
-  protected Long getLongId(Object o) {
66
-    if (getSession().contains(o)) {
67
-      return (Long) getSession().getIdentifier(o);
68
-    } else {
69
-      try {
70
-        Field id = o.getClass().getDeclaredField("id");
71
-        id.setAccessible(true);
72
-        return (Long) id.get(o);
73
-      } catch (Exception e) {
74
-        throw new RuntimeException(e);
75
-      }
76
-    }
77
-  }
78
-}

+ 178
- 118
src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/CargoRepositoryTest.java Wyświetl plik

@@ -1,171 +1,231 @@
1 1
 package se.citerus.dddsample.infrastructure.persistence.hibernate;
2 2
 
3
+import org.hibernate.SessionFactory;
4
+import org.hibernate.classic.Session;
5
+import org.junit.Before;
6
+import org.junit.Test;
7
+import org.junit.runner.RunWith;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.jdbc.core.JdbcTemplate;
10
+import org.springframework.orm.hibernate3.HibernateTransactionManager;
11
+import org.springframework.test.context.ContextConfiguration;
12
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13
+import org.springframework.test.context.transaction.TransactionConfiguration;
14
+import org.springframework.transaction.annotation.Transactional;
15
+import org.springframework.transaction.support.TransactionTemplate;
3 16
 import se.citerus.dddsample.application.util.SampleDataGenerator;
4 17
 import se.citerus.dddsample.domain.model.cargo.*;
5 18
 import se.citerus.dddsample.domain.model.handling.HandlingEvent;
6
-import static se.citerus.dddsample.domain.model.handling.HandlingEvent.Type.LOAD;
7
-import static se.citerus.dddsample.domain.model.handling.HandlingEvent.Type.RECEIVE;
19
+import se.citerus.dddsample.domain.model.handling.HandlingEventRepository;
8 20
 import se.citerus.dddsample.domain.model.location.Location;
9 21
 import se.citerus.dddsample.domain.model.location.LocationRepository;
10
-import static se.citerus.dddsample.domain.model.location.SampleLocations.*;
11 22
 import se.citerus.dddsample.domain.model.location.UnLocode;
12
-import static se.citerus.dddsample.domain.model.voyage.SampleVoyages.CM004;
13 23
 import se.citerus.dddsample.domain.model.voyage.Voyage;
14 24
 import se.citerus.dddsample.domain.model.voyage.VoyageNumber;
15 25
 import se.citerus.dddsample.domain.model.voyage.VoyageRepository;
26
+import static se.citerus.dddsample.domain.model.location.SampleLocations.*;
27
+import static se.citerus.dddsample.domain.model.voyage.SampleVoyages.*;
28
+import static se.citerus.dddsample.domain.model.handling.HandlingEvent.Type.*;
16 29
 
30
+import javax.sql.DataSource;
31
+
32
+import java.lang.reflect.Field;
17 33
 import java.util.Arrays;
18 34
 import java.util.Date;
19 35
 import java.util.List;
20 36
 import java.util.Map;
21 37
 
22
-public class CargoRepositoryTest extends AbstractRepositoryTest {
23
-
24
-  CargoRepository cargoRepository;
25
-  LocationRepository locationRepository;
26
-  VoyageRepository voyageRepository;
27
-
28
-  public void setCargoRepository(CargoRepository cargoRepository) {
29
-    this.cargoRepository = cargoRepository;
30
-  }
31
-
32
-  public void setLocationRepository(LocationRepository locationRepository) {
33
-    this.locationRepository = locationRepository;
34
-  }
35
-
36
-  public void setVoyageRepository(VoyageRepository voyageRepository) {
37
-    this.voyageRepository = voyageRepository;
38
-  }
38
+import static org.junit.Assert.*;
39 39
 
40
-  public void testFindByCargoId() {
41
-    final TrackingId trackingId = new TrackingId("FGH");
42
-    final Cargo cargo = cargoRepository.find(trackingId);
43
-    assertEquals(STOCKHOLM, cargo.origin());
44
-    assertEquals(HONGKONG, cargo.routeSpecification().origin());
45
-    assertEquals(HELSINKI, cargo.routeSpecification().destination());
40
+@RunWith(SpringJUnit4ClassRunner.class)
41
+@ContextConfiguration(value = {"/context-infrastructure-persistence.xml", "/context-domain.xml"})
42
+@TransactionConfiguration(transactionManager = "transactionManager")
43
+@Transactional
44
+public class CargoRepositoryTest {
46 45
 
47
-    assertNotNull(cargo.delivery());
46
+    @Autowired
47
+    CargoRepository cargoRepository;
48 48
 
49
-    final List<HandlingEvent> events = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
50
-    assertEquals(2, events.size());
49
+    @Autowired
50
+    LocationRepository locationRepository;
51 51
 
52
-    HandlingEvent firstEvent = events.get(0);
53
-    assertHandlingEvent(cargo, firstEvent, RECEIVE, HONGKONG, 100, 160, Voyage.NONE);
52
+    @Autowired
53
+    VoyageRepository voyageRepository;
54 54
 
55
-    HandlingEvent secondEvent = events.get(1);
55
+    @Autowired
56
+    HandlingEventRepository handlingEventRepository;
56 57
 
57
-    Voyage hongkongMelbourneTokyoAndBack = new Voyage.Builder(
58
-      new VoyageNumber("0303"), HONGKONG).
59
-      addMovement(MELBOURNE, new Date(), new Date()).
60
-      addMovement(TOKYO, new Date(), new Date()).
61
-      addMovement(HONGKONG, new Date(), new Date()).
62
-      build();
63
-    
64
-    assertHandlingEvent(cargo, secondEvent, LOAD, HONGKONG, 150, 110, hongkongMelbourneTokyoAndBack);
58
+    @Autowired
59
+    SessionFactory sessionFactory;
65 60
 
66
-    List<Leg> legs = cargo.itinerary().legs();
67
-    assertEquals(3, legs.size());
61
+    @Autowired
62
+    private DataSource dataSource;
68 63
 
69
-    Leg firstLeg = legs.get(0);
70
-    assertLeg(firstLeg, "0101", HONGKONG, MELBOURNE);
64
+    @Autowired
65
+    private HibernateTransactionManager transactionManager;
71 66
 
72
-    Leg secondLeg = legs.get(1);
73
-    assertLeg(secondLeg, "0101", MELBOURNE, STOCKHOLM);
67
+    private JdbcTemplate jdbcTemplate;
74 68
 
75
-    Leg thirdLeg = legs.get(2);
76
-    assertLeg(thirdLeg, "0101", STOCKHOLM, HELSINKI);
77
-  }
69
+    @Before
70
+    public void setup() {
71
+        jdbcTemplate = new JdbcTemplate(dataSource);
72
+        SampleDataGenerator.loadSampleData(jdbcTemplate, new TransactionTemplate(transactionManager));
73
+    }
78 74
 
79
-  private void assertHandlingEvent(Cargo cargo, HandlingEvent event, HandlingEvent.Type expectedEventType, Location expectedLocation, int completionTimeMs, int registrationTimeMs, Voyage voyage) {
80
-    assertEquals(expectedEventType, event.type());
81
-    assertEquals(expectedLocation, event.location());
75
+    @Test
76
+    public void testFindByCargoId() {
77
+        final TrackingId trackingId = new TrackingId("FGH");
78
+        final Cargo cargo = cargoRepository.find(trackingId);
79
+        assertEquals(STOCKHOLM, cargo.origin());
80
+        assertEquals(HONGKONG, cargo.routeSpecification().origin());
81
+        assertEquals(HELSINKI, cargo.routeSpecification().destination());
82 82
 
83
-    Date expectedCompletionTime = SampleDataGenerator.offset(completionTimeMs);
84
-    assertEquals(expectedCompletionTime, event.completionTime());
83
+        assertNotNull(cargo.delivery());
85 84
 
86
-    Date expectedRegistrationTime = SampleDataGenerator.offset(registrationTimeMs);
87
-    assertEquals(expectedRegistrationTime, event.registrationTime());
85
+        final List<HandlingEvent> events = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
86
+        assertEquals(2, events.size());
88 87
 
89
-    assertEquals(voyage, event.voyage());
90
-    assertEquals(cargo, event.cargo());
91
-  }
88
+        HandlingEvent firstEvent = events.get(0);
89
+        assertHandlingEvent(cargo, firstEvent, RECEIVE, HONGKONG, 100, 160, Voyage.NONE);
92 90
 
93
-  public void testFindByCargoIdUnknownId() {
94
-    assertNull(cargoRepository.find(new TrackingId("UNKNOWN")));
95
-  }
91
+        HandlingEvent secondEvent = events.get(1);
96 92
 
97
-  private void assertLeg(Leg firstLeg, String vn, Location expectedFrom, Location expectedTo) {
98
-    assertEquals(new VoyageNumber(vn), firstLeg.voyage().voyageNumber());
99
-    assertEquals(expectedFrom, firstLeg.loadLocation());
100
-    assertEquals(expectedTo, firstLeg.unloadLocation());
101
-  }
93
+        Voyage hongkongMelbourneTokyoAndBack = new Voyage.Builder(
94
+                new VoyageNumber("0303"), HONGKONG).
95
+                addMovement(MELBOURNE, new Date(), new Date()).
96
+                addMovement(TOKYO, new Date(), new Date()).
97
+                addMovement(HONGKONG, new Date(), new Date()).
98
+                build();
102 99
 
103
-  public void testSave() {
104
-    TrackingId trackingId = new TrackingId("AAA");
105
-    Location origin = locationRepository.find(STOCKHOLM.unLocode());
106
-    Location destination = locationRepository.find(MELBOURNE.unLocode());
100
+        assertHandlingEvent(cargo, secondEvent, LOAD, HONGKONG, 150, 110, hongkongMelbourneTokyoAndBack);
107 101
 
108
-    Cargo cargo = new Cargo(trackingId, new RouteSpecification(origin, destination, new Date()));
109
-    cargoRepository.store(cargo);
102
+        List<Leg> legs = cargo.itinerary().legs();
103
+        assertEquals(3, legs.size());
110 104
 
111
-    cargo.assignToRoute(new Itinerary(Arrays.asList(
112
-      new Leg(
113
-        voyageRepository.find(new VoyageNumber("0101")),
114
-        locationRepository.find(STOCKHOLM.unLocode()),
115
-        locationRepository.find(MELBOURNE.unLocode()),
116
-        new Date(), new Date())
117
-    )));
118
-    
119
-    flush();
105
+        Leg firstLeg = legs.get(0);
106
+        assertLeg(firstLeg, "0101", HONGKONG, MELBOURNE);
120 107
 
121
-    Map<String, Object> map = sjt.queryForMap(
122
-      "select * from Cargo where tracking_id = ?", trackingId.idString());
108
+        Leg secondLeg = legs.get(1);
109
+        assertLeg(secondLeg, "0101", MELBOURNE, STOCKHOLM);
123 110
 
124
-    assertEquals("AAA", map.get("TRACKING_ID"));
111
+        Leg thirdLeg = legs.get(2);
112
+        assertLeg(thirdLeg, "0101", STOCKHOLM, HELSINKI);
113
+    }
125 114
 
126
-    Long originId = getLongId(origin);
127
-    assertEquals(originId, map.get("SPEC_ORIGIN_ID"));
115
+    private void assertHandlingEvent(Cargo cargo, HandlingEvent event, HandlingEvent.Type expectedEventType, Location expectedLocation, int completionTimeMs, int registrationTimeMs, Voyage voyage) {
116
+        assertEquals(expectedEventType, event.type());
117
+        assertEquals(expectedLocation, event.location());
128 118
 
129
-    Long destinationId = getLongId(destination);
130
-    assertEquals(destinationId, map.get("SPEC_DESTINATION_ID"));
119
+        Date expectedCompletionTime = SampleDataGenerator.offset(completionTimeMs);
120
+        assertEquals(expectedCompletionTime, event.completionTime());
131 121
 
132
-    getSession().clear();
122
+        Date expectedRegistrationTime = SampleDataGenerator.offset(registrationTimeMs);
123
+        assertEquals(expectedRegistrationTime, event.registrationTime());
133 124
 
134
-    final Cargo loadedCargo = cargoRepository.find(trackingId);
135
-    assertEquals(1, loadedCargo.itinerary().legs().size());
136
-  }
125
+        assertEquals(voyage, event.voyage());
126
+        assertEquals(cargo, event.cargo());
127
+    }
137 128
 
138
-  public void testReplaceItinerary() {
139
-    Cargo cargo = cargoRepository.find(new TrackingId("FGH"));
140
-    Long cargoId = getLongId(cargo);
141
-    assertEquals(3, sjt.queryForInt("select count(*) from Leg where cargo_id = ?", cargoId));
129
+    @Test
130
+    public void testFindByCargoIdUnknownId() {
131
+        assertNull(cargoRepository.find(new TrackingId("UNKNOWN")));
132
+    }
142 133
 
143
-    Location legFrom = locationRepository.find(new UnLocode("FIHEL"));
144
-    Location legTo = locationRepository.find(new UnLocode("DEHAM"));
145
-    Itinerary newItinerary = new Itinerary(Arrays.asList(new Leg(CM004, legFrom, legTo, new Date(), new Date())));
134
+    private void assertLeg(Leg firstLeg, String vn, Location expectedFrom, Location expectedTo) {
135
+        assertEquals(new VoyageNumber(vn), firstLeg.voyage().voyageNumber());
136
+        assertEquals(expectedFrom, firstLeg.loadLocation());
137
+        assertEquals(expectedTo, firstLeg.unloadLocation());
138
+    }
146 139
 
147
-    cargo.assignToRoute(newItinerary);
140
+    @Test
141
+    public void testSave() {
142
+        TrackingId trackingId = new TrackingId("AAA");
143
+        Location origin = locationRepository.find(STOCKHOLM.unLocode());
144
+        Location destination = locationRepository.find(MELBOURNE.unLocode());
148 145
 
149
-    cargoRepository.store(cargo);
150
-    flush();
146
+        Cargo cargo = new Cargo(trackingId, new RouteSpecification(origin, destination, new Date()));
147
+        cargoRepository.store(cargo);
151 148
 
152
-    assertEquals(1, sjt.queryForInt("select count(*) from Leg where cargo_id = ?", cargoId));
153
-  }
149
+        cargo.assignToRoute(new Itinerary(Arrays.asList(
150
+                new Leg(
151
+                        voyageRepository.find(new VoyageNumber("0101")),
152
+                        locationRepository.find(STOCKHOLM.unLocode()),
153
+                        locationRepository.find(MELBOURNE.unLocode()),
154
+                        new Date(), new Date())
155
+        )));
154 156
 
157
+        flush();
158
+
159
+        Map<String, Object> map = jdbcTemplate.queryForMap(
160
+                "select * from Cargo where tracking_id = ?", trackingId.idString());
161
+
162
+        assertEquals("AAA", map.get("TRACKING_ID"));
155 163
 
156
-  public void testFindAll() {
157
-    List<Cargo> all = cargoRepository.findAll();
158
-    assertNotNull(all);
159
-    assertEquals(6, all.size());
160
-  }
164
+        Long originId = getLongId(origin);
165
+        assertEquals(originId, map.get("SPEC_ORIGIN_ID"));
166
+
167
+        Long destinationId = getLongId(destination);
168
+        assertEquals(destinationId, map.get("SPEC_DESTINATION_ID"));
169
+
170
+        sessionFactory.getCurrentSession().clear();
171
+
172
+        final Cargo loadedCargo = cargoRepository.find(trackingId);
173
+        assertEquals(1, loadedCargo.itinerary().legs().size());
174
+    }
175
+
176
+    @Test
177
+    public void testReplaceItinerary() {
178
+        Cargo cargo = cargoRepository.find(new TrackingId("FGH"));
179
+        Long cargoId = getLongId(cargo);
180
+        assertEquals(3, jdbcTemplate.queryForInt("select count(*) from Leg where cargo_id = ?", cargoId));
161 181
 
162
-  public void testNextTrackingId() {
163
-    TrackingId trackingId = cargoRepository.nextTrackingId();
164
-    assertNotNull(trackingId);
182
+        Location legFrom = locationRepository.find(new UnLocode("FIHEL"));
183
+        Location legTo = locationRepository.find(new UnLocode("DEHAM"));
184
+        Itinerary newItinerary = new Itinerary(Arrays.asList(new Leg(CM004, legFrom, legTo, new Date(), new Date())));
185
+
186
+        cargo.assignToRoute(newItinerary);
165 187
 
166
-    TrackingId trackingId2 = cargoRepository.nextTrackingId();
167
-    assertNotNull(trackingId2);
168
-    assertFalse(trackingId.equals(trackingId2));
169
-  }
188
+        cargoRepository.store(cargo);
189
+        flush();
190
+
191
+        assertEquals(1, jdbcTemplate.queryForInt("select count(*) from Leg where cargo_id = ?", cargoId));
192
+    }
193
+
194
+    @Test
195
+    public void testFindAll() {
196
+        List<Cargo> all = cargoRepository.findAll();
197
+        assertNotNull(all);
198
+        assertEquals(6, all.size());
199
+    }
200
+
201
+    @Test
202
+    public void testNextTrackingId() {
203
+        TrackingId trackingId = cargoRepository.nextTrackingId();
204
+        assertNotNull(trackingId);
205
+
206
+        TrackingId trackingId2 = cargoRepository.nextTrackingId();
207
+        assertNotNull(trackingId2);
208
+        assertFalse(trackingId.equals(trackingId2));
209
+    }
210
+
211
+
212
+    private void flush() {
213
+        sessionFactory.getCurrentSession().flush();
214
+    }
215
+
216
+    private Long getLongId(Object o) {
217
+        final Session session = sessionFactory.getCurrentSession();
218
+        if (session.contains(o)) {
219
+            return (Long) session.getIdentifier(o);
220
+        } else {
221
+            try {
222
+                Field id = o.getClass().getDeclaredField("id");
223
+                id.setAccessible(true);
224
+                return (Long) id.get(o);
225
+            } catch (Exception e) {
226
+                throw new RuntimeException();
227
+            }
228
+        }
229
+    }
170 230
 
171 231
 }

+ 64
- 27
src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/CarrierMovementRepositoryTest.java Wyświetl plik

@@ -1,27 +1,64 @@
1
-package se.citerus.dddsample.infrastructure.persistence.hibernate;
2
-
3
-import se.citerus.dddsample.domain.model.voyage.Voyage;
4
-import se.citerus.dddsample.domain.model.voyage.VoyageNumber;
5
-import se.citerus.dddsample.domain.model.voyage.VoyageRepository;
6
-
7
-public class CarrierMovementRepositoryTest extends AbstractRepositoryTest {
8
-
9
-  VoyageRepository voyageRepository;
10
-
11
-  public void setVoyageRepository(VoyageRepository voyageRepository) {
12
-    this.voyageRepository = voyageRepository;
13
-  }
14
-
15
-  public void testFind() throws Exception {
16
-    Voyage voyage = voyageRepository.find(new VoyageNumber("0101"));
17
-    assertNotNull(voyage);
18
-    assertEquals("0101", voyage.voyageNumber().idString());
19
-    /* TODO adapt
20
-    assertEquals(STOCKHOLM, carrierMovement.departureLocation());
21
-    assertEquals(HELSINKI, carrierMovement.arrivalLocation());
22
-    assertEquals(DateTestUtil.toDate("2007-09-23", "02:00"), carrierMovement.departureTime());
23
-    assertEquals(DateTestUtil.toDate("2007-09-23", "03:00"), carrierMovement.arrivalTime());
24
-    */
25
-  }
26
-
27
-}
1
+package se.citerus.dddsample.infrastructure.persistence.hibernate;
2
+
3
+import org.hibernate.SessionFactory;
4
+import org.junit.Before;
5
+import org.junit.Test;
6
+import org.junit.runner.RunWith;
7
+import org.springframework.beans.factory.annotation.Autowired;
8
+import org.springframework.jdbc.core.JdbcTemplate;
9
+import org.springframework.orm.hibernate3.HibernateTransactionManager;
10
+import org.springframework.test.context.ContextConfiguration;
11
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12
+import org.springframework.test.context.transaction.TransactionConfiguration;
13
+import org.springframework.transaction.annotation.Transactional;
14
+import org.springframework.transaction.support.TransactionTemplate;
15
+import se.citerus.dddsample.application.util.SampleDataGenerator;
16
+import se.citerus.dddsample.domain.model.voyage.Voyage;
17
+import se.citerus.dddsample.domain.model.voyage.VoyageNumber;
18
+import se.citerus.dddsample.domain.model.voyage.VoyageRepository;
19
+
20
+import javax.sql.DataSource;
21
+
22
+import static org.junit.Assert.assertEquals;
23
+import static org.junit.Assert.assertNotNull;
24
+
25
+@RunWith(SpringJUnit4ClassRunner.class)
26
+@ContextConfiguration(value = {"/context-infrastructure-persistence.xml", "/context-domain.xml"})
27
+@TransactionConfiguration(transactionManager = "transactionManager")
28
+@Transactional
29
+public class CarrierMovementRepositoryTest {
30
+
31
+    @Autowired
32
+    VoyageRepository voyageRepository;
33
+
34
+    @Autowired
35
+    SessionFactory sessionFactory;
36
+
37
+    @Autowired
38
+    private DataSource dataSource;
39
+
40
+    @Autowired
41
+    private HibernateTransactionManager transactionManager;
42
+
43
+    private JdbcTemplate jdbcTemplate;
44
+
45
+    @Before
46
+    public void setup() {
47
+        jdbcTemplate = new JdbcTemplate(dataSource);
48
+        SampleDataGenerator.loadSampleData(jdbcTemplate, new TransactionTemplate(transactionManager));
49
+    }
50
+
51
+    @Test
52
+    public void testFind() throws Exception {
53
+        Voyage voyage = voyageRepository.find(new VoyageNumber("0101"));
54
+        assertNotNull(voyage);
55
+        assertEquals("0101", voyage.voyageNumber().idString());
56
+    /* TODO adapt
57
+    assertEquals(STOCKHOLM, carrierMovement.departureLocation());
58
+    assertEquals(HELSINKI, carrierMovement.arrivalLocation());
59
+    assertEquals(DateTestUtil.toDate("2007-09-23", "02:00"), carrierMovement.departureTime());
60
+    assertEquals(DateTestUtil.toDate("2007-09-23", "03:00"), carrierMovement.arrivalTime());
61
+    */
62
+    }
63
+
64
+}

+ 86
- 33
src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/HandlingEventRepositoryTest.java Wyświetl plik

@@ -1,5 +1,19 @@
1 1
 package se.citerus.dddsample.infrastructure.persistence.hibernate;
2 2
 
3
+import org.hibernate.SessionFactory;
4
+import org.hibernate.classic.Session;
5
+import org.junit.Before;
6
+import org.junit.Test;
7
+import org.junit.runner.RunWith;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.jdbc.core.JdbcTemplate;
10
+import org.springframework.orm.hibernate3.HibernateTransactionManager;
11
+import org.springframework.test.context.ContextConfiguration;
12
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13
+import org.springframework.test.context.transaction.TransactionConfiguration;
14
+import org.springframework.transaction.annotation.Transactional;
15
+import org.springframework.transaction.support.TransactionTemplate;
16
+import se.citerus.dddsample.application.util.SampleDataGenerator;
3 17
 import se.citerus.dddsample.domain.model.cargo.Cargo;
4 18
 import se.citerus.dddsample.domain.model.cargo.CargoRepository;
5 19
 import se.citerus.dddsample.domain.model.cargo.TrackingId;
@@ -9,52 +23,91 @@ import se.citerus.dddsample.domain.model.location.Location;
9 23
 import se.citerus.dddsample.domain.model.location.LocationRepository;
10 24
 import se.citerus.dddsample.domain.model.location.UnLocode;
11 25
 
26
+import javax.sql.DataSource;
27
+import java.lang.reflect.Field;
12 28
 import java.util.Date;
13 29
 import java.util.List;
14 30
 import java.util.Map;
15 31
 
16
-public class HandlingEventRepositoryTest extends AbstractRepositoryTest {
32
+import static org.junit.Assert.assertEquals;
17 33
 
18
-  HandlingEventRepository handlingEventRepository;
19
-  CargoRepository cargoRepository;
20
-  LocationRepository locationRepository;
34
+@RunWith(SpringJUnit4ClassRunner.class)
35
+@ContextConfiguration(value = {"/context-infrastructure-persistence.xml", "/context-domain.xml"})
36
+@TransactionConfiguration(transactionManager = "transactionManager")
37
+@Transactional
38
+public class HandlingEventRepositoryTest {
21 39
 
22
-  public void setHandlingEventRepository(HandlingEventRepository handlingEventRepository) {
23
-    this.handlingEventRepository = handlingEventRepository;
24
-  }
40
+    @Autowired
41
+    HandlingEventRepository handlingEventRepository;
25 42
 
26
-  public void setCargoRepository(CargoRepository cargoRepository) {
27
-    this.cargoRepository = cargoRepository;
28
-  }
43
+    @Autowired
44
+    CargoRepository cargoRepository;
29 45
 
30
-  public void setLocationRepository(LocationRepository locationRepository) {
31
-    this.locationRepository = locationRepository;
32
-  }
46
+    @Autowired
47
+    LocationRepository locationRepository;
33 48
 
34
-  public void testSave() {
35
-    Location location = locationRepository.find(new UnLocode("SESTO"));
49
+    @Autowired
50
+    SessionFactory sessionFactory;
36 51
 
37
-    Cargo cargo = cargoRepository.find(new TrackingId("XYZ"));
38
-    Date completionTime = new Date(10);
39
-    Date registrationTime = new Date(20);
40
-    HandlingEvent event = new HandlingEvent(cargo, completionTime, registrationTime, HandlingEvent.Type.CLAIM, location);
52
+    @Autowired
53
+    private DataSource dataSource;
41 54
 
42
-    handlingEventRepository.store(event);
55
+    @Autowired
56
+    private HibernateTransactionManager transactionManager;
43 57
 
44
-    flush();
58
+    private JdbcTemplate jdbcTemplate;
45 59
 
46
-    Map<String,Object> result = sjt.queryForMap("select * from HandlingEvent where id = ?", getLongId(event));
47
-    assertEquals(1L, result.get("CARGO_ID"));
48
-    assertEquals(new Date(10), result.get("COMPLETIONTIME"));
49
-    assertEquals(new Date(20), result.get("REGISTRATIONTIME"));
50
-    assertEquals("CLAIM", result.get("TYPE"));
51
-    // TODO: the rest of the columns
52
-  }
60
+    @Before
61
+    public void setup() {
62
+        jdbcTemplate = new JdbcTemplate(dataSource);
63
+        SampleDataGenerator.loadSampleData(jdbcTemplate, new TransactionTemplate(transactionManager));
64
+    }
53 65
 
54
-  public void testFindEventsForCargo() throws Exception {
55
-    TrackingId trackingId = new TrackingId("XYZ");
56
-    List<HandlingEvent> handlingEvents = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
57
-    assertEquals(12, handlingEvents.size());
58
-  }
66
+    @Test
67
+    public void testSave() {
68
+        Location location = locationRepository.find(new UnLocode("SESTO"));
69
+
70
+        Cargo cargo = cargoRepository.find(new TrackingId("XYZ"));
71
+        Date completionTime = new Date(10);
72
+        Date registrationTime = new Date(20);
73
+        HandlingEvent event = new HandlingEvent(cargo, completionTime, registrationTime, HandlingEvent.Type.CLAIM, location);
74
+
75
+        handlingEventRepository.store(event);
76
+
77
+        flush();
78
+
79
+        Map<String, Object> result = jdbcTemplate.queryForMap("select * from HandlingEvent where id = ?", getLongId(event));
80
+        assertEquals(1L, result.get("CARGO_ID"));
81
+        assertEquals(new Date(10), result.get("COMPLETIONTIME"));
82
+        assertEquals(new Date(20), result.get("REGISTRATIONTIME"));
83
+        assertEquals("CLAIM", result.get("TYPE"));
84
+        // TODO: the rest of the columns
85
+    }
86
+
87
+    private void flush() {
88
+        sessionFactory.getCurrentSession().flush();
89
+    }
90
+
91
+    private Long getLongId(Object o) {
92
+        final Session session = sessionFactory.getCurrentSession();
93
+        if (session.contains(o)) {
94
+            return (Long) session.getIdentifier(o);
95
+        } else {
96
+            try {
97
+                Field id = o.getClass().getDeclaredField("id");
98
+                id.setAccessible(true);
99
+                return (Long) id.get(o);
100
+            } catch (Exception e) {
101
+                throw new RuntimeException();
102
+            }
103
+        }
104
+    }
105
+
106
+    @Test
107
+    public void testFindEventsForCargo() throws Exception {
108
+        TrackingId trackingId = new TrackingId("XYZ");
109
+        List<HandlingEvent> handlingEvents = handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId).distinctEventsByCompletionTime();
110
+        assertEquals(12, handlingEvents.size());
111
+    }
59 112
 
60 113
 }

+ 49
- 18
src/test/java/se/citerus/dddsample/infrastructure/persistence/hibernate/LocationRepositoryTest.java Wyświetl plik

@@ -1,31 +1,62 @@
1 1
 package se.citerus.dddsample.infrastructure.persistence.hibernate;
2 2
 
3
+import org.junit.Before;
4
+import org.junit.Test;
5
+import org.junit.runner.RunWith;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.jdbc.core.JdbcTemplate;
8
+import org.springframework.orm.hibernate3.HibernateTransactionManager;
9
+import org.springframework.test.context.ContextConfiguration;
10
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
11
+import org.springframework.test.context.transaction.TransactionConfiguration;
12
+import org.springframework.transaction.annotation.Transactional;
13
+import org.springframework.transaction.support.TransactionTemplate;
14
+import se.citerus.dddsample.application.util.SampleDataGenerator;
3 15
 import se.citerus.dddsample.domain.model.location.Location;
4 16
 import se.citerus.dddsample.domain.model.location.LocationRepository;
5 17
 import se.citerus.dddsample.domain.model.location.UnLocode;
6 18
 
19
+import javax.sql.DataSource;
7 20
 import java.util.List;
8 21
 
9
-public class LocationRepositoryTest extends AbstractRepositoryTest {
10
-  private LocationRepository locationRepository;
11
-  
12
-  public void testFind() throws Exception {
13
-    final UnLocode melbourne = new UnLocode("AUMEL");
14
-    Location location = locationRepository.find(melbourne);
15
-    assertNotNull(location);
16
-    assertEquals(melbourne, location.unLocode());
22
+import static org.junit.Assert.*;
17 23
 
18
-    assertNull(locationRepository.find(new UnLocode("NOLOC")));
19
-  }
24
+@RunWith(SpringJUnit4ClassRunner.class)
25
+@ContextConfiguration(value = {"/context-infrastructure-persistence.xml", "/context-domain.xml"})
26
+@TransactionConfiguration(transactionManager = "transactionManager")
27
+@Transactional
28
+public class LocationRepositoryTest {
29
+    @Autowired
30
+    private LocationRepository locationRepository;
20 31
 
21
-  public void testFindAll() throws Exception {
22
-    List<Location> allLocations = locationRepository.findAll();
32
+    @Autowired
33
+    private DataSource dataSource;
23 34
 
24
-    assertNotNull(allLocations);
25
-    assertEquals(7, allLocations.size());
26
-  }
35
+    @Autowired
36
+    private HibernateTransactionManager transactionManager;
37
+
38
+    @Before
39
+    public void setup() {
40
+        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
41
+        SampleDataGenerator.loadSampleData(jdbcTemplate, new TransactionTemplate(transactionManager));
42
+    }
43
+
44
+    @Test
45
+    public void testFind() throws Exception {
46
+        final UnLocode melbourne = new UnLocode("AUMEL");
47
+        Location location = locationRepository.find(melbourne);
48
+        assertNotNull(location);
49
+        assertEquals(melbourne, location.unLocode());
50
+
51
+        assertNull(locationRepository.find(new UnLocode("NOLOC")));
52
+    }
53
+
54
+    @Test
55
+    public void testFindAll() throws Exception {
56
+        List<Location> allLocations = locationRepository.findAll();
57
+
58
+        assertNotNull(allLocations);
59
+        assertEquals(7, allLocations.size());
60
+    }
27 61
 
28
-  public void setLocationRepository(LocationRepository locationRepository) {
29
-    this.locationRepository = locationRepository;
30
-  }
31 62
 }

+ 12
- 19
src/test/java/se/citerus/dddsample/interfaces/booking/web/CargoAdminControllerTest.java Wyświetl plik

@@ -1,29 +1,22 @@
1 1
 package se.citerus.dddsample.interfaces.booking.web;
2 2
 
3
-import junit.framework.TestCase;
4 3
 import org.easymock.EasyMock;
4
+import org.junit.Test;
5 5
 import org.springframework.mock.web.MockHttpServletRequest;
6 6
 import org.springframework.mock.web.MockHttpServletResponse;
7 7
 import se.citerus.dddsample.interfaces.booking.facade.BookingServiceFacade;
8 8
 
9
-public class CargoAdminControllerTest extends TestCase {
9
+public class CargoAdminControllerTest {
10 10
 
11
-  CargoAdminController controller;
12
-  BookingServiceFacade bookingServiceFacade;
13
-  MockHttpServletRequest request;
14
-  MockHttpServletResponse response;
11
+    @Test
12
+    public void testAssignItinerary() throws Exception {
13
+        CargoAdminController cargoAdminController = new CargoAdminController();
14
+        BookingServiceFacade bookingServiceFacade = EasyMock.createMock(BookingServiceFacade.class);
15
+        cargoAdminController.setBookingServiceFacade(bookingServiceFacade);
15 16
 
16
-  public CargoAdminControllerTest() {
17
-    controller = new CargoAdminController();
18
-    bookingServiceFacade = EasyMock.createMock(BookingServiceFacade.class);
19
-    controller.setBookingServiceFacade(bookingServiceFacade);
20
-  }
17
+        MockHttpServletRequest request = new MockHttpServletRequest("GET", "assignItinerary.html");
18
+        MockHttpServletResponse response = new MockHttpServletResponse();
21 19
 
22
-  public void testAssignItinerary() throws Exception {
23
-    request = new MockHttpServletRequest("GET","assignItinerary.html");
24
-    response = new MockHttpServletResponse();
25
-
26
-    controller.handleRequest(request, response);
27
-  }
28
-
29
-}
20
+        cargoAdminController.handleRequest(request, response);
21
+    }
22
+}

+ 31
- 29
src/test/java/se/citerus/dddsample/interfaces/booking/web/ItinerarySelectionCommandTest.java Wyświetl plik

@@ -1,48 +1,50 @@
1 1
 package se.citerus.dddsample.interfaces.booking.web;
2 2
 
3 3
 import junit.framework.TestCase;
4
+import org.junit.Test;
4 5
 import org.springframework.mock.web.MockHttpServletRequest;
5 6
 import org.springframework.web.bind.ServletRequestDataBinder;
6 7
 
7 8
 import java.util.List;
8 9
 
9
-public class ItinerarySelectionCommandTest extends TestCase {
10
+import static org.junit.Assert.assertEquals;
10 11
 
11
-  RouteAssignmentCommand command;
12
-  MockHttpServletRequest request;
12
+public class ItinerarySelectionCommandTest {
13 13
 
14
-  public void testBind() {
15
-    command = new RouteAssignmentCommand();
16
-    request = new MockHttpServletRequest();
14
+    RouteAssignmentCommand command;
15
+    MockHttpServletRequest request;
17 16
 
18
-    request.addParameter("legs[0].voyageNumber", "CM01");
19
-    request.addParameter("legs[0].fromUnLocode", "AAAAA");
20
-    request.addParameter("legs[0].toUnLocode", "BBBBB");
17
+    @Test
18
+    public void testBind() {
19
+        command = new RouteAssignmentCommand();
20
+        request = new MockHttpServletRequest();
21 21
 
22
-    request.addParameter("legs[1].voyageNumber", "CM02");
23
-    request.addParameter("legs[1].fromUnLocode", "CCCCC");
24
-    request.addParameter("legs[1].toUnLocode", "DDDDD");
22
+        request.addParameter("legs[0].voyageNumber", "CM01");
23
+        request.addParameter("legs[0].fromUnLocode", "AAAAA");
24
+        request.addParameter("legs[0].toUnLocode", "BBBBB");
25 25
 
26
-    request.addParameter("trackingId", "XYZ");
26
+        request.addParameter("legs[1].voyageNumber", "CM02");
27
+        request.addParameter("legs[1].fromUnLocode", "CCCCC");
28
+        request.addParameter("legs[1].toUnLocode", "DDDDD");
27 29
 
28
-    ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
29
-    binder.bind(request);
30
+        request.addParameter("trackingId", "XYZ");
30 31
 
31
-    List<RouteAssignmentCommand.LegCommand> legs = command.getLegs();
32
-    assertEquals(2, legs.size());
32
+        ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
33
+        binder.bind(request);
33 34
 
34
-    RouteAssignmentCommand.LegCommand leg = legs.get(0);
35
-    assertEquals("CM01", leg.getVoyageNumber());
36
-    assertEquals("AAAAA", leg.getFromUnLocode());
37
-    assertEquals("BBBBB", leg.getToUnLocode());
35
+        List<RouteAssignmentCommand.LegCommand> legs = command.getLegs();
36
+        assertEquals(2, legs.size());
38 37
 
39
-    leg = legs.get(1);
40
-    assertEquals("CM02", leg.getVoyageNumber());
41
-    assertEquals("CCCCC", leg.getFromUnLocode());
42
-    assertEquals("DDDDD", leg.getToUnLocode());
38
+        RouteAssignmentCommand.LegCommand leg = legs.get(0);
39
+        assertEquals("CM01", leg.getVoyageNumber());
40
+        assertEquals("AAAAA", leg.getFromUnLocode());
41
+        assertEquals("BBBBB", leg.getToUnLocode());
43 42
 
44
-    assertEquals("XYZ", command.getTrackingId());
45
-  }
43
+        leg = legs.get(1);
44
+        assertEquals("CM02", leg.getVoyageNumber());
45
+        assertEquals("CCCCC", leg.getFromUnLocode());
46
+        assertEquals("DDDDD", leg.getToUnLocode());
46 47
 
47
-
48
-}
48
+        assertEquals("XYZ", command.getTrackingId());
49
+    }
50
+}

+ 61
- 89
src/test/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingControllerTest.java Wyświetl plik

@@ -1,97 +1,69 @@
1 1
 package se.citerus.dddsample.interfaces.tracking;
2 2
 
3
-import junit.framework.TestCase;
4
-import org.easymock.EasyMock;
5
-import org.springframework.context.support.StaticApplicationContext;
6
-import org.springframework.mock.web.MockHttpServletRequest;
7
-import org.springframework.mock.web.MockHttpServletResponse;
8
-import org.springframework.mock.web.MockHttpSession;
9
-import org.springframework.mock.web.MockServletContext;
3
+import org.junit.Before;
4
+import org.junit.Test;
5
+import org.junit.runner.RunWith;
6
+import org.springframework.test.context.ContextConfiguration;
7
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
8
+import org.springframework.test.context.web.WebAppConfiguration;
9
+import org.springframework.test.web.servlet.MockMvc;
10
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
10 11
 import org.springframework.validation.BindingResult;
11 12
 import org.springframework.validation.Errors;
12 13
 import org.springframework.validation.FieldError;
13
-import org.springframework.web.servlet.ModelAndView;
14
-import se.citerus.dddsample.domain.model.cargo.CargoRepository;
15
-import se.citerus.dddsample.domain.model.handling.HandlingEventRepository;
14
+import org.springframework.web.servlet.view.InternalResourceViewResolver;
16 15
 import se.citerus.dddsample.infrastructure.persistence.inmemory.CargoRepositoryInMem;
17 16
 import se.citerus.dddsample.infrastructure.persistence.inmemory.HandlingEventRepositoryInMem;
18 17
 
19
-public class CargoTrackingControllerTest extends TestCase {
20
-  CargoTrackingController controller;
21
-  MockHttpServletRequest request;
22
-  MockHttpServletResponse response;
23
-  MockHttpSession session;
24
-  MockServletContext servletContext;
25
-  CargoRepositoryInMem cargoRepository;
26
-  HandlingEventRepository handlingEventRepository;
27
-
28
-  protected void setUp() throws Exception {
29
-    servletContext = new MockServletContext("test");
30
-    request = new MockHttpServletRequest(servletContext);
31
-    response = new MockHttpServletResponse();
32
-    session = new MockHttpSession(servletContext);
33
-    request.setSession(session);
34
-
35
-    controller = new CargoTrackingController();
36
-    StaticApplicationContext applicationContext = new StaticApplicationContext();
37
-    controller.setApplicationContext(applicationContext);
38
-    controller.setFormView("test-form");
39
-    controller.setSuccessView("test-success");
40
-    controller.setCommandName("test-command-name");
41
-    cargoRepository = new CargoRepositoryInMem();
42
-    cargoRepository.setHandlingEventRepository(new HandlingEventRepositoryInMem());
43
-    cargoRepository.init();
44
-
45
-    handlingEventRepository = new HandlingEventRepositoryInMem();
46
-    controller.setHandlingEventRepository(handlingEventRepository);
47
-  }
48
-
49
-  public void testHandleGet() throws Exception {
50
-    controller.setCargoRepository(new CargoRepositoryInMem());
51
-    request.setMethod("GET");
52
-
53
-    ModelAndView mav = controller.handleRequest(request, response);
54
-
55
-    assertEquals("test-form", mav.getViewName());
56
-    assertEquals(2, mav.getModel().size());
57
-    assertTrue(mav.getModel().get("test-command-name") instanceof TrackCommand);
58
-  }
59
-
60
-  public void testHandlePost() throws Exception {
61
-    controller.setCargoRepository(cargoRepository);
62
-    request.addParameter("trackingId", "ABC");
63
-    request.setMethod("POST");
64
-
65
-    ModelAndView mav = controller.handleRequest(request, response);
66
-
67
-    assertEquals("test-form", mav.getViewName());
68
-    // Errors, command are two standard map attributes, the third should be the cargo object
69
-    assertEquals(3, mav.getModel().size());
70
-    CargoTrackingViewAdapter cargo = (CargoTrackingViewAdapter) mav.getModel().get("cargo");
71
-    assertEquals("ABC", cargo.getTrackingId());
72
-  }
73
-
74
-  public void testUnknownCargo() throws Exception {
75
-    CargoRepository cargoRepository = EasyMock.createNiceMock(CargoRepository.class);
76
-    EasyMock.replay(cargoRepository);
77
-    controller.setCargoRepository(cargoRepository);
78
-    
79
-    request.setMethod("POST");
80
-    request.setParameter("trackingId", "unknown-id");
81
-
82
-    ModelAndView mav = controller.handleRequest(request, response);
83
-
84
-    assertEquals("test-form", mav.getViewName());
85
-    assertEquals(2, mav.getModel().size());
86
-
87
-    TrackCommand command = (TrackCommand) mav.getModel().get(controller.getCommandName());
88
-    assertEquals("unknown-id", command.getTrackingId());
89
-
90
-    Errors errors = (Errors) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + controller.getCommandName());
91
-    FieldError fe = errors.getFieldError("trackingId");
92
-    assertEquals("cargo.unknown_id", fe.getCode());
93
-    assertEquals(1, fe.getArguments().length);
94
-    assertEquals(command.getTrackingId(), fe.getArguments()[0]);
95
-  }
96
-
97
-}
18
+import java.util.Map;
19
+
20
+import static org.junit.Assert.assertEquals;
21
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
22
+
23
+
24
+@RunWith(SpringJUnit4ClassRunner.class)
25
+@WebAppConfiguration
26
+@ContextConfiguration(classes = CargoTrackingControllerTest.TestConfiguration.class)
27
+public class CargoTrackingControllerTest {
28
+    public static class TestConfiguration {
29
+
30
+    }
31
+
32
+    private MockMvc mockMvc;
33
+
34
+    @Before
35
+    public void setup() throws Exception {
36
+        CargoRepositoryInMem cargoRepository = new CargoRepositoryInMem();
37
+        cargoRepository.setHandlingEventRepository(new HandlingEventRepositoryInMem());
38
+        cargoRepository.init();
39
+
40
+        CargoTrackingController controller = new CargoTrackingController();
41
+        controller.setCargoRepository(cargoRepository);
42
+        controller.setHandlingEventRepository(new HandlingEventRepositoryInMem());
43
+
44
+        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
45
+        resolver.setPrefix("/jsp/");
46
+        resolver.setSuffix(".jsp");
47
+        this.mockMvc = MockMvcBuilders.standaloneSetup(controller).setViewResolvers(resolver).build();
48
+    }
49
+
50
+    @Test
51
+    public void canGetCargo() throws Exception {
52
+        String trackingId = "ABC";
53
+        Map<String, Object> model = mockMvc.perform(post("/track").param("trackingId", trackingId)).andReturn().getModelAndView().getModel();
54
+        CargoTrackingViewAdapter cargoTrackingViewAdapter = (CargoTrackingViewAdapter) model.get("cargo");
55
+        assertEquals(trackingId, cargoTrackingViewAdapter.getTrackingId());
56
+    }
57
+
58
+    @Test
59
+    public void cannnotGetUnknownCargo() throws Exception {
60
+        String trackingId = "UNKNOWN";
61
+        Map<String, Object> model = mockMvc.perform(post("/track").param("trackingId", trackingId)).andReturn().getModelAndView().getModel();
62
+        Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "trackCommand");
63
+        FieldError fe = errors.getFieldError("trackingId");
64
+        assertEquals("cargo.unknown_id", fe.getCode());
65
+        assertEquals(1, fe.getArguments().length);
66
+        assertEquals(trackingId, fe.getArguments()[0]);
67
+    }
68
+
69
+}

+ 1
- 1
src/test/java/se/citerus/dddsample/interfaces/tracking/CargoTrackingViewAdapterTest.java Wyświetl plik

@@ -30,7 +30,7 @@ public class CargoTrackingViewAdapterTest extends TestCase {
30 30
     applicationContext.addMessage("cargo.status.IN_PORT", Locale.GERMAN, "In port {0}");
31 31
     applicationContext.refresh();
32 32
 
33
-    CargoTrackingViewAdapter adapter = new CargoTrackingViewAdapter(cargo, applicationContext, Locale.GERMAN, events);
33
+    CargoTrackingViewAdapter adapter = new CargoTrackingViewAdapter(cargo, applicationContext, Locale.GERMAN, events, TimeZone.getTimeZone("Europe/Stockholm"));
34 34
 
35 35
     assertEquals("XYZ", adapter.getTrackingId());
36 36
     assertEquals("Hangzhou", adapter.getOrigin());