Example usage for org.apache.commons.csv CSVRecord toMap

List of usage examples for org.apache.commons.csv CSVRecord toMap

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVRecord toMap.

Prototype

public Map<String, String> toMap() 

Source Link

Document

Copies this record into a new Map.

Usage

From source file:com.denimgroup.threadfix.csv2ssl.serializer.RecordToXMLSerializer.java

public static String getFromReader(CSVParser parser) {
    StringBuilder builder = getStart();

    int i = -1;//  ww  w .j  av a  2 s .  c om
    for (CSVRecord strings : parser) {
        i++;
        addRecord(builder, i, strings.toMap());
    }

    return writeEnd(builder);
}

From source file:indexer.PDFDocument.java

PDFDocument(CSVRecord record) {
    record.toMap().forEach(this::addMetadata);
    path = record.get("file");
    name = record.get("title");
}

From source file:com.act.utils.TSVParser.java

public void parse(InputStream inStream) throws IOException {
    List<Map<String, String>> results = new ArrayList<>();
    try (CSVParser parser = new CSVParser(new InputStreamReader(inStream), TSV_FORMAT)) {
        headerMap = parser.getHeaderMap();
        Iterator<CSVRecord> iter = parser.iterator();
        while (iter.hasNext()) {
            CSVRecord r = iter.next();
            results.add(r.toMap());
        }/*from  ww  w  . j av a2s  . c  o  m*/
    }
    this.results = results;
}

From source file:com.intropro.prairie.format.sv.SvFormatReader.java

@Override
public Map<String, Object> next() throws IOException {
    if (csvParser == null) {
        csvParser = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter).parse(inputStream);
        iterator = csvParser.iterator();
    }/*from  www .  j av a2  s .  co  m*/
    if (!iterator.hasNext()) {
        return null;
    }
    CSVRecord csvRecord = iterator.next();
    return new HashMap<String, Object>(csvRecord.toMap());
}

From source file:ai.grakn.migration.csv.CSVMigrator.java

/**
 * Convert data in arrays (from CSV reader) to Map<String, Object>, the current input format for
 * graql templating./*w w  w  .  ja  v  a 2s .  c o m*/
 * @param data all bu first row of input file
 * @return given data in a map
 */
private Map<String, Object> parse(CSVRecord data) {
    if (!data.isConsistent()) {
        throw new RuntimeException("Invalid CSV " + data.toMap());
    }
    return data.toMap().entrySet().stream().filter((e) -> validValue(e.getValue()))
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
}

From source file:licenseUtil.LicensingObject.java

LicensingObject(CSVRecord record) throws IncompleteLicenseObjectException {
    super();/*from ww w .  j  av  a  2 s  . c om*/
    Map<String, String> recordMap = record.toMap();
    for (String key : recordMap.keySet()) {
        String value = recordMap.get(key);
        if (value != null && !value.equals("")) {
            String current = recordMap.get(key).trim();
            // remove text marker
            if (value.length() > 1 && value.charAt(0) == textMarker
                    && value.charAt(value.length() - 1) == textMarker) {
                put(key, current.substring(1, current.length() - 1));
            } else
                put(key, current);
        }
    }

    //check key header values
    for (String keyHeader : KEY_HEADERS) {
        if (Strings.isNullOrEmpty(get(keyHeader)))
            throw new IncompleteLicenseObjectException(
                    "Missing value: \"" + keyHeader + "\" in \"" + this + "\"");
    }
}

From source file:canreg.client.gui.components.PreviewFilePanel.java

/**
 *
 *///from  ww w .  j  a  v  a2  s  .c o m
@Action
public void previewAction() {
    // show the contents of the file
    BufferedReader br = null;
    try {
        changeFile();
        // numberOfRecordsTextField.setText(""+(canreg.common.Tools.numberOfLinesInFile(inFile.getAbsolutePath())-1));
        FileInputStream fis = new FileInputStream(inFile);
        br = new BufferedReader(new InputStreamReader(fis, (Charset) charsetsComboBox.getSelectedItem()));
        CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(getSeparator());

        CSVParser csvParser = new CSVParser(br, csvFormat);

        int linesToRead = Globals.NUMBER_OF_LINES_IN_IMPORT_PREVIEW;
        int numberOfLinesRead = 0;
        Vector<Vector<String>> data = new Vector<Vector<String>>();

        String[] headers = csvParser.getHeaderMap().keySet().toArray(new String[0]);

        for (CSVRecord csvRecord : csvParser) {
            csvRecord.toMap();
            Vector vec = new Vector();
            Iterator<String> iterator = csvRecord.iterator();
            while (iterator.hasNext()) {
                vec.add(iterator.next());
            }
            data.add(vec);
            numberOfLinesRead++;
            if (numberOfLinesRead >= linesToRead) {
                break;
            }
        }
        numberOfRecordsShownTextField.setText(numberOfLinesRead + "");

        // previewTextArea.setText(headers + "\n" + dataText);
        // previewTextArea.setCaretPosition(0);
        previewPanel.setVisible(true);
        Vector columnNames = new Vector(Arrays.asList(headers));
        previewTable.setModel(new DefaultTableModel(data, columnNames));
    } catch (FileNotFoundException fileNotFoundException) {
        JOptionPane.showInternalMessageDialog(CanRegClientApp.getApplication().getMainFrame().getContentPane(),
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("COULD_NOT_PREVIEW_FILE:") + " \'" + fileNameTextField.getText().trim()
                        + "\'.",
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("ERROR"),
                JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(PreviewFilePanel.class.getName()).log(Level.SEVERE, null, fileNotFoundException);
    } catch (IOException ex) {
        Logger.getLogger(PreviewFilePanel.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(PreviewFilePanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:canreg.client.gui.dataentry.ImportView.java

/**
 *
 *///ww  w .  j  av a2 s.c  om
@Action
public void previewAction() {
    // show the contents of the file
    BufferedReader br = null;
    try {
        changeFile();
        // numberOfRecordsTextField.setText(""+(canreg.common.Tools.numberOfLinesInFile(inFile.getAbsolutePath())-1));
        FileInputStream fis = new FileInputStream(inFile);
        br = new BufferedReader(new InputStreamReader(fis, (Charset) charsetsComboBox.getSelectedItem()));
        CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(getSeparator());

        CSVParser csvParser = new CSVParser(br, csvFormat);

        int linesToRead = Globals.NUMBER_OF_LINES_IN_IMPORT_PREVIEW;
        int numberOfLinesRead = 0;
        Vector<Vector<String>> data = new Vector<Vector<String>>();

        String[] headers = csvParser.getHeaderMap().keySet().toArray(new String[0]);

        for (CSVRecord csvRecord : csvParser) {
            csvRecord.toMap();
            Vector vec = new Vector();
            Iterator<String> iterator = csvRecord.iterator();
            while (iterator.hasNext()) {
                vec.add(iterator.next());
            }
            data.add(vec);
            numberOfLinesRead++;
            if (numberOfLinesRead >= linesToRead) {
                break;
            }
        }
        numberOfRecordsShownTextField.setText(numberOfLinesRead + "");

        // previewTextArea.setText(headers + "\n" + dataText);
        // previewTextArea.setCaretPosition(0);
        previewPanel.setVisible(true);
        Vector columnNames = new Vector(Arrays.asList(headers));
        previewTable.setModel(new DefaultTableModel(data, columnNames));
    } catch (FileNotFoundException fileNotFoundException) {
        JOptionPane.showInternalMessageDialog(CanRegClientApp.getApplication().getMainFrame().getContentPane(),
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("COULD_NOT_PREVIEW_FILE:") + " \'" + fileNameTextField.getText().trim()
                        + "\'.",
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("ERROR"),
                JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(ImportView.class.getName()).log(Level.SEVERE, null, fileNotFoundException);
    } catch (IOException ex) {
        JOptionPane.showInternalMessageDialog(CanRegClientApp.getApplication().getMainFrame().getContentPane(),
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("COULD_NOT_PREVIEW_FILE:") + " \'" + fileNameTextField.getText().trim()
                        + "\'.",
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("ERROR"),
                JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(ImportView.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(ImportView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:notaql.engines.csv.datamodel.ValueConverter.java

/**
 * Generates ObjectValues from a given csv record.
 * @param result/*  w w w.ja v a 2s.  c om*/
 * @return
 */
public static Value convertToNotaQL(CSVRecord result) {
    final ObjectValue object = new ObjectValue();

    for (Map.Entry<String, String> cell : result.toMap().entrySet()) {
        object.put(new Step<>(cell.getKey()), ValueUtils.parse(cell.getValue()));
    }

    return object;
}

From source file:nz.ac.waikato.cms.doc.ScriptedPDFOverlay.java

/**
 * Applies the groovy script to the PDF template, one time per row.
 *
 * @return      null if successful, otherwise error message
 *///from   ww  w .ja va2  s.  c o m
public String execute() {
    String result;
    ScriptedPDFOverlayProcessor processor;
    Reader in;
    Iterable<CSVRecord> records;
    int row;

    result = null;

    // initialize groovy script
    processor = (ScriptedPDFOverlayProcessor) newInstance(m_Groovy, ScriptedPDFOverlayProcessor.class);
    if (processor == null)
        return "Failed to instantiate Groovy script: " + m_Groovy;

    // process spreadsheet
    try {
        in = new FileReader(m_Params);
        records = CSVFormat.EXCEL.withHeader().parse(in);
        row = 0;
        for (CSVRecord record : records) {
            row++;
            result = processor.overlay(m_PdfTemplate, row, record.toMap(), m_OutputDir);
            if (result != null) {
                result = "Failed to process row #" + row + ":\n" + result;
                break;
            }
        }
    } catch (Exception e) {
        result = "Failed to process!\n" + Utils.throwableToString(e);
    }

    return result;
}