com.ctt.persistance.StorageFile.java Source code

Java tutorial

Introduction

Here is the source code for com.ctt.persistance.StorageFile.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ctt.persistance;

import com.ctt.entity.Transaction;
import com.ctt.sshlistener.Main;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author aleji_000
 */
public class StorageFile {

    public static void saveTransactions(byte[] file) throws IOException {
        try {

            List<String> list = new ArrayList<String>();

            CSVParser csv;
            csv = CSVParser.parse(new String(file), CSVFormat.DEFAULT);

            List<CSVRecord> it = csv.getRecords();
            Transaction obj;

            int i = 0;
            for (i = 0; i < it.size(); i++) {
                if (i != 0) {
                    obj = new Transaction((CSVRecord) it.get(i));

                    if (obj.validateCanonical() && obj.isRepayment()) {
                        list.add(obj.repaymentString());

                        StorageFile.saveTransaction(obj);
                    }
                }
            }
            FileUtils.writeLines(new File(Main.prop.getProperty("path_repayments")), list, "\n", true);
        } catch (Exception e) {
            Main.appendLog("Error: SAVE TRANSACTIONS: " + e.getMessage());
        }
    }

    public static void saveTransaction(Transaction t) throws IOException {
        try {

            List<String> list = new ArrayList<String>();
            list.add(t.transactionString());

            String name_file = Main.prop.getProperty("path_transactions") + "transactions_" + t.getCard_number()
                    + ".csv";

            File f = new File(name_file);
            if (!f.exists()) {
                f.createNewFile();
            }

            System.out.println("Guardar Transacciones");

            FileUtils.writeLines(new File(name_file), list, true);
        } catch (Exception e) {
            Main.appendLog("Error: SAVE TRANSACTION: " + e.getMessage());
        }
    }

}