package com.javahonk.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;

@Results({ @Result(name = "error", location = "/index.jsp"),
		   @Result(name = "input", location = "/index.jsp") })
public class Struts2SampleCodeAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	@Action(value = "/struts2SampleCodeAction")
	public String execute() throws Exception {
		return SUCCESS;
	}

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

		HttpServletResponse response = ServletActionContext.getResponse();
		ServletContext context = ServletActionContext.getServletContext();

		File downloadFile = new File("C:/JavaHonk/CustomJar.jar");
		FileInputStream inputStream = null;
		OutputStream outStream = null;

		try {
			inputStream = new FileInputStream(downloadFile);

			response.setContentLength((int) downloadFile.length());
			response.setContentType(context.getMimeType("C:/JavaHonk/CustomJar.jar"));

			// response header details
			String headerKey = "Content-Disposition";
			String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
			response.setHeader(headerKey, headerValue);

			// response
			outStream = response.getOutputStream();
			IOUtils.copy(inputStream, outStream);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != inputStream)
					inputStream.close();
				if (null != inputStream)
					outStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}
