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

📄 util.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
     * 
     * @param string
     * @return escaped string
     */
    public static String escapeForJavascriptString(String string) {
        if(string == null) {
            return "";
        }
        string = trimBoth(string);
        string = string.replaceAll("\\\\", "\\\\\\\\");
        string = string.replaceAll("'", "\\\\'");
        string = string.replaceAll("\"", "\\\\'");
        String[] lines = string.split("\n");
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < lines.length; i++) {
            if (buf.length() > 0) {
                buf.append("<br/>");
            }
            buf.append(trimBoth(lines[i]));
        }
        return buf.toString();
    }

    /**
     * Delete a file or a directory and all of its children.
     * <p>
     * <b>Use with care ;-)</b>
     * 
     * @param file file or directory to delete
     * @return file or directory deleted ok
     */
    public static boolean delTree(File file) {
    	if (log.isDebugEnabled())
    		log.debug("Deleting " + file.getAbsolutePath());
        if (file.isDirectory()) {
            File[] f = file.listFiles();
            if (f != null) {
                for (int i = 0; i < f.length; i++) {
                    if (!delTree(f[i])) {
                        return false;
                    }
                }
            }
        }
        if (!file.delete()) {
            log.warn("Failed to remove " + file.getAbsolutePath());
            return false;
        }
        return true;
    }

    /**
     * Trim a string to the specified size, optionally appending elipses (..) if
     * the string is too large. Eclipses are included in the final size.
     * Otherwise, the string is simply cut off at its maximum size.
     * 
     * @param text text
     * @param size maximum size
     * @param addElipses add elipses if text to larget
     * @return trimmed string
     */
    public static String trimToSize(String text, int size, boolean addElipses) {
        return text.length() <= size ? text
                        : (text.substring(0, size - (addElipses ? (size > 3 ? 3 : size) : 0)) + (addElipses ? " .." : ""));
    }

    /**
     * Encode a url. First UTF-8 is tried, and if that fails US-ASCII.
     * 
     * @param url url to encode
     * @return encoded url
     */
    public static String urlEncode(String url) {
        try {
            // W3C recommended
            return URLEncoder.encode(url, System.getProperty("sslexplorer.urlencoding", "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            try {
                //
                return URLEncoder.encode(url, "us-ascii");
            } catch (UnsupportedEncodingException uee2) {
                log.error("URL could not be encoded! This should NOT happen!!!");
                return url;
            }
        }
    }

    /**
     * Decode a url. First UTF-8 is tried, and if that fails US-ASCII.
     * 
     * @param url url to decode
     * @return decoded url
     */
    public static String urlDecode(String url) {
        try {
            // W3C recommended
            return URLDecoder.decode(url, System.getProperty("sslexplorer.urlencoding", "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            try {
                //
                return URLDecoder.decode(url, "us-ascii");
            } catch (UnsupportedEncodingException uee2) {
                log.error("URL could not be decoded! This should NOT happen!!!");
                return url;
            }
        }
    }

    /**
     * Add headers to a response that will prevent compliant clients from
     * caching.
     * 
     * @param response response to add appropriate headers to
     */
    public static void noCache(HttpServletResponse response) {
        response.setHeader("Pragma", "no-cache");
        // You cannot use setDateHeader with -1. This actually sets a date
        // rather than sending Expires: -1
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
    }

    /**
     * Decode a string based on the either the _charset_ request parameter that
     * may have been suplied with a request or the requests character encoding.
     * <p>
     * TODO Make sure this still works and it being used correctly, im not so
     * sure it is!
     * 
     * @param request request to get encoding from
     * @param string string to decode
     * @return decoded string
     */
    public static String decodeRequestString(HttpServletRequest request, String string) {
        String enc = request.getParameter("_charset_");
        if (enc != null && !enc.equals("ISO-8859-1")) {
            try {
                return new String(string.getBytes("ISO-8859-1"), enc);
            } catch (Exception e) {
            }
        }
        enc = request.getCharacterEncoding();
        if (enc != null && !enc.equals("ISO-8859-1")) {
            try {
                return new String(string.getBytes("ISO-8859-1"), enc);
            } catch (Exception e) {
            }

        }
        return string;
    }

    /**
     * Create a {@link Map} from a {@link java.util.List}. The key and value
     * objects of each entry will be identical.
     * 
     * @param list list to turn into map
     * @return map
     */
    public static Map listToHashMapKeys(List list) {
        HashMap map = new HashMap();
        Object k;
        for (Iterator i = list.iterator(); i.hasNext();) {
            k = i.next();
            map.put(k, k);
        }
        return map;
    }

    /**
     * Copy from an input stream to an output stream. It is up to the caller to
     * close the streams.
     * 
     * @param in input stream
     * @param out output stream
     * @throws IOException on any error
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        copy(in, out, -1);
    }

    /**
     * Copy the specified number of bytes from an input stream to an output
     * stream. It is up to the caller to close the streams.
     * 
     * @param in input stream
     * @param out output stream
     * @param count number of bytes to copy
     * @throws IOException on any error
     */
    public static void copy(InputStream in, OutputStream out, long count) throws IOException {
        byte buffer[] = new byte[BUFFER_SIZE];
        int i = BUFFER_SIZE;
        if (count >= 0) {
            while (count > 0) {
                if (count < BUFFER_SIZE)
                    i = in.read(buffer, 0, (int) count);
                else
                    i = in.read(buffer, 0, BUFFER_SIZE);

                if (i == -1)
                    break;

                count -= i;
                out.write(buffer, 0, i);
            }
        } else {
            while (true) {
                i = in.read(buffer, 0, BUFFER_SIZE);
                if (i < 0)
                    break;
                if (log.isDebugEnabled())
                	log.debug("Transfered " + i + " bytes");
                out.write(buffer, 0, i);
            }
        }
    }

    /**
     * Copy a file to another file.
     * 
     * @param f file to copy
     * @param t target file
     * @throws IOException on any error
     */
    public static void copy(File f, File t) throws IOException {
        copy(f, t, false);
    }

    /**
     * Copy a file to another file.
     * 
     * @param f file to copy
     * @param t target file
     * @param onlyIfNewer only copy if the target file is new
     * @throws IOException on any error
     */
    public static void copy(File f, File t, boolean onlyIfNewer) throws IOException {
        if (!onlyIfNewer || f.lastModified() > t.lastModified()) {
        	if (log.isInfoEnabled())
        		log.info("Copying " + f.getAbsolutePath() + " to " + t.getAbsolutePath());
            InputStream in = new FileInputStream(f);
            try {
                OutputStream out = new FileOutputStream(t);
                try {
                    copy(in, out);
                } finally {
                    out.close();
                }
            } finally {
                in.close();
            }
            t.setLastModified(f.lastModified());
        } else {
        	if (log.isInfoEnabled())
        		log.info("Skipping copying of file " + f.getAbsolutePath() + " as the target is newer than the source.");
        }
    }

    /**
     * Copy a file to a directory.
     * 
     * @param from file to copy
     * @param toDir target directory
     * @param replace replace existing file
     * @param onlyIfNewer only copy if the target file is new
     * @throws IOException on any error
     */
    public static void copyToDir(File from, File toDir, boolean replace, boolean onlyIfNewer) throws IOException {
        if (!toDir.exists()) {
            throw new IOException("Destination directory " + toDir.getAbsolutePath() + " doesn't exist.");
        }
        if (from.isDirectory()) {
            File toDirDir = new File(toDir, from.getName());
            if (toDirDir.exists() && replace) {
                delTree(toDirDir);
            }
            if (!toDirDir.exists()) {
            	if (log.isInfoEnabled())
            		log.info("Creating directory " + toDirDir.getAbsolutePath());
                if (!toDirDir.mkdirs()) {
                    throw new IOException("Failed to create directory " + toDirDir.getAbsolutePath());
                }
            }
            File[] f = from.listFiles();
            if (f != null) {
                for (int i = 0; i < f.length; i++) {
                    copyToDir(f[i], toDirDir, replace, onlyIfNewer);
                }
            } else {
                throw new IOException("Failed to list " + from.getAbsolutePath());
            }
        } else if (from.isFile()) {
            copy(from, new File(toDir, from.getName()), onlyIfNewer);
        } else {
            throw new IOException(from.getAbsolutePath() + " is not a plain file or directory.");
        }
    }

    /**
     * Return an empty string when null passed, otherwise return the string.
     * 
     * @param string string or null
     * @return string or empty string
     */
    public static String emptyWhenNull(String string) {
        return string == null ? "" : string;
    }

    /**
     * Turn a constant name into an english like phrase. E.g. <i>HTTP_ERROR</i>
     * would be turned into <i>Http Error</i>.
     * 
     * @param constant constant name
     * @return readable name
     */
    public static String makeConstantReadable(String constant) {
        StringBuffer buf = new StringBuffer();
        char ch;
        boolean firstChar = true;
        for (int i = 0; i < constant.length(); i++) {
            ch = constant.charAt(i);
            if (ch == '_') {
                ch = ' ';
                firstChar = true;
            } else {
                if (firstChar) {
                    ch = Character.toUpperCase(ch);
                    firstChar = false;
                } else {
                    ch = Character.toLowerCase(ch);
                }
            }
            buf.append(ch);
        }
        return buf.toString();
    }

    /**
     * Turn a key into an english like phrase. E.g. <i>webForwardURL</i>
     * would be turned into <i>Web Forward URL</i>.
     * 
     * @param constant constant name
     * @return readable name
     */
    public static String makeKeyReadable(String constant) {
        // vFSPath
        StringBuffer buf = new StringBuffer();
        char ch;
        char lastChar = 0;
        for (int i = 0; i < constant.length(); i++) {
            ch = constant.charAt(i);
            if(i == 0) {
                ch = Character.toUpperCase(ch);   
            }
            else {
                if(Character.isUpperCase(ch)) {
                    if(!Character.isUpperCase(lastChar)) {
                        buf.append(" ");
                    }
                }
            }
            buf.append(ch);
            lastChar = ch;
        }
        return buf.toString();
    }

    /**
     * Turn a constant like name into an key like structure. E.g. <i>HTTP_ERROR</i>
     * would be turned into <i>httpError</i>.
     * 
     * @param constant constant
     * @return key
     */
    public static String makeConstantKey(String constant) {
        StringBuffer buf = new StringBuffer();
        char ch;
        boolean firstChar = false;
        for (int i = 0; i < constant.length(); i++) {
            ch = constant.charAt(i);
            if (ch == '_') {
                firstChar = true;
            } else {
                if (firstChar) {
                    ch = Character.toUpperCase(ch);
                    firstChar = false;
                } else {
                    ch = Character.toLowerCase(ch);
                }
                buf.append(ch);
            }
        }
        return buf.toString();
    }

    /**
     * Re-process the case of a space separated string of words. The first
     * character is capitalised, all others or lower cased.
     * 
     * @param unCased uncased string
     * @return cased string
     */
    public static String reCase(String unCased) {
        StringBuffer buf = new StringBuffer();
        char ch;
        boolean wordNext = false;
        for (int i = 0; i < unCased.length(); i++) {
            ch = unCased.charAt(i);
            if (ch == ' ') {
                wordNext = true;
            } else {
                if (wordNext) {
                    ch = Character.toUpperCase(ch);
                    wordNext = false;
                } else {
                    ch = Character.toLowerCase(ch);
                }
                buf.append(ch);
            }

⌨️ 快捷键说明

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