View Javadoc

1   /*
2    * Copyright 2006-2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.batch.sample.domain.trade.internal;
18  
19  import java.util.Collections;
20  
21  import org.springframework.batch.item.ExecutionContext;
22  import org.springframework.batch.item.ItemStream;
23  import org.springframework.batch.item.ItemWriter;
24  import org.springframework.batch.sample.domain.trade.CustomerCredit;
25  import org.springframework.batch.sample.domain.trade.CustomerCreditDao;
26  import org.springframework.beans.factory.DisposableBean;
27  
28  /**
29   * Writes customer's credit information in a file.
30   *
31   * @see CustomerCreditDao
32   * @author Robert Kasanicky
33   */
34  public class FlatFileCustomerCreditDao implements CustomerCreditDao,
35  		DisposableBean {
36  
37  	private ItemWriter<String> itemWriter;
38  
39  	private String separator = "\t";
40  
41  	private volatile boolean opened = false;
42  
43  	public void writeCredit(CustomerCredit customerCredit) throws Exception {
44  
45  		if (!opened) {
46  			open(new ExecutionContext());
47  		}
48  
49  		String line = "" + customerCredit.getName() + separator
50  				+ customerCredit.getCredit();
51  
52  		itemWriter.write(Collections.singletonList(line));
53  	}
54  
55  	public void setSeparator(String separator) {
56  		this.separator = separator;
57  	}
58  
59  	public void setItemWriter(ItemWriter<String> itemWriter) {
60  		this.itemWriter = itemWriter;
61  	}
62  
63  	public void open(ExecutionContext executionContext) throws Exception {
64  		if (itemWriter instanceof ItemStream) {
65  			((ItemStream) itemWriter).open(executionContext);
66  		}
67  		opened = true;
68  	}
69  
70  	public void close() throws Exception {
71  		if (itemWriter instanceof ItemStream) {
72  			((ItemStream) itemWriter).close();
73  		}
74  	}
75  
76  	/*
77  	 * (non-Javadoc)
78  	 *
79  	 * @see org.springframework.beans.factory.DisposableBean#destroy()
80  	 */
81  	public void destroy() throws Exception {
82  		close();
83  	}
84  
85  }