Search in sources :

Example 1 with CsvWriter

use of com.univocity.parsers.csv.CsvWriter 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 CsvWriter

use of com.univocity.parsers.csv.CsvWriter 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 3 with CsvWriter

use of com.univocity.parsers.csv.CsvWriter in project deephaven-core by deephaven.

the class CsvResultWriter method recordResults.

public static void recordResults(final Collection<RunResult> results, final File file) {
    if (results.isEmpty()) {
        return;
    }
    final CsvWriter writer = new CsvWriter(file, new CsvWriterSettings());
    final Set<String> headers = new LinkedHashSet<>();
    headers.add("Benchmark");
    headers.add("Run");
    headers.add("Iteration");
    headers.add("Score");
    for (final RunResult runResult : results) {
        final BenchmarkParams runParams = runResult.getParams();
        headers.addAll(runParams.getParamsKeys());
    }
    writer.writeHeaders(headers);
    final DecimalFormat decimalFormat = new DecimalFormat("#0.000");
    int runNo = 0;
    for (final RunResult runResult : results) {
        final BenchmarkParams runParams = runResult.getParams();
        for (final BenchmarkResult benchResult : runResult.getBenchmarkResults()) {
            runNo++;
            int itNo = 0;
            for (final IterationResult itResult : benchResult.getIterationResults()) {
                itNo++;
                final Map<String, String> values = new HashMap<>();
                values.put("Benchmark", runParams.getBenchmark());
                for (String key : runParams.getParamsKeys()) {
                    values.put(key, runParams.getParam(key));
                }
                values.put("Score", decimalFormat.format(itResult.getPrimaryResult().getScore()));
                values.put("Run", Integer.toString(runNo));
                values.put("Iteration", Integer.toString(itNo));
                writer.writeRow(headers.stream().map(values::get).collect(Collectors.toList()));
            }
        }
    }
    writer.close();
}
Also used : CsvWriter(com.univocity.parsers.csv.CsvWriter) DecimalFormat(java.text.DecimalFormat) CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings) BenchmarkResult(org.openjdk.jmh.results.BenchmarkResult) IterationResult(org.openjdk.jmh.results.IterationResult) RunResult(org.openjdk.jmh.results.RunResult) BenchmarkParams(org.openjdk.jmh.infra.BenchmarkParams)

Example 4 with CsvWriter

use of com.univocity.parsers.csv.CsvWriter in project caffeine by ben-manes.

the class CsvReporter method assemble.

@Override
protected String assemble(List<PolicyStats> results) {
    StringWriter output = new StringWriter();
    CsvWriter writer = new CsvWriter(output, new CsvWriterSettings());
    writer.writeHeaders(headers());
    for (PolicyStats policyStats : results) {
        Object[] data = new Object[] { policyStats.name(), String.format("%.2f", 100 * policyStats.hitRate()), policyStats.hitCount(), policyStats.missCount(), policyStats.requestCount(), policyStats.evictionCount(), String.format("%.2f", 100 * policyStats.admissionRate()), (policyStats.operationCount() == 0) ? null : policyStats.operationCount(), policyStats.stopwatch().elapsed(TimeUnit.MILLISECONDS) };
        writer.writeRow(data);
    }
    writer.close();
    return output.toString();
}
Also used : StringWriter(java.io.StringWriter) CsvWriter(com.univocity.parsers.csv.CsvWriter) PolicyStats(com.github.benmanes.caffeine.cache.simulator.policy.PolicyStats) CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings)

Example 5 with CsvWriter

use of com.univocity.parsers.csv.CsvWriter in project powsybl-core by powsybl.

the class RecordGroupIOLegacyText method write.

protected void write(List<T> objects, String[] headers, String[] quotedFields, Context context, OutputStream outputStream) {
    CsvWriterSettings settings = recordGroup.settingsForCsvWriter(headers, quotedFields, context);
    CsvWriter writer = new CsvWriter(outputStream, settings);
    writer.processRecords(objects);
    writer.flush();
}
Also used : CsvWriter(com.univocity.parsers.csv.CsvWriter) CsvWriterSettings(com.univocity.parsers.csv.CsvWriterSettings)

Aggregations

CsvWriter (com.univocity.parsers.csv.CsvWriter)9 CsvWriterSettings (com.univocity.parsers.csv.CsvWriterSettings)7 CsvFormat (com.univocity.parsers.csv.CsvFormat)3 File (java.io.File)2 StringWriter (java.io.StringWriter)2 Writer (java.io.Writer)2 User (com.bakdata.conquery.models.auth.entities.User)1 PolicyStats (com.github.benmanes.caffeine.cache.simulator.policy.PolicyStats)1 CsvParser (com.univocity.parsers.csv.CsvParser)1 CsvParserSettings (com.univocity.parsers.csv.CsvParserSettings)1 java.awt (java.awt)1 BufferedImage (java.awt.image.BufferedImage)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 DataOutputStream (java.io.DataOutputStream)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StandardCharsets (java.nio.charset.StandardCharsets)1 DecimalFormat (java.text.DecimalFormat)1 java.util (java.util)1