package com.sino.publicclass.common;

import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HttpDataParser {
    private static final String READLINE_IOEXCEPTION =
	    "Fail to read data sent by the browser.";
    private static final String CORRUPTED_INPUT_STREAM =
	    "Data stream is corrupted.";
    private static final String FILE_OUTPUT_STREAM_IOEXCEPTION =
	    "Fail to create the attachment file.";
    private static final String CLOSE_IOEXCEPTION =
	    "Fail to close the attachment file.";
    private static final String WRITE_IOEXCEPTION =
	    "Fail to read the attachment file.";
    private static final String WORKING_DIR_IS_FILE =
	    "The working directory is a file.";
    private static final String WORKING_DIR_CREATE_ERROR =
	    "Cannot create the file working directory.";
    private static final String FILE_SIZE_ERROR =
	    "上传文件太大.";
    private static final String MULTIDATATYPE = "multipart/form-data";
    private static final int BUF_SIZE = 0x64000;
    private static final String NAME_STRING =
	    "Content-Disposition: form-data; name=\"";
    private static final String FILENAME_STRING = "\"; filename=\"";
    private static final String CONTENT_TYPE_STRING = "Content-Type:";
    protected Vector parameterNames;
    protected Vector parameterValues;
    protected Vector uploadParameterNames;
    protected Vector uploadSrcFileNames;
    protected Vector uploadFileNames;
    protected Vector uploadFileTypes;
    protected Vector uploadFileSizes;
    private int maxFileSize = 1024 * 1024 * 10;
    public HttpDataParser() {
    }

    public HttpDataParser(int maxSize) {
	setMaxFileSize(maxSize);
    }

    public void parser(HttpServletRequest httpservletrequest, String path, int maxSize)
	    throws Exception {
	setMaxFileSize(maxSize);
	parser(httpservletrequest, path);
    }

    public void parser(HttpServletRequest httpservletrequest, String path)
	    throws Exception {
	parameterNames = new Vector(0);
	parameterValues = new Vector(0);
	uploadParameterNames = new Vector(0);
	uploadSrcFileNames = new Vector(0);
	uploadFileNames = new Vector(0);
	uploadFileTypes = new Vector(0);
	uploadFileSizes = new Vector(0);
	byte abyte0[] = new byte[BUF_SIZE];
	String parameterName = "";
	String s12 = "";
	Integer integer = null;
	int len = 0; //长度
	int cursor = 0; //游标
	String contentType = httpservletrequest.getContentType();
	if (contentType != null) {
	    contentType = contentType.trim();
	}
	//ENCTYPE＝＝multipart/form-data？
	if (contentType == null || contentType.indexOf(MULTIDATATYPE) < 0) {
	    String parValue;
	    for (Enumeration enumeration = httpservletrequest.getParameterNames(); enumeration.hasMoreElements();
		    parameterValues.addElement(parValue)) {
		parameterName = (String) enumeration.nextElement();
		parameterNames.addElement(parameterName);
		parValue = getParameter(httpservletrequest, parameterName);
	    }
	    return;
	}
	ServletInputStream servletinputstream = httpservletrequest.getInputStream();
	int contentLength = httpservletrequest.getContentLength();
	try {
	    len = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
	}
	catch (IOException _ex) {
	    throw new Exception(READLINE_IOEXCEPTION);
	}
	cursor += len;
	String s1 = new String(abyte0, 0, len);
	String code = s1.substring(0, s1.length() - 2);
	int i2 = 0;
	while (contentLength > cursor) {
	    int k;
	    try {
		k = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
	    }
	    catch (IOException _ex) {
		throw new Exception(READLINE_IOEXCEPTION);
	    }
	    cursor += k;
	    String s2 = null;
	    s2 = new String(abyte0, 0, k);
	    boolean isFile = false; //是否是file
	    if (k > NAME_STRING.length()) {
		if (s2.substring(0, NAME_STRING.length()).equals(NAME_STRING)) {
		    int l1 = s2.indexOf("\"", NAME_STRING.length());
		    parameterName = s2.substring(NAME_STRING.length(), l1);
		    l1 = s2.indexOf(FILENAME_STRING, l1);
		    if (l1 >= 0) {
			isFile = true;
			s12 = s2.substring(l1 + FILENAME_STRING.length(), s2.indexOf("\"",
				l1 + FILENAME_STRING.length())).
				trim();
		    } else {
			isFile = false;
		    }
		} else {
		    throw new Exception(CORRUPTED_INPUT_STREAM);
		}
	    }
	    try {
		k = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
	    }
	    catch (IOException _ex) {
		throw new Exception(READLINE_IOEXCEPTION);
	    }
	    cursor += k;
	    if (isFile) {
		// is file
		String s14;
		String filetype;
		String s20 = "";
		if (s12 == null || s12.equals("")) {
		    filetype = "";
		    integer = new Integer(0);
		    s14 = "";
		    boolean flag1 = true;
		    do {
			try {
			    k = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
			}
			catch (IOException _ex) {
			    throw new Exception(READLINE_IOEXCEPTION);
			}
			cursor += k;
			String s3 = new String(abyte0, 0, k);
			if (s3.length() >= code.length() &&
				s3.substring(0, code.length()).equals(code)) {
			    flag1 = false;
			}
		    }
		    while (flag1);
		} else {
		    String s4 = new String(abyte0, 0, k);
		    //read filetype
		    if (k > CONTENT_TYPE_STRING.length()) {
			if (s4.substring(0,
				CONTENT_TYPE_STRING.length()).equals(CONTENT_TYPE_STRING)) {
			    filetype = s4.substring(CONTENT_TYPE_STRING.length(), s4.length()).trim();
			} else {
			    filetype = "";
			}
		    } else {
			filetype = "";
		    }
		    try {
			k = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
		    }
		    catch (IOException _ex) {
			throw new Exception(READLINE_IOEXCEPTION);
		    }
		    cursor += k;
		    File file = new File(path);
		    if (file.isFile()) {
			throw new Exception(WORKING_DIR_IS_FILE);
		    }
		    if (!file.exists() && !file.mkdirs()) {
			throw new Exception(WORKING_DIR_CREATE_ERROR);
		    }
		    i2++;
		    FileOutputStream fileoutputstream = null;
		    try {
			String s18;
			for (s18 = String.valueOf(i2); s18.length() < 3; s18 = '0' + s18) {
			    ;
			}
			//转换文件名
			s20 = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + s18;
			int j2 = s12.lastIndexOf(46);
			if (j2 > 0) {
			    String s19 = s12.substring(j2, s12.length());
			    s20 = s20 + s19;
			}

			s14 = path + File.separator + s20;
			fileoutputstream = new FileOutputStream(s14);
		    }
		    catch (IOException _ex) {
			throw new Exception(FILE_OUTPUT_STREAM_IOEXCEPTION);
		    }
		    int k1 = 0;
		    boolean flag2 = true;
		    boolean flag5 = false;
		    int k2 = 0;
		    int l2 = 0;
		    do {
			int l;
			try {
			    l = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
			}
			catch (IOException _ex) {
			    throw new Exception(READLINE_IOEXCEPTION);
			}
			cursor += l;
			k1 += l;
			if (k1 > maxFileSize)throw new Exception(FILE_SIZE_ERROR);
			String s5 = null;
			s5 = new String(abyte0, 0, l);
			if (s5.length() >= code.length() &&
				s5.substring(0, code.length()).equals(code)) {
			    try {
				fileoutputstream.close();
			    }
			    catch (IOException _ex) {
				throw new Exception(CLOSE_IOEXCEPTION);
			    }
			    k1 -= l;
			    k1 -= 2;
			    integer = new Integer(k1);
			    flag2 = false;
			}
			if (flag2) {
			    try {
				if (flag5) {
				    fileoutputstream.write(k2);
				    fileoutputstream.write(l2);
				}
				if (l >= 2) {
				    k2 = abyte0[l - 2];
				    l2 = abyte0[l - 1];
				    fileoutputstream.write(abyte0, 0, l - 2);
				    flag5 = true;
				} else {
				    k2 = 0;
				    l2 = 0;
				    fileoutputstream.write(abyte0, 0, l);
				    flag5 = false;
				}
			    }
			    catch (IOException _ex) {
				throw new Exception(WRITE_IOEXCEPTION);
			    }
			}
		    }
		    while (flag2 && contentLength > cursor);
		}
		String srcname = "";
		int b;
		b = s12.lastIndexOf(92);
		if (b < 0) b = s12.lastIndexOf(47);
		if (b > -1) {
		    srcname = s12.substring(b + 1, s12.length());
		}
		uploadParameterNames.addElement(parameterName);
		uploadSrcFileNames.addElement(srcname);

		uploadFileNames.addElement(s20);
		uploadFileTypes.addElement(filetype);
		uploadFileSizes.addElement(integer);
	    } else {
		// is not file
		boolean flag3 = true;
		String tempvalue = "";
		do {
		    int i1;
		    try {
			i1 = servletinputstream.readLine(abyte0, 0, BUF_SIZE);
		    }
		    catch (IOException _ex) {
			throw new Exception(READLINE_IOEXCEPTION);
		    }
		    cursor += i1;
		    String s6 = null;
		    s6 = new String(abyte0, 0, i1);
		    if (s6.length() >= code.length() &&
			    s6.substring(0, code.length()).equals(code)) {
			flag3 = false;
		    }
		    if (flag3) {
			tempvalue = tempvalue + s6.substring(0, s6.length());
		    }
		}
		while (flag3 && contentLength > cursor);
		tempvalue = tempvalue.substring(0, tempvalue.length() - 2);
		parameterNames.addElement(parameterName);
		parameterValues.addElement(tempvalue);
	    }
	}
    }

    private String getParameter(HttpServletRequest httpservletrequest, String s)
	    throws
	    Exception {
	String as[] = null;
	String s1 = null;
	as = httpservletrequest.getParameterValues(s);
	if (as != null) {
	    s1 = as[0];
	}
	return s1;
    }

    public String[] getParameterNames() {
	int j = parameterNames.size();
	String as[] = new String[j];
	for (int i = 0; i < j; i++) {
	    as[i] = (String) parameterNames.elementAt(i);

	}
	return as;
    }

    public String getParameterValue(String s) {
	int i = parameterNames.indexOf(s);
	String s1;
	if (i < 0) {
	    s1 = null;
	} else {
	    s1 = (String) parameterValues.elementAt(i);
	}
	if (s1 == null) {
	    return "";
	} else {
	    return s1;
	}
    }

    public String getUploadFileName(String s) {
	int i = uploadParameterNames.indexOf(s);
	String s1;
	if (i < 0) {
	    s1 = null;
	} else {
	    s1 = (String) uploadFileNames.elementAt(i);
	}
	return s1;
    }

    public String[] getUploadFileName() {

	int j = uploadParameterNames.size();
	String as[] = new String[j];
	for (int i = 0; i < j; i++) {
	    as[i] = (String) uploadParameterNames.elementAt(i);
	}

	return as;

    }

    public Integer getUploadFileSize(String s) {
	int i = uploadParameterNames.indexOf(s);
	Integer integer;
	if (i < 0) {
	    integer = null;
	} else {
	    integer = (Integer) uploadFileSizes.elementAt(i);
	}
	return integer;
    }

    public String getUploadFileType(String s) {
	int i = uploadParameterNames.indexOf(s);
	String s1;
	if (i < 0) {
	    s1 = null;
	} else {
	    s1 = (String) uploadFileTypes.elementAt(i);
	}
	return s1;
    }

    public String[] getUploadParameterNames() {
	int j = uploadParameterNames.size();
	String as[] = new String[j];
	for (int i = 0; i < j; i++) {
	    as[i] = (String) uploadParameterNames.elementAt(i);

	}
	return as;
    }

    public String getUploadSrcFileName(String s) {
	int i = uploadParameterNames.indexOf(s);
	String s1;
	if (i < 0) {
	    s1 = null;
	} else {
	    s1 = (String) uploadSrcFileNames.elementAt(i);
	}
	if (s1 == null) {
	    return "";
	} else {
	    return s1;
	}
    }

    public void release() {
	parameterNames.removeAllElements();
	parameterValues.removeAllElements();
	uploadParameterNames.removeAllElements();
	uploadSrcFileNames.removeAllElements();
	uploadFileNames.removeAllElements();
	uploadFileTypes.removeAllElements();
	uploadFileSizes.removeAllElements();
    }

    /**
     * 将文件名的属性改为小写字母。
     * 创建日期：(2002-9-28 16:54:47)
     * @return java.lang.String
     * @param filename java.lang.String
     */
    public static String convertSuffix(String filename) {
	int strNum = 0; //字符"."在字符串中的位置
	strNum = filename.indexOf(".");

	if (strNum > -1) {
	    String firstname = ""; //文件名
	    firstname = filename.substring(0, strNum);
	    String secondname = ""; //文件属性
	    secondname = filename.substring(strNum + 1);

	    secondname = secondname.toLowerCase(); //将文件属性转化为小写字母
	    filename = firstname + "." + secondname; //重新合成文件名
	}
	return filename;
    }

    public int getMaxFileSize() {
	return maxFileSize;
    }

    public void setMaxFileSize(int msize) {
	this.maxFileSize = msize;
    }

}
