Search in sources :

Example 1 with CsvWriterSettings

use of com.univocity.parsers.csv.CsvWriterSettings in project MCreator by MCreator.

the class WorkspacePanelLocalizations method reloadElements.

@Override
public void reloadElements() {
    for (var al : del.getActionListeners()) del.removeActionListener(al);
    for (var al : imp.getActionListeners()) imp.removeActionListener(al);
    for (var al : exp.getActionListeners()) exp.removeActionListener(al);
    pane.removeAll();
    sorters = new ArrayList<>();
    for (var entry : workspacePanel.getMcreator().getWorkspace().getLanguageMap().entrySet()) {
        ConcurrentHashMap<String, String> entries = entry.getValue();
        JTable elements = new JTable(new DefaultTableModel(new Object[] { L10N.t("workspace.localization.column_key"), "Localized text for " + entry.getKey() + (entry.getKey().equals("en_us") ? " - values in en_us might get overwritten!" : " - mappings can be edited here") }, 0));
        final Font textFont = new Font("Sans-Serif", Font.PLAIN, 13);
        elements.setFont(textFont);
        elements.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                var c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                c.setFont(textFont);
                return c;
            }
        });
        elements.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(new JTextField()) {

            final JComponent component = new JTextField();

            {
                component.setFont(textFont);
            }

            @Override
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
                ((JTextField) component).setText((String) value);
                return component;
            }

            @Override
            public Object getCellEditorValue() {
                return ((JTextField) component).getText();
            }
        });
        TableRowSorter<TableModel> sorter = new TableRowSorter<>(elements.getModel());
        elements.setRowSorter(sorter);
        sorters.add(sorter);
        elements.setBackground((Color) UIManager.get("MCreatorLAF.DARK_ACCENT"));
        elements.setSelectionBackground((Color) UIManager.get("MCreatorLAF.BRIGHT_COLOR"));
        elements.setForeground((Color) UIManager.get("MCreatorLAF.BRIGHT_COLOR"));
        elements.setSelectionForeground((Color) UIManager.get("MCreatorLAF.DARK_ACCENT"));
        elements.setBorder(BorderFactory.createEmptyBorder());
        elements.setGridColor((Color) UIManager.get("MCreatorLAF.LIGHT_ACCENT"));
        elements.setRowHeight(22);
        elements.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
        elements.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 13));
        JTableHeader header = elements.getTableHeader();
        header.setBackground((Color) UIManager.get("MCreatorLAF.MAIN_TINT"));
        header.setForeground((Color) UIManager.get("MCreatorLAF.DARK_ACCENT"));
        DefaultTableModel model = (DefaultTableModel) elements.getModel();
        for (Map.Entry<String, String> langs : entries.entrySet()) {
            model.addRow(new String[] { langs.getKey(), langs.getValue() });
        }
        // save values on table edit, do it in another thread
        // we add the listener after the values are inserted
        elements.getModel().addTableModelListener(e -> new Thread(() -> {
            if (e.getType() == TableModelEvent.UPDATE) {
                ConcurrentHashMap<String, String> keyValueMap = new ConcurrentHashMap<>();
                for (int i = 0; i < elements.getModel().getRowCount(); i++) {
                    keyValueMap.put((String) elements.getModel().getValueAt(i, 0), (String) elements.getModel().getValueAt(i, 1));
                }
                workspacePanel.getMcreator().getWorkspace().updateLanguage(entry.getKey(), keyValueMap);
            }
        }).start());
        JScrollPane sp = new JScrollPane(elements);
        sp.setOpaque(false);
        sp.getViewport().setOpaque(false);
        sp.getVerticalScrollBar().setUnitIncrement(11);
        sp.getVerticalScrollBar().setUI(new SlickDarkScrollBarUI((Color) UIManager.get("MCreatorLAF.DARK_ACCENT"), (Color) UIManager.get("MCreatorLAF.LIGHT_ACCENT"), sp.getVerticalScrollBar()));
        sp.getVerticalScrollBar().setPreferredSize(new Dimension(8, 0));
        sp.setColumnHeaderView(null);
        final int id = pane.getTabCount();
        pane.addTab(entry.getKey(), null, sp);
        JPanel tab = new JPanel(new FlowLayout(FlowLayout.LEFT, 1, 1));
        tab.setOpaque(false);
        JButton button = new JButton(UIRES.get("16px.delete.gif"));
        button.setContentAreaFilled(false);
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setMargin(new Insets(0, 0, 0, 0));
        button.addActionListener(e -> {
            int n = JOptionPane.showConfirmDialog(workspacePanel.getMcreator(), L10N.t("workspace.localization.confirm_delete_map"), L10N.t("common.confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null);
            if (n == 0) {
                workspacePanel.getMcreator().getWorkspace().removeLocalizationLanguage(entry.getKey());
                reloadElements();
            }
        });
        button.setEnabled(!entry.getKey().equals("en_us"));
        String flagpath = "/flags/" + entry.getKey().split("_")[1].toUpperCase(Locale.ENGLISH) + ".png";
        JLabel label = new JLabel(" " + entry.getKey() + " ");
        ComponentUtils.deriveFont(label, 12);
        try {
            @SuppressWarnings("ConstantConditions") BufferedImage image = ImageIO.read(getClass().getResourceAsStream(flagpath));
            label.setIcon(new ImageIcon(ImageUtils.crop(image, new Rectangle(1, 2, 14, 11))));
        } catch (Exception ignored) {
        // flag not found, ignore
        }
        label.setBorder(BorderFactory.createEmptyBorder());
        tab.add(label);
        tab.add(button);
        pane.setTabComponentAt(id, tab);
        del.addActionListener(e -> {
            if (elements.getSelectedRow() == -1 || pane.getSelectedIndex() != id)
                return;
            String key = (String) elements.getValueAt(elements.getSelectedRow(), 0);
            if (key != null) {
                int n = JOptionPane.showConfirmDialog(workspacePanel.getMcreator(), L10N.t("workspace.localization.confirm_delete_entry"), L10N.t("common.confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (n == 0) {
                    Arrays.stream(elements.getSelectedRows()).mapToObj(el -> (String) elements.getValueAt(el, 0)).forEach(workspacePanel.getMcreator().getWorkspace()::removeLocalizationEntryByKey);
                    reloadElements();
                }
            }
        });
        exp.addActionListener(e -> {
            if (pane.getSelectedIndex() != id)
                return;
            if (entry.getKey().equals("en_us")) {
                JOptionPane.showMessageDialog(workspacePanel.getMcreator(), L10N.t("workspace.localization.confirm_export"), L10N.t("workspace.localization.export_translation"), JOptionPane.WARNING_MESSAGE);
                return;
            }
            File expFile = FileDialogs.getSaveDialog(workspacePanel.getMcreator(), new String[] { ".csv" });
            if (expFile != null) {
                Map<String, String> en_us = workspacePanel.getMcreator().getWorkspace().getLanguageMap().get("en_us");
                ByteArrayOutputStream csvResult = new ByteArrayOutputStream();
                Writer outputWriter = new OutputStreamWriter(csvResult);
                CsvWriter writer = new CsvWriter(outputWriter, new CsvWriterSettings());
                writer.writeHeaders("Translation key (DON'T EDIT)", "TRANSLATION IN " + entry.getKey() + " - EDIT THIS COLUMN", "English text (DON'T EDIT - reference only)");
                for (Map.Entry<String, String> langs : workspacePanel.getMcreator().getWorkspace().getLanguageMap().get(entry.getKey()).entrySet()) writer.writeRow(langs.getKey(), langs.getValue(), en_us.get(langs.getKey()));
                writer.close();
                FileIO.writeUTF8toFile("SEP=,\n" + csvResult.toString(StandardCharsets.UTF_8), expFile);
            }
        });
        imp.addActionListener(e -> {
            if (pane.getSelectedIndex() != id)
                return;
            if (entry.getKey().equals("en_us")) {
                JOptionPane.showMessageDialog(workspacePanel.getMcreator(), L10N.t("workspace.localization.warning_export"), L10N.t("workspace.localization.export_translation"), JOptionPane.WARNING_MESSAGE);
                return;
            }
            File impFile = FileDialogs.getOpenDialog(workspacePanel.getMcreator(), new String[] { ".csv" });
            if (impFile != null) {
                ConcurrentHashMap<String, String> en_us = workspacePanel.getMcreator().getWorkspace().getLanguageMap().get("en_us");
                CsvParserSettings settings = new CsvParserSettings();
                settings.setDelimiterDetectionEnabled(true);
                CsvParser parser = new CsvParser(settings);
                List<String[]> rows = parser.parseAll(impFile, StandardCharsets.UTF_8);
                ConcurrentHashMap<String, String> keyValueMap = new ConcurrentHashMap<>();
                for (String[] row : rows) {
                    if (row.length < 2)
                        continue;
                    String key = row[0];
                    String value = row[1];
                    if (en_us.containsKey(key) && value != null)
                        keyValueMap.put(key, value);
                }
                workspacePanel.getMcreator().getWorkspace().updateLanguage(entry.getKey(), keyValueMap);
                SwingUtilities.invokeLater(this::reloadElements);
            }
        });
    }
    int lastid = pane.getTabCount();
    pane.addTab("", null, null);
    pane.setTabComponentAt(lastid, new JLabel(UIRES.get("16px.add.gif")));
    pane.removeChangeListener(changeListener);
    changeListener = e -> {
        if (pane.getSelectedIndex() == lastid) {
            pane.setSelectedIndex(0);
            newLocalizationDialog();
        }
    };
    pane.addChangeListener(changeListener);
    refilterElements();
}
Also used : java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TransparentToolBar(net.mcreator.ui.component.TransparentToolBar) ComponentUtils(net.mcreator.ui.component.util.ComponentUtils) javax.swing.table(javax.swing.table) FileDialogs(net.mcreator.ui.dialogs.FileDialogs) UIRES(net.mcreator.ui.init.UIRES) ImageIO(javax.imageio.ImageIO) OutputStreamWriter(java.io.OutputStreamWriter) CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings) ChangeListener(javax.swing.event.ChangeListener) CsvParser(com.univocity.parsers.csv.CsvParser) L10N(net.mcreator.ui.init.L10N) CsvParserSettings(com.univocity.parsers.csv.CsvParserSettings) FileIO(net.mcreator.io.FileIO) TableModelEvent(javax.swing.event.TableModelEvent) BufferedImage(java.awt.image.BufferedImage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ImageUtils(net.mcreator.util.image.ImageUtils) CsvWriter(com.univocity.parsers.csv.CsvWriter) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) java.awt(java.awt) SlickDarkScrollBarUI(net.mcreator.ui.laf.SlickDarkScrollBarUI) List(java.util.List) Writer(java.io.Writer) javax.swing(javax.swing) SlickDarkScrollBarUI(net.mcreator.ui.laf.SlickDarkScrollBarUI) CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings) CsvParser(com.univocity.parsers.csv.CsvParser) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) File(java.io.File) BufferedImage(java.awt.image.BufferedImage) CsvParserSettings(com.univocity.parsers.csv.CsvParserSettings) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CsvWriter(com.univocity.parsers.csv.CsvWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) OutputStreamWriter(java.io.OutputStreamWriter) CsvWriter(com.univocity.parsers.csv.CsvWriter) Writer(java.io.Writer)

Example 2 with CsvWriterSettings

use of com.univocity.parsers.csv.CsvWriterSettings in project tablesaw by jtablesaw.

the class CsvWriter method createSettings.

protected static CsvWriterSettings createSettings(CsvWriteOptions options) {
    CsvWriterSettings settings = new CsvWriterSettings();
    // Sets the character sequence to write for the values that are null.
    settings.setNullValue(nullValue);
    if (options.separator() != null) {
        settings.getFormat().setDelimiter(options.separator());
    }
    if (options.quoteChar() != null) {
        settings.getFormat().setQuote(options.quoteChar());
    }
    if (options.escapeChar() != null) {
        settings.getFormat().setQuoteEscape(options.escapeChar());
    }
    if (options.lineEnd() != null) {
        settings.getFormat().setLineSeparator(options.lineEnd());
    }
    settings.setIgnoreLeadingWhitespaces(options.ignoreLeadingWhitespaces());
    settings.setIgnoreTrailingWhitespaces(options.ignoreTrailingWhitespaces());
    // writes empty lines as well.
    settings.setSkipEmptyLines(false);
    settings.setQuoteAllFields(options.quoteAllFields());
    return settings;
}
Also used : CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings)

Example 3 with CsvWriterSettings

use of com.univocity.parsers.csv.CsvWriterSettings in project conquery by bakdata.

the class CSVConfig method createCsvWriterSettings.

/**
 * Helper method to generate writer settings from the provided options in this class.
 * @return Setting object that can be passed into a {@link CsvWriter}.
 */
private CsvWriterSettings createCsvWriterSettings() {
    CsvWriterSettings settings = new CsvWriterSettings();
    settings.setMaxColumns(maxColumns);
    settings.setFormat(createCsvFormat());
    return settings;
}
Also used : CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings)

Example 4 with CsvWriterSettings

use of com.univocity.parsers.csv.CsvWriterSettings in project hillview by vmware.

the class CsvFileWriter method writeTable.

public void writeTable(ITable table) {
    try {
        Schema schema = table.getSchema();
        List<IColumn> cols = table.getLoadedColumns(schema.getColumnNames());
        CsvWriterSettings settings = new CsvWriterSettings();
        CsvFormat format = new CsvFormat();
        format.setDelimiter(this.separator);
        settings.setFormat(format);
        settings.setEmptyValue("\"\"");
        settings.setNullValue(null);
        OutputStream output;
        FileOutputStream fs = null;
        if (this.compress) {
            String fn = this.fileName;
            if (!this.fileName.endsWith(".gz"))
                fn += ".gz";
            fs = new FileOutputStream(fn);
            output = new GZIPOutputStream(fs);
        } else {
            output = new FileOutputStream(this.fileName);
        }
        CsvWriter writer = new CsvWriter(output, settings);
        String[] data = new String[schema.getColumnCount()];
        int index = 0;
        for (String c : schema.getColumnNames()) {
            data[index] = c;
            index++;
        }
        if (this.writeHeaderRow)
            writer.writeHeaders(data);
        IRowIterator rowIter = table.getMembershipSet().getIterator();
        int nextRow = rowIter.getNextRow();
        while (nextRow >= 0) {
            for (index = 0; index < cols.size(); index++) {
                IColumn colI = cols.get(index);
                String d = colI.isMissing(nextRow) ? null : colI.asString(nextRow);
                data[index] = d;
            }
            writer.writeRow(data);
            nextRow = rowIter.getNextRow();
        }
        writer.close();
        output.close();
        if (fs != null)
            fs.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : CsvWriter(com.univocity.parsers.csv.CsvWriter) Schema(org.hillview.table.Schema) GZIPOutputStream(java.util.zip.GZIPOutputStream) CsvFormat(com.univocity.parsers.csv.CsvFormat) GZIPOutputStream(java.util.zip.GZIPOutputStream) CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings)

Example 5 with CsvWriterSettings

use of com.univocity.parsers.csv.CsvWriterSettings in project symja_android_library by axkr.

the class CsvWriter method write.

public void write(Table table, CsvWriteOptions options) {
    CsvWriterSettings settings = createSettings(options);
    com.univocity.parsers.csv.CsvWriter csvWriter = null;
    // Creates a writer with the above settings;
    try {
        csvWriter = new com.univocity.parsers.csv.CsvWriter(options.destination().createWriter(), settings);
        writeHeader(table, options, csvWriter);
        for (int r = 0; r < table.rowCount(); r++) {
            String[] entries = new String[table.columnCount()];
            for (int c = 0; c < table.columnCount(); c++) {
                writeValues(table, options, r, entries, c);
            }
            csvWriter.writeRow(entries);
        }
    } finally {
        if (csvWriter != null) {
            csvWriter.flush();
            if (options.autoClose())
                csvWriter.close();
        }
    }
}
Also used : CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings)

Aggregations

CsvWriterSettings (com.univocity.parsers.csv.CsvWriterSettings)16 CsvWriter (com.univocity.parsers.csv.CsvWriter)7 CsvFormat (com.univocity.parsers.csv.CsvFormat)5 CsvParserSettings (com.univocity.parsers.csv.CsvParserSettings)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 Writer (java.io.Writer)2 PolicyStats (com.github.benmanes.caffeine.cache.simulator.policy.PolicyStats)1 LEGACY_TEXT (com.powsybl.psse.model.io.FileFormat.LEGACY_TEXT)1 BeanWriterProcessor (com.univocity.parsers.common.processor.BeanWriterProcessor)1 CsvParser (com.univocity.parsers.csv.CsvParser)1 java.awt (java.awt)1 BufferedImage (java.awt.image.BufferedImage)1 FileWriter (java.io.FileWriter)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StringWriter (java.io.StringWriter)1 StandardCharsets (java.nio.charset.StandardCharsets)1 DecimalFormat (java.text.DecimalFormat)1 java.util (java.util)1 List (java.util.List)1