/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 * This code is part of the Core project.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.utils.web;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * ServletResponseUtils
 *
 * @author Patrick
 */
public abstract class ServletResponseUtils {

	/**
	 * Writes a String to HttpServletResponse encoded with the specified charsetName, and then flush and close it.
	 *
	 * @param response
	 *            HttpServletResponse
	 * @param charsetName
	 *            The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
	 * @param str
	 *            String to be written
	 */
	public static void writeStringToStream(HttpServletResponse response, String charsetName, String str) throws UnsupportedEncodingException, IOException {
		OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), charsetName);
		out.write(str);
		out.flush();
		out.close();
	}

	/**
	 * Writes bytes to HttpServletResponse, and then flush and close it.
	 *
	 * @param response
	 *            HttpServletResponse
	 * @param bytes
	 *            The bytes array to be written
	 * @throws IOException
	 */
	public static void writeBytesToStream(HttpServletResponse response, byte[] bytes) throws IOException {
		ServletOutputStream out = response.getOutputStream();
		out.write(bytes);
		out.flush();
		out.close();
	}

	/**
	 * Disables caching by modifying the response header.
	 *
	 * @param response
	 *            HttpServletResponse
	 */
	public static void disableCaching(HttpServletResponse response) {
		response.addHeader("Pragma", "no-cache");
		response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
		response.addDateHeader("Expires", 1L);
	}

}
