Java Examples for com.csvreader.CsvWriter

The following java examples will help you to understand the usage of com.csvreader.CsvWriter. These source code samples are taken from different open source projects.

Example 1
Project: BikeStats-master  File: DataGrabber.java View source code
/**
     *
     * @return
     * @throws IOException
     */
public String getStatsAsCSV() throws IOException {
    String temp = "CSV";
    StringWriter strWriter = new StringWriter();
    char delimeter = ',';
    CsvWriter writer = new CsvWriter(strWriter, delimeter);
    MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
    String[] columnName = { "ID", "Name", "Latitude", "Longitude", "BikesAvailable", "EmptySlots", "Installed", "Locked", "Temporary", "UpdateTime" };
    writer.writeRecord(columnName);
    if (memcache.contains("cycleData")) {
        // buffer.append("<updatedOn>" + memcache.get("updateTime") + "</updatedOn>");
        Map<Integer, DockStation> mp = (Map<Integer, DockStation>) memcache.get("cycleData");
        Iterator it = mp.entrySet().iterator();
        String updateTime = (String) memcache.get("updateTime");
        List<String> columnValues = null;
        // writer.writeRecord(columns);
        while (it.hasNext()) {
            columnValues = new ArrayList<String>();
            Map.Entry pairs = (Map.Entry) it.next();
            DockStation ds = (DockStation) pairs.getValue();
            columnValues.add(ds.getId() + "");
            columnValues.add(ds.getName() + "");
            columnValues.add(ds.getLatitude() + "");
            columnValues.add(ds.getLongitude() + "");
            columnValues.add(ds.getNbBikeAvailable() + "");
            columnValues.add(ds.getNbEmptyDocks() + "");
            columnValues.add(ds.isInstalled() + "");
            columnValues.add(ds.isLocked() + "");
            columnValues.add(ds.isTemporary() + "");
            columnValues.add(updateTime);
            String str[] = (String[]) columnValues.toArray(new String[columnValues.size()]);
            writer.writeRecord(str);
        }
    } else {
    // buffer.append("<error>Data Feed not available</error>");
    }
    temp = strWriter.toString();
    return temp;
}
Example 2
Project: JCOP-master  File: CSVRender.java View source code
public void render(Result result) throws IOException {
    CsvWriter csvWriter = new CsvWriter(this.outputStream, this.delimiter, this.charset);
    // basics
    csvWriter.write("Algorithm");
    csvWriter.write("Problem");
    // times
    csvWriter.write("CPU Time [ms]");
    csvWriter.write("System Time [ms]");
    csvWriter.write("User Time [ms]");
    csvWriter.write("Clock Time [ms]");
    // optimize stats
    csvWriter.write("Optimize counter");
    csvWriter.write("Optimize/sec (CPU) [1/s]");
    csvWriter.write("Optimize/sec (Clock) [1/s]");
    // solution
    csvWriter.write("Exception");
    csvWriter.write("Best solution");
    csvWriter.write("Best solution (human readable)");
    csvWriter.write("Depth");
    csvWriter.write("Fitness");
    csvWriter.write("Operations");
    csvWriter.endRecord();
    for (ResultEntry resultEntry : result.getResultEntries()) {
        PreciseTimestamp start = resultEntry.getStartTimestamp();
        PreciseTimestamp stop = resultEntry.getStopTimestamp();
        // basics
        csvWriter.write(resultEntry.getAlgorithm().toString());
        csvWriter.write(resultEntry.getProblem().toString());
        // times
        csvWriter.write(Long.toString(start.getCpuTimeSpent(stop)));
        csvWriter.write(Long.toString(start.getSystemTimeSpent(stop)));
        csvWriter.write(Long.toString(start.getUserTimeSpent(stop)));
        csvWriter.write(Long.toString(start.getClockTimeSpent(stop)));
        // optimize stats
        csvWriter.write(Long.toString(resultEntry.getOptimizeCounter()));
        csvWriter.write(Long.toString(resultEntry.getOptimizeCounter() * 1000L / start.getCpuTimeSpent(stop)));
        csvWriter.write(Long.toString(resultEntry.getOptimizeCounter() * 1000L / start.getClockTimeSpent(stop)));
        csvWriter.write(resultEntry.getException() == null ? "none" : resultEntry.getException().getClass().toString());
        // solution
        if (resultEntry.getBestConfiguration() == null) {
            csvWriter.write("none");
            csvWriter.write("-");
            csvWriter.write("-");
            csvWriter.write("-");
        } else {
            StringBuffer stringBufferHumanReadable = new StringBuffer("[");
            StringBuffer stringBuffer = new StringBuffer("[");
            ConfigurationMap configurationMap = resultEntry.getProblem().getConfigurationMap();
            for (int i = 0; i < resultEntry.getBestConfiguration().getDimension(); ++i) {
                stringBuffer.append(i == 0 ? "" : ", ").append(configurationMap.map(resultEntry.getBestConfiguration().valueAt(i), i));
                stringBufferHumanReadable.append(i == 0 ? "" : ", ").append(resultEntry.getBestConfiguration().valueAt(i));
            }
            stringBuffer.append("]");
            stringBufferHumanReadable.append("]");
            csvWriter.write(stringBuffer.toString());
            csvWriter.write(stringBufferHumanReadable.toString());
            csvWriter.write(Long.toString(resultEntry.getBestConfiguration().getOperationHistory().getCounter()));
            csvWriter.write(Double.toString(resultEntry.getBestFitness()));
            for (OperationHistory operationHistory : resultEntry.getBestConfiguration().getOperationHistory().getChronologicalList()) {
                csvWriter.write(operationHistory.getOperation().toString());
            }
        }
        csvWriter.endRecord();
    }
    csvWriter.flush();
}
Example 3
Project: CrowdBenchmark-master  File: My_CsvWriter.java View source code
public void WriteToFile(List<Data> input, String path, String title) {
    try {
        CsvWriter csvOutput = new CsvWriter(new FileWriter(path, false), ',');
        String[] labels = title.split("\t");
        for (String piece : labels) {
            csvOutput.write(piece);
        }
        csvOutput.endRecord();
        int size = input.size();
        int start = 0;
        for (; start < size; start++) {
            Data onerow = input.get(start);
            String[] content = onerow.toString().split("\t");
            for (String piece : content) {
                csvOutput.write(piece);
            }
            csvOutput.endRecord();
        }
        csvOutput.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 4
Project: upm-swing-master  File: AccountsCSVMarshaller.java View source code
public void marshal(ArrayList accounts, File file) throws ExportException {
    if (file.exists()) {
        throw new ExportException("The file to export to already exists");
    }
    try {
        FileWriter writer = new FileWriter(file);
        CsvWriter csvWriter = new CsvWriter(writer, ',');
        for (int i = 0; i < accounts.size(); i++) {
            csvWriter.writeRecord(getAccountAsStringArray((AccountInformation) accounts.get(i)));
        }
        csvWriter.close();
    } catch (IOException e) {
        throw new ExportException(e);
    }
}
Example 5
Project: jMemorize-master  File: CsvBuilder.java View source code
/**
     * Exports the given lesson to a CSV-file with given delimiter and given
     * character set.
     */
public static void exportLesson(OutputStream out, Lesson lesson, char delimiter, Charset charset) throws IOException {
    try {
        CsvWriter writer = new CsvWriter(out, delimiter, charset);
        writeHeader(writer);
        List<Card> cards = lesson.getRootCategory().getCards();
        for (Card card : cards) {
            writer.write(card.getFrontSide().getText().getFormatted());
            writer.write(card.getBackSide().getText().getFormatted());
            if (lesson.getRootCategory() == card.getCategory())
                writer.write("");
            else
                writer.write(card.getCategory().getName());
            writer.write(Integer.toString(card.getLevel()));
            writer.endRecord();
        }
        writer.close();
    } catch (com.csvreader.CsvWriter.FinalizedException e) {
        throw new IOException(e.getMessage());
    }
}
Example 6
Project: aloe-master  File: MessageSet.java View source code
@Override
public boolean save(OutputStream destination) throws IOException {
    if (dateFormat == null) {
        throw new IllegalStateException("No date format provided.");
    }
    //Add a BOM for Excel
    destination.write(charset.encode("").array());
    CsvWriter out = new CsvWriter(destination, ',', charset);
    String[] row = new String[NUM_OUTPUT_COLUMNS];
    row[ID_COLUMN] = ID_COLUMN_NAME;
    row[PARTICIPANT_COLUMN] = PARTICIPANT_COLUMN_NAME;
    row[TIME_COLUMN] = TIME_COLUMN_NAME;
    row[MESSAGE_COLUMN] = MESSAGE_COLUMN_NAME;
    row[TRUTH_COLUMN] = TRUTH_COLUMN_NAME;
    row[PREDICTION_COLUMN] = PREDICTION_COLUMN_NAME;
    row[CONFIDENCE_COLUMN] = CONFIDENCE_COLUMN_NAME;
    row[SEGMENT_COLUMN] = SEGMENT_COLUMN_NAME;
    out.writeRecord(row);
    for (Message message : messages) {
        row[ID_COLUMN] = Integer.toString(message.getId());
        row[PARTICIPANT_COLUMN] = message.getParticipant();
        row[TIME_COLUMN] = dateFormat.format(message.getTimestamp());
        row[MESSAGE_COLUMN] = message.getMessage();
        row[TRUTH_COLUMN] = message.hasTrueLabel() ? message.getTrueLabel().toString() : null;
        row[PREDICTION_COLUMN] = message.hasPredictedLabel() ? message.getPredictedLabel().toString() : null;
        row[CONFIDENCE_COLUMN] = message.hasPredictionConfidence() ? message.getPredictionConfidence().toString() : null;
        row[SEGMENT_COLUMN] = message.hasSegmentId() ? Integer.toString(message.getSegmentId()) : null;
        out.writeRecord(row);
    }
    out.flush();
    return true;
}
Example 7
Project: geotools-master  File: CSVLatLonStrategy.java View source code
@Override
public void createSchema(SimpleFeatureType featureType) throws IOException {
    List<String> header = new ArrayList<String>();
    GeometryDescriptor geometryDescrptor = featureType.getGeometryDescriptor();
    if (geometryDescrptor != null && CRS.equalsIgnoreMetadata(DefaultGeographicCRS.WGS84, geometryDescrptor.getCoordinateReferenceSystem()) && geometryDescrptor.getType().getBinding().isAssignableFrom(Point.class)) {
        header.add(this.latField);
        header.add(this.lngField);
    } else {
        throw new IOException("Unable use " + this.latField + "/" + this.lngField + " to represent " + geometryDescrptor);
    }
    for (AttributeDescriptor descriptor : featureType.getAttributeDescriptors()) {
        if (descriptor instanceof GeometryDescriptor)
            continue;
        header.add(descriptor.getLocalName());
    }
    // Write out header, producing an empty file of the correct type
    CsvWriter writer = new CsvWriter(new FileWriter(this.csvFileState.getFile()), ',');
    try {
        writer.writeRecord(header.toArray(new String[header.size()]));
    } finally {
        writer.close();
    }
}
Example 8
Project: gephi-neo4j-plugin-master  File: TableCSVExporter.java View source code
/**
     * <p>Export a JTable to the specified file.</p>
     * @param table Table to export
     * @param file File to write
     * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used.
     * @param charset Charset encoding for the file
     * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null
     * @throws IOException When an error happens while writing the file
     */
public static void writeCSVFile(JTable table, File file, Character separator, Charset charset, Integer[] columnsToExport) throws IOException {
    TableModel model = table.getModel();
    FileOutputStream out = new FileOutputStream(file);
    if (separator == null) {
        separator = DEFAULT_SEPARATOR;
    }
    if (columnsToExport == null) {
        columnsToExport = new Integer[model.getColumnCount()];
        for (int i = 0; i < columnsToExport.length; i++) {
            columnsToExport[i] = i;
        }
    }
    CsvWriter writer = new CsvWriter(out, separator, charset);
    //Write column headers:
    for (int column = 0; column < columnsToExport.length; column++) {
        writer.write(model.getColumnName(columnsToExport[column]), true);
    }
    writer.endRecord();
    //Write rows:
    Object value;
    String text;
    for (int row = 0; row < table.getRowCount(); row++) {
        for (int column = 0; column < columnsToExport.length; column++) {
            value = model.getValueAt(table.convertRowIndexToModel(row), columnsToExport[column]);
            if (value != null) {
                text = value.toString();
            } else {
                text = "";
            }
            writer.write(text, true);
        }
        writer.endRecord();
    }
    writer.close();
}
Example 9
Project: WS_2011-master  File: Convert2X.java View source code
public static void Convert2CSV(List<Map<String, Double>> data, String filename) throws IOException {
    CsvWriter writer = new CsvWriter(filename, ',', Charset.forName("ISO-8859-1"));
    // Header row
    for (int i = 0; i < titles.length; i++) {
        writer.write(titles[i]);
    }
    writer.endRecord();
    // copy data
    for (int i = 0; i < data.size(); i++) {
        if (data.get(i) == null)
            continue;
        for (int j = 0; j < quanLayer + 1; j++) {
            double value = 0;
            switch(j) {
                case 0:
                    value = i + 1.0;
                    break;
                case 1:
                    value = data.get(i).get(EB_SECURITY);
                    break;
                case 2:
                    value = data.get(i).get(EB_FUN);
                    break;
                case 3:
                    value = data.get(i).get(EB_SOZIOLOGY);
                    break;
                case 4:
                    value = data.get(i).get(EB_PRODUCTIVITY);
                    break;
            }
            writer.write(String.valueOf(value));
        }
        // new line
        writer.endRecord();
    }
    // save csv data
    writer.close();
}
Example 10
Project: yamcs-master  File: EventViewer.java View source code
void saveTableAs() {
    if (filechooser == null) {
        filechooser = new JFileChooser() {

            private static final long serialVersionUID = 1L;

            @Override
            public File getSelectedFile() {
                File file = super.getSelectedFile();
                if (getFileFilter() instanceof ExtendedFileFilter) {
                    file = ((ExtendedFileFilter) getFileFilter()).appendExtensionIfNeeded(file);
                }
                return file;
            }

            @Override
            public void approveSelection() {
                File file = getSelectedFile();
                if (file.exists()) {
                    int response = JOptionPane.showConfirmDialog(filechooser, "The file " + file + " already exists. Do you want to replace the existing file?", "Overwrite file", JOptionPane.YES_NO_OPTION);
                    if (response != JOptionPane.YES_OPTION) {
                        return;
                    }
                }
                super.approveSelection();
            }
        };
        filechooser.setMultiSelectionEnabled(false);
        FileFilter csvFilter = new ExtendedFileFilter("csv", "CSV File");
        filechooser.addChoosableFileFilter(csvFilter);
        FileFilter txtFilter = new ExtendedFileFilter("txt", "Text File");
        filechooser.addChoosableFileFilter(txtFilter);
        // By default, choose CSV
        filechooser.setFileFilter(csvFilter);
    }
    int ret = filechooser.showSaveDialog(this);
    if (ret == JFileChooser.APPROVE_OPTION) {
        File file = filechooser.getSelectedFile();
        CsvWriter writer = null;
        try {
            writer = new CsvWriter(new FileOutputStream(file), '\t', Charset.forName("UTF-8"));
            int cols = tableModel.getColumnCount();
            String[] colNames = new String[cols];
            colNames[0] = "Source";
            colNames[1] = "Generation Time";
            colNames[2] = "Reception Time";
            colNames[3] = "Event Type";
            colNames[4] = "Event Text";
            for (int i = 5; i < cols; i++) {
                colNames[i] = tableModel.getColumnName(i);
            }
            writer.writeRecord(colNames);
            writer.setForceQualifier(true);
            int iend = tableModel.getRowCount();
            for (int i = 0; i < iend; i++) {
                String[] rec = new String[cols];
                rec[0] = (String) tableModel.getValueAt(i, 0);
                rec[1] = (String) tableModel.getValueAt(i, 1);
                rec[2] = (String) tableModel.getValueAt(i, 2);
                rec[3] = (String) tableModel.getValueAt(i, 3);
                rec[4] = ((Event) tableModel.getValueAt(i, 4)).getMessage();
                for (int j = 5; j < cols; j++) {
                    rec[j] = (String) tableModel.getValueAt(i, j);
                }
                writer.writeRecord(rec);
            }
        } catch (IOException e) {
            e.printStackTrace();
            showMessage("Could not export events to file '" + file.getPath() + "': " + e.getMessage());
        } finally {
            writer.close();
        }
        log("Saved table to " + file.getAbsolutePath());
    }
}
Example 11
Project: starschema-talend-plugins-master  File: GuessSchemaProcess.java View source code
private void buildProcess() {
    process = new Process(property);
    process.getContextManager().getListContext().addAll(node.getProcess().getContextManager().getListContext());
    process.getContextManager().setDefaultContext(this.selectContext);
    outputComponent = ComponentsFactoryProvider.getInstance().get(EDatabaseComponentName.FILEDELIMITED.getOutPutComponentName());
    if (node.getComponent().getModulesNeeded().size() > 0) {
        for (ModuleNeeded module : node.getComponent().getModulesNeeded()) {
            if (module.isRequired(node.getElementParameters())) {
                Node libNode1 = new Node(ComponentsFactoryProvider.getInstance().get(LIB_NODE), process);
                //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                libNode1.setPropertyValue("LIBRARY", "\"" + module.getModuleName() + "\"");
                NodeContainer nc = null;
                if (libNode1.isJoblet()) {
                    nc = new JobletContainer(libNode1);
                } else {
                    nc = new NodeContainer(libNode1);
                }
                process.addNodeContainer(nc);
            }
        }
    } else {
        // hywang add for 9594
        if (node.getComponent().getName().equals("tJDBCInput")) {
            //$NON-NLS-N$
            List<String> drivers = EDatabaseVersion4Drivers.getDrivers(info.getTrueDBTypeForJDBC(), info.getDbVersion());
            String moduleNeedName = "";
            Node libNode1 = new Node(ComponentsFactoryProvider.getInstance().get(LIB_NODE), process);
            if (drivers.size() > 0) {
                // use the first driver as defalult.
                // added for bug 13592
                moduleNeedName = drivers.get(0).toString();
                //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                libNode1.setPropertyValue("LIBRARY", "\"" + moduleNeedName + "\"");
            }
            // for (int i = 0; i < drivers.size(); i++) {
            // moduleNeedName = drivers.get(i).toString();
            //                    libNode1.setPropertyValue("LIBRARY", "\"" + moduleNeedName + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            // }
            process.addNodeContainer(new NodeContainer(libNode1));
        }
    }
    for (IElementParameter param : node.getElementParameters()) {
        List<ModuleNeeded> neededLibraries = new ArrayList<ModuleNeeded>();
        // add by hywang
        JavaProcessUtil.findMoreLibraries(process, neededLibraries, param, true);
        // add for tJDBCInput component
        if (param.getFieldType().equals(EParameterFieldType.MODULE_LIST)) {
            if (!"".equals(param.getValue())) {
                //$NON-NLS-1$
                // if the parameter is not empty.
                String moduleValue = (String) param.getValue();
                //$NON-NLS-1$
                neededLibraries.add(new ModuleNeeded(null, moduleValue, null, true));
            }
            if (param.isShow(node.getElementParameters())) {
                JavaProcessUtil.findMoreLibraries(process, neededLibraries, param, true);
            } else {
                JavaProcessUtil.findMoreLibraries(process, neededLibraries, param, false);
            }
        }
        for (ModuleNeeded module : neededLibraries) {
            Node libNode1 = new Node(ComponentsFactoryProvider.getInstance().get(LIB_NODE), process);
            //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            libNode1.setPropertyValue("LIBRARY", "\"" + module.getModuleName() + "\"");
            process.addNodeContainer(new NodeContainer(libNode1));
        }
    }
    // create the tLibraryLoad for the output component which is "tFileOutputDelimited"
    for (ModuleNeeded module : outputComponent.getModulesNeeded()) {
        Node libNode2 = new Node(ComponentsFactoryProvider.getInstance().get(LIB_NODE), process);
        //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        libNode2.setPropertyValue("LIBRARY", "\"" + module.getModuleName() + "\"");
        process.addNodeContainer(new NodeContainer(libNode2));
    }
    // for sql statement, feature 6622.
    int fetchSize = maximumRowsToPreview;
    if (maximumRowsToPreview > 1000) {
        fetchSize = 1000;
    }
    String codeStart, codeMain, codeEnd;
    temppath = (Path) buildTempCSVFilename();
    // Should also replace "/r". NMa.
    // ISO-8859-15
    memoSQL = memoSQL.replace("\r", " ");
    codeStart = //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    "java.lang.Class.forName(\"" + info.getDriverClassName() + "\");\r\n" + "String url = \"" + info.getUrl() + "\";\r\n" + "java.sql.Connection conn = java.sql.DriverManager.getConnection(url, \"" + //$NON-NLS-1$ //$NON-NLS-2$
    info.getUsername() + "\", \"" + info.getPwd() + "\");\r\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    "java.sql.Statement stm = conn.createStatement();\r\n" + "try {\r\nstm.setFetchSize(" + fetchSize + //$NON-NLS-1$ //$NON-NLS-2$
    ");\r\n} catch (Exception e) {\r\n// Exception is thrown if db don't support, no need to catch exception here\r\n} \r\n" + "java.sql.ResultSet rs = stm.executeQuery(" + memoSQL + //$NON-NLS-1$ //$NON-NLS-2$
    ");\r\n" + "java.sql.ResultSetMetaData rsmd = rs.getMetaData();\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "int numbOfColumn = rsmd.getColumnCount();\r\n" + "\r\n" + "String fileName = (new java.io.File(\r\n" + "                    \"" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    temppath + "\")).getAbsolutePath().replace(\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "                    \"\\\\\", \"/\");\r\n" + //$NON-NLS-1$
    "com.csvreader.CsvWriter csvWriter = new com.csvreader.CsvWriter(\r\n" + //$NON-NLS-1$
    "                    new java.io.BufferedWriter(new java.io.OutputStreamWriter(\r\n" + //$NON-NLS-1$
    "                            new java.io.FileOutputStream(\r\n" + //$NON-NLS-1$
    "                                    fileName, false),\r\n" + "                            \"GBK\")), ';');\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "                            \r\n" + //$NON-NLS-1$
    "csvWriter.setEscapeMode(com.csvreader.CsvWriter.ESCAPE_MODE_DOUBLED);\r\n" + "csvWriter.setTextQualifier('\"');\r\n" + "csvWriter.setForceQualifier(true);\r\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    "int nbRows = 0;\r\n" + "String[] columnNames = new String[numbOfColumn];\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "String[] nullables = new String[numbOfColumn];\r\n" + "String[] lengths = new String[numbOfColumn];\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "String[] precisions = new String[numbOfColumn];\r\n" + //$NON-NLS-1$
    "String[] dbtypes = new String[numbOfColumn];\r\n" + "for(int i = 1;i<=numbOfColumn;i++){\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "columnNames[i-1] = rsmd.getColumnName(i);\r\n" + //$NON-NLS-1$
    "nullables[i-1] = rsmd.isNullable(i) == 0? \"false\" : \"true\";\r\n" + //$NON-NLS-1$
    "lengths[i-1] = Integer.toString(rsmd.getScale(i));\r\n" + //$NON-NLS-1$
    "precisions[i-1] = Integer.toString(rsmd.getPrecision(i));" + "dbtypes[i-1] = rsmd.getColumnTypeName(i);\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "}\r\n" + "csvWriter.writeRecord(columnNames);\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "csvWriter.writeRecord(nullables);\r\n" + "csvWriter.writeRecord(lengths);\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "csvWriter.writeRecord(precisions);\r\n" + "csvWriter.writeRecord(dbtypes);\r\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    "while (rs.next()) {";
    codeMain = //$NON-NLS-1$ //$NON-NLS-2$
    "String[] dataOneRow = new String[numbOfColumn];\r\n" + "for (int i = 1; i <= numbOfColumn; i++) {\r\n" + "    \r\n" + "    String tempStr = rs.getString(i);\r\n" + "    dataOneRow[i-1] = tempStr;\r\n" + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    "}\r\n" + //$NON-NLS-1$
    "csvWriter.writeRecord(dataOneRow);";
    codeEnd = //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
    "nbRows++;\r\n" + "    if (nbRows > " + maximumRowsToPreview + ") break;\r\n" + "}\r\n" + "stm.close();\r\n" + "conn.close();\r\n" + //$NON-NLS-1$ //$NON-NLS-2$
    "csvWriter.close();\r\n";
    IComponent component = null;
    switch(LanguageManager.getCurrentLanguage()) {
        case JAVA:
            //$NON-NLS-1$
            component = ComponentsFactoryProvider.getInstance().get("tJavaFlex");
            break;
        case PERL:
        default:
            //$NON-NLS-1$
            component = ComponentsFactoryProvider.getInstance().get("tPerlFlex");
            break;
    }
    //$NON-NLS-1$
    Node flexNode = new Node(component, process);
    //$NON-NLS-1$
    flexNode.setPropertyValue("CODE_START", codeStart);
    //$NON-NLS-1$
    flexNode.setPropertyValue("CODE_MAIN", codeMain);
    //$NON-NLS-1$
    flexNode.setPropertyValue("CODE_END", codeEnd);
    process.addNodeContainer(new NodeContainer(flexNode));
}
Example 12
Project: AirCastingAndroidClient-master  File: CSVHelper.java View source code
public Uri prepareCSV(Session session) throws IOException {
    try {
        File storage = Environment.getExternalStorageDirectory();
        File dir = new File(storage, "aircasting_sessions");
        dir.mkdirs();
        File file = new File(dir, fileName(session.getTitle()) + ZIP_EXTENSION);
        OutputStream outputStream = new FileOutputStream(file);
        closer.register(outputStream);
        ZipOutputStream zippedOutputStream = new ZipOutputStream(outputStream);
        zippedOutputStream.putNextEntry(new ZipEntry(fileName(session.getTitle()) + CSV_EXTENSION));
        Writer writer = new OutputStreamWriter(zippedOutputStream);
        CsvWriter csvWriter = new CsvWriter(writer, ',');
        write(session).toWriter(csvWriter);
        csvWriter.flush();
        csvWriter.close();
        Uri uri = Uri.fromFile(file);
        if (Constants.isDevMode()) {
            Logger.i("File path [" + uri + "]");
        }
        return uri;
    } finally {
        closer.close();
    }
}
Example 13
Project: cta-otp-master  File: GraphStats.java View source code
private void run() {
    /* open input graph (same for all commands) */
    File graphFile = new File(graphPath);
    try {
        graph = Graph.load(graphFile, Graph.LoadLevel.FULL);
    } catch (Exception e) {
        LOG.error("Exception while loading graph from " + graphFile);
        return;
    }
    /* open output stream (same for all commands) */
    if (outPath != null) {
        try {
            writer = new CsvWriter(outPath, ',', Charset.forName("UTF8"));
        } catch (Exception e) {
            LOG.error("Exception while opening output file " + outPath);
            return;
        }
    } else {
        writer = new CsvWriter(System.out, ',', Charset.forName("UTF8"));
    }
    LOG.info("done loading graph.");
    String command = jc.getParsedCommand();
    if (command.equals("endpoints")) {
        commandEndpoints.run();
    } else if (command.equals("speedstats")) {
        commandSpeedStats.run();
    } else if (command.equals("patternstats")) {
        commandPatternStats.run();
    }
    writer.close();
}
Example 14
Project: FDEB-master  File: TableCSVExporter.java View source code
/**
     * <p>Export a JTable to the specified file.</p>
     * @param table Table to export
     * @param file File to write
     * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used.
     * @param charset Charset encoding for the file
     * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null
     * @throws IOException When an error happens while writing the file
     */
public static void writeCSVFile(JTable table, File file, Character separator, Charset charset, Integer[] columnsToExport) throws IOException {
    TableModel model = table.getModel();
    FileOutputStream out = new FileOutputStream(file);
    if (separator == null) {
        separator = DEFAULT_SEPARATOR;
    }
    if (columnsToExport == null) {
        columnsToExport = new Integer[model.getColumnCount()];
        for (int i = 0; i < columnsToExport.length; i++) {
            columnsToExport[i] = i;
        }
    }
    CsvWriter writer = new CsvWriter(out, separator, charset);
    //Write column headers:
    for (int column = 0; column < columnsToExport.length; column++) {
        writer.write(model.getColumnName(columnsToExport[column]), true);
    }
    writer.endRecord();
    //Write rows:
    Object value;
    String text;
    for (int row = 0; row < table.getRowCount(); row++) {
        for (int column = 0; column < columnsToExport.length; column++) {
            value = model.getValueAt(table.convertRowIndexToModel(row), columnsToExport[column]);
            if (value != null) {
                text = value.toString();
            } else {
                text = "";
            }
            writer.write(text, true);
        }
        writer.endRecord();
    }
    writer.close();
}
Example 15
Project: gephi-gsoc13-legendmodule-master  File: TableCSVExporter.java View source code
/**
     * <p>Export a JTable to the specified file.</p>
     * @param table Table to export
     * @param file File to write
     * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used.
     * @param charset Charset encoding for the file
     * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null
     * @throws IOException When an error happens while writing the file
     */
public static void writeCSVFile(JTable table, File file, Character separator, Charset charset, Integer[] columnsToExport) throws IOException {
    TableModel model = table.getModel();
    FileOutputStream out = new FileOutputStream(file);
    if (separator == null) {
        separator = DEFAULT_SEPARATOR;
    }
    if (columnsToExport == null) {
        columnsToExport = new Integer[model.getColumnCount()];
        for (int i = 0; i < columnsToExport.length; i++) {
            columnsToExport[i] = i;
        }
    }
    CsvWriter writer = new CsvWriter(out, separator, charset);
    //Write column headers:
    for (int column = 0; column < columnsToExport.length; column++) {
        writer.write(model.getColumnName(columnsToExport[column]), true);
    }
    writer.endRecord();
    //Write rows:
    Object value;
    String text;
    for (int row = 0; row < table.getRowCount(); row++) {
        for (int column = 0; column < columnsToExport.length; column++) {
            value = model.getValueAt(table.convertRowIndexToModel(row), columnsToExport[column]);
            if (value != null) {
                text = value.toString();
            } else {
                text = "";
            }
            writer.write(text, true);
        }
        writer.endRecord();
    }
    writer.close();
}
Example 16
Project: longneck-core-master  File: CsvTarget.java View source code
@Override
public void init() {
    if (path == null) {
        // Read target path from runtime properties
        path = runtimeProperties.getProperty(String.format("csvTarget.%1$s.path", name));
    }
    try {
        // Initialize writer
        writer = new CsvWriter(new BufferedWriter(new FileWriter(path)), delimiter);
        if (columns == null) {
            Logger.getLogger(CsvTarget.class).info("Output columns unspecified, using detection from first record.");
        } else {
            headerFieldMapping = new LinkedHashMap<String, String>();
            String[] keyVal;
            for (String c : columns) {
                // Check, if the column is mapped
                if (c.contains("=")) {
                    keyVal = c.split("=");
                } else {
                    keyVal = new String[] { c, c };
                }
                headerFieldMapping.put(trimColumnName(keyVal[0]), trimColumnName(keyVal[1]));
            }
            // Write header
            writer.writeRecord(headerFieldMapping.keySet().toArray(new String[0]));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 17
Project: magnificent-mileage-master  File: GraphStats.java View source code
private void run() {
    /* open input graph (same for all commands) */
    File graphFile = new File(graphPath);
    try {
        graph = Graph.load(graphFile, Graph.LoadLevel.FULL);
    } catch (Exception e) {
        LOG.error("Exception while loading graph from " + graphFile);
        return;
    }
    /* open output stream (same for all commands) */
    if (outPath != null) {
        try {
            writer = new CsvWriter(outPath, ',', Charset.forName("UTF8"));
        } catch (Exception e) {
            LOG.error("Exception while opening output file " + outPath);
            return;
        }
    } else {
        writer = new CsvWriter(System.out, ',', Charset.forName("UTF8"));
    }
    LOG.info("done loading graph.");
    String command = jc.getParsedCommand();
    if (command.equals("endpoints")) {
        commandEndpoints.run();
    } else if (command.equals("speedstats")) {
        commandSpeedStats.run();
    } else if (command.equals("patternstats")) {
        commandPatternStats.run();
    }
    writer.close();
}
Example 18
Project: OpenTripPlanner-master  File: GraphStats.java View source code
private void run() {
    /* open input graph (same for all commands) */
    File graphFile = new File(graphPath);
    try {
        graph = Graph.load(graphFile, Graph.LoadLevel.FULL);
    } catch (Exception e) {
        LOG.error("Exception while loading graph from " + graphFile);
        return;
    }
    /* open output stream (same for all commands) */
    if (outPath != null) {
        try {
            writer = new CsvWriter(outPath, ',', Charset.forName("UTF8"));
        } catch (Exception e) {
            LOG.error("Exception while opening output file " + outPath);
            return;
        }
    } else {
        writer = new CsvWriter(System.out, ',', Charset.forName("UTF8"));
    }
    LOG.info("done loading graph.");
    String command = jc.getParsedCommand();
    if (command.equals("endpoints")) {
        commandEndpoints.run();
    } else if (command.equals("speedstats")) {
        commandSpeedStats.run();
    } else if (command.equals("patternstats")) {
        commandPatternStats.run();
    }
    writer.close();
}
Example 19
Project: Planner-master  File: GraphStats.java View source code
private void run() {
    /* open input graph (same for all commands) */
    File graphFile = new File(graphPath);
    try {
        graph = Graph.load(graphFile, Graph.LoadLevel.FULL);
    } catch (Exception e) {
        LOG.error("Exception while loading graph from " + graphFile);
        return;
    }
    /* open output stream (same for all commands) */
    if (outPath != null) {
        try {
            writer = new CsvWriter(outPath, ',', Charset.forName("UTF8"));
        } catch (Exception e) {
            LOG.error("Exception while opening output file " + outPath);
            return;
        }
    } else {
        writer = new CsvWriter(System.out, ',', Charset.forName("UTF8"));
    }
    LOG.info("done loading graph.");
    String command = jc.getParsedCommand();
    if (command.equals("endpoints")) {
        commandEndpoints.run();
    } else if (command.equals("speedstats")) {
        commandSpeedStats.run();
    } else if (command.equals("patternstats")) {
        commandPatternStats.run();
    }
    writer.close();
}
Example 20
Project: ranger-master  File: CSVFormatter.java View source code
/**
     * Called to output the data.  This class uses a third party library to output
     * the CSV data.  The library escapes the data as needed.
     *
     * @param out the PrintStream to output data to.
     * @param resultSet the ResultSet for the row.
     * @param metaData the ResultSetMetaData for the row.
     *
     *
     */
public void formatData(PrintStream out, ResultSet resultSet, ResultSetMetaData metaData) throws Exception {
    CsvWriter csvWriter = new CsvWriter(out, delimiter, Charset.forName("us-ascii"));
    while (resultSet.next()) {
        int numColumns = metaData.getColumnCount();
        for (int i = 1; i <= numColumns; i++) {
            String result = resultSet.getString(i);
            if (!resultSet.wasNull())
                csvWriter.write(result);
            else
                csvWriter.write("");
        }
        csvWriter.endRecord();
    }
    csvWriter.flush();
}
Example 21
Project: alfresco-audit-share-master  File: AuditExportGet.java View source code
@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    try {
        if (PermissionsHelper.isAuthorized(req)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Charset charset = // ISO-8859-1
            Charset.forName(// ISO-8859-1
            "UTF-8");
            CsvWriter csv = new CsvWriter(baos, ',', charset);
            Map<String, Object> model = new HashMap<String, Object>();
            AuditQueryParameters params = wsSelectAudits.buildParametersFromRequest(req);
            String interval = req.getParameter("interval");
            String type = req.getParameter("type");
            if (type.equals("volumetry") || type.equals("users-count")) {
                String values = req.getParameter("values");
                model.put("values", values.split(","));
            } else {
                wsSelectAudits.checkForQuery(model, params, type);
            }
            buildCsvFromRequest(model, csv, params, type, interval);
            csv.close();
            res.setHeader("Content-Disposition", "attachment; filename=\"export.csv\"");
            // application/octet-stream
            res.setContentType("application/csv");
            baos.writeTo(res.getOutputStream());
        } else {
            res.setStatus(Status.STATUS_UNAUTHORIZED);
        }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        res.reset();
    }
}
Example 22
Project: esms-master  File: ExportManager.java View source code
/** Export contacts to csv format
     * @param contacts contacts, not null
     * @param out output stream, not null
     */
public static void exportContacts(Collection<Contact> contacts, OutputStream out) throws IOException {
    Validate.notNull(contacts);
    Validate.notNull(out);
    logger.finer("Exporting " + contacts.size() + " contacts to CSV");
    CsvWriter writer = new CsvWriter(out, ',', Charset.forName("UTF-8"));
    writer.writeComment(l10n.getString("ExportManager.contact_list"));
    for (Contact contact : contacts) {
        writer.writeRecord(new String[] { contact.getName(), contact.getNumber(), contact.getGateway() });
    }
    writer.flush();
}
Example 23
Project: meclipse-master  File: MeclipsePlugin.java View source code
private void saveServers() {
    // save server preferences here
    CsvWriter writer = null;
    try {
        IPath libPath = getStateLocation();
        libPath = libPath.append("servers.cfg");
        File file = libPath.toFile();
        if (!file.exists()) {
            file.createNewFile();
        }
        writer = new CsvWriter(new FileWriter(file, false), ',');
        for (MongoInstance server : mongoInstances.values()) {
            writer.write(server.getName());
            writer.write(server.getHost());
            writer.write(String.valueOf(server.getPort()));
            writer.endRecord();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
Example 24
Project: sleeparchiver-master  File: Document.java View source code
static String join(List<String> columns) {
    try {
        StringWriter buffer = new StringWriter();
        CsvWriter writer = new CsvWriter(buffer, ';');
        writer.writeRecord(columns.toArray(new String[] {}));
        writer.close();
        return buffer.toString().trim().replaceAll("\r", "\\\\r").replaceAll("\n", "\\\\n");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 25
Project: aliyun-odps-java-sdk-master  File: WareHouse.java View source code
/**
   * copy output data files from job directory to warehouse
   *
   * @param srcDir
   * @param indexes
   * @param destDir
   * @throws IOException
   */
public void copyDataFiles(File srcDir, List<Integer> indexes, File destDir, char inputColumnSeperator) throws IOException {
    if (indexes == null || indexes.isEmpty()) {
        for (File file : LocalRunUtils.listDataFiles(srcDir)) {
            FileUtils.copyFileToDirectory(file, destDir);
        }
    } else {
        for (File file : LocalRunUtils.listDataFiles(srcDir)) {
            CsvReader reader = DownloadUtils.newCsvReader(file.getAbsolutePath(), inputColumnSeperator, encoding);
            CsvWriter writer = new CsvWriter(new File(destDir, file.getName()).getAbsolutePath(), inputColumnSeperator, encoding);
            while (reader.readRecord()) {
                String[] vals = reader.getValues();
                String[] newVals = new String[indexes.size()];
                for (int i = 0; i < indexes.size(); ++i) {
                    newVals[i] = vals[indexes.get(i)];
                }
                writer.writeRecord(newVals);
            }
            writer.close();
            reader.close();
        }
    }
}
Example 26
Project: liferay-webforms-master  File: WebFormControlBean.java View source code
public void downloadResults(Long formId) throws IOException, PortalException, SystemException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out);
    char separator = ';';
    CsvWriter csvWriter = new CsvWriter(writer, separator);
    int offset = 2;
    Form form = formController.getForm(formId);
    List<Field> fields = new ArrayList<Field>(form.getFields());
    Collections.sort(fields, Form.fieldWeightComparator);
    List<FormResult> formResults = formController.getFormResults(formId);
    String[] header = new String[fields.size() + offset];
    header[0] = "screename";
    header[1] = "creation";
    int y = offset;
    for (Field field : fields) {
        header[y] = field.getName();
        y++;
    }
    csvWriter.writeRecord(header);
    for (FormResult formResult : formResults) {
        // Users
        String[] values = new String[fields.size() + offset];
        values[0] = "0";
        if (!formResult.getUserId().equals(new Long(0))) {
            User user = null;
            try {
                user = UserLocalServiceUtil.getUser(formResult.getUserId());
                values[0] = user.getScreenName();
            } catch (PortalException e) {
                e.printStackTrace();
            } catch (SystemException e) {
                e.printStackTrace();
            }
        }
        // Date
        DateTime dateTime = new DateTime(formResult.getCreated());
        values[1] = dateTime.getDayOfMonth() + "/" + dateTime.getMonthOfYear() + "/" + dateTime.getYear() + " " + dateTime.getHourOfDay() + ":" + dateTime.getMinuteOfHour() + ":" + dateTime.getSecondOfMinute();
        int x = offset;
        for (Field field : fields) {
            String content = "";
            if (field.getName().equals("text")) {
                content = field.getValue().getContent();
            } else {
                for (FieldResult fieldResult : formResult.getFields()) {
                    if (field.getId().equals(fieldResult.getFieldId())) {
                        content = fieldResult.getContent();
                    }
                }
            }
            values[x] = content;
            x++;
        }
        csvWriter.writeRecord(values);
    }
    csvWriter.close();
    PortletRequest portletRequest = (PortletRequest) LiferayFacesContext.getCurrentInstance().getExternalContext().getRequest();
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    Long groupId = themeDisplay.getCompany().getGroup().getGroupId();
    DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(groupId, new Long(0), DefaultValuesBuilder.FOLDER_DOWNLOAD);
    DateTime dateTime = new DateTime();
    ServiceContext serviceContext = new ServiceContext();
    Long userId = themeDisplay.getCompany().getDefaultUser().getUserId();
    long repositoryId = groupId;
    long folderId = dlFolder.getFolderId();
    String sourceFileName = "webform_export_" + dateTime.getDayOfMonth() + "-" + dateTime.getMonthOfYear() + "-" + dateTime.getYear() + "_" + dateTime.getMillis() + ".csv";
    String mimeType = "application/csv";
    String title = sourceFileName;
    String description = "";
    String changeLog = "";
    long fileEntryTypeId = new Long(0);
    Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
    File file = null;
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    long size = out.toByteArray().length;
    DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, repositoryId, folderId, sourceFileName, mimeType, title, description, changeLog, fileEntryTypeId, fieldsMap, file, is, size, serviceContext);
    String url = "/../documents/" + groupId + "/" + folderId + "/" + URLEncoder.encode(dlFileEntry.getName(), "UTF-8") + "/" + dlFileEntry.getUuid();
    FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
Example 27
Project: csv2rdf4lod-automation-master  File: AllTests.java View source code
@Test
public void test31() throws Exception {
    CsvWriter writer = new CsvWriter(new PrintWriter(new OutputStreamWriter(new FileOutputStream("temp.csv"), Charset.forName("UTF-8"))), ',');
    // writer will trim all whitespace and put this in quotes to preserve
    // it's existance
    writer.write(" \t \t");
    writer.close();
    CsvReader reader = new CsvReader(new InputStreamReader(new FileInputStream("temp.csv"), Charset.forName("UTF-8")));
    Assert.assertTrue(reader.readRecord());
    Assert.assertEquals("", reader.get(0));
    Assert.assertEquals(1, reader.getColumnCount());
    Assert.assertEquals(0L, reader.getCurrentRecord());
    Assert.assertEquals("\"\"", reader.getRawRecord());
    Assert.assertFalse(reader.readRecord());
    reader.close();
    new File("temp.csv").delete();
}
Example 28
Project: Dead-Reckoning-Android-master  File: AllTests.java View source code
@Test
public void test31() throws Exception {
    CsvWriter writer = new CsvWriter(new PrintWriter(new OutputStreamWriter(new FileOutputStream("temp.csv"), Charset.forName("UTF-8"))), ',');
    // writer will trim all whitespace and put this in quotes to preserve
    // it's existence
    writer.write(" \t \t");
    writer.close();
    CsvReader reader = new CsvReader(new InputStreamReader(new FileInputStream("temp.csv"), Charset.forName("UTF-8")));
    Assert.assertTrue(reader.readRecord());
    Assert.assertEquals("", reader.get(0));
    Assert.assertEquals(1, reader.getColumnCount());
    Assert.assertEquals(0L, reader.getCurrentRecord());
    Assert.assertEquals("\"\"", reader.getRawRecord());
    Assert.assertFalse(reader.readRecord());
    reader.close();
    new File("temp.csv").delete();
}
Example 29
Project: ef-orm-master  File: CsvWriter.java View source code
/**
	 * 
	 */
private void checkClosed() throws IOException {
    if (closed) {
        throw new IOException("This instance of the CsvWriter class has already been closed.");
    }
}
Example 30
Project: geolocator-3.0-master  File: CsvWriter.java View source code
/**
	 * 
	 */
private void checkClosed() throws IOException {
    if (closed) {
        throw new IOException("This instance of the CsvWriter class has already been closed.");
    }
}
Example 31
Project: JavaMultiAgentSocial-master  File: CsvWriter.java View source code
/**
   * 
   */
private void checkClosed() throws IOException {
    if (closed) {
        throw new IOException("This instance of the CsvWriter class has already been closed.");
    }
}
Example 32
Project: shade-master  File: CsvWriter.java View source code
/**
	 * 
	 */
private void checkClosed() throws IOException {
    if (closed) {
        throw new IOException("This instance of the CsvWriter class has already been closed.");
    }
}
Example 33
Project: PhotoSpread-master  File: CsvWriter.java View source code
/**
	 * 
	 */
private void checkClosed() throws IOException {
    if (closed) {
        throw new IOException("This instance of the CsvWriter class has already been closed.");
    }
}