package com.javahonk.action;

import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;

public class Struts2CSVDownloadAction{

	@Action(value = "/downloadCSVFileAction")
	public void downloadCSVFileAction() throws Exception {

		HttpServletResponse response = ServletActionContext.getResponse();
		
		try {
			response.setContentType("text/csv");
			String reportName = "JavaHonk.csv";
			response.setHeader("Content-disposition", "attachment;filename="+reportName);
	 
			ArrayList<String> rows = new ArrayList<String>();
			rows.add("Name,Result");
			rows.add("\n");
	 
			for (int i = 0; i < 10; i++) {
				rows.add("Java Honk,Success");
				rows.add("\n");
			}
	 
			Iterator<String> iter = rows.iterator();
			while (iter.hasNext()) {
				String outputString = (String) iter.next();
				response.getOutputStream().print(outputString);
			}
	 
			response.getOutputStream().flush();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
