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

📄 util.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
        }
        return buf.toString();
    }

    /**
     * Read from the provided input stream until the buffer is full, blocking if
     * there are no bytes available until there are.
     * 
     * @param in input stream
     * @param buf buffer to read into
     * @return bytes read
     * @throws IOException on any error
     */
    public static int readFullyIntoBuffer(InputStream in, byte[] buf) throws IOException {
        int read;
        while ((read = in.read(buf)) > -1) {
            ;
        }
        return read;
    }

    /**
     * Parse a simple pattern into a regular expression. Simple expressions
     * simply support '*' and '?' for 'any characters' and 'single character'.
     * By simplifying of the pattern may be defeated by starting the string with
     * a '#' or any exact matched may be specified by starting the string with a
     * '='.
     * 
     * @param simplePattern simple pattern
     * @return regular expression pattern
     * 
     */
    public static String parseSimplePatternToRegExp(String simplePattern) {
        if (simplePattern.startsWith("#")) {
            simplePattern = simplePattern.substring(1);
        } else if (simplePattern.startsWith("=")) {
            simplePattern = "^" + Util.simplePatternToRegExp(simplePattern.substring(1)) + "$";
        } else {
            simplePattern = "^" + Util.simplePatternToRegExp(simplePattern)
                            + (simplePattern.indexOf('*') == -1 && simplePattern.indexOf('?') == -1 ? ".*" : "") + "$";
        }
        return simplePattern;
    }

    /*
     * Convert a simple pattern into a regular expression. Simple expressions
     * simply support '*' and '?' for 'any characters' and 'single character'.
     * 
     * @param simplePattern simple pattern @return regular expression pattern
     */
    static String simplePatternToRegExp(String simplePattern) {
        int c = simplePattern.length();
        char ch;
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < c; i++) {
            ch = simplePattern.charAt(i);
            if (Character.isLetterOrDigit(ch)) {
                buf.append(ch);
            } else if (ch == '*') {
                buf.append(".*");
            } else if (ch == '?') {
                buf.append(".?");
            } else {
                buf.append("\\");
                buf.append(ch);
            }
        }
        return buf.toString();
    }

    /**
     * Get the class path from a class loader (must be an instance
     * of a {@link java.net.URLClassLoader}.
     * 
     * @param classLoader
     * @return class path
     */
    public static String getClassPath(ClassLoader classLoader) {
        StringBuffer buf = new StringBuffer();
        if(classLoader instanceof URLClassLoader) {
            URLClassLoader urlc = (URLClassLoader)classLoader;
            URL[] urls = urlc.getURLs();
            for(int i = 0 ; i < urls.length; i++) {
                if(urls[i].getProtocol().equals("file")) {
                    File f = new File(urls[i].getPath());
                    if(buf.length() > 0) {
                        buf.append(File.pathSeparator);
                    }
                    buf.append(f.getPath());
                }
            }
        }
        return buf.toString();
    }

    /**
     * Append a string to another string inserting a comma if the original
     * string is not blank. If the original string is <code>null</code> it will be
     * treated as if it were blank. The value to append cannot be <code>null</code>.
     * 
     * @param original original string 
     * @param value string to append 
     * @return new string
     */
    public static String appendToCommaSeparatedList(String original, String value) {
        if(original == null || original.equals("")) {
            return value;
        }
        return original + "," + value;
    }

    /**
     * Append a string to the value of a system property insert a comma
     * if the original value is not blank. If the current value of the 
     * original string is <code>null</code> it will be
     * treated as if it were blank. The value to append cannot be <code>null</code>.
     * 
     * @param systemPropertyName system property name to append 
     * @param value string to append 
     */
    public static void appendToCommaSeparatedSystemProperty(String systemPropertyName, String value) {
        System.setProperty(systemPropertyName, appendToCommaSeparatedList(System.getProperty(systemPropertyName), value));
    }

    /**
     * Get the simple name of a class.
     * 
     * @param cls class
     * @return simple name
     */
    public static String getSimpleClassName(Class cls) {
        int idx = cls.getName().lastIndexOf(".");
        return idx == -1 ? cls.getName() : cls.getName().substring(idx + 1);
    }

    /**
     * Split a string into an array taking into account delimiters, quotes and
     * escapes
     * 
     * @param str string to split
     * @param delim delimiter
     * @param quote quote character
     * @param escape escape character
     * @return array
     */
    
    public static String[] splitString(String str, char delim, char quote, char escape) {
        Vector v = new Vector();
        StringBuffer str1 = new StringBuffer();
        char ch = ' ';
        boolean inQuote = false;
        boolean escaped = false;
    
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
    
            if ((escape != -1) && (ch == escape) && !escaped) {
                escaped = true;
            } else {
                if ((quote != -1) && (ch == quote) && !escaped) {
                    inQuote = !inQuote;
                } else if (!inQuote && (ch == delim && !escaped)) {
                    v.addElement(str1.toString());
                    str1.setLength(0);
                } else {
                    str1.append(ch);
                }
                if (escaped) {
                    escaped = false;
                }
            }
        }
    
        if (str.length() > 0) {
            v.addElement(str1.toString());
    
        }
        String[] array;
        array = new String[v.size()];
        v.copyInto(array);
    
        return array;
    }

    /**
     * Escape a string suitable for RFC2253.
     * 
     * @param string
     * @return escaped string
     */
    public static String escapeForDNString(String string) {
        char ch;
        StringBuffer b = new StringBuffer(string.length());
        for(int i = 0 ; i < string.length(); i++) {
            ch = string.charAt(i);
            if(ch == ',' || ch == '+' || ch == '"' || ch == '<' || ch == '>' || ch == ';' || ch == '.') {
                b.append("\\");
                b.append(Integer.toHexString(ch));
            }
            else {
                b.append(ch);
            }
        }
        return b.toString();
    }

    
    public static boolean checkVersion(String actual, String required) {

        int[] applicationVersion = getVersion(actual);
        int[] installedJREVersion = getVersion(required);

        for (int i = 0; i < applicationVersion.length && i < installedJREVersion.length; i++) {
            if (applicationVersion[i] < installedJREVersion[i])
                return false;
        }

        return true;
    }

    public static int[] getVersion(String version) {

        int idx = 0;
        int pos = 0;
        int[] result = new int[0];
        do {

            idx = version.indexOf('.', pos);
            int v;
            if (idx > -1) {
                v = Integer.parseInt(version.substring(pos, idx));
                pos = idx + 1;
            } else {
                try {
                    int sub = version.indexOf('_', pos);
                    if (sub == -1) {
                        sub = version.indexOf('-', pos);
                    }
                    if (sub > -1) {
                        v = Integer.parseInt(version.substring(pos, sub));
                    } else {
                        v = Integer.parseInt(version.substring(pos));
                    }
                } catch (NumberFormatException ex) {
                    // Ignore the exception and return what version we have
                    break;
                }
            }
            int[] tmp = new int[result.length + 1];
            System.arraycopy(result, 0, tmp, 0, result.length);
            tmp[tmp.length - 1] = v;
            result = tmp;

        } while (idx > -1);

        return result;
    }

    public static String escapeForRegexpReplacement(String repl) {
        StringBuffer buf = new StringBuffer(repl.length());
        char ch;
        int len = repl.length();
        for(int i = 0 ; i < len; i++) {
            ch = repl.charAt(i);
            if(ch == '\\') {
                buf.append(ch);
            }
            else if(ch == '$') {
                buf.append('\\');
            }
            buf.append(ch);
        }
        return buf.toString();
    }    
    
    /**
     * Get a day of week constant suitable for use with {@link Calendar}
     * given an english day day. This may be any case and only the first
     * 3 characters are tested for (i.e. sun, mon, tue, etc ..)
     * 
     * @param text
     * @return day of week
     */
    public static int getDayOfWeekForText(String text) {
        text = text.toLowerCase();
        if(text.startsWith("sun")) {
            return Calendar.SUNDAY;
        }
        else if(text.startsWith("mon")) {
            return Calendar.MONDAY;
        }
        else if(text.startsWith("tue")) {
            return Calendar.TUESDAY;
        }
        else if(text.startsWith("wed")) {
            return Calendar.WEDNESDAY;
        }
        else if(text.startsWith("thu")) {
            return Calendar.THURSDAY;
        }
        else if(text.startsWith("fri")) {
            return Calendar.FRIDAY;
        }
        else if(text.startsWith("sat")) {
            return Calendar.SATURDAY;
        }
        return 0;
    }

    /**
     * Set a value in the system.properties file without destroying the
     * format. Note, be careful with this, its pretty simple at the moment
     * and doesn't encode property values.
     * 
     * @param key key (required)
     * @param value value or <code>null</code> to comment
     * @param comment comment to set for new value or <code>null</code> to omit
     * @throws IOException on any error
     */
    public static void setSystemProperty(String key, String value, String comment) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        File f = new File(ContextHolder.getContext().getConfDirectory(), "system.properties");
        File tf = new File(ContextHolder.getContext().getConfDirectory(), "system.properties.tmp");
        File of = new File(ContextHolder.getContext().getConfDirectory(), "system.properties.old");
        try {
            in = new FileInputStream(f);
            out = new FileOutputStream(tf);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter pw = new PrintWriter(out);
            String line = null;
            boolean found = false;
            while( ( line = br.readLine() ) != null ) {
                if(found) {
                    pw.println(line);
                }
                else {
                    String trimLine = Util.trimBoth(line);
                    boolean commented = false;
                    int idx = 0;
                    while(idx < trimLine.length() && trimLine.charAt(idx) == '#') {
                        commented = true;
                        idx++;
                    }
                    String tVal = trimLine.substring(idx);
                    if(tVal.startsWith(key + "=")) {
                        found = true;
                        if(commented) {
                            if(value == null) {
                            //  leave alone
                            }
                            else {
                                // set value
                                pw.println(key + "=" + value);
                            }
                        }
                        else {
                            if(value == null) {
                                // comment
                                pw.println("#" + line);
                            }
                            else {
                                // set value
                                pw.println(key + "=" + value);
                            }
                        }
                    }
                    else {
                        pw.println(line);
                    }
                    trimLine.startsWith("#");
                }
                
            }
            if(!found) {
                if(comment != null) {
                    pw.println();
                    pw.println(comment);
                }
                pw.println(key + "=" + value);
            }
            pw.flush();
            
        } finally {
            Util.closeStream(in);
            Util.closeStream(out);
        }
        
        // Move files
        if(of.exists() && !of.delete()) {
            log.warn("Failed to delete old backup system properties file");
        } 
        copy(f, of);
        copy(tf, f);
        if(!tf.delete()) {
            log.warn("Failed to delete temporary system properties file");
        } 
        

    }

    /**
     * Convert an array of objects to a comma separated string (using
     * each elements {@link Object#toString()} method.
     * 
     * @param elements
     * @return as comma separated string
     */
    public static String arrayToCommaSeparatedList(Object[] elements) {
        StringBuffer buf = new StringBuffer();
        for(int i = 0 ; i < elements.length; i++) {
            if(i > 0) 
                buf.append(",");
            buf.append(elements[i].toString());
        }
        return buf.toString();
    }
}

⌨️ 快捷键说明

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