ExporterToCSV.java
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.server.service.impl;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import com.opencsv.CSVWriter;
/**
* Writes data in CSV format
*
* @author Andrey Lugovskoy.
*/
@Slf4j
public abstract class ExporterToCSV<T> {
private static final int FLUSH_INTERVAL = 100;
public void downloadMetadata(Stream<T> entities, HttpServletResponse response, char separator, char quoteChar, char escapeChar, String lineEnd, String encoding) throws IOException {
int rowCounter = 0;
try (Stream<T> stream = entities;
CSVWriter writer = new CSVWriter(new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), encoding)), separator, quoteChar, escapeChar, lineEnd)) {
writer.writeNext(writeHeaders());
var iterator = stream.iterator();
while (iterator.hasNext()) {
writer.writeNext(prepareLine(iterator.next()), true);
if (++rowCounter % FLUSH_INTERVAL == 0) {
log.trace("Wrote {} rows...", rowCounter);
writer.flush();
response.flushBuffer();
}
}
log.trace("Flushing the CSV writer!");
writer.flush();
response.flushBuffer();
}
log.debug("Done with metadata download!");
}
protected abstract String[] writeHeaders();
protected abstract String[] prepareLine(T element);
}