com.threewks.thundr.view.csv.CsvViewResolver Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of thundr-contrib-csv Show documentation
Show all versions of thundr-contrib-csv Show documentation
A thundr module for working with csvs
The newest version!
/*
* This file is a component of thundr, a software library from 3wks.
* Read more: http://3wks.github.io/thundr/
* Copyright (C) 2014 3wks,
*
* 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 com.threewks.thundr.view.csv;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import com.opencsv.CSVWriter;
import com.opencsv.bean.MappingStrategy;
import com.threewks.thundr.csv.BeanToCsvStreamer;
import com.threewks.thundr.csv.CsvMappingFactory;
import com.threewks.thundr.request.Request;
import com.threewks.thundr.request.Response;
import com.threewks.thundr.transformer.TransformerManager;
import com.threewks.thundr.view.BaseView;
import com.threewks.thundr.view.ViewResolutionException;
import com.threewks.thundr.view.ViewResolver;
public class CsvViewResolver implements ViewResolver {
private static final String[] EmptyStringArray = new String[0];
private CsvMappingFactory mappingFactory;
private TransformerManager transformerManager;
public CsvViewResolver(TransformerManager transformerManager, CsvMappingFactory mappingFactory) {
super();
this.mappingFactory = mappingFactory;
this.transformerManager = transformerManager;
}
@Override
public void resolve(Request req, Response resp, CsvView viewResult) {
BaseView.applyToResponse(viewResult, resp);
resp.finaliseHeaders();
try {
PrintWriter writer = new PrintWriter(resp.getOutputStream());
if (viewResult.getRowProvider() != null) {
writeStringRows(viewResult, writer);
} else {
writeBeanRows(viewResult, writer);
}
} catch (IOException e) {
throw new ViewResolutionException(e, "Failed to write to csv to response stream: %s", e.getMessage());
}
}
protected void writeBeanRows(CsvView viewResult, PrintWriter writer) {
Class