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

📄 textutil.java

📁 jspwiki source code,jspwiki source code
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     *  @since 2.0.11     */    public static boolean getBooleanProperty( Properties props,                                              String key,                                              boolean defval )    {        String val = props.getProperty( key );        if( val == null ) return defval;        return isPositive( val );    }    /**     *  Fetches a String property from the set of Properties.  This differs from     *  Properties.getProperty() in a couple of key respects: First, property value     *  is trim()med (so no extra whitespace back and front), and well, that's it.     *     *  @param props The Properties to search through     *  @param key   The property key     *  @param defval A default value to return, if the property does not exist.     *  @return The property value.     *  @since 2.1.151     */    public static String getStringProperty( Properties props,                                            String key,                                            String defval )    {        String val = props.getProperty( key );        if( val == null ) return defval;        return val.trim();    }    /**     *  Returns true, if the string "val" denotes a positive string.  Allowed     *  values are "yes", "on", and "true".  Comparison is case-insignificant.     *  Null values are safe.     *     *  @param val Value to check.     *  @return True, if val is "true", "on", or "yes"; otherwise false.     *     *  @since 2.0.26     */    public static boolean isPositive( String val )    {        if( val == null ) return false;        val = val.trim();        return val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on") ||                 val.equalsIgnoreCase("yes");    }    /**     *  Makes sure that the POSTed data is conforms to certain rules.  These     *  rules are:     *  <UL>     *  <LI>The data always ends with a newline (some browsers, such     *      as NS4.x series, does not send a newline at the end, which makes     *      the diffs a bit strange sometimes.     *  <LI>The CR/LF/CRLF mess is normalized to plain CRLF.     *  </UL>     *     *  The reason why we're using CRLF is that most browser already     *  return CRLF since that is the closest thing to a HTTP standard.     *       *  @param postData The data to normalize     *  @return Normalized data     */    public static String normalizePostData( String postData )    {        StringBuffer sb = new StringBuffer();        for( int i = 0; i < postData.length(); i++ )        {            switch( postData.charAt(i) )            {              case 0x0a: // LF, UNIX                sb.append( "\r\n" );                break;              case 0x0d: // CR, either Mac or MSDOS                sb.append( "\r\n" );                // If it's MSDOS, skip the LF so that we don't add it again.                if( i < postData.length()-1 && postData.charAt(i+1) == 0x0a )                {                    i++;                }                break;              default:                sb.append( postData.charAt(i) );                break;            }        }        if( sb.length() < 2 || !sb.substring( sb.length()-2 ).equals("\r\n") )        {            sb.append( "\r\n" );        }        return sb.toString();    }    private static final int EOI   = 0;    private static final int LOWER = 1;    private static final int UPPER = 2;    private static final int DIGIT = 3;    private static final int OTHER = 4;    private static final Random RANDOM = new SecureRandom();    private static int getCharKind(int c)    {        if (c==-1)        {            return EOI;        }        char ch = (char) c;        if (Character.isLowerCase(ch))            return LOWER;        else if (Character.isUpperCase(ch))            return UPPER;        else if (Character.isDigit(ch))            return DIGIT;        else            return OTHER;    }    /**     *  Adds spaces in suitable locations of the input string.  This is     *  used to transform a WikiName into a more readable format.     *     *  @param s String to be beautified.     *  @return A beautified string.     */    public static String beautifyString( String s )    {        return beautifyString( s, " " );    }    /**     *  Adds spaces in suitable locations of the input string.  This is     *  used to transform a WikiName into a more readable format.     *     *  @param s String to be beautified.     *  @param space Use this string for the space character.     *  @return A beautified string.     *  @since 2.1.127     */    public static String beautifyString( String s, String space )    {        StringBuffer result = new StringBuffer();        if( s == null || s.length() == 0 ) return "";        int cur     = s.charAt(0);        int curKind = getCharKind(cur);        int prevKind = LOWER;        int nextKind = -1;        int next = -1;        int nextPos = 1;        while( curKind != EOI )        {            next = (nextPos < s.length()) ? s.charAt(nextPos++) : -1;            nextKind = getCharKind( next );            if( (prevKind == UPPER) && (curKind == UPPER) && (nextKind == LOWER) )            {                result.append(space);                result.append((char) cur);            }            else            {                result.append((char) cur);                if( ( (curKind == UPPER) && (nextKind == DIGIT) )                    || ( (curKind == LOWER) && ((nextKind == DIGIT) || (nextKind == UPPER)) )                    || ( (curKind == DIGIT) && ((nextKind == UPPER) || (nextKind == LOWER)) ))                {                    result.append(space);                }            }            prevKind = curKind;            cur      = next;            curKind  = nextKind;        }        return result.toString();    }    /**     *  Creates a Properties object based on an array which contains alternatively     *  a key and a value.  It is useful for generating default mappings.     *  For example:     *  <pre>     *     String[] properties = { "jspwiki.property1", "value1",     *                             "jspwiki.property2", "value2 };     *     *     Properties props = TextUtil.createPropertes( values );     *     *     System.out.println( props.getProperty("jspwiki.property1") );     *  </pre>     *  would output "value1".     *     *  @param values Alternating key and value pairs.     *  @return Property object     *  @see java.util.Properties     *  @throws IllegalArgumentException if the property array is missing     *          a value for a key.     *  @since 2.2.     */    public static Properties createProperties( String[] values )        throws IllegalArgumentException    {        if( values.length % 2 != 0 )            throw new IllegalArgumentException( "One value is missing.");        Properties props = new Properties();        for( int i = 0; i < values.length; i += 2 )        {            props.setProperty( values[i], values[i+1] );        }        return props;    }    /**     *  Counts the number of sections (separated with "----") from the page.     *     *  @param pagedata The WikiText to parse.     *  @return int Number of counted sections.     *  @since 2.1.86.     */    public static int countSections( String pagedata )    {        int tags  = 0;        int start = 0;        while( (start = pagedata.indexOf("----",start)) != -1 )        {            tags++;            start+=4; // Skip this "----"        }        //        // The first section does not get the "----"        //        return pagedata.length() > 0 ? tags+1 : 0;    }    /**     *  Gets the given section (separated with "----") from the page text.     *  Note that the first section is always #1.  If a page has no section markers,     *  then there is only a single section, #1.     *     *  @param pagedata WikiText to parse.     *  @param section  Which section to get.     *  @return String  The section.     *  @throws IllegalArgumentException If the page does not contain this many sections.     *  @since 2.1.86.     */    public static String getSection( String pagedata, int section )        throws IllegalArgumentException    {        int tags  = 0;        int start = 0;        int previous = 0;        while( (start = pagedata.indexOf("----",start)) != -1 )        {            if( ++tags == section )            {                return pagedata.substring( previous, start );            }            start += 4; // Skip this "----"            // allow additional dashes, treat it as if it was a correct 4-dash            while (start < pagedata.length() && pagedata.charAt(start) == '-')            {                start++;            }            previous = start;        }        if( ++tags == section )        {            return pagedata.substring( previous );        }        throw new IllegalArgumentException("There is no section no. "+section+" on the page.");    }    /**     *  A simple routine which just repeates the arguments.  This is useful     *  for creating something like a line or something.     *     *  @param what String to repeat     *  @param times How many times to repeat the string.     *  @return Guess what?     *  @since 2.1.98.     */    public static String repeatString( String what, int times )    {        StringBuffer sb = new StringBuffer();        for( int i = 0; i < times; i++ )        {            sb.append( what );        }        return sb.toString();    }    /**     *  Converts a string from the Unicode representation into something that can be     *  embedded in a java properties file.  All references outside the ASCII range     *  are replaced with \\uXXXX.     *     *  @param s The string to convert     *  @return the ASCII string     */    public static String native2Ascii(String s)    {        StringBuffer sb = new StringBuffer();        for(int i = 0; i < s.length(); i++)        {            char aChar = s.charAt(i);            if ((aChar < 0x0020) || (aChar > 0x007e))            {                sb.append('\\');                sb.append('u');                sb.append(toHex((aChar >> 12) & 0xF));                sb.append(toHex((aChar >>  8) & 0xF));                sb.append(toHex((aChar >>  4) & 0xF));                sb.append(toHex( aChar        & 0xF));            }            else            {                sb.append(aChar);            }        }        return sb.toString();    }    private static char toHex(int nibble)    {        final char[] hexDigit =        {            '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'        };        return hexDigit[nibble & 0xF];    }    /**     *  Generates a hexadecimal string from an array of bytes.  For     *  example, if the array contains { 0x01, 0x02, 0x3E }, the resulting     *  string will be "01023E".     *     * @param bytes A Byte array     * @return A String representation     * @since 2.3.87     */    public static String toHexString( byte[] bytes )    {        StringBuffer sb = new StringBuffer( bytes.length*2 );        for( int i = 0; i < bytes.length; i++ )        {            sb.append( toHex(bytes[i] >> 4) );            sb.append( toHex(bytes[i]) );        }        return sb.toString();    }    /**     *  Returns true, if the argument contains a number, otherwise false.     *  In a quick test this is roughly the same speed as Integer.parseInt()     *  if the argument is a number, and roughly ten times the speed, if     *  the argument is NOT a number.     *     *  @since 2.4     *  @param s String to check     *  @return True, if s represents a number.  False otherwise.     */    public static boolean isNumber( String s )    {        if( s == null ) return false;        if( s.length() > 1 && s.charAt(0) == '-' )            s = s.substring(1);        for( int i = 0; i < s.length(); i++ )        {            if( !Character.isDigit(s.charAt(i)) )                return false;        }        return true;    }    /** Length of password. @see #generateRandomPassword() */    public static final int PASSWORD_LENGTH = 8;    /**     * Generate a random String suitable for use as a temporary password.     *     * @return String suitable for use as a temporary password     * @since 2.4     */    public static String generateRandomPassword()    {        // Pick from some letters that won't be easily mistaken for each        // other. So, for example, omit o O and 0, 1 l and L.        String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789+@";        String pw = "";        for (int i=0; i<PASSWORD_LENGTH; i++)        {            int index = (int)(RANDOM.nextDouble()*letters.length());            pw += letters.substring(index, index+1);        }        return pw;    }}

⌨️ 快捷键说明

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