com.opencsv.CSVWriter Java Examples

The following examples show how to use com.opencsv.CSVWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MatchServiceTest.java    From fuzzy-matcher with Apache License 2.0 7 votes vote down vote up
public static void writeOutput(Set<Set<Match<Document>>> result) throws IOException {
    CSVWriter writer = new CSVWriter(new FileWriter("src/test/resources/output.csv"));
    writer.writeNext(new String[]{"Key", "Matched Key", "Score", "Name", "Address", "Email", "Phone"});

    result.forEach(matches -> {
        String[] arr = {"Group"};
        writer.writeNext(arr);

        matches.stream().forEach(match -> {
                    Document md = match.getMatchedWith();
                    String[] matchArrs = Stream.concat(Stream.of("", md.getKey(), Double.toString(match.getResult())),
                            getOrderedElements(md.getElements()).map(e -> e.getValue())).toArray(String[]::new);
                    writer.writeNext(matchArrs);
                });
            });
    writer.close();
}
 
Example #2
Source File: GtfsTools.java    From pt2matsim with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Experimental class to write stops.txt (i.e. after filtering for one date)
 */
public static void writeStops(Collection<Stop> stops, String path) throws IOException {
	CSVWriter stopsWriter = new CSVWriter(new FileWriter(path + GtfsDefinitions.Files.STOPS.fileName), ',');
	String[] header = GtfsDefinitions.Files.STOPS.columns;
	stopsWriter.writeNext(header, true);
	for(Stop stop : stops) {
		// STOP_ID, STOP_LON, STOP_LAT, STOP_NAME
		String[] line = new String[header.length];
		line[0] = stop.getId();
		line[1] = String.valueOf(stop.getLon());
		line[2] = String.valueOf(stop.getLat());
		line[3] = stop.getName();
		stopsWriter.writeNext(line);
	}
	stopsWriter.close();
}
 
Example #3
Source File: ObjectDataExportServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
private MetaFile writeCSV(Map<String, List<String[]>> data) throws IOException {

    File zipFile = MetaFiles.createTempFile("Data", ".zip").toFile();
    try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile))) {

      for (String model : data.keySet()) {
        File modelFile = MetaFiles.createTempFile(model, ".csv").toFile();
        CSVWriter writer = new CSVWriter(new FileWriter(modelFile), ';');
        writer.writeAll(data.get(model));
        writer.close();
        zout.putNextEntry(new ZipEntry(model + ".csv"));
        zout.write(IOUtils.toByteArray(new FileInputStream(modelFile)));
        zout.closeEntry();
      }
      zout.close();
    }
    return metaFiles.upload(zipFile);
  }
 
Example #4
Source File: GtfsTools.java    From pt2matsim with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Experimental class to write transfers.txt (i.e. after creating additional walk transfer)
 */
public static void writeTransfers(Collection<Transfer> transfers, String path) throws IOException {
	CSVWriter transfersWiter = new CSVWriter(new FileWriter(path + GtfsDefinitions.Files.TRANSFERS.fileName), ',');
	String[] columns = GtfsDefinitions.Files.TRANSFERS.columns;
	String[] optionalColumns = GtfsDefinitions.Files.TRANSFERS.optionalColumns;
	String[] header = Stream.concat(Arrays.stream(columns), Arrays.stream(optionalColumns)).toArray(String[]::new);
	transfersWiter.writeNext(header, true);
	for(Transfer transfer : transfers) {
		// FROM_STOP_ID, TO_STOP_ID, TRANSFER_TYPE, (MIN_TRANSFER_TIME)
		String[] line = new String[header.length];
		line[0] = transfer.getFromStopId();
		line[1] = transfer.getToStopId();
		line[2] = String.valueOf(transfer.getTransferType().index);
		String minTransferTime = (transfer.getMinTransferTime() != null ? transfer.getMinTransferTime().toString() : "");
		line[3] = minTransferTime;
		transfersWiter.writeNext(line);
	}
	transfersWiter.close();
}
 
Example #5
Source File: CsvFormatter.java    From yarg with Apache License 2.0 6 votes vote down vote up
protected void writeCsvDocument(BandData rootBand, OutputStream outputStream) {
    try {
        List<BandData> actualData = getActualData(rootBand);
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(outputStream), separator, CSVWriter.DEFAULT_QUOTE_CHARACTER);

        writer.writeNext(header);

        for (BandData row : actualData) {
            String[] entries = new String[parametersToInsert.size()];
            for (int i = 0; i < parametersToInsert.size(); i++) {
                String parameterName = parametersToInsert.get(i);
                String fullParameterName = row.getName() + "." + parameterName;
                entries[i] = formatValue(row.getData().get(parameterName), parameterName, fullParameterName);
            }
            writer.writeNext(entries);
        }

        writer.close();
    } catch (IOException e) {
        throw new ReportFormattingException("Error while writing a csv document", e);
    }
}
 
Example #6
Source File: BeanExamples.java    From tutorials with MIT License 6 votes vote down vote up
public static String writeCsvFromBean(Path path) {
    try {
        Writer writer = new FileWriter(path.toString());

        StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR)
            .build();

        List<CsvBean> list = new ArrayList<>();
        list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd"));
        list.add(new WriteExampleBean("Test2", "ipso", "facto"));

        sbc.write(list);
        writer.close();

    } catch (Exception ex) {
        Helpers.err(ex);
    }
    return Helpers.readFile(path);
}
 
Example #7
Source File: MatchServiceTest.java    From fuzzy-matcher with Apache License 2.0 6 votes vote down vote up
public static void writeOutput(Map<String, List<Match<Document>>> result) throws IOException {
    CSVWriter writer = new CSVWriter(new FileWriter("src/test/resources/output.csv"));
    writer.writeNext(new String[]{"Key", "Matched Key", "Score", "Name", "Address", "Email", "Phone"});

    result.entrySet().stream().sorted(Map.Entry.<String, List<Match<Document>>>comparingByKey())
            .forEach(entry -> {
                String[] keyArrs = Stream.concat(Stream.of(entry.getKey(), entry.getKey(), ""),
                        getOrderedElements(entry.getValue().stream()
                                .map(match -> match.getData())
                                .findFirst().get()
                                .getElements()).map(e -> e.getValue())).toArray(String[]::new);
                writer.writeNext(keyArrs);

                entry.getValue().stream().forEach(match -> {
                    Document md = match.getMatchedWith();
                    String[] matchArrs = Stream.concat(Stream.of("", md.getKey(), Double.toString(match.getResult())),
                            getOrderedElements(md.getElements()).map(e -> e.getValue())).toArray(String[]::new);
                    writer.writeNext(matchArrs);
                    LOGGER.info("        " + match);
                });
            });
    writer.close();
}
 
Example #8
Source File: UserController.java    From code-examples with MIT License 6 votes vote down vote up
@GetMapping("/export-users")
public void exportCSV(HttpServletResponse response) throws Exception {

    //set file name and content type
    String filename = "users.csv";

    response.setContentType("text/csv");
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"" + filename + "\"");

    //create a csv writer
    StatefulBeanToCsv<User> writer = new StatefulBeanToCsvBuilder<User>(response.getWriter())
            .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
            .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
            .withOrderedResults(false)
            .build();

    //write all users to csv file
    writer.write(userService.listUsers());

}
 
Example #9
Source File: GenePvalueCalculator.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
private static void saveEigenValues(double[] eigenValues, File file) throws IOException {

		final CSVWriter eigenWriter = new CSVWriter(new FileWriter(file), '\t', '\0', '\0', "\n");
		final String[] outputLine = new String[2];
		int c = 0;
		outputLine[c++] = "Component";
		outputLine[c++] = "EigenValue";
		eigenWriter.writeNext(outputLine);

		for (int i = 0; i < eigenValues.length; ++i) {

			c = 0;
			outputLine[c++] = "PC" + (i + 1);
			outputLine[c++] = String.valueOf(eigenValues[i]);
			eigenWriter.writeNext(outputLine);

		}

		eigenWriter.close();

	}
 
Example #10
Source File: HostSubDao.java    From burp_data_collector with Apache License 2.0 6 votes vote down vote up
public void exportSub(String dirName, int subCount) throws SQLException, IOException {
    String sql = "SELECT stat.sub, sum(subCount) AS allCount\n" +
            "FROM ((SELECT hsm.sub, count(*) AS subCount FROM host_sub_map hsm GROUP BY hsm.sub)\n" +
            "      UNION ALL\n" +
            "      (SELECT sub, count AS subCount FROM sub)) stat\n" +
            "GROUP BY stat.sub\n" +
            "HAVING allCount >= ?\n" +
            "ORDER BY allCount DESC";
    PreparedStatement preparedStatement = getPreparedStatement(sql);
    preparedStatement.setInt(1, subCount);
    ResultSet resultSet = preparedStatement.executeQuery();

    File subFile = new File(dirName + SUB_FILE);
    File subImportFile = new File(dirName + SUB_IMPORT_FILE);
    FileOutputStream pathOutputStream = new FileOutputStream(subFile);
    FileWriter fileWriter = new FileWriter(subImportFile);
    CSVWriter csvWriter = new CSVWriter(fileWriter);
    String[] fileHead = {"sub", "count"};
    csvWriter.writeNext(fileHead);
    while (resultSet.next()) {
        String sub = resultSet.getString(1);
        String row = sub + "\n";
        int count = resultSet.getInt(2);
        pathOutputStream.write(row.getBytes());
        csvWriter.writeNext(new String[]{sub, String.valueOf(count)}, true);
    }
    pathOutputStream.close();
    csvWriter.close();
}
 
Example #11
Source File: Init4pxp2p.java    From WeSync with MIT License 6 votes vote down vote up
public static boolean init() {
    StatusLog.setStatusDetail("开始初始化第一次快照,请耐心等待……", LogLevel.INFO);

    boolean isSuccess = true;
    DbUtilMySQL mySql = DbUtilMySQL.getInstance();
    DbUtilSQLServer sqlserver = DbUtilSQLServer.getInstance();
    CSVWriter csvWriterRole = null;
    CSVWriter csvWriterUser = null;
    File snapsDir = null;
    StatusPanel.progressCurrent.setMaximum(7);
    int progressValue = 0;
    StatusPanel.progressCurrent.setValue(progressValue);

    /*Do Sth you need to init*/
    return isSuccess;
}
 
Example #12
Source File: AbstractCsvConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
  super.doInitialize(aContext);

  try {
    // Attempt to create the path if it doesn't exist
    new File(filename).getParentFile().mkdirs();

    writer =
        new CSVWriter(
            new OutputStreamWriter(new FileOutputStream(filename, false), StandardCharsets.UTF_8),
            separator.charAt(0),
            getQuote(),
            getEscape(),
            lineEnding);
  } catch (final IOException e) {
    throw new ResourceInitializationException(e);
  }
}
 
Example #13
Source File: CsvInteractionWriter.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public void initialise() throws IOException {
  // Create the parent dirs
  new File(csvFilename).getAbsoluteFile().getParentFile().mkdirs();

  writer =
      new CSVWriter(
          new FileWriter(csvFilename, false),
          CSVWriter.DEFAULT_SEPARATOR,
          CSVWriter.NO_QUOTE_CHARACTER,
          CSVWriter.DEFAULT_ESCAPE_CHARACTER,
          CSVWriter.DEFAULT_LINE_END);

  // Print the header
  writer.writeNext(
      new String[] {
        "Type", "Subtype", "Source type", "Target type", "Lemma", "Lemma POS", "Alternatives...."
      });
}
 
Example #14
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void saveInternal(String outputFileName, boolean append) {
    try (CSVWriter writer = new CSVWriter(new FileWriter(outputFileName, append), SEPARATOR)) {
        if (append) {
            if (!headerWritten) {
                write(writer, Entry.header, null, null);
                headerWritten = true;
            }
        } else {
            write(writer, Entry.header, null, null);
        }

        Map<Level, LoadRecord> loadMap = load.getLoadMap();
        for (Map.Entry<Level, LoadRecord> entry : loadMap.entrySet()) {
            Level level = entry.getKey();
            LoadRecord loadRecord = entry.getValue();

            write(writer, Entry.body, level, loadRecord);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void write(CSVWriter writer, Entry entry, Level level, LoadRecord loadRecord) {
    String[] record = new String[RegionLoadAdapter.loadEntries.length + 2];
    if (entry == Entry.header) {
        record[0] = load.getLevelClass().getLevelTypeString();
        record[1] = HEADER_TIMESTAMP;
    } else {
        record[0] = level.toString();
        record[1] = String.valueOf(load.getTimestampIteration());
    }
    for (LoadEntry loadEntry : RegionLoadAdapter.loadEntries) {
        if (entry == Entry.header) {
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = loadEntry.name();
        } else {
            Number number = loadRecord.get(loadEntry);
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = number == null ? "" : number.toString();
        }
    }
    writer.writeNext(record);
}
 
Example #16
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void saveInternal(String outputFileName, boolean append) {
    try (CSVWriter writer = new CSVWriter(new FileWriter(outputFileName, append), SEPARATOR)) {
        if (append) {
            if (!headerWritten) {
                write(writer, Entry.header, null, null);
                headerWritten = true;
            }
        } else {
            write(writer, Entry.header, null, null);
        }

        Map<Level, LoadRecord> loadMap = load.getLoadMap();
        for (Map.Entry<Level, LoadRecord> entry : loadMap.entrySet()) {
            Level level = entry.getKey();
            LoadRecord loadRecord = entry.getValue();

            write(writer, Entry.body, level, loadRecord);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void write(CSVWriter writer, Entry entry, Level level, LoadRecord loadRecord) {
    String[] record = new String[RegionLoadAdapter.loadEntries.length + 2];
    if (entry == Entry.header) {
        record[0] = load.getLevelClass().getLevelTypeString();
        record[1] = HEADER_TIMESTAMP;
    } else {
        record[0] = level.toString();
        record[1] = String.valueOf(load.getTimestampIteration());
    }
    for (LoadEntry loadEntry : RegionLoadAdapter.loadEntries) {
        if (entry == Entry.header) {
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = loadEntry.name();
        } else {
            Number number = loadRecord.get(loadEntry);
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = number == null ? "" : number.toString();
        }
    }
    writer.writeNext(record);
}
 
Example #18
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void saveInternal(String outputFileName, boolean append) {
    try (CSVWriter writer = new CSVWriter(new FileWriter(outputFileName, append), SEPARATOR)) {
        if (append) {
            if (!headerWritten) {
                write(writer, Entry.header, null, null);
                headerWritten = true;
            }
        } else {
            write(writer, Entry.header, null, null);
        }

        Map<Level, LoadRecord> loadMap = load.getLoadMap();
        for (Map.Entry<Level, LoadRecord> entry : loadMap.entrySet()) {
            Level level = entry.getKey();
            LoadRecord loadRecord = entry.getValue();

            write(writer, Entry.body, level, loadRecord);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void write(CSVWriter writer, Entry entry, Level level, LoadRecord loadRecord) {
    String[] record = new String[RegionLoadAdapter.loadEntries.length + 2];
    if (entry == Entry.header) {
        record[0] = load.getLevelClass().getLevelTypeString();
        record[1] = HEADER_TIMESTAMP;
    } else {
        record[0] = level.toString();
        record[1] = String.valueOf(load.getTimestampIteration());
    }
    for (LoadEntry loadEntry : RegionLoadAdapter.loadEntries) {
        if (entry == Entry.header) {
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = loadEntry.name();
        } else {
            Number number = loadRecord.get(loadEntry);
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = number == null ? "" : number.toString();
        }
    }
    writer.writeNext(record);
}
 
Example #20
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void saveInternal(String outputFileName, boolean append) {
    try (CSVWriter writer = new CSVWriter(new FileWriter(outputFileName, append), SEPARATOR)) {
        if (append) {
            if (!headerWritten) {
                write(writer, Entry.header, null, null);
                headerWritten = true;
            }
        } else {
            write(writer, Entry.header, null, null);
        }

        Map<Level, LoadRecord> loadMap = load.getLoadMap();
        for (Map.Entry<Level, LoadRecord> entry : loadMap.entrySet()) {
            Level level = entry.getKey();
            LoadRecord loadRecord = entry.getValue();

            write(writer, Entry.body, level, loadRecord);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #21
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void write(CSVWriter writer, Entry entry, Level level, LoadRecord loadRecord) {
    String[] record = new String[RegionLoadAdapter.loadEntries.length + 2];
    if (entry == Entry.header) {
        record[0] = load.getLevelClass().getLevelTypeString();
        record[1] = HEADER_TIMESTAMP;
    } else {
        record[0] = level.toString();
        record[1] = String.valueOf(load.getTimestampIteration());
    }
    for (LoadEntry loadEntry : RegionLoadAdapter.loadEntries) {
        if (entry == Entry.header) {
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = loadEntry.name();
        } else {
            Number number = loadRecord.get(loadEntry);
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = number == null ? "" : number.toString();
        }
    }
    writer.writeNext(record);
}
 
Example #22
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void saveInternal(String outputFileName, boolean append) {
    try (CSVWriter writer = new CSVWriter(new FileWriter(outputFileName, append), SEPARATOR)) {
        if (append) {
            if (!headerWritten) {
                write(writer, Entry.header, null, null);
                headerWritten = true;
            }
        } else {
            write(writer, Entry.header, null, null);
        }

        Map<Level, LoadRecord> loadMap = load.getLoadMap();
        for (Map.Entry<Level, LoadRecord> entry : loadMap.entrySet()) {
            Level level = entry.getKey();
            LoadRecord loadRecord = entry.getValue();

            write(writer, Entry.body, level, loadRecord);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #23
Source File: LoadIO.java    From hbase-tools with Apache License 2.0 6 votes vote down vote up
private void write(CSVWriter writer, Entry entry, Level level, LoadRecord loadRecord) {
    String[] record = new String[RegionLoadAdapter.loadEntries.length + 2];
    if (entry == Entry.header) {
        record[0] = load.getLevelClass().getLevelTypeString();
        record[1] = HEADER_TIMESTAMP;
    } else {
        record[0] = level.toString();
        record[1] = String.valueOf(load.getTimestampIteration());
    }
    for (LoadEntry loadEntry : RegionLoadAdapter.loadEntries) {
        if (entry == Entry.header) {
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = loadEntry.name();
        } else {
            Number number = loadRecord.get(loadEntry);
            record[RegionLoadAdapter.loadEntryOrdinal(loadEntry) + 2] = number == null ? "" : number.toString();
        }
    }
    writer.writeNext(record);
}
 
Example #24
Source File: ExportSpiceRequest.java    From wifi_backend with GNU General Public License v3.0 6 votes vote down vote up
private void writeCSV(CSVWriter out, AccessPoint value, boolean exportAll) throws IOException {

        if(value.moveGuard() != 0) {        // Don't export suspect (moved/moving) APs
            return;
        }

        final String rfId = value.rfId();
        String ssid = "";

        if(!TextUtils.isEmpty(value.ssid())) {
            ssid = value.ssid();
        }

        for(SimpleLocation sample : value.samples()) {
            if (exportAll || sample.changed()) {
                out.writeNext(new String[]{rfId,
                        Double.toString(sample.latitude()),
                        Double.toString(sample.longitude()),
                        ssid});
            }
        }
    }
 
Example #25
Source File: CsvTool.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void csvWriter(
    String filePath,
    String fileName,
    char separator,
    char quoteChar,
    String[] headers,
    List<String[]> dataList)
    throws IOException {
  CSVWriter reconWriter = setCsvFile(filePath, fileName, separator, quoteChar);
  if (headers != null) {
    reconWriter.writeNext(headers);
  }
  reconWriter.writeAll(dataList);
  reconWriter.flush();
  try {
    reconWriter.close();
  } catch (IOException e) {

    reconWriter = null;
  }
}
 
Example #26
Source File: CsvTool.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void csvWriter(
    String filePath, String fileName, char separator, String[] headers, List<String[]> dataList)
    throws IOException {
  CSVWriter reconWriter = setCsvFile(filePath, fileName, separator);
  if (headers != null) {
    reconWriter.writeNext(headers);
  }
  reconWriter.writeAll(dataList);
  reconWriter.flush();
  try {
    reconWriter.close();
  } catch (IOException e) {

    reconWriter = null;
  }
}
 
Example #27
Source File: MetaGroupMenuAssistantService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Transactional(rollbackOn = {Exception.class})
public void createGroupMenuFile(MetaGroupMenuAssistant groupMenuAssistant) throws IOException {

  setBundle(new Locale(groupMenuAssistant.getLanguage()));
  File groupMenuFile = MetaFiles.createTempFile("MenuGroup", ".csv").toFile();

  try {

    List<String[]> rows = createHeader(groupMenuAssistant);

    addMenuRows(groupMenuAssistant, rows);

    addGroupAccess(rows);

    try (CSVWriter csvWriter =
            new CSVWriter(new FileWriterWithEncoding(groupMenuFile, "utf-8"), ';');
        FileInputStream fis = new FileInputStream(groupMenuFile)) {
      csvWriter.writeAll(rows);

      groupMenuAssistant.setMetaFile(metaFiles.upload(fis, getFileName(groupMenuAssistant)));
    }
    menuAssistantRepository.save(groupMenuAssistant);
  } catch (Exception e) {
    TraceBackService.trace(e);
  }
}
 
Example #28
Source File: PermissionAssistantService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
public void createFile(PermissionAssistant assistant) {

    File permFile = new File(Files.createTempDir(), getFileName(assistant));

    try {

      try (FileWriterWithEncoding fileWriter =
          new FileWriterWithEncoding(permFile, StandardCharsets.UTF_8)) {
        CSVWriter csvWriter = new CSVWriter(fileWriter, ';');
        writeGroup(csvWriter, assistant);
      }

      createMetaFile(permFile, assistant);

    } catch (Exception e) {
      LOG.error(e.getLocalizedMessage());
      TraceBackService.trace(e);
    }
  }
 
Example #29
Source File: Csv.java    From http-builder-ng with Apache License 2.0 6 votes vote down vote up
/**
 * Used to encode the request content using the OpenCsv writer.
 *
 * @param config the configuration
 * @param ts the server request content accessor
 */
public static void encode(final ChainedHttpConfig config, final ToServer ts) {
    if (handleRawUpload(config, ts)) {
        return;
    }

    final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
    final Csv.Context ctx = (Csv.Context) config.actualContext(request.actualContentType(), Csv.Context.ID);
    final Object body = checkNull(request.actualBody());
    checkTypes(body, new Class[]{Iterable.class});
    final StringWriter writer = new StringWriter();
    final CSVWriter csvWriter = ctx.makeWriter(new StringWriter());

    Iterable<?> iterable = (Iterable<?>) body;
    for (Object o : iterable) {
        csvWriter.writeNext((String[]) o);
    }

    ts.toServer(stringToStream(writer.toString(), request.actualCharset()));
}
 
Example #30
Source File: DownloadEventBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void csvSpreadsheet(OutputStream os, List<SignupMeetingWrapper> meetingWrappers) throws IOException {
	
	CSVExport export = new CSVExport(meetingWrappers, getSakaiFacade());

	
	CSVWriter writer = new CSVWriter(new OutputStreamWriter(os), ',', CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, downloadVersion);
	//header
	List<String> header = export.getHeaderRow();
	
	int cols = header.size(); //total number of columns is based on header row
	
	String[] headerRow = new String[cols];
	headerRow = header.toArray(headerRow);
	writer.writeNext(headerRow);
	
	//data rows
	List<List<String>> data = export.getDataRows();
	Iterator<List<String>> iter = data.iterator();
	while(iter.hasNext()) {
		List<String> row = iter.next();
		String[] dataRow = new String[cols];
		dataRow = row.toArray(dataRow);
		writer.writeNext(dataRow);
	}
	
	writer.close();
	
}