⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 util.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*
 */
package com.sslexplorer.boot;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * Utilities used throughout the SSL-Explorer boot environment, server
 * implementation and web application.
 * 
 * @author Brett Smith <a href="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
 * @version $Revision: 1.32 $
 */
public class Util {

    final static Log log = LogFactory.getLog(Util.class);

    /**
     * Default buffer size for stream utility methods
     */
    public static int BUFFER_SIZE = 8192;

    /*
     * Prevent instantiation
     */
    private Util() {
        super();
    }

    /**
     * Get the statement from the current stack trace given its depth. I.e, a
     * depth of 0 will return this method, a depth of 1 will return the method
     * that called this method etc.
     * 
     * @param depth depth
     * @return statement as string
     */
    public static String getCurrentStatement(int depth) {
        try {
            throw new Exception();
        } catch (Exception e) {
            try {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                BufferedReader reader = new BufferedReader(new StringReader(sw.toString()));
                reader.readLine();
                reader.readLine();
                sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                for (int i = 0; i < depth; i++) {
                    String s = reader.readLine();
                    pw.println(s.substring(7));
                }
                return sw.toString();

            } catch (Throwable t) {
                return "Unknown.";
            }
        }
    }

    /**
     * Trim spaces from both ends of string
     * 
     * @param string string to trim
     * @return trimmed string
     */
    public static String trimBoth(String string) {
        string = string.trim();
        for (int i = 0; i < string.length(); i++) {
            if (string.charAt(i) != ' ') {
                return string.substring(i);
            }
        }
        return string;
    }

    /**
     * Close an output stream, ignoing any exceptions. No error will be thrown
     * if the provided stream is <code>null</code>
     * 
     * @param outputStream stream to close
     */
    public static void closeStream(OutputStream outputStream) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ioe) {

            }
        }
    }

    /**
     * Close an input stream, ignoing any exceptions. No error will be thrown if
     * the provided stream is <code>null</code>
     * 
     * @param inputStream stream to close
     */
    public static void closeStream(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ioe) {

            }
        }
    }

    /**
     * Extract the value portion of a string in the format of a named value pair
     * i.e. <i>[name]=[value]</i>.
     * 
     * @param nameEqualsValue string
     * @return value portion of name / value pair
     */
    public static String valueOfNameValuePair(String nameEqualsValue) {
        String value = nameEqualsValue.substring(nameEqualsValue.indexOf('=') + 1).trim();

        int i = value.indexOf(';');
        if (i > 0)
            value = value.substring(0, i);
        if (value.startsWith("\"")) {
            value = value.substring(1, value.indexOf('"', 1));
        }

        else {
            i = value.indexOf(' ');
            if (i > 0)
                value = value.substring(0, i);
        }
        return value;
    }

    /**
     * Convert a byte array to a hex string
     * 
     * @param data
     * @return hex string
     */
    public static String toHexString(byte[] data) {
        return toHexString(data, 0, data.length);
    }

    /**
     * Convert a byte array to a hex string
     * 
     * @param data bytes to convert
     * @param offset offset in array to start from
     * @param len number of bytes to convert
     * @return hex string
     */
    public static String toHexString(byte[] data, int offset, int len) {
        StringBuffer buf = new StringBuffer("0x");
        for (int i = offset; i < len; i++) {
            String s = Integer.toHexString(data[i]);
            if (s.length() < 2) {
                buf.append("0");
            }
            buf.append(s);
        }
        return buf.toString();
    }

    /**
     * Rebuild the URI of the request by concatenating the servlet path and and
     * request parameters
     * 
     * @param request request to extra path from
     * @return path
     */
    public static String getOriginalRequest(HttpServletRequest request) {
        StringBuffer req = new StringBuffer(request.getServletPath());
        if (request.getQueryString() != null && request.getQueryString().length() > 0) {
            req.append("?");
            req.append(request.getQueryString());
        }
        return req.toString();
    }

    /**
     * Read an input stream and load it into a string.
     * 
     * @param in input stream
     * @param charsetName encoding or <code>null</code> for default
     * @return string
     * @throws IOException on any error
     */
    public static String loadStreamToString(InputStream in, String charsetName) throws IOException {
        StringBuffer licenseText = new StringBuffer();
        BufferedReader br = new BufferedReader(charsetName == null ? new InputStreamReader(in) : new InputStreamReader(in,
                        charsetName));
        try {
            char[] buf = new char[65536];
            int r = 0;
            while ((r = br.read(buf)) != -1)
                licenseText.append(buf, 0, r);
        } finally {
            br.close();
        }
        return licenseText.toString();
    }

    /**
     * Dump all session attributes to {@link System#err}.
     * 
     * @param session session to get attributes from
     */
    public static void dumpSessionAttributes(HttpSession session) {
        System.err.println("Session attributes for " + session.getId());
        for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
            String n = (String) e.nextElement();
            System.err.println("   " + n + " = " + session.getAttribute(n));
        }
    }

    /**
     * Dump all request attributes to {@link System#err}.
     * 
     * @param request request to get attributes from
     */
    public static void dumpRequestAttributes(HttpServletRequest request) {
        System.err.println("Request attributes for " + request.getPathTranslated());
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String n = (String) e.nextElement();
            System.err.println("   " + n + " = " + request.getAttribute(n));
        }
    }

    /**
     * Dump all request headers to {@link System#err}.
     * 
     * @param request request to get headers from
     */
    public static void dumpRequestHeaders(HttpServletRequest request) {
        System.err.println("Request headers for " + request.getPathTranslated());
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String n = (String) e.nextElement();
            for(Enumeration e2 = request.getHeaders(n); e2.hasMoreElements(); ) {
                String v = (String)e2.nextElement();
                System.err.println("   " + n + " = " + v);
            }
        }
    }

    /**
     * Dump all servlet context attributes to {@link System#err}.
     * 
     * @param context context to get attributes from
     */
    public static void dumpServletContextAttributes(ServletContext context) {
        System.err.println("Servlet context attributes for");
        for (Enumeration e = context.getAttributeNames(); e.hasMoreElements();) {
            String n = (String) e.nextElement();
            System.err.println("   " + n + " = " + context.getAttribute(n));
        }

    }

    /**
     * Dump all request parameters to {@link System#err}
     * 
     * @param request request to get parameters from
     */
    public static void dumpRequestParameters(HttpServletRequest request) {
        System.err.println("Request parameters for session #" + request.getSession().getId());
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
            String n = (String) e.nextElement();
            String[] vals = request.getParameterValues(n);
            for (int i = 0; i < vals.length; i++) {
                System.err.println("   " + n + " = " + vals[i]);
            }
        }

    }

    /**
     * Dump all request parameters and some other useful stuff from
     * the request to {@link System#err}
     * 
     * @param request request to get parameters from
     */
    public static void dumpRequest(HttpServletRequest request) {
        System.err.println("Context Path " + request.getContextPath());
        System.err.println("Path Translated " + request.getPathTranslated());
        System.err.println("Query: " + request.getQueryString());
        System.err.println("Request URI: " + request.getRequestURI());
        System.err.println("Is Secure: " + request.isSecure());
        System.err.println("Scheme: " + request.getScheme());
        dumpRequestParameters(request);
        dumpRequestAttributes(request);
        dumpRequestHeaders(request);

    }

    /**
     * Dump the contents of a {@link Map} to {@link System#err}.
     * 
     * @param map map to dump
     */
    public static void dumpMap(Map map) {
        System.err.println("Map dump");
        for (Iterator i = map.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            System.err.println("   Key = " + entry.getKey() + " Val = " + entry.getValue());
        }

    }

    /**
     * Dump an exception to {@link System#err}.
     * 
     * @param exception exception to dump
     */
    public static void printStackTrace(Throwable exception) {
        Exception e;
        try {
            throw new Exception();
        } catch (Exception ex) {
            e = ex;
        }
        StackTraceElement[] trace = e.getStackTrace();
        System.err.println("[REMOVE-ME] - " + trace[1].getClassName() + ":" + trace[1].getLineNumber());
        exception.printStackTrace();

    }

    /**
     * Concatenate all of the non null messages from an exception chain,
     * appending full stops after each messages if they do not end with one.
     * 
     * @param t trace
     * @return exception message chain text
     */
    public static String getExceptionMessageChain(Throwable t) {
        StringBuffer buf = new StringBuffer();
        while (t != null) {
            if (buf.length() > 0 && !buf.toString().endsWith(".")) {
                buf.append(". ");
            }
            if (t.getMessage() != null) {
                buf.append(t.getMessage().trim());
            }
            t = t.getCause();
        }
        return buf.toString();
    }

    /**
     * Print a TODO message to {@link System#err}, including the current class
     * and line number call was made along with a specified message.
     * <p>
     * Use for temporary debug. Calling statement should be removed.
     * </p>
     * 
     * @param message message to display
     */
    public static void toDo(String message) {
        Exception e;
        try {
            throw new Exception();
        } catch (Exception ex) {
            e = ex;
        }
        StackTraceElement[] trace = e.getStackTrace();
        System.err.println("[***TODO***] - " + trace[1].getClassName() + ":" + trace[1].getLineNumber() + " - " + message);
    }

    /**
     * Print some temporary debug to {@link System#err}, including the current
     * class and line number call was made along with a specified message.
     * <p>
     * Use for temporary debug. Calling statement should be removed.
     * </p>
     * 
     * @param message message to display
     */
    public static void removeMe(String message) {
        Exception e;
        try {
            throw new Exception();
        } catch (Exception ex) {
            e = ex;
        }
        StackTraceElement[] trace = e.getStackTrace();
        System.err.println("[REMOVE-ME] - " + trace[1].getClassName() + ":" + trace[1].getLineNumber() + " - " + message);

    }

    /**
     * Escape a string so it is suitable for including as a Javascript string.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -