forked from joscha/csv2mt940
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCsvToMT940.java
More file actions
268 lines (240 loc) · 9.12 KB
/
CsvToMT940.java
File metadata and controls
268 lines (240 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
* Created on 21.09.2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import mt940.MT940File;
import mt940.MT940Section;
import mt940.TOB5BookingCodeTranslator;
import mt940.fields.AccountDesignation;
import mt940.fields.AccountStatementNumber;
import mt940.fields.ClosingBalance;
import mt940.fields.MultiPurposeField;
import mt940.fields.OpeningBalance;
import mt940.fields.TransactionReferenceNumber;
import mt940.fields.TurnOverLine;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
/**
* @author Joscha Feth
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class CsvToMT940 {
private static final int MAX_BOOKING_TEXT = 27;
private static final SimpleDateFormat inFormat = new SimpleDateFormat("dd.MM.yyyy");
private static final CSVFormat csvFormat = CSVFormat.DEFAULT.withDelimiter(';');
private final CsvToMT940Frame ctmf;
private String[][] csvData;
private Date startDate;
/* public static String autoDecode(byte[] bytes) {
// fix charset
CharsetDetector charsetDetector = new CharsetDetector();
charsetDetector.setText(bytes);
// fix for mis-detection
CharsetMatch[] detectAll = charsetDetector.detectAll();
String encodingName = null;
for (int i = 0; i < detectAll.length; i++) {
CharsetMatch detect = detectAll[i];
encodingName = detect.getName();
int confidence = detect.getConfidence();
if ("Big5".equals(encodingName)) { // higher confidence required
if (i * 2 < detectAll.length) {
// enough other options
continue;
}
confidence -= 15;
}
if (confidence > 50) {
break;
}
if (encodingName.startsWith("ISO-8859")
|| encodingName.startsWith("windows-125")) {
break;
}
}
// ltr/rtl suffixes not supported
encodingName = StringUtils.removeEnd(encodingName, "_ltr");
encodingName = StringUtils.removeEnd(encodingName, "_rtl");
try {
return new String(bytes, encodingName);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CsvToMT940.class.getName()).log(Level.SEVERE, null, ex);
}
return new String(bytes);
} */
public CsvToMT940(CsvToMT940Frame ctmf) {
this.ctmf = ctmf;
}
public int getCount() {
return csvData.length - 1; // 1st line is headline
}
public void loadCSV(File csvfile) {
FileInputStream fis = null;
//String csvdata = null;
try {
fis = new FileInputStream(csvfile);
//csvdata = autoDecode(IOUtils.toByteArray(fis));
//CSVParser parser = CSVParser.parse(csvdata, csvFormat);
CSVParser parser = CSVParser.parse(fis, Charsets.ISO_8859_1, csvFormat);
List<CSVRecord> records = parser.getRecords();
int recordCount = records.size();
csvData = new String[recordCount][];
for (int i = 0; i < recordCount; i++) {
CSVRecord record = records.get(i);
int columnCount = record.size();
csvData[i] = new String[columnCount];
for (int j = 0; j < columnCount; j++) {
csvData[i][j] = record.get(j);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(fis);
}
}
public void writeMT940(File mt940file) {
createMT940();
}
public String getFilename() {
if (startDate != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + ".txt";
}
return "";
}
public MT940File createMT940() {
// reset
startDate = null;
// get data entered by user
String currency = ctmf.getCurrency(),
bankSortingCode = ctmf.getBankSortingCode(),
accountNumber = ctmf.getAccountNumber();
double closingBalance = ctmf.getClosingBalance(), openingBalance = closingBalance;
int dateIdx = 0, bookingTextIdx = 1, counterPartyIdx = 2, amountIdx = 3;
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
dfs.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat("#0.00", dfs);
//df.setPositivePrefix("+");
df.setGroupingUsed(true);
MT940File m = new MT940File();
try {
Date endDate = null;
// calculate initial balance
for (int i = 1; i < csvData.length; i++) {
Number amount = df.parse(csvData[i][amountIdx]);
Date valueDate = inFormat.parse(csvData[i][dateIdx]);
if (valueDate != null) {
if (startDate == null) {
DateTime temp = new DateTime(valueDate).withDayOfMonth(1).withMillisOfDay(0);
startDate = temp.toDate();
endDate = temp.plusMonths(1).minusMillis(1).toDate();
} else if (startDate.after(valueDate) || endDate.before(valueDate)) {
throw new UnsupportedOperationException("Alle Daten müssen in einem Monat liegen.");
}
}
if (amount != null) {
openingBalance -= amount.doubleValue();
}
}
String balanceCurrency = currency;
// initial balance, calculated
MT940Section ms = new MT940Section();
ms.addField(new TransactionReferenceNumber());
// ms.addField(new RelatedReferenceNumber());
ms.addField(new AccountDesignation(accountNumber,
bankSortingCode, currency));
// ms.addField(new AccountStatementNumber("" +
// statementNumber, ""));
ms.addField(new AccountStatementNumber());
ms.addField(new OpeningBalance(true, (openingBalance > 0), startDate, balanceCurrency,
openingBalance));
for (int i = csvData.length - 1; i > 0; i--) { // reverse order to have output old -> new
Date valueDate = inFormat.parse(csvData[i][dateIdx]);
String bookingText = csvData[i][bookingTextIdx],
bookingTextLong = "",
counterParty = csvData[i][counterPartyIdx],
customerRef = "", orderingAccNo = "", orderingName = "", bankRef = "";
// List<String> customerIdentification = new ArrayList<String>();
String[] bookingTextSplit = StringUtils.split(bookingText, " :"),
counterPartySplit = StringUtils.split(counterParty, ",:");
String fidorBookingString = bookingTextSplit[0], prev;
bookingText = StringUtils.strip(StringUtils.substringAfter(bookingText, fidorBookingString), " :"); // cut away fidorBookingString
if (bookingText.length() > MAX_BOOKING_TEXT) {
bookingTextLong = bookingText.substring(MAX_BOOKING_TEXT);
bookingText = bookingText.substring(0, MAX_BOOKING_TEXT);
}
if (counterPartySplit.length > 0) {
prev = counterPartySplit[0];
for (int j = 1; j < counterPartySplit.length; j++) {
String current = counterPartySplit[j];
if ("absender".equalsIgnoreCase(prev)
|| "empfänger".equalsIgnoreCase(prev)) {
orderingName = current;
} else if ("iban".equalsIgnoreCase(prev)) {
// customerIdentification.add("IBAN: " + current);
orderingAccNo = current;
} else if ("bic".equalsIgnoreCase(prev)) {
bankRef = current;
}
prev = current;
}
}
// overwrite customerRef if UMR is available
prev = bookingTextSplit[0];
for (int j = 1; j < bookingTextSplit.length; j++) {
String current = bookingTextSplit[j];
if ("umr".equalsIgnoreCase(prev)) { // Unique Mandate Reference (= Eindeutige Mandatsnummer)
// customerIdentification.add("UMR: " + current);
customerRef = current; // everything else is too long anyway
} else if ("uci".equalsIgnoreCase(prev)) { // Unique Creditor Identifier, Gläubigeridentifikationsnummer
// customerIdentification.add("UCI: " + current);
}
prev = current;
}
// TODO: parse bookingText, counterParty
String bookingCode = TOB5BookingCodeTranslator.getTransactionCode(fidorBookingString),
swiftCode = TOB5BookingCodeTranslator.getSwiftCode(fidorBookingString);
Number amount = df.parse(csvData[i][amountIdx]);
String amountCurrency = currency;
// StringUtils.join(customerIdentification, ", ")
ms.addField(new TurnOverLine(valueDate, valueDate,
(amount.doubleValue() > 0), false, amountCurrency,
amount, swiftCode, customerRef, bankRef));
ms.addField(new MultiPurposeField(bookingCode, bookingText,
bookingTextLong, orderingAccNo, orderingName));
}
ms.addField(new ClosingBalance(true, (closingBalance > 0), endDate, balanceCurrency,
closingBalance));
m.addSection(ms);
} catch (ArrayIndexOutOfBoundsException aiobe) {
aiobe.printStackTrace();
ctmf.addInfo("Keine gültige CSV-Datei! Abbruch...");
return null;
} catch (ParseException e) {
e.printStackTrace();
ctmf.addInfo("Parsing-Fehler! Abbruch...");
return null;
}
return m;
}
}