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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.opencsv.CSVWriter;
/**
* Writes data in CSV format
*
* @author Andrey Lugovskoy.
*/
public abstract class ExporterToCSV<T> {
public static final Log LOG = LogFactory.getLog(ExporterToCSV.class);
public void downloadMetadata(Stream<T> entities, HttpServletResponse response, char separator, char quoteChar, char escapeChar, String lineEnd, String encoding) throws IOException {
try (CSVWriter writer = new CSVWriter(new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), encoding)), separator, quoteChar, escapeChar, lineEnd)) {
writer.writeNext(writeHeaders());
entities.forEach(element -> {
writer.writeNext(prepareLine(element), true);
});
writer.flush();
}
}
protected abstract String[] writeHeaders();
protected abstract String[] prepareLine(T element);
}