PageRenderTime 134ms CodeModel.GetById 43ms app.highlight 51ms RepoModel.GetById 37ms app.codeStats 0ms

/src/mpv5/utils/files/TextDatFile.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 286 lines | 177 code | 31 blank | 78 comment | 13 complexity | e30fe800da0a00e6572f633eb3302bfa MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *  
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *  
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *  
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.utils.files;
 18
 19import java.io.File;
 20import java.io.FileNotFoundException;
 21import java.io.IOException;
 22import java.lang.reflect.Method;
 23import java.util.ArrayList;
 24import java.util.List;
 25import java.util.logging.Level;
 26import java.util.logging.Logger;
 27import javax.print.DocFlavor;
 28import javax.swing.JTable;
 29import javax.swing.table.DefaultTableModel;
 30
 31import mpv5.db.common.DatabaseObject;
 32import mpv5.logging.Log;
 33
 34import mpv5.utils.arrays.ArrayUtilities;
 35import mpv5.utils.jobs.Waitable;
 36
 37/**
 38 * This is a helper class for reading and writing csv files
 39 * 
 40 */
 41public class TextDatFile extends File implements Waitable {
 42
 43    private static final long serialVersionUID = 2059941918698508985L;
 44    private FileReaderWriter rw;
 45    private String fieldSeparator = ";";
 46    private String[][] data;
 47    private String[] header;
 48    private int mode;
 49    private DefaultTableModel model;
 50    private JTable table;
 51
 52    /**
 53     * Constructs a new text file
 54     */
 55    public TextDatFile() {
 56        super(FileDirectoryHandler.getTempFile().getPath());
 57        rw = new FileReaderWriter(this);
 58    }
 59
 60    /**
 61     * Constructs a new temporary text file
 62     * @param data The data to write to the file
 63     * @param header 
 64     */
 65    public TextDatFile(String[][] data, String[] header) {
 66        super(FileDirectoryHandler.getTempFile().getPath());
 67        rw = new FileReaderWriter(this);
 68        this.data = data;
 69        this.header = header;
 70        mode = 0;
 71        this.deleteOnExit();
 72    }
 73
 74    /**
 75     * Constructs a new text file
 76     * @param data The data to write to the file
 77     * @param header 
 78     * @param name The name/path of the file
 79     */
 80    public TextDatFile(String[][] data, String[] header, String name) {
 81        super(name);
 82        rw = new FileReaderWriter(this);
 83        this.data = data;
 84        this.header = header;
 85        mode = 0;
 86    }
 87
 88    /**
 89     * Constructs a new file and sets 'read' mode
 90     * @param file The file (to read from)
 91     */
 92    public TextDatFile(File file) {
 93        super(file.getPath());
 94        rw = new FileReaderWriter(this);
 95        mode = 1;
 96    }
 97
 98    /**
 99     * Constructs a new file and sets 'read' mode
100     * @param file The file (to read from)
101     * @param table The table to retrieve the data
102     */
103    public TextDatFile(File file, JTable table) {
104        super(file.getPath());
105        rw = new FileReaderWriter(this);
106        this.table = table;
107        mode = 2;
108    }
109
110    public void parse(ArrayList<DatabaseObject> dbobjarr) {
111        String[] headers;
112        Method[] headerx;
113           if (dbobjarr.size() > 0) {
114                    headerx = dbobjarr.get(0).getVars().values().toArray(new Method[]{});
115                    headers = new String[headerx.length];
116                    for (int i = 0; i < headerx.length; i++) {
117                        Method method = headerx[i];
118                        headers[i] = method.getName().substring(5);
119                    }
120                    data = new String[dbobjarr.size()][dbobjarr.get(0).getVars().size()];
121                    for (int i = 0; i < dbobjarr.size(); i++) {
122                        DatabaseObject databaseObject = dbobjarr.get(i);
123                        List<String[]> temp = databaseObject.getValues();
124
125                        for (int j = 0; j < temp.size(); j++) {
126                            String[] strings = temp.get(j);
127                            data[i][j] = strings[1];
128                        }
129                    }
130
131                   setData(data);
132                   setHeader(headers);
133                }
134    }
135
136    @Override
137    public Exception waitFor() {
138
139            switch (mode) {
140                case 0:
141                    print();
142                    break;
143                case 1:
144                    read();
145                    break;
146                case 2:
147                    readToTable();
148                    break;
149            }
150
151        return null;
152    }
153
154    /**
155     * Write the file to disk
156     */
157    public void print() {
158
159        if (header != null) {
160            rw.writeLine(header, getFieldSeparator());
161        }
162
163        for (int i = 0; i < getData().length; i++) {
164            String[] strings = getData()[i];
165            String line = "";
166            for (int j = 0; j < strings.length; j++) {
167                String string = strings[j];
168                line += string + getFieldSeparator();
169            }
170            line = (line.substring(0, line.length() - getFieldSeparator().length())).replaceAll("[\\r\\n]", "");
171//            Log.Debug(this, line);
172            rw.write(line);
173        }
174    }
175
176    /**
177     * Reads the file, no headers given
178     * @return The data from file
179     */
180    public String[][] read() {
181        @SuppressWarnings("unchecked")
182        ArrayList<String[]> arr = new ArrayList();
183        String[] line = rw.readLines();
184        Log.Debug(this, "Reading file: " + this.getPath() + " (" + line.length + " lines)");
185        for (int i = 0; i < line.length; i++) {
186            arr.add(line[i].split(getFieldSeparator()));
187            line = rw.readLines();
188//            Log.Debug(this, "Line.. " + i);
189        }
190        data = ArrayUtilities.listToStringArrayArray(arr);
191        model = new DefaultTableModel(data, header);
192        return data;
193    }
194
195    /**
196     * Reads the file, assuming the first line contains the header
197     * @return The data from file
198     */
199    public DefaultTableModel readToTable() {
200        @SuppressWarnings("unchecked")
201        ArrayList<String[]> arr = new ArrayList();
202        String[] line = rw.readLines();
203        Log.Debug(this, "Reading file: " + this.getPath() + " (" + line.length + " lines)");
204        header = line[0].split(getFieldSeparator());
205        for (int i = 1; i < line.length; i++) {
206            arr.add(line[i].split(getFieldSeparator()));
207//            Log.Debug(this, "Line.. " + arr.get(i-1));
208        }
209        data = ArrayUtilities.listToStringArrayArray(arr);
210        model = new DefaultTableModel(data, header);
211        if (table != null) {
212            this.table.setModel(model);
213        }
214        return model;
215    }
216
217    public DocFlavor getFlavor() {
218        return DocFlavor.CHAR_ARRAY.TEXT_PLAIN;
219    }
220
221    public File getFile() {
222        return this;
223    }
224
225    /**
226     * 
227     * @return the field separating char
228     */
229    public String getFieldSeparator() {
230        return fieldSeparator;
231    }
232
233    /**
234     * Set the field separating char (default: ';')
235     * @param fieldSeparator
236     */
237    public void setFieldSeparator(String fieldSeparator) {
238        this.fieldSeparator = fieldSeparator;
239    }
240
241    /**
242     * 
243     * @return The data
244     */
245    public String[][] getData() {
246        return data;
247    }
248
249    /**
250     * 
251     * @param data Set the data of the file
252     */
253    public void setData(String[][] data) {
254        this.data = data;
255    }
256
257    public String[] getHeader() {
258        return header;
259    }
260
261    public void setHeader(String[] header) {
262        this.header = header;
263    }
264
265    public DefaultTableModel getModel() {
266        return model;
267    }
268
269    /**
270     * Create a new file
271     * @param filename
272     * @return
273     */
274    public File createFile(String filename) {
275        File f = FileDirectoryHandler.getTempFile(filename, "csv");
276        try {
277            print();
278            FileDirectoryHandler.copyFile(this, f);
279        } catch (FileNotFoundException ex) {
280            mpv5.logging.Log.Debug(ex);//Logger.getLogger(TextDatFile.class.getName()).log(Level.SEVERE, null, ex);
281        } catch (IOException ex) {
282            mpv5.logging.Log.Debug(ex);//Logger.getLogger(TextDatFile.class.getName()).log(Level.SEVERE, null, ex);
283        }
284        return f;
285    }
286}