[Schmitzm-commits] r1936 - in trunk/schmitzm-excelcsv: . src/main/java/de/schmitzm src/main/java/de/schmitzm/csv src/main/java/de/schmitzm/csv/gui src/main/resources src/main/resources/de src/main/resources/de/schmitzm src/main/resources/de/schmitzm/csv src/main/resources/de/schmitzm/csv/resource src/main/resources/de/schmitzm/csv/resource/locales src/test/java/de/schmitzm src/test/java/de/schmitzm/csv
scm-commit at wald.intevation.org
scm-commit at wald.intevation.org
Wed Apr 4 16:38:08 CEST 2012
Author: mojays
Date: 2012-04-04 16:38:08 +0200 (Wed, 04 Apr 2012)
New Revision: 1936
Added:
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/CsvUtil.java
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationDialog.java
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationPanel.java
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewDialog.java
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewPanel.java
trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewTable.java
trunk/schmitzm-excelcsv/src/main/resources/de/
trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/
trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/
trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/
trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/
trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle.properties
trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle_de.properties
trunk/schmitzm-excelcsv/src/test/java/de/schmitzm/csv/
trunk/schmitzm-excelcsv/src/test/java/de/schmitzm/csv/CsvTest.java
Modified:
trunk/schmitzm-excelcsv/
Log:
First commit of some nice classes, especially:
- CSVPreviewPanel and Dialog
- CSVColumnAllocationPanel and Dialog
Property changes on: trunk/schmitzm-excelcsv
___________________________________________________________________
Added: svn:ignore
+ target
.settings
Added: trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/CsvUtil.java
===================================================================
--- trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/CsvUtil.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/CsvUtil.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,373 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.supercsv.cellprocessor.ift.CellProcessor;
+import org.supercsv.io.CsvListReader;
+import org.supercsv.io.CsvListWriter;
+import org.supercsv.io.CsvMapReader;
+import org.supercsv.io.CsvMapWriter;
+import org.supercsv.io.ICsvListReader;
+import org.supercsv.io.ICsvListWriter;
+import org.supercsv.io.ICsvMapReader;
+import org.supercsv.io.ICsvMapWriter;
+import org.supercsv.prefs.CsvPreference;
+import org.supercsv.util.CSVContext;
+
+import de.schmitzm.data.DataUtil;
+import de.schmitzm.io.FileOutputStream;
+import de.schmitzm.lang.LangUtil;
+import de.schmitzm.lang.ResourceProvider;
+import de.schmitzm.swing.input.FileInputOption;
+import de.schmitzm.swing.input.InputOption;
+import de.schmitzm.swing.input.ManualInputOption;
+import de.schmitzm.swing.input.MultipleOptionPane;
+import de.schmitzm.swing.input.SelectionInputOption;
+import de.schmitzm.temp.BaseTypeUtil;
+
+/**
+ * Utility methods for handling CSV files. Bases on project "SuperCSV".
+ * @author Martin O.J. Schmitz
+ */
+public class CsvUtil {
+ /** {@link ResourceProvider}, der die Lokalisation fuer Komponenten
+ * des Package {@code schmitzm.data} zur Verfuegung stellt. Diese sind
+ * in properties-Datein unter {@code schmitzm.data.resource.locales}
+ * hinterlegt. */
+ public static ResourceProvider RESOURCE = ResourceProvider.newInstance( LangUtil.extendPackagePath(CsvUtil.class,"resource.locales.CsvResourceBundle"), Locale.ENGLISH );
+
+ /** Default delimiter for CSV files (Semicolon ';'). Can be modified to
+ * change application wide default! */
+ public static char DEFAULT_CSV_DELIMITER = ';';
+ /** Default decimal sign for CSV files (Comma ','). Can be modified to
+ * change application wide default! */
+ public static char DEFAULT_CSV_DECIMALSIGN = ',';
+ /** Default text quote character for CSV files (Quotation mark '"'). Can be modified to
+ * change application wide default! */
+ public static char DEFAULT_CSV_QUOTESIGN = '"';
+ /** Default {@link Charset} used for CSV files. Can be modified to
+ * change application wide default!
+ * @see Charset#defaultCharset() */
+ public static Charset DEFAULT_CSV_CHARSET = Charset.defaultCharset();
+ /** Default NoData value used for CSV files. Can be modified to
+ * change application wide default!
+ * @see Charset#defaultCharset() */
+ public static String DEFAULT_CSV_NODATA = "";
+
+ /**
+ * Convenience method to access the translation resources.
+ */
+ public static String R(String key, Object... values) {
+ return RESOURCE.getString(key, values);
+ }
+
+ /**
+ * Initializes a {@link CsvMapReader} according to the given parameters
+ * @param csvInputStream stream to import (requires a header line with column titles!)
+ * @param delimChar character used as column delimiter
+ * @param quoteChar character used to mask strings
+ * @param charset {@link Charset} of the file
+ */
+ public static ICsvMapReader createCsvMapReader(InputStream csvInputStream, char delimChar, char quoteChar, Charset charset) throws IOException {
+ if (charset == null)
+ charset = Charset.defaultCharset();
+ CsvPreference csvPreference = new CsvPreference(quoteChar, delimChar, "\n");
+ ICsvMapReader inFile = new CsvMapReader(new InputStreamReader(csvInputStream,charset), csvPreference);
+ return inFile;
+ }
+
+ /**
+ * Initializes a {@link CsvMapReader} according to the given parameters
+ * @param csvFile file to import (requires a header line with column titles!)
+ * @param delimChar character used as column delimiter
+ * @param quoteChar character used to mask strings
+ * @param charset {@link Charset} of the file
+ */
+ public static ICsvMapReader createCsvMapReader(File csvFile, char delimChar, char quoteChar, Charset charset) throws IOException {
+ return createCsvMapReader(new FileInputStream(csvFile), delimChar, quoteChar, charset);
+ }
+
+ /**
+ * Initializes a {@link CsvListReader} according to the given parameters
+ * @param csvInputStream stream to import (requires a header line with column titles!)
+ * @param delimChar character used as column delimiter
+ * @param quoteChar character used to mask strings
+ * @param charset {@link Charset} of the file
+ */
+ public static ICsvListReader createCsvListReader(InputStream csvInputStream, char delimChar, char quoteChar, Charset charset) throws IOException {
+ if (charset == null)
+ charset = Charset.defaultCharset();
+ CsvPreference csvPreference = new CsvPreference(quoteChar, delimChar, "\n");
+ ICsvListReader inFile = new CsvListReader(new InputStreamReader(csvInputStream,charset), csvPreference);
+ return inFile;
+ }
+
+ /**
+ * Initializes a {@link CsvListReader} according to the given parameters
+ * @param csvFile file to import (requires a header line with column titles!)
+ * @param delimChar character used as column delimiter
+ * @param quoteChar character used to mask strings
+ * @param charset {@link Charset} of the file
+ */
+ public static ICsvListReader createCsvListReader(File csvFile, char delimChar, char quoteChar, Charset charset) throws IOException {
+ return createCsvListReader(new FileInputStream(csvFile), delimChar, quoteChar, charset);
+ }
+
+ /**
+ * Creates a {@link CellProcessor} which converts empty strings to {@code null}
+ * for each column (of the header) of the CSV file
+ * @param inFile CSV file
+ * @param noDataValues additional values (besides empty string) which are
+ * converted to {@code null}.
+ */
+ public static CellProcessor[] createNullConverterCellProcessors(String[] header, final Object... noDataValues) throws IOException {
+ // CellProessor to convert blank strings to NULL
+ CellProcessor cp = new CellProcessor() {
+ @Override
+ public Object execute(Object value, CSVContext context) {
+ if ( value instanceof String && ((String)value).trim().isEmpty() )
+ return null;
+ if ( value != null )
+ for (Object noDataValue : noDataValues)
+ if ( value.equals(noDataValue) )
+ return null;
+ return value;
+ }
+ };
+ // Processor needed for each CSV column
+ CellProcessor[] cps = new CellProcessor[header.length];
+ for (int i=0; i<cps.length; i++)
+ cps[i] = cp;
+
+ return cps;
+ }
+
+ /**
+ * Converts a string to double.
+ * @return 0 if input string is {@code null}
+ */
+ public static double convertDouble(String str, char decimalSign, Double... defaultValue) {
+ double defValue = defaultValue.length > 0 ? defaultValue[0] : 0.0;
+
+ if ( str == null || str.trim().isEmpty() )
+ return defValue;
+
+ if ( decimalSign != '.' )
+ str = str.replace(decimalSign, '.');
+ str = str.trim();
+ return BaseTypeUtil.convertFromString(str, Double.class);
+ }
+
+ /**
+ * Converts a string to double.
+ * @return 0 if input string is {@code null}
+ */
+ public static <K> Map<K,Object> convertNumericValues(Map<K,?> colValues, char decimalSign) {
+ Map<K,Object> dest = new HashMap<K,Object>();
+
+ for (K key : colValues.keySet() ) {
+ Object value = colValues.get(key);
+ if ( value != null ) {
+ String str = value.toString();
+ // decimal sign is not dot, but value contains dot, leave
+ // value as it is (do not convert dotted decimals implicitly)
+ if ( str.contains(".") && decimalSign != '.' ) {
+ dest.put(key, value);
+ continue;
+ }
+ if ( decimalSign != '.' )
+ str = str.replace(decimalSign, '.');
+ str = str.trim();
+ try {
+ if ( str.contains(".") )
+ value = BaseTypeUtil.convertFromString(str, Double.class);
+ else
+ value = BaseTypeUtil.convertFromString(str, Integer.class);
+ } catch (Exception err) {
+ // ignore; leave value as it is
+ }
+ }
+ dest.put(key, value);
+ }
+ return dest;
+ }
+
+ /**
+ * Creates 5 {@link InputOption} for {@link MultipleOptionPane} to specify CSV
+ * import/export parameters.
+ * @param labels indicates whether input options are generated with or
+ * without labels
+ * @param file Default for import file
+ * @param delimiter Default for CSV delimiter
+ * @param quoteChar Default for the quote character
+ * @param decimalSign Default for the decimal sign
+ * @param noDataValue Default for value indicating no data value
+ */
+ public static List<InputOption<?>> createCSVDialogOptions(boolean labels, File file,
+ Character delimiter, Character quoteChar, Character decimalSign, Charset charset, String noDataValue) {
+ return createCSVDialogOptions(labels,
+ file,
+ delimiter != null ? ""+delimiter : (String)null,
+ quoteChar != null ? ""+quoteChar : (String)null,
+ decimalSign != null ? ""+decimalSign : (String)null,
+ charset,
+ noDataValue);
+ }
+
+ /**
+ * Creates 5 {@link InputOption} for {@link MultipleOptionPane} to specify CSV
+ * import/export parameters.
+ * @param labels indicates whether input options are generated with or
+ * without labels
+ * @param file Default for import file
+ * @param delimiter Default for CSV delimiter
+ * @param quoteChar Default for the quote character
+ * @param decimalSign Default for the decimal sign
+ * @param noDataValue Default for value indicating no data value
+ */
+ public static List<InputOption<?>> createCSVDialogOptions(boolean labels, File file,
+ String delimiter, String quoteChar, String decimalSign, Charset charset, String noDataValue) {
+ List<InputOption<?>> inputOptions = new ArrayList<InputOption<?>>();
+ // File
+ FileInputOption fileInputOption = new FileInputOption(labels ? R("CSVDialogOptions.file.label") : null, true);
+
+ // Delimiter character
+ SelectionInputOption.Combo<String> delimInputOption = new SelectionInputOption.Combo<String>(
+ labels ? R("CSVDialogOptions.delim.label") : null,
+ true,
+ new String[] { "\t", ";", "|", "," },
+ new String[] { R("CSVDialogOptions.delim.tab.desc"),
+ R("CSVDialogOptions.delim.semicolon.desc"),
+ R("CSVDialogOptions.delim.pipe.desc"),
+ R("CSVDialogOptions.delim.comma.desc") });
+ // Text-Quotation character
+ SelectionInputOption.Combo<String> quoteInputOption = new SelectionInputOption.Combo<String>(
+ labels ? R("CSVDialogOptions.quote.label") : null,
+ true,
+ new String[] { "\\", "\"", "'" },
+ new String[] { "\\", "\"", "'" });
+ // Decimal sign
+ SelectionInputOption.Combo<String> decimalInputOption = new SelectionInputOption.Combo<String>(
+ labels ? R("CSVDialogOptions.decimal.label") : null,
+ true,
+ new String[] { ",", "." },
+ new String[] { ",", "." });
+ // Charset
+ Charset[] charsets = new Charset[] {Charset.forName("cp850"),
+ Charset.forName("cp1252"),
+ Charset.forName("UTF-8"),
+ Charset.forName("ISO-8859-15")};
+ String[] charsetDescs = new String[] {R("CSVDialogOptions.charset.cp850.desc"),
+ R("CSVDialogOptions.charset.cp1252.desc"),
+ R("CSVDialogOptions.charset.utf8.desc"),
+ R("CSVDialogOptions.charset.iso-8859-15.desc")};
+ Charset defCharset = charsets[3]; // ISO
+ SelectionInputOption.Combo<Charset> charSetInputOption = new SelectionInputOption.Combo<Charset>(
+ labels ? R("CSVDialogOptions.charset.label") : null,
+ true,
+ charsets,
+ defCharset,
+ charsetDescs);
+ // No data value
+ ManualInputOption.Text noDataInputOption = new ManualInputOption.Text(
+ labels ? R("CSVDialogOptions.nodata.label") : null, false);
+
+ if (file != null)
+ fileInputOption.setValue(file);
+ if (delimiter != null)
+ delimInputOption.setValue(delimiter);
+ if (quoteChar != null)
+ quoteInputOption.setValue(quoteChar);
+ if (decimalSign != null)
+ decimalInputOption.setValue(decimalSign);
+ if (charset != null)
+ charSetInputOption.setValue(charset);
+ if (noDataValue != null)
+ noDataInputOption.setValue(noDataValue);
+ inputOptions.add(fileInputOption);
+ inputOptions.add(delimInputOption);
+ inputOptions.add(decimalInputOption);
+ inputOptions.add(quoteInputOption);
+ inputOptions.add(charSetInputOption);
+ inputOptions.add(noDataInputOption);
+
+ return inputOptions;
+ }
+
+ /**
+ * Initializes a {@link CsvMapWriter} according to the given parameters
+ * @param csvFile file to export to
+ * @param delimChar character used as column delimiter
+ * @param quoteChar character used to mask strings
+ * @param charset {@link Charset} of the file
+ */
+ public static ICsvMapWriter createCsvMapWriter(File csvFile, char delimChar, char quoteChar, Charset charset) throws IOException {
+ if (charset == null)
+ charset = Charset.defaultCharset();
+ CsvPreference csvPreference = new CsvPreference(quoteChar, delimChar, "\n");
+ Writer writer = new OutputStreamWriter(new FileOutputStream(csvFile),charset);
+ ICsvMapWriter outFile = new CsvMapWriter(writer, csvPreference);
+
+ return outFile;
+ }
+
+ /**
+ * Initializes a {@link CsvListWriter} according to the given parameters
+ * @param csvFile file to export to
+ * @param delimChar character used as column delimiter
+ * @param quoteChar character used to mask strings
+ * @param charset {@link Charset} of the file
+ */
+ public static ICsvListWriter createCsvListWriter(File csvFile, char delimChar, char quoteChar, Charset charset) throws IOException {
+ if (charset == null)
+ charset = Charset.defaultCharset();
+ CsvPreference csvPreference = new CsvPreference(quoteChar, delimChar, "\n");
+ Writer writer = new OutputStreamWriter(new FileOutputStream(csvFile),charset);
+ ICsvListWriter outFile = new CsvListWriter(writer, csvPreference);
+
+ return outFile;
+ }
+
+
+}
Added: trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationDialog.java
===================================================================
--- trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationDialog.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationDialog.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,141 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv.gui;
+
+import java.awt.BorderLayout;
+import java.awt.Dialog;
+import java.awt.Frame;
+import java.util.List;
+import java.util.Map;
+
+import de.schmitzm.lang.LangUtil;
+import de.schmitzm.swing.OkCancelDialog;
+import de.schmitzm.swing.SwingUtil;
+
+/**
+ * Dialog to allocate CSV columns to predefined fields. See {@link CSVColumnAllocationPanel}
+ * for details.
+ * @author Martin O.J. Schmitz
+ *
+ */
+public class CSVColumnAllocationDialog extends OkCancelDialog {
+ /** Holds the allocation panel */
+ protected CSVColumnAllocationPanel allocationPanel;
+
+ /**
+ * Creates a new dialog
+ * @param owner parent component
+ * @param title dialog title
+ */
+ public CSVColumnAllocationDialog(Frame owner, String title) {
+ super(owner, title, true);
+ }
+
+ /**
+ * Creates a new dialog
+ * @param owner parent component
+ * @param title dialog title
+ */
+ public CSVColumnAllocationDialog(Dialog owner, String title) {
+ super(owner, title, true);
+ }
+
+ /**
+ * Called immediately by the constructor to initialize the
+ * dialog.
+ */
+ @Override
+ protected void init() {
+ super.init();
+ setPreferredSize( null ); // overwrite default of OkCancelDialog to indefinite
+
+ this.allocationPanel = new CSVColumnAllocationPanel();
+ getContentPane().add(allocationPanel, BorderLayout.CENTER);
+
+ pack();
+ SwingUtil.setRelativeFramePosition(this, getOwner(), 0.5, 0.5);
+ }
+
+ /**
+ * Sets the header label above the field descriptions.
+ */
+ public void setFieldsHeaderCaption(String caption) {
+ allocationPanel.setFieldsHeaderCaption(caption);
+ }
+
+
+ /**
+ * Returns the header label above the field descriptions.
+ */
+ public String getFieldsHeaderCaption() {
+ return allocationPanel.getFieldsHeaderCaption();
+ }
+
+ /**
+ * Initializes the panel with a new set of fields.
+ * @param fields map of fields (key = field ID; value = description for GUI label);
+ * for each entry a combo box is created to allocate a CSV column
+ * @param csvColumns list of CSV column names which can be allocated to the fields
+ * @param defaultMapping default CSV column names by field (ID); can be {@code null}
+ */
+ public void setAllocationOptions(Map<String,String> fields, List<String> csvColumns, Map<String,String> defaultMapping) {
+ allocationPanel.init(fields, csvColumns, defaultMapping);
+ pack();
+ SwingUtil.setRelativeFramePosition(this, getOwner(), 0.5, 0.5);
+ }
+
+ /**
+ * Initializes the panel with a new set of fields.
+ * @param fields list of fields (entry is used as ID and GUI label);
+ * for each entry a combo box is created to allocate a CSV column
+ * @param csvColumns list of CSV column names which can be allocated to the fields
+ * @param defaultMapping default CSV column names by field (ID); can be {@code null}
+ */
+ public void setAllocationOptions(List<String> fields, List<String> csvColumns, Map<String,String> defaultMapping) {
+ setAllocationOptions( LangUtil.convertToMap(fields), csvColumns, defaultMapping );
+ }
+
+ /**
+ * Returns the mapping specified by the input fields. The map key identifies
+ * the field (field id) and the value represents the allocated CSV column.
+ */
+ public Map<String,String> getMappingFieldToCsv() {
+ return allocationPanel.getMappingFieldToCsv();
+ }
+
+ /**
+ * Returns the mapping specified by the input fields. The map key identifies
+ * the CSV column and the value the corresponding field (field id).
+ */
+ public Map<String,String> getMappingCsvToField() {
+ return allocationPanel.getMappingCsvToField();
+ }
+
+}
Added: trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationPanel.java
===================================================================
--- trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationPanel.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVColumnAllocationPanel.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,226 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv.gui;
+
+import java.awt.Font;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.swing.JLabel;
+
+import net.miginfocom.swing.MigLayout;
+
+import de.schmitzm.csv.CsvUtil;
+import de.schmitzm.lang.LangUtil;
+import de.schmitzm.lang.SequentialOrderedMap;
+import de.schmitzm.swing.JPanel;
+import de.schmitzm.swing.SwingUtil;
+import de.schmitzm.swing.input.SelectionInputOption;
+
+
+/**
+ * Panel which shows an allocation between needed data fields and available CSV columns.
+ * For each data field a label and combo box is shown to select the allocated CSV column.
+ * The data fields (+ description) and CSV columns can be specified in constructor or
+ * by calling one of the {@code init(.)}-methods.
+ * @see #init(List, List, Map)
+ * @see #init(Map, List, Map)
+ * @author Martin O.J. Schmitz
+ *
+ */
+public class CSVColumnAllocationPanel extends JPanel {
+ private static final Font HEADER_FONT = SwingUtil.DEFAULT_FONT.deriveFont(Font.BOLD).deriveFont(SwingUtil.FONT_ATTR_UNDERLINED);
+
+ /** Header caption for list of fields. */
+ protected JLabel fieldsHeader;
+ /** Header caption for list of CSV column combo boxes. */
+ protected JLabel columnsHeader;
+ /** Holds for each field (ID) the GUI label. */
+ protected Map<String,JLabel> allocationCaptions = new SequentialOrderedMap<String, JLabel>();
+ /** Holds for each field (ID) the combo box to select the CSV column. */
+ protected Map<String,SelectionInputOption.Combo<String>> allocationColumns = new SequentialOrderedMap<String, SelectionInputOption.Combo<String>>();
+
+ /**
+ * Creates a new allocation panel.
+ * @param fieldHeaderCaption short description/title for application depending fields (first column)
+ * @param fields map of fields (key = field ID; value = description for GUI label);
+ * for each entry a combo box is created to allocate a CSV column
+ * @param csvColumns list of CSV column names which can be allocated to the fields
+ */
+ public CSVColumnAllocationPanel(String fieldHeaderCaption, Map<String,String> fields, List<String> csvColumns) {
+ super( new MigLayout("wrap 2","[]20[grow]","") );
+ this.fieldsHeader = new JLabel(fieldHeaderCaption);
+ fieldsHeader.setFont(HEADER_FONT);
+ this.columnsHeader = new JLabel( CsvUtil.R("CSVColumnAllocationPanel.columns.label") );
+ columnsHeader.setFont(HEADER_FONT);
+
+ init(fields,csvColumns,null);
+ }
+
+ /**
+ * Creates a new allocation panel.
+ * @param fieldHeaderCaption short description/title for application depending fields (first column)
+ * @param fields list of fields (entry is used as ID and GUI label);
+ * for each entry a combo box is created to allocate a CSV column
+ * @param csvColumns list of CSV column names which can be allocated to the fields
+ */
+ public CSVColumnAllocationPanel(String fieldHeaderCaption, List<String> fields, List<String> csvColumns) {
+ this( fieldHeaderCaption, LangUtil.convertToMap(fields), csvColumns );
+ }
+
+ /**
+ * Creates a new allocation panel. The panel is empty. One of the
+ * {@code init(.)}-methods must be called.
+ * @param fieldHeaderCaption short description/title for application depending fields (first column)
+ * @see #init(Map, List)
+ * @see #init(List, List)
+ */
+ public CSVColumnAllocationPanel(String fieldHeaderCaption) {
+ this( fieldHeaderCaption, (Map<String,String>)null, null );
+ }
+
+ /**
+ * Creates a new allocation panel. The panel is empty. One of the
+ * {@code init(.)}-methods must be called.
+ * @see #init(Map, List)
+ * @see #init(List, List)
+ */
+ public CSVColumnAllocationPanel() {
+ this("");
+ }
+
+
+ /**
+ * Initializes the panel with a new set of fields.
+ * @param fields map of fields (key = field ID; value = description for GUI label);
+ * for each entry a combo box is created to allocate a CSV column
+ * @param csvColumns list of CSV column names which can be allocated to the fields
+ * @param defaultMapping default CSV column names by field (ID); can be {@code null}
+ */
+ public void init(Map<String,String> fields, List<String> csvColumns, Map<String,String> defaultMapping) {
+ allocationCaptions.clear();
+ allocationColumns.clear();
+ removeAll();
+ if ( fields == null )
+ return;
+
+ // Add header fields
+ add(fieldsHeader,"");
+ add(columnsHeader,"growx");
+ // Add row field for each field defined in the map
+ String[] csvColumnArray = csvColumns.toArray(new String[0]);
+ for (String fieldID : fields.keySet()) {
+ String fieldCaptionStr = fields.get(fieldID);
+ JLabel fieldCaption = new JLabel(fieldCaptionStr);
+ String defaultValue = fieldID; // naive try "CSV column name equals field ID"
+ SelectionInputOption.Combo<String> fieldColumn = new SelectionInputOption.Combo<String>(
+ null, false, csvColumnArray, defaultValue, null);
+ allocationCaptions.put(fieldID, fieldCaption);
+ allocationColumns.put(fieldID, fieldColumn);
+
+ add(fieldCaption,"");
+ add(fieldColumn,"growx");
+ }
+
+ setMapping(defaultMapping, true);
+ }
+
+ /**
+ * Initializes the panel with a new set of fields.
+ * @param fields list of fields (entry is used as ID and GUI label);
+ * for each entry a combo box is created to allocate a CSV column
+ * @param csvColumns list of CSV column names which can be allocated to the fields
+ * @param defaultMapping default CSV column names by field (ID); can be {@code null}
+ */
+ public void init(List<String> fields, List<String> csvColumns, Map<String,String> defaultMapping) {
+ init( LangUtil.convertToMap(fields), csvColumns, defaultMapping );
+ }
+
+
+ /**
+ * Sets the header label above the field descriptions.
+ */
+ public void setFieldsHeaderCaption(String caption) {
+ this.fieldsHeader.setText(caption);
+ }
+
+
+ /**
+ * Returns the header label above the field descriptions.
+ */
+ public String getFieldsHeaderCaption() {
+ return this.fieldsHeader.getText();
+ }
+
+ /**
+ * Returns the mapping specified by the input fields. The map key identifies
+ * the field (field id) and the value represents the allocated CSV column.
+ */
+ public Map<String,String> getMappingFieldToCsv() {
+ Map<String,String> allocation = new SequentialOrderedMap<String, String>();
+ for (String fieldID : allocationColumns.keySet()) {
+ SelectionInputOption.Combo<String> fieldColumn = allocationColumns.get(fieldID);
+ String columnName = (String)fieldColumn.getValue();
+ allocation.put(fieldID, columnName);
+ }
+ return allocation;
+ }
+
+ /**
+ * Sets the mapping between field (IDs) and CSV column.
+ * @param mapping mapping between field (IDs) and CSV column
+ * @param ignoreNulls indicates whether {@code null} values are ignored
+ * or applied to combo box
+ */
+ public void setMapping(Map<String,String> mapping, boolean ignoreNulls) {
+ for (String fieldID : allocationColumns.keySet()) {
+ SelectionInputOption.Combo<String> fieldColumn = allocationColumns.get(fieldID);
+ String defaultValue = mapping != null ? mapping.get(fieldID) : null;
+ if ( !ignoreNulls || defaultValue != null )
+ fieldColumn.setValue(defaultValue);
+ }
+ }
+
+ /**
+ * Returns the mapping specified by the input fields. The map key identifies
+ * the CSV column and the value the corresponding field (field id).
+ */
+ public Map<String,String> getMappingCsvToField() {
+ Map<String,String> allocation = new SequentialOrderedMap<String, String>();
+ for (String fieldID : allocationColumns.keySet()) {
+ SelectionInputOption.Combo<String> fieldColumn = allocationColumns.get(fieldID);
+ String columnName = (String)fieldColumn.getValue();
+ if ( columnName != null )
+ allocation.put(columnName,fieldID);
+ }
+ return allocation;
+ }
+}
Added: trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewDialog.java
===================================================================
--- trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewDialog.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewDialog.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,198 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv.gui;
+
+import java.awt.BorderLayout;
+import java.awt.Dialog;
+import java.awt.Dimension;
+import java.awt.Frame;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+
+import de.schmitzm.swing.OkCancelDialog;
+import de.schmitzm.swing.SwingUtil;
+
+/**
+ * Dialog to specify CSV parameters (delimiter, decimal sign, text quote sign and
+ * Charset). The panel shows a preview table which is automatically updated when
+ * the parameters change. The CSV input source (e.g. file) can not be specified
+ * by panel, but must specified statically.
+ * @author Martin O.J. Schmitz
+ *
+ */
+public class CSVPreviewDialog extends OkCancelDialog {
+ /** Holds the preview panel */
+ protected CSVPreviewPanel previewPanel;
+
+ /**
+ * Creates a new dialog
+ * @param owner parent component
+ * @param title dialog title
+ */
+ public CSVPreviewDialog(Frame owner, String title) {
+ super(owner, title, true);
+ }
+
+ /**
+ * Creates a new dialog
+ * @param owner parent component
+ * @param title dialog title
+ */
+ public CSVPreviewDialog(Dialog owner, String title) {
+ super(owner, title, true);
+ }
+
+ /**
+ * Called immediately by the constructor to initialize the
+ * dialog.
+ */
+ @Override
+ protected void init() {
+ super.init();
+ setPreferredSize( new Dimension(800,500) );
+
+ this.previewPanel = new CSVPreviewPanel();
+ getContentPane().add(previewPanel, BorderLayout.CENTER);
+
+ pack();
+ SwingUtil.setRelativeFramePosition(this, getOwner(), 0.5, 0.5);
+ }
+
+ /**
+ * Returns a byte stream which contains the source used
+ * to generate the preview. This is NOT the original stream set by
+ * {@link #setSource(InputStream)}, because this stream is only read once
+ * and buffered internally.
+ */
+ public InputStream getSource() {
+ return previewPanel.getSource();
+ }
+
+ /**
+ * Sets the data source used to generate the preview.
+ * The preview is automatically updated after changing the parameters.
+ */
+ public void setSource(InputStream inputStream) {
+ previewPanel.setSource(inputStream);
+ }
+
+
+ /**
+ * Returns the row limit for the CSV preview.
+ * @return -1 for no limit
+ */
+ public int getPreviewLimit() {
+ return previewPanel.getPreviewLimit();
+ }
+
+ /**
+ * Sets the row limit for the CSV preview. If limit is reduced the
+ * current preview is simply cut. Otherwise the preview is completely
+ * renewed.
+ * @param limit maximum number of rows (-1 for no limit)
+ */
+ public void setPreviewLimit(int limit) {
+ previewPanel.setPreviewLimit(limit);
+ }
+
+ /**
+ * Returns the first row for the CSV preview (>=1).
+ */
+ public int getPreviewFirstLine() {
+ return previewPanel.getPreviewFirstLine();
+ }
+
+ /**
+ * Sets the first row for the CSV preview.
+ * @param firstLine first CSV data line shown in preview (>=1)
+ */
+ public void setPreviewFirstLine(int firstLine) {
+ previewPanel.setPreviewFirstLine(firstLine);
+ }
+
+ /**
+ * Returns the CSV delimiter used to generate the preview.
+ */
+ public char getCsvDelimiter() {
+ return previewPanel.getCsvDelimiter();
+ }
+
+ /**
+ * Returns the CSV decimal sign used to generate the preview.
+ */
+ public char getCsvDecimalSign() {
+ return previewPanel.getCsvDecimalSign();
+ }
+
+
+ /**
+ * Returns the CSV text quote sign used to generate the preview.
+ */
+ public char getCsvQuoteSign() {
+ return previewPanel.getCsvQuoteSign();
+ }
+
+ /**
+ * Returns the "no data" value used to generate the preview.
+ */
+ public String getCsvNoDataValue() {
+ return previewPanel.getNoDataValue();
+ }
+
+ /**
+ * Returns the CSV {@link Charset} used to generate the preview.
+ */
+ public Charset getCsvCharset() {
+ return previewPanel.getCsvCharset();
+ }
+
+ /**
+ * Returns the CSV column named according to the current
+ * configuration / preview.
+ */
+ public String[] getCsvColumns() {
+ return previewPanel.getCsvColumns();
+ }
+
+ /**
+ * Sets the CSV parameter used to generate the preview. If a method
+ * parameter is {@code null}, the respective parameter remains unchanged.
+ * The preview is automatically updated after changing the parameters.
+ * @param delimiter CSV delimiter used to generate the preview.
+ * @param decimalSign decimal sign used to generate the preview.
+ * @param quoteSign CSV text quote sign used to generate the preview.
+ * @param charset {@link Charset} used to generate the preview.
+ * @param noData value indicating "no data"
+ */
+ public void setCsvParameters(Character delimiter, Character decimalSign, Character quoteSign, Charset charset, String noData) {
+ previewPanel.setCsvParameters(delimiter, decimalSign, quoteSign, charset, noData);
+ }
+
+}
Added: trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewPanel.java
===================================================================
--- trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewPanel.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewPanel.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,371 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv.gui;
+
+import java.awt.BorderLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.List;
+
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JScrollPane;
+import javax.swing.JSpinner;
+import javax.swing.JTabbedPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.SwingUtilities;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+
+import net.miginfocom.swing.MigLayout;
+import de.schmitzm.csv.CsvUtil;
+import de.schmitzm.swing.JPanel;
+import de.schmitzm.swing.SwingUtil;
+import de.schmitzm.swing.TextLineNumber;
+import de.schmitzm.swing.input.InputOption;
+import de.schmitzm.swing.input.ManualInputOption;
+import de.schmitzm.swing.input.SelectionInputOption;
+
+/**
+ * Panel to specify CSV parameters (delimiter, decimal sign, text quote sign and
+ * Charset). The panel shows a preview table which is automatically updated when
+ * the parameters change. The CSV input source (e.g. file) can not be specified
+ * by panel, but must specified statically.
+ * @author Martin O.J. Schmitz
+ */
+public class CSVPreviewPanel extends JPanel {
+
+ protected JTabbedPane tabPane = new JTabbedPane();
+ protected JPanel configTab;
+ protected JPanel csvSourceTab;
+
+ protected JLabel delimiterCaption;
+ protected SelectionInputOption.Combo<String> delimiter;
+ protected JLabel decimalSignCaption;
+ protected SelectionInputOption.Combo<String> decimalSign;
+ protected JLabel quoteSignCaption;
+ protected SelectionInputOption.Combo<String> quoteSign;
+ protected JLabel charsetCaption;
+ protected SelectionInputOption.Combo<Charset> charset;
+ protected JLabel noDataCaption;
+ protected ManualInputOption.Text noData;
+ protected JLabel previewCaption;
+ protected CSVPreviewTable preview;
+ protected JLabel limitCaption;
+ protected JSpinner limit;
+ protected JLabel firstLineCaption;
+ protected JSpinner firstLine;
+ protected JTextArea csvSource;
+ protected JScrollPane csvSourceScrollPane;
+
+
+ /**
+ * Creates a new panel.
+ */
+ public CSVPreviewPanel() {
+ super( new BorderLayout() );
+
+
+
+ // create input options to specify the CSV parameters
+ List<InputOption<?>> csvParameterList = CsvUtil.createCSVDialogOptions(
+ false,
+ null,
+ CsvUtil.DEFAULT_CSV_DELIMITER,
+ CsvUtil.DEFAULT_CSV_QUOTESIGN,
+ CsvUtil.DEFAULT_CSV_DECIMALSIGN,
+ CsvUtil.DEFAULT_CSV_CHARSET,
+ CsvUtil.DEFAULT_CSV_NODATA);
+ delimiterCaption = new JLabel( CsvUtil.R("CSVDialogOptions.delim.label")+":" );
+ delimiter = (SelectionInputOption.Combo<String>)csvParameterList.get(1);
+ decimalSignCaption = new JLabel( CsvUtil.R("CSVDialogOptions.decimal.label")+":" );
+ decimalSign = (SelectionInputOption.Combo<String>)csvParameterList.get(2);
+ quoteSignCaption = new JLabel( CsvUtil.R("CSVDialogOptions.quote.label")+":" );
+ quoteSign = (SelectionInputOption.Combo<String>)csvParameterList.get(3);
+ charsetCaption = new JLabel( CsvUtil.R("CSVDialogOptions.charset.label")+":" );
+ charset = (SelectionInputOption.Combo<Charset>)csvParameterList.get(4);
+ noDataCaption = new JLabel( CsvUtil.R("CSVDialogOptions.nodata.label")+":" );
+ noData = (ManualInputOption.Text)csvParameterList.get(5);
+ previewCaption = new JLabel( CsvUtil.R("CSVPreviewPanel.preview.label")+":" );
+ preview = new CSVPreviewTable(10);
+ limitCaption = new JLabel( CsvUtil.R("CSVPreviewPanel.preview.limit.label")+":" );
+ limit = SwingUtil.createIntSpinner(-1, 1000, preview.getPreviewLimit());
+ firstLineCaption = new JLabel( CsvUtil.R("CSVPreviewPanel.preview.firstLine.label")+":" );
+ firstLine = SwingUtil.createIntSpinner(1, 1000, 1);
+ csvSource = new JTextArea();
+ csvSource.setEditable(false);
+ csvSource.setLineWrap(false);
+ csvSourceScrollPane = new JScrollPane(csvSource);
+ csvSourceScrollPane.setRowHeaderView( new TextLineNumber(csvSource) );
+
+ // InputOptionListener reacts only on focus lost, so we use
+ // ActionListener for ComboBoxes
+ ParameterChangeListener changeListener = new ParameterChangeListener();
+ ((JComboBox)delimiter.getInputComponent()).addActionListener(changeListener);
+ ((JComboBox)quoteSign.getInputComponent()).addActionListener(changeListener);
+ ((JComboBox)decimalSign.getInputComponent()).addActionListener(changeListener);
+ ((JComboBox)charset.getInputComponent()).addActionListener(changeListener);
+ ((JTextField)noData.getInputComponent()).getDocument().addDocumentListener(changeListener);
+ limit.addChangeListener(changeListener);
+ firstLine.addChangeListener(changeListener);
+
+ configTab = new JPanel(new MigLayout("wrap 2","[]20[grow]","[grow]"));
+ configTab.add(delimiterCaption,"");
+ configTab.add(delimiter,"w 100::");
+ configTab.add(decimalSignCaption,"");
+ configTab.add(decimalSign,"w 100::");
+ configTab.add(quoteSignCaption,"");
+ configTab.add(quoteSign,"w 100::");
+ configTab.add(noDataCaption,"");
+ configTab.add(noData,"w 100::");
+ configTab.add(charsetCaption,"");
+ configTab.add(charset,"w 100::");
+ configTab.add(previewCaption,"span 2");
+ configTab.add(new JScrollPane(preview),"span 2, growx, growy");
+ configTab.add(limitCaption,"");//"span 2, split 2");
+ configTab.add(limit,"");
+ configTab.add(firstLineCaption,"");//"span 2, split 2");
+ configTab.add(firstLine,"");
+ tabPane.addTab(CsvUtil.R("CSVPreviewPanel.tab.preview"), configTab);
+
+ csvSourceTab = new JPanel(new BorderLayout());
+ csvSourceTab.add(csvSourceScrollPane, BorderLayout.CENTER);
+ tabPane.addTab(CsvUtil.R("CSVPreviewPanel.tab.source"), csvSourceTab);
+
+ add(tabPane,BorderLayout.CENTER);
+ }
+
+ public void updateSourceTab() {
+ csvSource.setText( new String(preview.getModel().csvSourceBuffer,preview.getCsvCharset()) );
+ csvSource.setCaretPosition(0);
+ }
+
+ /**
+ * Returns a byte stream which contains the source used
+ * to generate the preview. This is NOT the original stream set by
+ * {@link #setSource(InputStream)}, because this stream is only read once
+ * and buffered internally.
+ */
+ public InputStream getSource() {
+ return preview.getSource();
+ }
+
+ /**
+ * Sets the data source used to generate the preview.
+ * The preview is automatically updated after changing the parameters.
+ */
+ public void setSource(InputStream inputStream) {
+ preview.setSource(inputStream);
+ updateSourceTab();
+ }
+
+
+ /**
+ * Returns the row limit for the CSV preview.
+ * @return -1 for no limit
+ */
+ public int getPreviewLimit() {
+ return preview.getPreviewLimit();
+ }
+
+ /**
+ * Sets the row limit for the CSV preview. If limit is reduced the
+ * current preview is simply cut. Otherwise the preview is completely
+ * renewed.
+ * @param limit maximum number of rows (-1 for no limit)
+ */
+ public void setPreviewLimit(int limit) {
+ preview.setPreviewLimit(limit);
+ }
+
+ /**
+ * Returns the first row for the CSV preview (>=1).
+ */
+ public int getPreviewFirstLine() {
+ return preview.getPreviewFirstLine();
+ }
+
+ /**
+ * Sets the first row for the CSV preview.
+ * @param firstLine first CSV data line shown in preview (>=1)
+ */
+ public void setPreviewFirstLine(int firstLine) {
+ preview.setPreviewFirstLine(firstLine);
+ }
+
+ /**
+ * Returns the CSV delimiter used to generate the preview.
+ */
+ public char getCsvDelimiter() {
+ return preview.getCsvDelimiter();
+ }
+
+ /**
+ * Returns the CSV decimal sign used to generate the preview.
+ */
+ public char getCsvDecimalSign() {
+ return preview.getCsvDecimalSign();
+ }
+
+
+ /**
+ * Returns the CSV text quote sign used to generate the preview.
+ */
+ public char getCsvQuoteSign() {
+ return preview.getCsvQuoteSign();
+ }
+
+ /**
+ * Returns the CSV {@link Charset} used to generate the preview.
+ */
+ public Charset getCsvCharset() {
+ return preview.getCsvCharset();
+ }
+
+ /**
+ * Returns the CSV column named according to the current
+ * configuration / preview.
+ */
+ public String[] getCsvColumns() {
+ return preview.getCsvColumns();
+ }
+
+ /**
+ * Returns the "no data" value used to generate the preview.
+ */
+ public String getNoDataValue() {
+ return preview.getNoDataValue();
+ }
+
+
+ /**
+ * Sets the CSV parameter used to generate the preview. If a method
+ * parameter is {@code null}, the respective parameter remains unchanged.
+ * The preview is automatically updated after changing the parameters.
+ * @param delimiter CSV delimiter used to generate the preview.
+ * @param decimalSign decimal sign used to generate the preview.
+ * @param quoteSign CSV text quote sign used to generate the preview.
+ * @param charset {@link Charset} used to generate the preview.
+ * @param noData value indicating no data value
+ */
+ public void setCsvParameters(Character delimiter, Character decimalSign, Character quoteSign, Charset charset, String noData) {
+ if ( delimiter != null )
+ this.delimiter.setValue(delimiter.toString());
+ if ( decimalSign != null )
+ this.decimalSign.setValue(decimalSign.toString());
+ if ( quoteSign != null )
+ this.quoteSign.setValue(quoteSign.toString());
+ if ( charset != null )
+ this.charset.setValue(charset);
+ if ( noData != null )
+ this.noData.setValue(noData);
+ preview.setCsvParameters(delimiter, decimalSign, quoteSign, charset, noData);
+ updateSourceTab();
+ }
+
+ /**
+ * Listener whichs reacts on changes of CSV parameter GUI components with
+ * update of preview table.
+ * @author Martin O.J. Schmitz
+ *
+ */
+ protected class ParameterChangeListener implements ActionListener, ChangeListener, DocumentListener {
+ protected void invokeLaterCsvParametersUpdate() {
+ SwingUtilities.invokeLater( new Runnable() {
+ @Override
+ public void run() {
+ preview.setCsvParameters(((String)delimiter.getValue()).charAt(0),
+ ((String)decimalSign.getValue()).charAt(0),
+ ((String)quoteSign.getValue()).charAt(0),
+ (Charset)charset.getValue(),
+ (String)noData.getValue());
+ updateSourceTab();
+ }
+ });
+ }
+
+ /**
+ * Reacts on {@link JComboBox} value changes with update of preview
+ * table.
+ */
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if ( e.getSource() == delimiter.getInputComponent() ||
+ e.getSource() == decimalSign.getInputComponent() ||
+ e.getSource() == quoteSign.getInputComponent() ||
+ e.getSource() == charset.getInputComponent() )
+ invokeLaterCsvParametersUpdate();
+ }
+
+ /**
+ * Reacts on {@link JSpinner} value changes with update of preview
+ * table.
+ */
+ @Override
+ public void stateChanged(final ChangeEvent e) {
+ if ( e.getSource() == limit ||
+ e.getSource() == firstLine )
+ SwingUtilities.invokeLater( new Runnable() {
+ @Override
+ public void run() {
+ if ( e.getSource() == limit )
+ preview.setPreviewLimit((Integer)limit.getValue());
+ if ( e.getSource() == firstLine )
+ preview.setPreviewFirstLine((Integer)firstLine.getValue());
+ }
+ });
+ }
+
+ @Override
+ public void insertUpdate(DocumentEvent e) {
+ if ( e.getDocument() == ((JTextField)noData.getInputComponent()).getDocument() )
+ invokeLaterCsvParametersUpdate();
+ }
+
+ @Override
+ public void removeUpdate(DocumentEvent e) {
+ if ( e.getDocument() == ((JTextField)noData.getInputComponent()).getDocument() )
+ invokeLaterCsvParametersUpdate();
+ }
+
+
+ @Override
+ public void changedUpdate(DocumentEvent e) {
+ }
+
+ }
+
+
+}
Added: trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewTable.java
===================================================================
--- trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewTable.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/java/de/schmitzm/csv/gui/CSVPreviewTable.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,663 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv.gui;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Vector;
+
+import org.supercsv.cellprocessor.ift.CellProcessor;
+import org.supercsv.io.ICsvMapReader;
+
+import de.schmitzm.csv.CsvUtil;
+import de.schmitzm.io.IOUtil;
+import de.schmitzm.swing.ExceptionDialog;
+import de.schmitzm.swing.SortableJTable;
+import de.schmitzm.swing.SwingUtil;
+import de.schmitzm.swing.table.AbstractTableModel;
+
+/**
+ * Table which shows CSV data as preview. If CSV parameters are changed (e.g. delimiter)
+ * the table is updated automatically.
+ * @author Martin O.J. Schmitz
+ */
+public class CSVPreviewTable extends SortableJTable {
+
+ /**
+ * Creates a new table.
+ * @param model
+ */
+ public CSVPreviewTable(CSVPreviewTableModel model) {
+ super(model);
+// setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
+ getTableHeader().setDefaultRenderer( SwingUtil.createTableColumnHeaderRendererWithColumnTypes(null) );
+ setAutoGrowColums(true);
+ }
+
+ /**
+ * Creates an empty table with defaults defined in
+ * {@link CsvUtil} and no preview limit.
+ * @see CsvUtil#DEFAULT_CSV_DELIMITER
+ * @see CsvUtil#DEFAULT_CSV_DECIMALSIGN
+ * @see CsvUtil#DEFAULT_CSV_QUOTESIGN
+ * @see CsvUtil#DEFAULT_CSV_CHARSET
+ * @see CsvUtil#DEFAULT_CSV_NODATA
+ */
+ public CSVPreviewTable() {
+ this(new CSVPreviewTableModel());
+ }
+
+ /**
+ * Creates an empty table with defaults defined in
+ * {@link CsvUtil}.
+ * @param limit limit for row preview
+ * @see CsvUtil#DEFAULT_CSV_DELIMITER
+ * @see CsvUtil#DEFAULT_CSV_DECIMALSIGN
+ * @see CsvUtil#DEFAULT_CSV_QUOTESIGN
+ * @see CsvUtil#DEFAULT_CSV_CHARSET
+ * @see CsvUtil#DEFAULT_CSV_NODATA
+ */
+ public CSVPreviewTable(int limit) {
+ this(new CSVPreviewTableModel(limit));
+ }
+
+ /**
+ * Creates a new table with defaults defined in
+ * {@link CsvUtil}.
+ * @param source data source for CSV preview
+ * @param limit limit for row preview
+ * @see CsvUtil#DEFAULT_CSV_DELIMITER
+ * @see CsvUtil#DEFAULT_CSV_DECIMALSIGN
+ * @see CsvUtil#DEFAULT_CSV_QUOTESIGN
+ * @see CsvUtil#DEFAULT_CSV_CHARSET
+ * @see CsvUtil#DEFAULT_CSV_NODATA
+ */
+ public CSVPreviewTable(InputStream source, int limit) {
+ this(new CSVPreviewTableModel(source,limit));
+ }
+
+ /**
+ * Creates a new table model.
+ * @param source data source for CSV preview
+ * @param delimiter CSV delimiter used for preview import
+ * @param decimalSign decimal sign used for preview import
+ * @param quoteSign CSV text quote sign used for preview import
+ * @param charset {@link Charset} used for preview import
+ * @param noData value indicating no data value
+ * @param limit limit for row preview
+ */
+ public CSVPreviewTable(InputStream source, char delimiter, char decimalSign, char quoteSign, Charset charset, String noData, int limit) {
+ this(new CSVPreviewTableModel(source,
+ delimiter,
+ decimalSign,
+ quoteSign,
+ charset,
+ noData,
+ limit));
+ }
+
+ /**
+ * Returns the table model.
+ */
+ public CSVPreviewTableModel getModel() {
+ return (CSVPreviewTableModel)super.getModel();
+ }
+
+ /**
+ * Returns a byte stream which contains the source used
+ * to generate the preview. This is NOT the original stream set by
+ * {@link #setSource(InputStream)}, because this stream is only read once
+ * and buffered internally.
+ */
+ public InputStream getSource() {
+ return getModel().getSource();
+ }
+
+ /**
+ * Returns the row limit for the CSV preview.
+ * @return -1 for no limit
+ */
+ public int getPreviewLimit() {
+ return getModel().getPreviewLimit();
+ }
+
+ /**
+ * Returns the first data row for the CSV preview (>=1).
+ */
+ public int getPreviewFirstLine() {
+ return getModel().getPreviewFirstLine();
+ }
+
+ /**
+ * Returns the CSV delimiter used to generate the preview.
+ */
+ public char getCsvDelimiter() {
+ return getModel().getCsvDelimiter();
+ }
+
+ /**
+ * Returns the CSV decimal sign used to generate the preview.
+ */
+ public char getCsvDecimalSign() {
+ return getModel().getCsvDecimalSign();
+ }
+
+
+ /**
+ * Returns the CSV text quote sign used to generate the preview.
+ */
+ public char getCsvQuoteSign() {
+ return getModel().getCsvQuoteSign();
+ }
+
+ /**
+ * Returns the CSV {@link Charset} used to generate the preview.
+ */
+ public Charset getCsvCharset() {
+ return getModel().getCsvCharset();
+ }
+
+ /**
+ * Returns the "no data" value used to generate the preview.
+ */
+ public String getNoDataValue() {
+ return getModel().getNoDataValue();
+ }
+
+ /**
+ * Returns the CSV column named according to the current
+ * configuration / preview.
+ */
+ public String[] getCsvColumns() {
+ return getModel().getColumnNames();
+ }
+
+ /**
+ * Sets the data source used to generate the preview.
+ * The preview is automatically updated after changing the parameter.
+ */
+ public void setSource(InputStream inputStream) {
+ try {
+ SwingUtil.setWaitCursor(this);
+ getModel().setSource(inputStream);
+ } finally {
+ SwingUtil.resetCursor(this);
+ }
+ }
+
+ /**
+ * Sets the row limit for the CSV preview. If limit is reduced the
+ * current preview is simply cut. Otherwise the preview is completely
+ * renewed.
+ * @param limit maximum number of rows (-1 for no limit)
+ */
+ public void setPreviewLimit(int limit) {
+ try {
+ SwingUtil.setWaitCursor(this);
+ getModel().setPreviewLimit(limit);
+ } finally {
+ SwingUtil.resetCursor(this);
+ }
+ }
+
+ /**
+ * Sets the first data row for the CSV preview.
+ * The preview is automatically updated after changing the parameter.
+ * @param firstLine first CSV data line shown in preview (>=1)
+ */
+ public void setPreviewFirstLine(int firstLine) {
+ try {
+ SwingUtil.setWaitCursor(this);
+ getModel().setPreviewFirstLine(firstLine);
+ } finally {
+ SwingUtil.resetCursor(this);
+ }
+ }
+
+ /**
+ * Sets the CSV parameter used to generate the preview. If a method
+ * parameter is {@code null}, the respective parameter remains unchanged.
+ * The preview is automatically updated after changing the parameters.
+ * @param delimiter CSV delimiter used to generate the preview.
+ * @param decimalSign decimal sign used to generate the preview.
+ * @param quoteSign CSV text quote sign used to generate the preview.
+ * @param charset {@link Charset} used to generate the preview.
+ * @param noData value indicating no data value
+ */
+ public void setCsvParameters(Character delimiter, Character decimalSign, Character quoteSign, Charset charset, String noData) {
+ try {
+ SwingUtil.setWaitCursor(this);
+ getModel().setCsvParameters(delimiter, decimalSign, quoteSign, charset, noData);
+ } finally {
+ SwingUtil.resetCursor(this);
+ }
+ }
+
+ /**
+ * Updates the CSV preview according to the current CSV parameters and
+ * input stream.
+ */
+ public void updatePreview() {
+ try {
+ SwingUtil.setWaitCursor(this);
+ getModel().updatePreview();
+ } finally {
+ SwingUtil.resetCursor(this);
+ }
+ }
+
+
+
+
+ /**
+ * Table model for the CSV preview table.
+ * @see CSVPreviewTable
+ * @author Martin O.J. Schmitz
+ */
+ public static class CSVPreviewTableModel extends AbstractTableModel {
+ /** Holds the header of */
+ protected String[] previewCsvHeader = null;
+ /** Holds the header of */
+ protected Map<String,Class<?>> previewCsvClasses = new HashMap<String, Class<?>>();
+ /** Holds the preview data generated from CSV file. */
+ protected Vector<Map<?,?>> previewCsvData = new Vector<Map<?,?>>();
+ /** Holds a row limit for the displayed preview (-1 for no limit). */
+ protected int previewRowLimit = -1;
+ /** Holds a first CSV data line used for the displayed preview (>=1). */
+ protected int previewFirstLine = 1;
+ /** Buffers the source stream used to re-generate the preview. */
+ protected byte[] csvSourceBuffer = null;
+ /** Holds the CSV delimiter used to generate the preview. */
+ protected char csvDelimiter = ';';
+ /** Holds the CSV decimal sign used to generate the preview. */
+ protected char csvDecimalSign = ',';
+ /** Holds the CSV text quote sign used to generate the preview. */
+ protected char csvQuoteSign = '"';
+ /** Holds the value indicating "No Data" used to generate the preview. */
+ protected String noDataValue = "";
+ /** Holds the CSV {@link Charset} used to generate the preview. */
+ protected Charset csvCharset = Charset.defaultCharset();
+
+ /**
+ * Creates an empty table model with defaults defined in
+ * {@link CsvUtil} and no preview limit.
+ * @see CsvUtil#DEFAULT_CSV_DELIMITER
+ * @see CsvUtil#DEFAULT_CSV_DECIMALSIGN
+ * @see CsvUtil#DEFAULT_CSV_QUOTESIGN
+ * @see CsvUtil#DEFAULT_CSV_CHARSET
+ * @see CsvUtil#DEFAULT_CSV_NODATA
+ */
+ public CSVPreviewTableModel() {
+ this(null,-1);
+ }
+
+ /**
+ * Creates an empty table model with defaults defined in
+ * {@link CsvUtil}.
+ * @param limit limit for row preview
+ * @see CsvUtil#DEFAULT_CSV_DELIMITER
+ * @see CsvUtil#DEFAULT_CSV_DECIMALSIGN
+ * @see CsvUtil#DEFAULT_CSV_QUOTESIGN
+ * @see CsvUtil#DEFAULT_CSV_CHARSET
+ * @see CsvUtil#DEFAULT_CSV_NODATA
+ */
+ public CSVPreviewTableModel(int limit) {
+ this(null,limit);
+ }
+
+ /**
+ * Creates a new table model with defaults defined in
+ * {@link CsvUtil}.
+ * @param source data source for CSV preview
+ * @param limit limit for row preview
+ * @see CsvUtil#DEFAULT_CSV_DELIMITER
+ * @see CsvUtil#DEFAULT_CSV_DECIMALSIGN
+ * @see CsvUtil#DEFAULT_CSV_QUOTESIGN
+ * @see CsvUtil#DEFAULT_CSV_CHARSET
+ * @see CsvUtil#DEFAULT_CSV_NODATA
+ */
+ public CSVPreviewTableModel(InputStream source, int limit) {
+ this(source,
+ CsvUtil.DEFAULT_CSV_DELIMITER,
+ CsvUtil.DEFAULT_CSV_DECIMALSIGN,
+ CsvUtil.DEFAULT_CSV_QUOTESIGN,
+ CsvUtil.DEFAULT_CSV_CHARSET,
+ CsvUtil.DEFAULT_CSV_NODATA,
+ limit);
+ }
+
+ /**
+ * Creates a new table model.
+ * @param source data source for CSV preview
+ * @param delimiter CSV delimiter used for preview import
+ * @param decimalSign decimal sign used for preview import
+ * @param quoteSign CSV text quote sign used for preview import
+ * @param charset {@link Charset} used for preview import
+ * @param noData value indicating no data value
+ * @param limit limit for row preview
+ */
+ public CSVPreviewTableModel(InputStream source, char delimiter, char decimalSign, char quoteSign, Charset charset, String noData, int limit) {
+ super();
+ setSource(source,false);
+ setPreviewLimit(limit, false);
+ setCsvParameters(delimiter, decimalSign, quoteSign, charset, noData);
+ }
+
+ /**
+ * Creates the header column names for the preview.
+ */
+ @Override
+ public String[] createColumnNames() {
+ if ( previewCsvHeader == null )
+ return new String[0];
+ return previewCsvHeader;
+ }
+
+ /**
+ * Returns the number of preview rows
+ */
+ @Override
+ public int getRowCount() {
+ return previewCsvData.size();
+ }
+
+ /**
+ * Returns the type for a column.
+ */
+ @Override
+ public Class getColumnClass(int col) {
+ Class<?> type = previewCsvClasses.get( previewCsvHeader[col] );
+ return type != null ? type : Object.class;
+ }
+
+ /**
+ * Returns the type for a column.
+ */
+ @Override
+ public String getColumnName(int col) {
+ String name = super.getColumnName(col);
+ name = "<html>"+name+"</html>";
+ return name;
+ }
+
+ /**
+ * Returns a value of the preview data.
+ */
+ @Override
+ public Object getValueAt(int row, int col) {
+ Map<?, ?> csvLine = previewCsvData.get(row);
+ String colName = previewCsvHeader[col];
+ return csvLine.get(colName);
+ }
+
+ /**
+ * Returns a {@link ByteArrayInputStream} which contains the source used
+ * to generate the preview. This is NOT the original stream set by
+ * {@link #setSource(InputStream)}, because this stream is only read once
+ * and buffered internally.
+ */
+ public InputStream getSource() {
+ if ( csvSourceBuffer == null )
+ return null;
+ return new ByteArrayInputStream(csvSourceBuffer);
+ }
+
+ /**
+ * Returns the row limit for the CSV preview.
+ * @return -1 for no limit
+ */
+ public int getPreviewLimit() {
+ return previewRowLimit;
+ }
+
+ /**
+ * Returns the first data row for the CSV preview (>=1).
+ */
+ public int getPreviewFirstLine() {
+ return previewFirstLine;
+ }
+
+ /**
+ * Returns the CSV delimiter used to generate the preview.
+ */
+ public char getCsvDelimiter() {
+ return csvDelimiter;
+ }
+
+ /**
+ * Returns the CSV decimal sign used to generate the preview.
+ */
+ public char getCsvDecimalSign() {
+ return csvDecimalSign;
+ }
+
+
+ /**
+ * Returns the CSV text quote sign used to generate the preview.
+ */
+ public char getCsvQuoteSign() {
+ return csvQuoteSign;
+ }
+
+ /**
+ * Returns the CSV {@link Charset} used to generate the preview.
+ */
+ public Charset getCsvCharset() {
+ return csvCharset;
+ }
+
+ /**
+ * Returns the "no data" value used to generate the preview.
+ */
+ public String getNoDataValue() {
+ return noDataValue;
+ }
+
+ /**
+ * Sets the data source used to generate the preview.
+ * The preview is automatically updated after changing the parameter.
+ */
+ public void setSource(InputStream inputStream) {
+ setSource(inputStream,true);
+ }
+
+ /**
+ * Sets the data source used to generate the preview.
+ * @param updatePreview indicates whether preview is updated immediately
+ */
+ public void setSource(InputStream inputStream, boolean updatePreview) {
+ try {
+ if ( inputStream == null )
+ this.csvSourceBuffer = null;
+ else {
+ this.csvSourceBuffer = new byte[inputStream != null ? inputStream.available() : 0];
+ inputStream.read(csvSourceBuffer);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ IOUtil.closeInputStream(inputStream);
+ }
+ if ( updatePreview )
+ updatePreview();
+ }
+
+ /**
+ * Sets the row limit for the CSV preview. If limit is reduced the
+ * current preview is simply cut. Otherwise the preview is completely
+ * renewed.
+ * @param limit maximum number of rows (-1 for no limit)
+ */
+ public void setPreviewLimit(int limit) {
+ setPreviewLimit(limit, true);
+ }
+
+ /**
+ * Sets the row limit for the CSV preview. If limit is reduced the
+ * current preview is simply cut. Otherwise the preview is completely
+ * renewed.
+ * @param limit maximum number of rows (-1 for no limit)
+ * @param updatePreview indicates whether preview is updated immediately
+ */
+ public void setPreviewLimit(int limit, boolean updatePreview) {
+ if ( limit == getPreviewLimit() )
+ return;
+ this.previewRowLimit = limit;
+
+ // if limit is set to no limit, update complete data
+ if ( updatePreview ) {
+ if ( limit < 0 )
+ updatePreview();
+ else {
+ // if limit reduces the current size, simply cut the
+ // data (without total renew)
+ if ( limit < getRowCount() ) {
+ previewCsvData.setSize(limit);
+ fireTableDataChanged();
+ } else
+ updatePreview();
+ }
+ }
+ }
+
+ /**
+ * Sets the first data row for the CSV preview.
+ * The preview is automatically updated after changing the parameter.
+ * @param firstLine first CSV data line shown in preview (>=1)
+ */
+ public void setPreviewFirstLine(int firstLine) {
+ setPreviewFirstLine(firstLine, true);
+ }
+
+ /**
+ * Sets the first data row for the CSV preview.
+ * @param firstLine first CSV data line shown in preview (>=1)
+ */
+ public void setPreviewFirstLine(int firstLine, boolean updatePreview) {
+ this.previewFirstLine = Math.max(1, firstLine);
+ if ( updatePreview )
+ updatePreview();
+ }
+
+ /**
+ * Sets the CSV parameter used to generate the preview. If a method
+ * parameter is {@code null}, the respective parameter remains unchanged.
+ * The preview is automatically updated after changing the parameters.
+ * @param delimiter CSV delimiter used to generate the preview.
+ * @param decimalSign decimal sign used to generate the preview.
+ * @param quoteSign CSV text quote sign used to generate the preview.
+ * @param charset {@link Charset} used to generate the preview.
+ * @param noData value indicating no data value
+ */
+ public void setCsvParameters(Character delimiter, Character decimalSign, Character quoteSign, Charset charset, String noData) {
+ setCsvParameters(delimiter, decimalSign, quoteSign, charset, noData, true);
+ }
+
+ /**
+ * Sets the CSV parameter used to generate the preview. If a method
+ * parameter is {@code null}, the respective parameter remains unchanged.
+ * @param delimiter CSV delimiter used to generate the preview.
+ * @param decimalSign decimal sign used to generate the preview.
+ * @param quoteSign CSV text quote sign used to generate the preview.
+ * @param charset {@link Charset} used to generate the preview.
+ * @param updatePreview indicates whether preview is updated immediately
+ * @param noData value indicating no data value
+ */
+ public void setCsvParameters(Character delimiter, Character decimalSign, Character quoteSign, Charset charset, String noData, boolean updatePreview) {
+ if ( delimiter != null )
+ this.csvDelimiter = delimiter;
+ if ( decimalSign != null )
+ this.csvDecimalSign = decimalSign;
+ if ( quoteSign != null )
+ this.csvQuoteSign = quoteSign;
+ if ( charset != null )
+ this.csvCharset = charset;
+ if ( noData != null )
+ this.noDataValue = noData;
+ if ( updatePreview )
+ updatePreview();
+ }
+
+ /**
+ * Updates the CSV preview according to the current CSV parameters and
+ * input stream.
+ */
+ public void updatePreview() {
+ previewCsvData.clear();
+ previewCsvClasses.clear();
+ InputStream input = getSource();
+ if ( input == null )
+ return;
+ ICsvMapReader inFile = null;
+ try {
+ try {
+ inFile = CsvUtil.createCsvMapReader(input, getCsvDelimiter(), getCsvQuoteSign(), getCsvCharset());
+ previewCsvHeader = inFile.getCSVHeader(true);
+ CellProcessor[] cps = CsvUtil.createNullConverterCellProcessors(previewCsvHeader,getNoDataValue());
+ // Import lines
+ int recordNo;
+ Map colValues;
+ int previewLastLine = previewFirstLine+previewRowLimit-1;
+ for (recordNo = 1; (colValues = inFile.read(previewCsvHeader,cps)) != null && (previewRowLimit<0 || recordNo<=previewLastLine); recordNo++) {
+ if ( recordNo < previewFirstLine )
+ continue;
+ colValues = CsvUtil.convertNumericValues(colValues, getCsvDecimalSign());
+ // determine column classes if not yet determined for all columns
+ if ( previewCsvClasses.size() < previewCsvHeader.length ) {
+ for (String colName : previewCsvHeader) {
+ Object colValue = colValues.get(colName);
+ if ( previewCsvClasses.get(colName) == null && colValue != null ) {
+ previewCsvClasses.put(colName, colValue.getClass());
+ }
+ }
+ }
+ previewCsvData.add(colValues);
+ }
+ } finally {
+ if ( inFile != null )
+ inFile.close();
+ updateColumnStructure();
+ }
+ } catch (Exception e) {
+ ExceptionDialog.show(null,
+ e,
+ CsvUtil.R("CSVPreviewTableModel.error.title"),
+ CsvUtil.R("CSVPreviewTableModel.error.mess")+":\n"+e.getMessage());
+ }
+ }
+
+
+ }
+
+}
Added: trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle.properties
===================================================================
--- trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle.properties (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle.properties 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,60 @@
+##########
+#Copyright (c) 2009 Martin O. J. Schmitz.
+#
+#This file is part of the SCHMITZM library - a collection of utility
+#classes based on Java 1.6, focusing (not only) on Java Swing
+#and the Geotools library.
+#
+#The SCHMITZM project is hosted at:
+#http://wald.intevation.org/projects/schmitzm/
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU Lesser General Public License
+#as published by the Free Software Foundation; either version 3
+#of the License, or (at your option) any later version.
+#
+#This program is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+#GNU General Public License for more details.
+#
+#You should have received a copy of the GNU Lesser General Public License (license.txt)
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#or try this link: http://www.gnu.org/licenses/lgpl.html
+#
+#Contributors:
+# Martin O. J. Schmitz - initial API and implementation
+# Stefan A. Tzeggai - additional utility classes
+##########
+
+# -----------------------------------------------------------
+# ------ Default Translations (english) for components ------
+# ------ in Package de.schmitzm.csv ------
+# -----------------------------------------------------------
+
+CSVDialogOptions.file.label=CSV file
+CSVDialogOptions.delim.label=CSV delimiter character
+CSVDialogOptions.delim.tab.desc=Tab (\\t)
+CSVDialogOptions.delim.semicolon.desc=Semicolon (;)
+CSVDialogOptions.delim.pipe.desc=Pipe (|)
+CSVDialogOptions.delim.comma.desc=Comma (,)
+CSVDialogOptions.quote.label=CSV text quote character
+CSVDialogOptions.decimal.label=CSV decimal sign
+CSVDialogOptions.charset.label=Character set of file
+CSVDialogOptions.charset.cp850.desc=Codepage 850 (Windows)
+CSVDialogOptions.charset.cp1252.desc=Codepage 1252 (Windows)
+CSVDialogOptions.charset.utf8.desc=UTF-8 (modern OS, e.g. Linux)
+CSVDialogOptions.charset.iso-8859-15.desc=ISO-8859-15 Western Europe (Windows)
+CSVDialogOptions.nodata.label=Value indicating \"no data\"
+
+CSVPreviewTableModel.error.title=CSV preview
+CSVPreviewTableModel.error.mess=Error generating CSV preview (take a look at CSV source for details)
+
+CSVPreviewPanel.tab.preview=Configuration & Preview
+CSVPreviewPanel.tab.source=Source file
+CSVPreviewPanel.preview.label=Preview
+CSVPreviewPanel.preview.limit.label=Limit for number of preview rows
+CSVPreviewPanel.preview.firstLine.label=First line for preview
+
+CSVColumnAllocationPanel.columns.label=CSV column allocation
\ No newline at end of file
Added: trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle_de.properties
===================================================================
--- trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle_de.properties (rev 0)
+++ trunk/schmitzm-excelcsv/src/main/resources/de/schmitzm/csv/resource/locales/CsvResourceBundle_de.properties 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,60 @@
+##########
+#Copyright (c) 2009 Martin O. J. Schmitz.
+#
+#This file is part of the SCHMITZM library - a collection of utility
+#classes based on Java 1.6, focusing (not only) on Java Swing
+#and the Geotools library.
+#
+#The SCHMITZM project is hosted at:
+#http://wald.intevation.org/projects/schmitzm/
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU Lesser General Public License
+#as published by the Free Software Foundation; either version 3
+#of the License, or (at your option) any later version.
+#
+#This program is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+#GNU General Public License for more details.
+#
+#You should have received a copy of the GNU Lesser General Public License (license.txt)
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#or try this link: http://www.gnu.org/licenses/lgpl.html
+#
+#Contributors:
+# Martin O. J. Schmitz - initial API and implementation
+# Stefan A. Tzeggai - additional utility classes
+##########
+
+# ------------------------------------------------
+# ------ German Translations for components ------
+# ------ in Package de.schmitzm.csv ------
+# ------------------------------------------------
+
+CSVDialogOptions.file.label=CSV Datei
+CSVDialogOptions.delim.label=CSV Spalten-Trennzeichen
+CSVDialogOptions.delim.tab.desc=Tab (\\t)
+CSVDialogOptions.delim.semicolon.desc=Semikolon (;)
+CSVDialogOptions.delim.pipe.desc=Pipe (|)
+CSVDialogOptions.delim.comma.desc=Komma (,)
+CSVDialogOptions.quote.label=CSV Text-Maskierungs-Zeichen
+CSVDialogOptions.decimal.label=CSV Dezimal-Trennzeichen
+CSVDialogOptions.charset.label=Zeichensatz der Datei
+CSVDialogOptions.charset.cp850.desc=Codepage 850 (Windows)
+CSVDialogOptions.charset.cp1252.desc=Codepage 1252 (Windows)
+CSVDialogOptions.charset.utf8.desc=UTF-8 (moderne Betriebssysteme, z.B. Linux)
+CSVDialogOptions.charset.iso-8859-15.desc=ISO-8859-15 Westeuropa (Windows)
+CSVDialogOptions.nodata.label=Wert der \"no data\" darstellt
+
+CSVPreviewTableModel.error.title=CSV Vorschau
+CSVPreviewTableModel.error.mess=Fehler bei der Generierung der CSV-Vorschau (siehe CSV-Quelle für Details)
+
+CSVPreviewPanel.tab.preview=Konfiguration & Vorschau
+CSVPreviewPanel.tab.source=Quell-Datei
+CSVPreviewPanel.preview.label=Vorschau
+CSVPreviewPanel.preview.limit.label=Limit für Vorschau-Zeilen
+CSVPreviewPanel.preview.firstLine.label=Erste Zeile für Vorschau
+
+CSVColumnAllocationPanel.columns.label=CSV-Spalten Zuweisung
Added: trunk/schmitzm-excelcsv/src/test/java/de/schmitzm/csv/CsvTest.java
===================================================================
--- trunk/schmitzm-excelcsv/src/test/java/de/schmitzm/csv/CsvTest.java (rev 0)
+++ trunk/schmitzm-excelcsv/src/test/java/de/schmitzm/csv/CsvTest.java 2012-04-04 14:38:08 UTC (rev 1936)
@@ -0,0 +1,87 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ *
+ * This file is part of the SCHMITZM library - a collection of utility
+ * classes based on Java 1.6, focusing (not only) on Java Swing
+ * and the Geotools library.
+ *
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ *
+ * Contributors:
+ * Martin O. J. Schmitz - initial API and implementation
+ * Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.csv;
+
+import java.awt.Frame;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+import de.schmitzm.csv.gui.CSVColumnAllocationDialog;
+import de.schmitzm.csv.gui.CSVPreviewDialog;
+import de.schmitzm.swing.ExceptionDialog;
+import de.schmitzm.testing.TestingClass;
+
+/**
+ * Tests for CSV package
+ * @author Martin O.J. Schmitz
+ *
+ */
+public class CsvTest extends TestingClass {
+
+ @Test
+ @Ignore
+ public void testCsvPreviewDialog() {
+ if ( !isInteractive() )
+ return;
+ Locale.setDefault( Locale.ENGLISH );
+ CSVPreviewDialog dialog = new CSVPreviewDialog((Frame)null, "Test CSV");
+ dialog.setVisible(true);
+ }
+
+ @Test
+ @Ignore
+ public void testCsvColumnAllocationDialog() {
+ if ( !isInteractive() )
+ return;
+ Locale.setDefault( Locale.GERMAN );
+ // Create dummy allocation
+ Map<String, String> fields = new HashMap<String, String>();
+ List<String> csvColumns = new ArrayList<String>();
+ Map<String, String> defaultMapping = new HashMap<String, String>();
+ fields.put("A", "Das erste Feld");
+ fields.put("B", "Das zweite Feld");
+ csvColumns.add("CSVSpalte1");
+ csvColumns.add("CSVSpalte2");
+ csvColumns.add("CSVSpalte3");
+ defaultMapping.put("A", "CSVSpalte2");
+
+ // Create dialog and set content
+ CSVColumnAllocationDialog dialog = new CSVColumnAllocationDialog((Frame)null, "Test CSV");
+ dialog.setAllocationOptions(fields, csvColumns, defaultMapping);
+ dialog.setVisible(true);
+ }
+
+}
More information about the Schmitzm-commits
mailing list