1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.batch.sample.domain.trade.internal;
18
19 import java.math.BigDecimal;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.springframework.batch.core.annotation.AfterWrite;
26 import org.springframework.batch.item.ExecutionContext;
27 import org.springframework.batch.item.ItemStreamException;
28 import org.springframework.batch.item.ItemStreamSupport;
29 import org.springframework.batch.item.ItemWriter;
30 import org.springframework.batch.item.WriteFailedException;
31 import org.springframework.batch.sample.domain.trade.Trade;
32 import org.springframework.batch.sample.domain.trade.TradeDao;
33 import org.springframework.util.Assert;
34
35
36
37
38
39 public class TradeWriter extends ItemStreamSupport implements ItemWriter<Trade> {
40
41 private static Log log = LogFactory.getLog(TradeWriter.class);
42
43 public static final String TOTAL_AMOUNT_KEY = "TOTAL_AMOUNT";
44
45 private TradeDao dao;
46
47 private List<String> failingCustomers = new ArrayList<String>();
48
49 private BigDecimal totalPrice = BigDecimal.ZERO;
50
51 public void write(List<? extends Trade> trades) {
52
53 for (Trade trade : trades) {
54
55 log.debug(trade);
56
57 dao.writeTrade(trade);
58
59 Assert.notNull(trade.getPrice());
60
61 if (this.failingCustomers.contains(trade.getCustomer())) {
62 throw new WriteFailedException("Something unexpected happened!");
63 }
64 }
65
66 }
67
68 @AfterWrite
69 public void updateTotalPrice(List<Trade> trades) {
70 for (Trade trade : trades) {
71 this.totalPrice = this.totalPrice.add(trade.getPrice());
72 }
73 }
74
75 @Override
76 public void open(ExecutionContext executionContext) throws ItemStreamException {
77 if (executionContext.containsKey(TOTAL_AMOUNT_KEY)) {
78 this.totalPrice = (BigDecimal) executionContext.get(TOTAL_AMOUNT_KEY);
79 }
80 else {
81
82
83
84 this.totalPrice = BigDecimal.ZERO;
85 }
86 }
87
88 @Override
89 public void update(ExecutionContext executionContext) {
90 executionContext.put(TOTAL_AMOUNT_KEY, this.totalPrice);
91 }
92
93 public BigDecimal getTotalPrice() {
94 return totalPrice;
95 }
96
97 public void setDao(TradeDao dao) {
98 this.dao = dao;
99 }
100
101
102
103
104
105
106 public void setFailingCustomers(List<String> failingCustomers) {
107 this.failingCustomers = failingCustomers;
108 }
109 }