package nc.bs.servlet.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.codehaus.jettison.json.JSONException;

import uap.json.JSONObject;

/**
 * 提供一些公共方法
 * 具体业务请在实际服务类实现
 */
public class BaseServlet {

	public static String STATUS_SUCCESS ="success";
	public static String STATUS_FAILURE ="fail";

	/**
	 * 格式化传入的数据，JSON化在具体服务类实现
	 * @param req
	 * @param resp
	 * @param 类名
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	protected String buildJson(HttpServletRequest req,
							   HttpServletResponse resp, String classname)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		/* 设置格式为text/json */
		resp.setContentType("text/json");
		/* 设置字符集为'UTF-8' */
		resp.setCharacterEncoding("UTF-8");
		String reqJsonData = null;
		// 接收流
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				req.getInputStream(), "UTF-8"));
		StringBuffer jsonStr = new StringBuffer();
		try {
			String line = "";
			while ((line = reader.readLine()) != null) {
				jsonStr.append(line);
			}
			if (jsonStr != null && !"".equals(jsonStr.toString())) {
				reqJsonData = jsonStr.toString();
//				PrLogger.error(new UFDateTime(System.currentTimeMillis()).toString()
//						+ "客户端传入：" + classname + "~~" + reqJsonData);
			} else {
				throw new ServletException("传入的数据不合法！");
			}
		} catch (IOException e) {
			throw new IOException("数据读取失败" + e.getMessage());
		} finally {
			reader.close();
		}
		return reqJsonData;
	}



	/**
	 * 格式返回json数据
	 *
	 * @return
	 * @throws JSONException
	 * @throws Exception
	 */
	public static JSONObject formatRSJsonData(String status,String error,String message){
		JSONObject rs = new JSONObject();
		rs.put("status", status);
		rs.put("message", message);
		rs.put("error", error);
		return rs;
	}
	
}
