Input: / * ( non - Javadoc ) [CODESPLIT] public synchronized Charset detectCodepage ( InputStream in , int length ) throws IOException { this . Reset ( ) ; int len ; int read = 0 ; boolean done = false ; boolean isAscii = true ; Charset ret = null ; do { len = in . read ( buf , 0 , Math . min ( buf . length , length - read ) ) ; if ( len > 0 ) { read += len ; } if ( ! done ) done = det . DoIt ( buf , len , false ) ; } while ( len > 0 && ! done ) ; det . DataEnd ( ) ; if ( this . codpage == null ) { if ( this . m_guessing ) { ret = guess ( ) ; } else { ret = UnknownCharset . getInstance ( ) ; } } else { ret = this . codpage ; } return ret ; }


Input: Sets the bindings for this namespace context . The supplied map must consist of string key value pairs . [CODESPLIT] public void setBindings ( Map < String , String > bindings ) { for ( Map . Entry < String , String > entry : bindings . entrySet ( ) ) { bindNamespaceUri ( entry . getKey ( ) , entry . getValue ( ) ) ; } }


Input: Binds the given prefix to the given namespace . [CODESPLIT] public void bindNamespaceUri ( String prefix , String namespaceUri ) { Assert . notNull ( prefix , "No prefix given" ) ; Assert . notNull ( namespaceUri , "No namespaceUri given" ) ; if ( XMLConstants . DEFAULT_NS_PREFIX . equals ( prefix ) ) { defaultNamespaceUri = namespaceUri ; } else { prefixToNamespaceUri . put ( prefix , namespaceUri ) ; getPrefixesInternal ( namespaceUri ) . add ( prefix ) ; } }


Input: Removes the given prefix from this context . [CODESPLIT] public void removeBinding ( String prefix ) { if ( XMLConstants . DEFAULT_NS_PREFIX . equals ( prefix ) ) { defaultNamespaceUri = "" ; } else { String namespaceUri = prefixToNamespaceUri . remove ( prefix ) ; List < String > prefixes = getPrefixesInternal ( namespaceUri ) ; prefixes . remove ( prefix ) ; } }


Input: 使用工具获取文件的编码方式 [CODESPLIT] public static synchronized String getEncodeByUtil ( File file ) { CodepageDetectorProxy detector = CodepageDetectorProxy . getInstance ( ) ; detector . add ( new ParsingDetector ( false ) ) ; detector . add ( JChardetFacade . getInstance ( ) ) ; // 用到antlr.jar、chardet.jar // ASCIIDetector用于ASCII编码测定 detector . add ( ASCIIDetector . getInstance ( ) ) ; // UnicodeDetector用于Unicode家族编码的测定 //        detector.add(UnicodeDetector.getInstance()); Charset charset = null ; try { charset = detector . detectCodepage ( file . toURI ( ) . toURL ( ) ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } if ( charset != null ) return charset . name ( ) ; else return null ; }


Input: 获取加载的所有类 [CODESPLIT] public static Class [ ] getAllClasses ( ) { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Class < ? > cla = classLoader . getClass ( ) ; while ( cla != ClassLoader . class ) cla = cla . getSuperclass ( ) ; Field field = null ; try { field = cla . getDeclaredField ( "classes" ) ; field . setAccessible ( true ) ; Vector < Class > v = null ; try { v = ( Vector < Class > ) field . get ( classLoader ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { System . out . println ( v . get ( i ) ) ; } return v . toArray ( new Class [ ] { } ) ; } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } return null ; }


Input: 检查类是否直接或间接实现接口 [CODESPLIT] public static boolean isImplementsInterface ( Class clazz , Class enterface ) { Assert . notNull ( clazz ) ; Assert . notNull ( enterface ) ; Class [ ] interfaces = clazz . getInterfaces ( ) ; Class superclass = clazz . getSuperclass ( ) ; if ( superclass != null ) { boolean implementsInterface = isImplementsInterface ( superclass , enterface ) ; if ( implementsInterface ) { return true ; } } boolean flag = false ; for ( Class anInterface : interfaces ) { if ( enterface == anInterface ) { return true ; } else { flag = isImplementsInterface ( anInterface , enterface ) ; if ( flag ) { return flag ; } } } return flag ; }


Input: Parse the given String into a single { @code MimeType } . [CODESPLIT] public static MimeType parseMimeType ( String mimeType ) { if ( ! StringUtils . hasLength ( mimeType ) ) { throw new InvalidMimeTypeException ( mimeType , "'mimeType' must not be empty" ) ; } String [ ] parts = StringUtils . tokenizeToStringArray ( mimeType , ";" ) ; String fullType = parts [ 0 ] . trim ( ) ; // java.net.HttpURLConnection returns a *; q=.2 Accept header if ( MimeType . WILDCARD_TYPE . equals ( fullType ) ) { fullType = "*/*" ; } int subIndex = fullType . indexOf ( ' ' ) ; if ( subIndex == - 1 ) { throw new InvalidMimeTypeException ( mimeType , "does not contain '/'" ) ; } if ( subIndex == fullType . length ( ) - 1 ) { throw new InvalidMimeTypeException ( mimeType , "does not contain subtype after '/'" ) ; } String type = fullType . substring ( 0 , subIndex ) ; String subtype = fullType . substring ( subIndex + 1 , fullType . length ( ) ) ; if ( MimeType . WILDCARD_TYPE . equals ( type ) && ! MimeType . WILDCARD_TYPE . equals ( subtype ) ) { throw new InvalidMimeTypeException ( mimeType , "wildcard type is legal only in '*/*' (all mime types)" ) ; } Map < String , String > parameters = null ; if ( parts . length > 1 ) { parameters = new LinkedHashMap < String , String > ( parts . length - 1 ) ; for ( int i = 1 ; i < parts . length ; i ++ ) { String parameter = parts [ i ] ; int eqIndex = parameter . indexOf ( ' ' ) ; if ( eqIndex != - 1 ) { String attribute = parameter . substring ( 0 , eqIndex ) ; String value = parameter . substring ( eqIndex + 1 , parameter . length ( ) ) ; parameters . put ( attribute , value ) ; } } } try { return new MimeType ( type , subtype , parameters ) ; } catch ( UnsupportedCharsetException ex ) { throw new InvalidMimeTypeException ( mimeType , "unsupported charset '" + ex . getCharsetName ( ) + "'" ) ; } catch ( IllegalArgumentException ex ) { throw new InvalidMimeTypeException ( mimeType , ex . getMessage ( ) ) ; } }


Input: Parse the given comma - separated string into a list of { @code MimeType } objects . [CODESPLIT] public static List < MimeType > parseMimeTypes ( String mimeTypes ) { if ( ! StringUtils . hasLength ( mimeTypes ) ) { return Collections . emptyList ( ) ; } String [ ] tokens = mimeTypes . split ( ",\\s*" ) ; List < MimeType > result = new ArrayList < MimeType > ( tokens . length ) ; for ( String token : tokens ) { result . add ( parseMimeType ( token ) ) ; } return result ; }


Input: Sorts the given list of { @code MimeType } objects by specificity . <p > Given two mime types : <ol > <li > if either mime type has a { @linkplain MimeType#isWildcardType () wildcard type } then the mime type without the wildcard is ordered before the other . < / li > <li > if the two mime types have different { @linkplain MimeType#getType () types } then they are considered equal and remain their current order . < / li > <li > if either mime type has a { @linkplain MimeType#isWildcardSubtype () wildcard subtype } then the mime type without the wildcard is sorted before the other . < / li > <li > if the two mime types have different { @linkplain MimeType#getSubtype () subtypes } then they are considered equal and remain their current order . < / li > <li > if the two mime types have a different amount of { @linkplain MimeType#getParameter ( String ) parameters } then the mime type with the most parameters is ordered before the other . < / li > < / ol > <p > For example : <blockquote > audio / basic &lt ; audio / * &lt ; * &#047 ; * < / blockquote > <blockquote > audio / basic ; level = 1 &lt ; audio / basic< / blockquote > <blockquote > audio / basic == text / html< / blockquote > <blockquote > audio / basic == audio / wave< / blockquote > [CODESPLIT] public static void sortBySpecificity ( List < MimeType > mimeTypes ) { Assert . notNull ( mimeTypes , "'mimeTypes' must not be null" ) ; if ( mimeTypes . size ( ) > 1 ) { Collections . sort ( mimeTypes , SPECIFICITY_COMPARATOR ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public Charset detectCodepage ( final InputStream in , final int length ) throws IOException { EncodingLexer lexer ; EncodingParser parser ; Charset charset = null ; String csName = null ; InputStream limitedInputStream = new LimitedInputStream ( in , length ) ; if ( this . m_verbose ) { System . out . println ( "  parsing for html-charset/xml-encoding attribute with codepage: US-ASCII" ) ; } try { lexer = new EncodingLexer ( new InputStreamReader ( limitedInputStream , "US-ASCII" ) ) ; parser = new EncodingParser ( lexer ) ; csName = parser . htmlDocument ( ) ; if ( csName != null ) { // TODO: prepare document with illegal value, then test: Decide to catch // exception and return // UnsupportedCharset. try { charset = Charset . forName ( csName ) ; } catch ( UnsupportedCharsetException uce ) { charset = UnsupportedCharset . forName ( csName ) ; } } else { charset = UnknownCharset . getInstance ( ) ; } } catch ( ANTLRException ae ) { if ( this . m_verbose ) { System . out . println ( "  ANTLR parser exception: " + ae . getMessage ( ) ) ; } } catch ( Exception deepdown ) { if ( this . m_verbose ) { System . out . println ( "  Decoding Exception: " + deepdown . getMessage ( ) + " (unsupported java charset)." ) ; } if ( charset == null ) { if ( csName != null ) { charset = UnsupportedCharset . forName ( csName ) ; } else { charset = UnknownCharset . getInstance ( ) ; } } } return charset ; }


Input: Detect the validation mode for the XML document in the supplied { @link java . io . InputStream } . Note that the supplied { @link java . io . InputStream } is closed by this method before returning . [CODESPLIT] public int detectValidationMode ( InputStream inputStream ) throws IOException { // Peek into the file to look for DOCTYPE. BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; try { boolean isDtdValidated = false ; String content ; while ( ( content = reader . readLine ( ) ) != null ) { content = consumeCommentTokens ( content ) ; if ( this . inComment || ! StringUtils . hasText ( content ) ) { continue ; } if ( hasDoctype ( content ) ) { isDtdValidated = true ; break ; } if ( hasOpeningTag ( content ) ) { // End of meaningful data... break ; } } return ( isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD ) ; } catch ( CharConversionException ex ) { // Choked on some character encoding... // Leave the decision up to the caller. return VALIDATION_AUTO ; } finally { reader . close ( ) ; } }


Input: Does the supplied content contain an XML opening tag . If the parse state is currently in an XML comment then this method always returns false . It is expected that all comment tokens will have consumed for the supplied content before passing the remainder to this method . [CODESPLIT] private boolean hasOpeningTag ( String content ) { if ( this . inComment ) { return false ; } int openTagIndex = content . indexOf ( ' ' ) ; return ( openTagIndex > - 1 && content . length ( ) > openTagIndex && Character . isLetter ( content . charAt ( openTagIndex + 1 ) ) ) ; }


Input: Consumes all the leading comment data in the given String and returns the remaining content which may be empty since the supplied content might be all comment data . For our purposes it is only important to strip leading comment content on a line since the first piece of non comment content will be either the DOCTYPE declaration or the root element of the document . [CODESPLIT] private String consumeCommentTokens ( String line ) { if ( line . indexOf ( START_COMMENT ) == - 1 && line . indexOf ( END_COMMENT ) == - 1 ) { return line ; } while ( ( line = consume ( line ) ) != null ) { if ( ! this . inComment && ! line . trim ( ) . startsWith ( START_COMMENT ) ) { return line ; } } return line ; }


Input: Consume the next comment token update the inComment flag and return the remaining content . [CODESPLIT] private String consume ( String line ) { int index = ( this . inComment ? endComment ( line ) : startComment ( line ) ) ; return ( index == - 1 ? null : line . substring ( index ) ) ; }


Input: Try to consume the supplied token against the supplied content and update the in comment parse state to the supplied value . Returns the index into the content which is after the token or - 1 if the token is not found . [CODESPLIT] private int commentToken ( String line , String token , boolean inCommentIfPresent ) { int index = line . indexOf ( token ) ; if ( index > - 1 ) { this . inComment = inCommentIfPresent ; } return ( index == - 1 ? index : index + token . length ( ) ) ; }


Input: 计算日期之间相差多少天 [CODESPLIT] public static int diffOfDay ( Date date1 , Date date2 ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( date1 . getTime ( ) ) ; int i = calendar . get ( Calendar . DAY_OF_YEAR ) ; Calendar calendar2 = Calendar . getInstance ( ) ; calendar2 . setTimeInMillis ( date2 . getTime ( ) ) ; int i2 = calendar2 . get ( Calendar . DAY_OF_YEAR ) ; return i2 - i ; }


Input: 获取现在时间 [CODESPLIT] public static Date getNowDate ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; ParsePosition pos = new ParsePosition ( 8 ) ; Date currentTime_2 = FORMATTER_LONG . parse ( dateString , pos ) ; return currentTime_2 ; }


Input: 获取现在时间 [CODESPLIT] public static Date getNowDateShort ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_SHORT . format ( currentTime ) ; ParsePosition pos = new ParsePosition ( 8 ) ; Date currentTime_2 = FORMATTER_SHORT . parse ( dateString , pos ) ; return currentTime_2 ; }


Input: 获取现在时间 [CODESPLIT] public static String getStringDate ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; return dateString ; }


Input: 获取现在时间 [CODESPLIT] public static String getStringDateShort ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_SHORT . format ( currentTime ) ; return dateString ; }


Input: 获取时间 小时 : 分 ; 秒 HH : mm : ss [CODESPLIT] public static String getTimeShort ( ) { SimpleDateFormat formatter = new SimpleDateFormat ( "HH:mm:ss" ) ; Date currentTime = new Date ( ) ; String dateString = formatter . format ( currentTime ) ; return dateString ; }


Input: 将长时间格式字符串转换为时间 yyyy - MM - dd HH : mm : ss [CODESPLIT] public static Date strToDateLong ( String strDate ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = FORMATTER_LONG . parse ( strDate , pos ) ; return strtodate ; }


Input: 字符串转换为时间 [CODESPLIT] public static Date strToDate ( String strDate , String dateFormat ) { return strToDate ( strDate , new SimpleDateFormat ( dateFormat ) ) ; }


Input: 字符串转换为时间 [CODESPLIT] public static Date strToDate ( String strDate , DateFormat dateFormat ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = dateFormat . parse ( strDate , pos ) ; return strtodate ; }


Input: 将长时间格式时间转换为字符串 yyyy - MM - dd HH : mm : ss [CODESPLIT] public static String dateToStrLong ( Date dateDate ) { String dateString = FORMATTER_LONG . format ( dateDate ) ; return dateString ; }


Input: 将短时间格式时间转换为字符串 yyyy - MM - dd [CODESPLIT] public static String dateToStr ( Date dateDate ) { String dateString = FORMATTER_SHORT . format ( dateDate ) ; return dateString ; }


Input: 将短时间格式字符串转换为时间 yyyy - MM - dd [CODESPLIT] public static Date strToDate ( String strDate ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = FORMATTER_SHORT . parse ( strDate , pos ) ; return strtodate ; }


Input: 提取一个月中的最后一天 [CODESPLIT] public static Date getLastDate ( long day ) { Date date = new Date ( ) ; long date_3_hm = date . getTime ( ) - 3600000 * 34 * day ; Date date_3_hm_date = new Date ( date_3_hm ) ; return date_3_hm_date ; }


Input: 得到现在时间 [CODESPLIT] public static String getStringToday ( ) { Date currentTime = new Date ( ) ; SimpleDateFormat formatter = new SimpleDateFormat ( "yyyyMMdd HHmmss" ) ; String dateString = formatter . format ( currentTime ) ; return dateString ; }


Input: 得到现在小时 [CODESPLIT] public static String getHour ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; String hour ; hour = dateString . substring ( 11 , 13 ) ; return hour ; }


Input: 得到现在分钟 [CODESPLIT] public static String getTime ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; String min ; min = dateString . substring ( 14 , 16 ) ; return min ; }


Input: 根据用户传入的时间表示格式，返回当前时间的格式 如果是yyyyMMdd，注意字母y不能大写。 [CODESPLIT] public static String getUserDate ( String sformat ) { Date currentTime = new Date ( ) ; SimpleDateFormat formatter = new SimpleDateFormat ( sformat ) ; String dateString = formatter . format ( currentTime ) ; return dateString ; }


Input: 二个小时时间间的差值 必须保证二个时间都是 HH : MM 的格式，返回字符型的分钟 [CODESPLIT] public static String getTwoHour ( String st1 , String st2 ) { String [ ] kk = null ; String [ ] jj = null ; kk = st1 . split ( ":" ) ; jj = st2 . split ( ":" ) ; if ( Integer . parseInt ( kk [ 0 ] ) < Integer . parseInt ( jj [ 0 ] ) ) return "0" ; else { double y = Double . parseDouble ( kk [ 0 ] ) + Double . parseDouble ( kk [ 1 ] ) / 60 ; double u = Double . parseDouble ( jj [ 0 ] ) + Double . parseDouble ( jj [ 1 ] ) / 60 ; if ( ( y - u ) > 0 ) return y - u + "" ; else return "0" ; } }


Input: 得到二个日期间的间隔天数 [CODESPLIT] public static String getTwoDay ( String sj1 , String sj2 ) { SimpleDateFormat myFormatter = new SimpleDateFormat ( "yyyy-MM-dd" ) ; long day = 0 ; try { Date date = myFormatter . parse ( sj1 ) ; Date mydate = myFormatter . parse ( sj2 ) ; day = ( date . getTime ( ) - mydate . getTime ( ) ) / ( 24 * 60 * 60 * 1000 ) ; } catch ( Exception e ) { return "" ; } return day + "" ; }


Input: 时间前推或后推分钟 其中JJ表示分钟 . [CODESPLIT] public static String getPreTime ( String sj1 , String jj ) { SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; String mydate1 = "" ; try { Date date1 = format . parse ( sj1 ) ; long Time = ( date1 . getTime ( ) / 1000 ) + Integer . parseInt ( jj ) * 60 ; date1 . setTime ( Time * 1000 ) ; mydate1 = format . format ( date1 ) ; } catch ( Exception e ) { } return mydate1 ; }


Input: 得到一个时间延后或前移几天的时间 nowdate为时间 delay为前移或后延的天数 [CODESPLIT] public static Date getNextDay ( Date nowDate , int delay ) { long myTime = ( nowDate . getTime ( ) / 1000 ) + delay * 24 * 60 * 60 ; Date date = new Date ( ) ; date . setTime ( myTime * 1000 ) ; return date ; }


Input: 得到一个时间延后或前移几天的时间 nowdate为时间 delay为前移或后延的天数 [CODESPLIT] public static String getNextDay ( String nowDate , int delay ) { try { SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd" ) ; String mdate = "" ; Date d = strToDate ( nowDate ) ; long myTime = ( d . getTime ( ) / 1000 ) + delay * 24 * 60 * 60 ; d . setTime ( myTime * 1000 ) ; mdate = format . format ( d ) ; return mdate ; } catch ( Exception e ) { return "" ; } }


Input:
判断是否润年 [CODESPLIT] public static boolean isLeapYear ( String ddate ) { /**
         * 详细设计： 1.被400整除是闰年，否则： 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
         * 3.能被4整除同时能被100整除则不是闰年
         */ Date d = strToDate ( ddate ) ; GregorianCalendar gc = ( GregorianCalendar ) Calendar . getInstance ( ) ; gc . setTime ( d ) ; int year = gc . get ( Calendar . YEAR ) ; if ( ( year % 400 ) == 0 ) return true ; else if ( ( year % 4 ) == 0 ) { if ( ( year % 100 ) == 0 ) return false ; else return true ; } else return false ; }


Input: 返回美国时间格式 26 Apr 2006 [CODESPLIT] public static String getEDate ( String str ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = FORMATTER_SHORT . parse ( str , pos ) ; String j = strtodate . toString ( ) ; String [ ] k = j . split ( " " ) ; return k [ 2 ] + k [ 1 ] . toUpperCase ( ) + k [ 5 ] . substring ( 2 , 4 ) ; }


Input: 获取一个月的最后一天 [CODESPLIT] public static String getEndDateOfMonth ( String dat ) { // yyyy-MM-dd String str = dat . substring ( 0 , 8 ) ; String month = dat . substring ( 5 , 7 ) ; int mon = Integer . parseInt ( month ) ; if ( mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12 ) { str += "31" ; } else if ( mon == 4 || mon == 6 || mon == 9 || mon == 11 ) { str += "30" ; } else { if ( isLeapYear ( dat ) ) { str += "29" ; } else { str += "28" ; } } return str ; }


Input: 判断二个时间是否在同一个周 [CODESPLIT] public static boolean isSameWeekDates ( Date date1 , Date date2 ) { Calendar cal1 = Calendar . getInstance ( ) ; Calendar cal2 = Calendar . getInstance ( ) ; cal1 . setTime ( date1 ) ; cal2 . setTime ( date2 ) ; int subYear = cal1 . get ( Calendar . YEAR ) - cal2 . get ( Calendar . YEAR ) ; if ( 0 == subYear ) { if ( cal1 . get ( Calendar . WEEK_OF_YEAR ) == cal2 . get ( Calendar . WEEK_OF_YEAR ) ) return true ; } else if ( 1 == subYear && 11 == cal2 . get ( Calendar . MONTH ) ) { // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周 if ( cal1 . get ( Calendar . WEEK_OF_YEAR ) == cal2 . get ( Calendar . WEEK_OF_YEAR ) ) return true ; } else if ( - 1 == subYear && 11 == cal1 . get ( Calendar . MONTH ) ) { if ( cal1 . get ( Calendar . WEEK_OF_YEAR ) == cal2 . get ( Calendar . WEEK_OF_YEAR ) ) return true ; } return false ; }


Input: 产生周序列 即得到当前时间所在的年度是第几周 [CODESPLIT] public static String getSeqWeek ( ) { Calendar c = Calendar . getInstance ( Locale . CHINA ) ; String week = Integer . toString ( c . get ( Calendar . WEEK_OF_YEAR ) ) ; if ( week . length ( ) == 1 ) week = "0" + week ; String year = Integer . toString ( c . get ( Calendar . YEAR ) ) ; return year + week ; }


Input: 获得一个日期所在的周的星期几的日期，如要找出2002年2月3日所在周的星期一是几号 [CODESPLIT] public static String getWeek ( String sdate , String num ) { // 再转换为时间 Date dd = DateHelper . strToDate ( sdate ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( dd ) ; if ( num . equals ( "1" ) ) // 返回星期一所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . MONDAY ) ; else if ( num . equals ( "2" ) ) // 返回星期二所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . TUESDAY ) ; else if ( num . equals ( "3" ) ) // 返回星期三所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . WEDNESDAY ) ; else if ( num . equals ( "4" ) ) // 返回星期四所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . THURSDAY ) ; else if ( num . equals ( "5" ) ) // 返回星期五所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . FRIDAY ) ; else if ( num . equals ( "6" ) ) // 返回星期六所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . SATURDAY ) ; else if ( num . equals ( "0" ) ) // 返回星期日所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . SUNDAY ) ; return new SimpleDateFormat ( "yyyy-MM-dd" ) . format ( c . getTime ( ) ) ; }


Input: 根据一个日期，返回是星期几的字符串 [CODESPLIT] public static String getWeek ( String sdate ) { // 再转换为时间 Date date = DateHelper . strToDate ( sdate ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( date ) ; // int hour=c.get(Calendar.DAY_OF_WEEK); // hour中存的就是星期几了，其范围 1~7 // 1=星期日 7=星期六，其他类推 return new SimpleDateFormat ( "EEEE" ) . format ( c . getTime ( ) ) ; }


Input: 两个时间之间的天数 [CODESPLIT] public static long getDays ( String date1 , String date2 ) { if ( date1 == null || date1 . equals ( "" ) ) return 0 ; if ( date2 == null || date2 . equals ( "" ) ) return 0 ; // 转换为标准时间 SimpleDateFormat myFormatter = new SimpleDateFormat ( "yyyy-MM-dd" ) ; Date date = null ; Date mydate = null ; try { date = myFormatter . parse ( date1 ) ; mydate = myFormatter . parse ( date2 ) ; } catch ( Exception e ) { } long day = ( date . getTime ( ) - mydate . getTime ( ) ) / ( 24 * 60 * 60 * 1000 ) ; return day ; }


Input: 形成如下的日历 ， 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间 此函数返回该日历第一行星期日所在的日期 [CODESPLIT] public static String getNowMonth ( String sdate ) { // 取该时间所在月的一号 sdate = sdate . substring ( 0 , 8 ) + "01" ; // 得到这个月的1号是星期几 Date date = DateHelper . strToDate ( sdate ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( date ) ; int u = c . get ( Calendar . DAY_OF_WEEK ) ; String newday = DateHelper . getNextDay ( sdate , 1 - u ) ; return newday ; }


Input: 返回一个随机数 [CODESPLIT] public static String getRandom ( int i ) { Random jjj = new Random ( ) ; // int suiJiShu = jjj.nextInt(9); if ( i == 0 ) return "" ; String jj = "" ; for ( int k = 0 ; k < i ; k ++ ) { jj = jj + jjj . nextInt ( 9 ) ; } return jj ; }


Input: 获取时间的日期（转换为0时） [CODESPLIT] public static Date getDay ( Date date ) { //        long time = date.getTime() / 1000; //        System.out.println(time); //        System.out.println(CalendarHelper.DAY); //        long day = 24 * 60 * 60; //        System.out.println(time % (day * 1000)); //        System.out.println((time % day) / CalendarHelper.HOUR); //        time = time - (time % day); //        Date date1 = new Date(time * 1000); String dateStr = FORMATTER_SHORT . format ( date ) ; Date date1 = strToDate ( dateStr , FORMATTER_SHORT ) ; return date1 ; }


Input: Initialize log4j from the given file location with no config file refreshing . Assumes an XML file in case of a . xml file extension and a properties file otherwise . [CODESPLIT] public static void initLogging ( String location ) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils . resolvePlaceholders ( location ) ; URL url = ResourceUtils . getURL ( resolvedLocation ) ; if ( resolvedLocation . toLowerCase ( ) . endsWith ( XML_FILE_EXTENSION ) ) { DOMConfigurator . configure ( url ) ; } else { PropertyConfigurator . configure ( url ) ; } }


Input: Initialize log4j from the given location with the given refresh interval for the config file . Assumes an XML file in case of a . xml file extension and a properties file otherwise . <p > Log4j s watchdog thread will asynchronously check whether the timestamp of the config file has changed using the given interval between checks . A refresh interval of 1000 milliseconds ( one second ) which allows to do on - demand log level changes with immediate effect is not unfeasible . <p > <b > WARNING : < / b > Log4j s watchdog thread does not terminate until VM shutdown ; in particular it does not terminate on LogManager shutdown . Therefore it is recommended to <i > not< / i > use config file refreshing in a production J2EE environment ; the watchdog thread would not stop on application shutdown there . [CODESPLIT] public static void initLogging ( String location , long refreshInterval ) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils . resolvePlaceholders ( location ) ; File file = ResourceUtils . getFile ( resolvedLocation ) ; if ( ! file . exists ( ) ) { throw new FileNotFoundException ( "Log4j config file [" + resolvedLocation + "] not found" ) ; } if ( resolvedLocation . toLowerCase ( ) . endsWith ( XML_FILE_EXTENSION ) ) { DOMConfigurator . configureAndWatch ( file . getAbsolutePath ( ) , refreshInterval ) ; } else { PropertyConfigurator . configureAndWatch ( file . getAbsolutePath ( ) , refreshInterval ) ; } }


Input: Binds the given prefix to the given namespaces . [CODESPLIT] @ Override public final void startPrefixMapping ( String prefix , String uri ) { namespaceContext . bindNamespaceUri ( prefix , uri ) ; namespaceContextChanged = true ; }


Input: Convert a namespace URI and DOM or SAX qualified name to a { @code QName } . The qualified name can have the form { @code prefix : localname } or { @code localName } . [CODESPLIT] protected QName toQName ( String namespaceUri , String qualifiedName ) { int idx = qualifiedName . indexOf ( ' ' ) ; if ( idx == - 1 ) { return new QName ( namespaceUri , qualifiedName ) ; } else { String prefix = qualifiedName . substring ( 0 , idx ) ; String localPart = qualifiedName . substring ( idx + 1 ) ; return new QName ( namespaceUri , localPart , prefix ) ; } }


Input: Add given iterator to this composite . [CODESPLIT] public void add ( Iterator < E > iterator ) { Assert . state ( ! inUse , "You can no longer add iterator to a composite iterator that's already in use" ) ; if ( iterators . contains ( iterator ) ) { throw new IllegalArgumentException ( "You cannot add the same iterator twice" ) ; } iterators . add ( iterator ) ; }


Input: 发送邮件 [CODESPLIT] @ Override public void sendEmail ( EmailVo emailVo ) throws MessagingException { Assert . notNull ( emailVo . getTo ( ) , "接收人不能为空");   MimeMessage msg = javaMailSenderFactory . createMimeMessage ( ) ; MimeMessageHelper msgHelper = null ; if ( ( emailVo . getInlineImageVos ( ) != null && emailVo . getInlineImageVos ( ) . size ( ) > 0 ) || ( emailVo . getAttachmentVos ( ) != null && emailVo . getAttachmentVos ( ) . size ( ) > 0 ) ) { msgHelper = new MimeMessageHelper ( msg , true , "utf-8" ) ; } else { msgHelper = new MimeMessageHelper ( msg , "utf-8" ) ; } if ( emailVo . getFrom ( ) == null || "" . equals ( emailVo . getFrom ( ) . trim ( ) ) ) { emailVo . setFrom ( javaMailSenderFactory . getSystemEmail ( ) ) ; } if ( ( emailVo . getCc ( ) == null || "" . equals ( emailVo . getCc ( ) . length == 0 ) ) && javaMailSenderFactory . getDefaultCc ( ) != null && ! javaMailSenderFactory . getDefaultCc ( ) . equals ( "" ) ) { emailVo . setCc ( javaMailSenderFactory . getDefaultCc ( ) . split ( "," ) ) ; } if ( ( emailVo . getBcc ( ) == null || "" . equals ( emailVo . getBcc ( ) . length == 0 ) ) && javaMailSenderFactory . getDefaultBcc ( ) != null && ! javaMailSenderFactory . getDefaultBcc ( ) . equals ( "" ) ) { emailVo . setBcc ( javaMailSenderFactory . getDefaultBcc ( ) . split ( "," ) ) ; } if ( emailVo . getMessageDate ( ) == null ) { emailVo . setMessageDate ( new Date ( ) ) ; } if ( emailVo . getCc ( ) != null ) { msgHelper . setCc ( emailVo . getCc ( ) ) ; // 抄送 } if ( emailVo . getBcc ( ) != null ) { msgHelper . setBcc ( emailVo . getBcc ( ) ) ; // 密送 } if ( emailVo . getSubject ( ) != null ) { msgHelper . setSubject ( emailVo . getSubject ( ) ) ; } handlerAttachments ( emailVo , msgHelper ) ; String from = null ; if ( emailVo . getFrom ( ) != null && ! "" . equals ( emailVo . getFrom ( ) ) ) { from = emailVo . getFrom ( ) ; } else { if ( javaMailSenderFactory . getEmailAccount ( ) . getFrom ( ) != null && ! "" . equals ( javaMailSenderFactory . getEmailAccount ( ) . getFrom ( ) ) ) { from = javaMailSenderFactory . getEmailAccount ( ) . getFrom ( ) ; } else { from = javaMailSenderFactory . getEmailAccount ( ) . getUsername ( ) ; } } try { if ( javaMailSenderFactory . getEmailAccount ( ) . getNickName ( ) != null ) { msgHelper . setFrom ( from , javaMailSenderFactory . getEmailAccount ( ) . getNickName ( ) ) ; } else { msgHelper . setFrom ( from ) ; } } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; msgHelper . setFrom ( from ) ; } msgHelper . setTo ( emailVo . getTo ( ) ) ; // 接收人 Collection < Inline > inlines = handlerInlineImages ( emailVo , msgHelper ) ; if ( emailVo . getHtml ( ) != null ) { msgHelper . setText ( emailVo . getHtml ( ) , emailVo . isHtml ( ) ) ; if ( inlines != null ) { // 添加inline for ( Inline inline : inlines ) { msgHelper . addInline ( inline . getContentId ( ) , inline . getFile ( ) ) ; } } } javaMailSenderFactory . send ( msg ) ; }


Input: 处理内嵌对象 [CODESPLIT] private Collection < Inline > handlerInlineImages ( EmailVo emailVo , MimeMessageHelper msgHelper ) throws MessagingException { Collection < Inline > inlines = null ; if ( emailVo . getInlineImageVos ( ) != null && emailVo . getInlineImageVos ( ) . size ( ) > 0 ) { inlines = new HashSet < Inline > ( ) ; String html = emailVo . getHtml ( ) ; if ( html == null || html . trim ( ) . equals ( "" ) ) { // 如果内容空或者不是 html则直接跳过 return inlines ; } //  ------------------------------------------- 查找带数字的标记 ${数字} ------------------------------------------- Matcher matcherIndexTag = PATTERN_FIND_TAG_AND_INDEX . matcher ( html ) ; int contentIdIndex = 0 ; while ( matcherIndexTag . find ( ) ) { String htmlTag = matcherIndexTag . group ( ) ; // 查找到 的内容 Matcher matcherDollar = PATTERN_DOLLAR_VARIABLE_INDEX . matcher ( htmlTag ) ; if ( matcherDollar . find ( ) ) { String dollarFind = matcherDollar . group ( ) ; // 查找到${1}内容 String indexStr = dollarFind . replace ( "$" , "" ) . replace ( "{" , "" ) . replace ( "}" , "" ) . trim ( ) ; // 移除外面的$符号和大括号 int index = Integer . parseInt ( indexStr ) ; try { InlineImageVo inlineImageVo = emailVo . getInlineImageVos ( ) . get ( index ) ; File file = inlineImageVo . getFile ( ) ; String contentId = "file" + contentIdIndex ++ ; // 生成contentId //                        msgHelper.addInline(contentId, file);// 将附件内容传送给MimeMessageHelper Inline inline = new Inline ( ) ; inline . setFile ( file ) ; inline . setContentId ( contentId ) ; inlines . add ( inline ) ; htmlTag = matcherDollar . replaceAll ( "cid:" + contentId ) ; //                        System.out.println("indexStr ====== " + indexStr); //                        System.out.println("htmlTag ====== " + htmlTag); html = matcherIndexTag . replaceFirst ( htmlTag ) ; matcherIndexTag = PATTERN_FIND_TAG_AND_INDEX . matcher ( html ) ; //                        System.out.println("html ====== " + html); } catch ( Exception e ) { e . printStackTrace ( ) ; } } } //  ------------------------------------------- 查找带字母变量的标记 ${variable} ------------------------------------------- Matcher matcherTag = PATTERN_FIND_TAG . matcher ( html ) ; while ( matcherTag . find ( ) ) { String htmlTag = matcherTag . group ( ) ; // 查找到 的内容 Matcher matcherDollar = PATTERN_DOLLAR_VARIABLE_SELF_DEFINE . matcher ( htmlTag ) ; if ( matcherDollar . find ( ) ) { String dollarFind = matcherDollar . group ( ) ; // 查找到${1}内容 String dollarVariable = dollarFind . replace ( "$" , "" ) . replace ( "{" , "" ) . replace ( "}" , "" ) . trim ( ) ; // 移除外面的$符号和大括号 try { InlineImageVo inlineImageVo = null ; for ( InlineImageVo imageVo : emailVo . getInlineImageVos ( ) ) { if ( imageVo . getContentId ( ) != null && imageVo . getContentId ( ) . equals ( dollarVariable ) ) { inlineImageVo = imageVo ; } } if ( inlineImageVo == null ) { continue ; } File file = inlineImageVo . getFile ( ) ; //                        String contentId = "file" + contentIdIndex++; // 生成contentId //                        msgHelper.addInline(contentId, file);// 将附件内容传送给MimeMessageHelper Inline inline = new Inline ( ) ; inline . setFile ( file ) ; inline . setContentId ( inlineImageVo . getContentId ( ) ) ; inlines . add ( inline ) ; htmlTag = matcherDollar . replaceAll ( "cid:" + inlineImageVo . getContentId ( ) ) ; //                        System.out.println("htmlTag ====== " + htmlTag); html = matcherTag . replaceFirst ( htmlTag ) ; matcherTag = PATTERN_FIND_TAG . matcher ( html ) ; //                        System.out.println("html ====== " + html); } catch ( Exception e ) { e . printStackTrace ( ) ; } } } emailVo . setHtml ( html ) ; if ( inlines != null && inlines . size ( ) > 0 ) { emailVo . setHtml ( true ) ; } } return inlines ; }


Input: 处理附件 [CODESPLIT] private void handlerAttachments ( EmailVo emailVo , MimeMessageHelper msgHelper ) throws MessagingException { if ( emailVo . getAttachmentVos ( ) != null ) { // 检查附件 for ( AttachmentVo attachmentVo : emailVo . getAttachmentVos ( ) ) { File attachment = attachmentVo . getAttachment ( ) ; if ( attachment == null ) { InputStream inputStream = attachmentVo . getAttachmentInputStream ( ) ; if ( attachmentVo . getAttachmentName ( ) == null ) { attachmentVo . setAttachmentName ( new Date ( ) . toString ( ) ) ; } InputStreamSource inputStreamSource = new InputStreamResource ( inputStream ) ; msgHelper . addAttachment ( attachmentVo . getAttachmentName ( ) , inputStreamSource ) ; } else { if ( attachmentVo . getAttachmentName ( ) == null ) { attachmentVo . setAttachmentName ( attachment . getName ( ) ) ; } try { msgHelper . addAttachment ( MimeUtility . encodeWord ( attachmentVo . getAttachmentName ( ) ) , attachment ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } } } }


Input: 设置继承类 [CODESPLIT] public CodeBuilder superClass ( Class < ? > clazz ) { if ( clazz . isInterface ( ) ) { System . out . println ( clazz + "为接口对象！取消设为继承类。");   return this ; } String simpleName = clazz . getSimpleName ( ) ; Package pkg = clazz . getPackage ( ) ; imports . add ( pkg . getName ( ) + "." + simpleName ) ; // 导入包 this . superClass = simpleName ; // 设置继承的类名 return this ; }


Input: 增加接口 [CODESPLIT] public CodeBuilder addInterface ( Class < ? > interfaceClass ) { if ( ! interfaceClass . isInterface ( ) ) { System . out . println ( interfaceClass + "不是接口类型！取消设为实现。");   return this ; } String simpleName = interfaceClass . getSimpleName ( ) ; Package pkg = interfaceClass . getPackage ( ) ; imports . add ( pkg . getName ( ) + "." + simpleName ) ; // 导入包 this . interfaces . add ( simpleName ) ; // 添加实现的接口 return this ; }


Input: 过滤包含规则 [CODESPLIT] private void filterInclude ( ) { if ( include == null || files == null ) { return ; } Set < File > toIncludes = new HashSet < File > ( ) ; for ( File file : files ) { Matcher matcher = include . matcher ( file . getPath ( ) ) ; if ( matcher . find ( ) ) { toIncludes . add ( file ) ; } } this . files = toIncludes ; }


Input: 过滤排除规则 [CODESPLIT] private void filterExclude ( ) { if ( exclude == null || files == null ) { return ; } Set < File > toExcludes = new HashSet < File > ( ) ; for ( File file : files ) { Matcher matcher = exclude . matcher ( file . getPath ( ) ) ; if ( matcher . find ( ) ) { toExcludes . add ( file ) ; } } files . removeAll ( toExcludes ) ; }


Input: 开始重写文件 [CODESPLIT] public void build ( ) { filterInclude ( ) ; filterExclude ( ) ; for ( final File file : files ) { ThreadPool . invoke ( new Thread ( ) { @ Override public void run ( ) { new CodeProcessor ( file , CodeBuilder . this ) ; } } ) ; // 在线程池内运行 } ThreadPool . shutDown ( ) ; // 开启停止线程 }


Input: 或者被<code > orAnnotationClass< / code > 注解的条件，与andAnnotation方法冲突 [CODESPLIT] public CodeCondition orAnnotation ( Class < ? > orAnnotationClass ) { if ( ! orAnnotationClass . isAnnotation ( ) ) { System . out . println ( "Class: " + orAnnotationClass + " 不是注解类！");   return this ; } orAnnotatedClasses = CollectionHelper . checkOrInitHashSet ( orAnnotatedClasses ) ; orAnnotatedClasses . add ( orAnnotationClass ) ; return this ; }


Input: 并且被<code > andAnnotationClass< / code > 注解的条件 [CODESPLIT] public CodeCondition andAnnotation ( Class < ? > andAnnotationClass ) { if ( ! andAnnotationClass . isAnnotation ( ) ) { System . out . println ( "Class: " + andAnnotationClass + " 不是注解类！");   return this ; } andAnnotatedClasses = CollectionHelper . checkOrInitHashSet ( andAnnotatedClasses ) ; andAnnotatedClasses . add ( andAnnotationClass ) ; return this ; }


Input: 条件且 [CODESPLIT] public CodeCondition and ( CodeCondition anotherCodeCondition ) { if ( anotherCodeCondition == null ) { System . out . println ( "CodeCondition为空！");   return this ; } andCodeConditions = CollectionHelper . checkOrInitHashSet ( andCodeConditions ) ; return this ; }


Input: 条件或 [CODESPLIT] public CodeCondition or ( CodeCondition anotherCodeCondition ) { if ( anotherCodeCondition == null ) { System . out . println ( "CodeCondition为空！");   return this ; } orCodeConditions = CollectionHelper . checkOrInitHashSet ( orCodeConditions ) ; return this ; }


Input: 填充0 <br > 2013 - 10 - 31 下午2 : 46 : 15 [CODESPLIT] public static String fillZero ( long number , int length ) { StringBuilder builder = new StringBuilder ( ) ; int least = length - numberLength ( number ) ; char [ ] zeros = new char [ least ] ; for ( int i = 0 ; i < least ; i ++ ) { zeros [ i ] = ' ' ; } builder . append ( new String ( zeros ) ) ; builder . append ( number ) ; return builder . toString ( ) ; }


Input: Function to return a string from the set : A - Za - z0 - 9 . / [CODESPLIT] static private final String to64 ( long v , int size ) { StringBuffer result = new StringBuffer ( ) ; while ( -- size >= 0 ) { result . append ( itoa64 . charAt ( ( int ) ( v & 0x3f ) ) ) ; v >>>= 6 ; } return result . toString ( ) ; }


Input: LINUX / BSD MD5Crypt function [CODESPLIT] static public final String crypt ( String password ) { StringBuffer salt = new StringBuffer ( ) ; java . util . Random rnd = new java . util . Random ( ) ; // build a random 8 chars salt while ( salt . length ( ) < 8 ) { int index = ( int ) ( rnd . nextFloat ( ) * SALTCHARS . length ( ) ) ; salt . append ( SALTCHARS . substring ( index , index + 1 ) ) ; } // crypt return crypt ( password , salt . toString ( ) , "$1$" ) ; }


Input:
Linux / BSD MD5Crypt function [CODESPLIT] static public final String crypt ( String password , String salt , String magic ) { byte finalState [ ] ; long l ; /**
         * Two MD5 hashes are used
         */ MessageDigest ctx , ctx1 ; try { ctx = MessageDigest . getInstance ( "md5" ) ; ctx1 = MessageDigest . getInstance ( "md5" ) ; } catch ( NoSuchAlgorithmException ex ) { System . err . println ( ex ) ; return null ; } /* Refine the Salt first */ /* If it starts with the magic string, then skip that */ if ( salt . startsWith ( magic ) ) { salt = salt . substring ( magic . length ( ) ) ; } /* It stops at the first '$', max 8 chars */ if ( salt . indexOf ( ' ' ) != - 1 ) { salt = salt . substring ( 0 , salt . indexOf ( ' ' ) ) ; } if ( salt . length ( ) > 8 ) { salt = salt . substring ( 0 , 8 ) ; } /**
         * Transformation set #1: The password first, since that is what is most
         * unknown Magic string Raw salt
         */ ctx . update ( password . getBytes ( ) ) ; ctx . update ( magic . getBytes ( ) ) ; ctx . update ( salt . getBytes ( ) ) ; /* Then just as many characters of the MD5(pw,salt,pw) */ ctx1 . update ( password . getBytes ( ) ) ; ctx1 . update ( salt . getBytes ( ) ) ; ctx1 . update ( password . getBytes ( ) ) ; finalState = ctx1 . digest ( ) ; // ctx1.Final(); for ( int pl = password . length ( ) ; pl > 0 ; pl -= 16 ) { ctx . update ( finalState , 0 , pl > 16 ? 16 : pl ) ; } /**
         * the original code claimed that finalState was being cleared to keep
         * dangerous bits out of memory, but doing this is also required in
         * order to get the right output.
         */ clearbits ( finalState ) ; /* Then something really weird... */ for ( int i = password . length ( ) ; i != 0 ; i >>>= 1 ) { if ( ( i & 1 ) != 0 ) { ctx . update ( finalState , 0 , 1 ) ; } else { ctx . update ( password . getBytes ( ) , 0 , 1 ) ; } } finalState = ctx . digest ( ) ; /**
         * and now, just to make sure things don't run too fast On a 60 Mhz
         * Pentium this takes 34 msec, so you would need 30 seconds to build a
         * 1000 entry dictionary... (The above timings from the C version)
         */ for ( int i = 0 ; i < 1000 ; i ++ ) { try { ctx1 = MessageDigest . getInstance ( "md5" ) ; } catch ( NoSuchAlgorithmException e0 ) { return null ; } if ( ( i & 1 ) != 0 ) { ctx1 . update ( password . getBytes ( ) ) ; } else { ctx1 . update ( finalState , 0 , 16 ) ; } if ( ( i % 3 ) != 0 ) { ctx1 . update ( salt . getBytes ( ) ) ; } if ( ( i % 7 ) != 0 ) { ctx1 . update ( password . getBytes ( ) ) ; } if ( ( i & 1 ) != 0 ) { ctx1 . update ( finalState , 0 , 16 ) ; } else { ctx1 . update ( password . getBytes ( ) ) ; } finalState = ctx1 . digest ( ) ; // Final(); } /* Now make the output string */ StringBuffer result = new StringBuffer ( ) ; result . append ( magic ) ; result . append ( salt ) ; result . append ( "$" ) ; /**
         * Build a 22 byte output string from the set: A-Za-z0-9./
         */ l = ( bytes2u ( finalState [ 0 ] ) << 16 ) | ( bytes2u ( finalState [ 6 ] ) << 8 ) | bytes2u ( finalState [ 12 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 1 ] ) << 16 ) | ( bytes2u ( finalState [ 7 ] ) << 8 ) | bytes2u ( finalState [ 13 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 2 ] ) << 16 ) | ( bytes2u ( finalState [ 8 ] ) << 8 ) | bytes2u ( finalState [ 14 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 3 ] ) << 16 ) | ( bytes2u ( finalState [ 9 ] ) << 8 ) | bytes2u ( finalState [ 15 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 4 ] ) << 16 ) | ( bytes2u ( finalState [ 10 ] ) << 8 ) | bytes2u ( finalState [ 5 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = bytes2u ( finalState [ 11 ] ) ; result . append ( to64 ( l , 2 ) ) ; /* Don't leave anything around in vm they could use. */ clearbits ( finalState ) ; return result . toString ( ) ; }


Input: 从所有的 classpath 下面搜索指定的 Class [CODESPLIT] public static Collection < Class < ? > > getClasses ( ClassFileFilter filter ) { Set < URLClassLoader > loaders = new LinkedHashSet < URLClassLoader > ( 8 ) ; loaders . addAll ( getClassLoaders ( Thread . currentThread ( ) . getContextClassLoader ( ) ) ) ; loaders . addAll ( getClassLoaders ( ClassLookupHelper . class . getClassLoader ( ) ) ) ; Set < Class < ? > > klasses = new LinkedHashSet < Class < ? > > ( ) ; for ( URLClassLoader cl : loaders ) { for ( URL url : cl . getURLs ( ) ) { String file = url . getFile ( ) ; if ( file . endsWith ( ".jar" ) || file . endsWith ( ".zip" ) ) { lookupClassesInJar ( null , url , true , cl , filter , klasses ) ; } else { lookupClassesInFileSystem ( null , new File ( file ) , true , cl , filter , klasses ) ; } } } return klasses ; }


Input: 根据 baseClassLoader 找到所有的祖先 URLClassLoader ( 包括自己 ) [CODESPLIT] private static Collection < URLClassLoader > getClassLoaders ( ClassLoader baseClassLoader ) { Collection < URLClassLoader > loaders = new ArrayList < URLClassLoader > ( 8 ) ; ClassLoader loader = baseClassLoader ; while ( loader != null ) { if ( "sun.misc.Launcher$ExtClassLoader" . equals ( loader . getClass ( ) . getName ( ) ) ) { break ; } if ( loader instanceof URLClassLoader ) { loaders . add ( ( URLClassLoader ) loader ) ; } loader = loader . getParent ( ) ; } return loaders ; }


Input: 从指定 package 中获取所有的 Class [CODESPLIT] public static Set < Class < ? > > getClasses ( Package pkg , boolean recursive , ClassFileFilter filter ) { return getClasses ( pkg . getName ( ) , recursive , filter ) ; }


Input: 从指定 package 中获取所有的 Class [CODESPLIT] public static Set < Class < ? > > getClasses ( String packageName , boolean recursive , ClassFileFilter filter ) { if ( packageName == null || packageName . length ( ) == 0 ) { throw new IllegalArgumentException ( "packageName is empty." ) ; } ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String packageDirName = packageName . replace ( ' ' , ' ' ) ; Collection < URL > urls ; try { Enumeration < URL > dirs = loader . getResources ( packageDirName ) ; urls = Collections . list ( dirs ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } Set < Class < ? > > klasses = new LinkedHashSet < Class < ? > > ( ) ; for ( URL url : urls ) { String protocol = url . getProtocol ( ) ; if ( "file" . equals ( protocol ) ) { lookupClassesInFileSystem ( packageName , new File ( url . getFile ( ) ) , recursive , loader , filter , klasses ) ; } else if ( "jar" . equals ( protocol ) ) { lookupClassesInJar ( packageName , url , recursive , loader , filter , klasses ) ; } } return klasses ; }


Input: 以文件的形式来获取包下的所有 Class [CODESPLIT] private static void lookupClassesInFileSystem ( String packageName , File packagePath , final boolean recursive , ClassLoader loader , ClassFileFilter filter , Set < Class < ? > > klasses ) { if ( ! packagePath . exists ( ) || ! packagePath . isDirectory ( ) ) { return ; } File [ ] dirfiles = packagePath . listFiles ( new FileFilter ( ) { public boolean accept ( File file ) { return ( recursive && file . isDirectory ( ) ) || ( file . getName ( ) . endsWith ( ".class" ) ) ; } } ) ; String packageNamePrefix = "" ; if ( packageName != null && packageName . length ( ) > 0 ) { packageNamePrefix = packageName + ' ' ; } for ( File file : dirfiles ) { if ( file . isDirectory ( ) ) { lookupClassesInFileSystem ( packageNamePrefix + file . getName ( ) , file , recursive , loader , filter , klasses ) ; } else { // 去掉后面的 .class 只留下类名 String klassName = packageNamePrefix + file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - 6 ) ; try { if ( filter == null || filter . accept ( klassName , file , loader ) ) { Class < ? > klass = loader . loadClass ( klassName ) ; klasses . add ( klass ) ; } } catch ( Throwable e ) { } } } }


Input: 以在 Jar 包中获取指定包下的所有 Class [CODESPLIT] private static void lookupClassesInJar ( String packageName , URL jarUrl , boolean recursive , ClassLoader loader , ClassFileFilter filter , Set < Class < ? > > klasses ) { String packageDirName = "" ; if ( packageName != null && packageName . length ( ) > 0 ) { packageDirName = packageName . replace ( ' ' , ' ' ) + ' ' ; } JarFile jar = null ; try { if ( "jar" . equals ( jarUrl . getProtocol ( ) ) ) { jar = ( ( JarURLConnection ) jarUrl . openConnection ( ) ) . getJarFile ( ) ; } else { jar = new JarFile ( jarUrl . getFile ( ) ) ; } Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { // 获取jar里的一个实体 可以是目录和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries . nextElement ( ) ; if ( entry . isDirectory ( ) ) { continue ; } String name = entry . getName ( ) ; if ( name . charAt ( 0 ) == ' ' ) { name = name . substring ( 1 ) ; } if ( name . startsWith ( packageDirName ) && name . endsWith ( ".class" ) ) { if ( name . lastIndexOf ( ' ' ) > packageDirName . length ( ) ) { // 在子包内 if ( ! recursive ) continue ; } // 去掉后面的 .class 只留下类名 String klassName = name . substring ( 0 , name . length ( ) - 6 ) ; klassName = klassName . replace ( ' ' , ' ' ) ; try { if ( filter == null || filter . accept ( klassName , jar , entry , loader ) ) { Class < ? > klass = loader . loadClass ( klassName ) ; klasses . add ( klass ) ; } } catch ( Throwable e ) { } } } } catch ( IOException e ) { } finally { } }


Input: Returns an input stream that contains what will written in this Application to { @link System#err } . <p > <b > Caution< / b > If you do not consume the bytes to read from the result you may block the whole application . Do only use this for debugging purposes or end to end test code! <p > Attempting to read from the result in the same thread that called here is not recommended as it may deadlock the thread . Also the thread reading from the stream result should not write anything to { @link System#err } . <p > Prefer using { @link #findMatchInSystemErr ( String ) } to avoid deadlocks . <p > [CODESPLIT] public static InputStream captureSystemErrForDebuggingPurposesOnly ( final boolean teeToOriginalSysErr ) throws IOException { PipedOutputStream pipeOut = new PipedOutputStream ( ) ; PipedInputStream pipeIn = new PipedInputStream ( pipeOut ) ; OutputStream out = pipeOut ; if ( teeToOriginalSysErr ) { out = new MultiplexingOutputStream ( System . err , pipeOut ) ; } PrintStream streamOut = new PrintStream ( out ) ; System . setErr ( streamOut ) ; return pipeIn ; }


Input: Returns an input stream that contains what will written in this Application to { @link System#out } . <p > <b > Caution< / b > If you do not consume the bytes to read from the result you may block the whole application . Do only use this for debugging purposes or end to end test code! <p > Attempting to read from the result in the same thread that called here is not recommended as it may deadlock the thread . Also the thread reading from the stream result should not write anything to { @link System#out } . <p > Prefer using { @link #findMatchInSystemOut ( String ) } to avoid deadlocks . <p > [CODESPLIT] public static InputStream captureSystemOutForDebuggingPurposesOnly ( final boolean teeToOriginalSysOut ) throws IOException { PipedOutputStream pipeOut = new PipedOutputStream ( ) ; PipedInputStream pipeIn = new PipedInputStream ( pipeOut ) ; OutputStream out = pipeOut ; if ( teeToOriginalSysOut ) { out = new MultiplexingOutputStream ( System . out , pipeOut ) ; } PrintStream streamOut = new PrintStream ( out ) ; System . setOut ( streamOut ) ; return pipeIn ; }


Input: Returns an instance to a runnable running in a separate Thread that tries to match the expected output in { @link System#out } . <p > Ensure that you found the expected String in the input stream given by calling { @link info . monitorenter . util . ExceptionUtil . InputStreamTracer#isMatched () } . But take into account that it is time - critical ( concurrency ) if your result was found . <p > Prefer this instead of { @link #captureSystemOutForDebuggingPurposesOnly ( boolean ) } as this will avoid blocking your application . <p > [CODESPLIT] public static InputStreamTracer findMatchInSystemOut ( final String expectMatch ) throws IOException { InputStream systemout = captureSystemOutForDebuggingPurposesOnly ( true ) ; InputStreamTracer result = new InputStreamTracer ( systemout , expectMatch , Charset . defaultCharset ( ) ) ; Thread traceThread = new Thread ( result ) ; traceThread . setDaemon ( true ) ; traceThread . start ( ) ; return result ; }


Input: Returns an instance to a runnable running in a separate Thread that tries to match the expected output in { @link System#err } . <p > Ensure that you found the expected String in the input stream given by calling { @link info . monitorenter . util . ExceptionUtil . InputStreamTracer#isMatched () } . But take into account that it is time - critical ( concurrency ) if your result was found . <p > Prefer this instead of { @link #captureSystemErrForDebuggingPurposesOnly ( boolean ) } as this will avoid blocking your application . <p > [CODESPLIT] public static InputStreamTracer findMatchInSystemErr ( final String expectMatch ) throws IOException { InputStream systemout = captureSystemErrForDebuggingPurposesOnly ( true ) ; InputStreamTracer result = new InputStreamTracer ( systemout , expectMatch , Charset . defaultCharset ( ) ) ; Thread traceThread = new Thread ( result ) ; traceThread . setDaemon ( true ) ; traceThread . start ( ) ; return result ; }


Input: Prints out the current Thread stack to the given stream . <p > [CODESPLIT] public static void dumpThreadStack ( PrintStream outprint ) { StackTraceElement [ ] stackTrace = Thread . currentThread ( ) . getStackTrace ( ) ; String stackTraceString = StringUtil . arrayToString ( stackTrace , "\n" ) ; outprint . println ( stackTraceString ) ; }


Input: Returns the singleton instance of this class . <p > This method is useless for now as all methods are static . It may be used in future if VM - global configuration will be put to the state of the instance . <p > [CODESPLIT] public static ExceptionUtil instance ( ) { if ( ExceptionUtil . instance == null ) { ExceptionUtil . instance = new ExceptionUtil ( ) ; } return ExceptionUtil . instance ; }


Input: Add the specified Option to the list of accepted options [CODESPLIT] public final Option addOption ( Option opt ) { if ( opt . shortForm ( ) != null ) this . options . put ( "-" + opt . shortForm ( ) , opt ) ; this . options . put ( "--" + opt . longForm ( ) , opt ) ; return opt ; }


Input: Convenience method for adding a string option . [CODESPLIT] public final Option addStringOption ( char shortForm , String longForm ) { return addOption ( new Option . StringOption ( shortForm , longForm ) ) ; }


Input: Convenience method for adding an integer option . [CODESPLIT] public final Option addIntegerOption ( char shortForm , String longForm ) { return addOption ( new Option . IntegerOption ( shortForm , longForm ) ) ; }


Input: Convenience method for adding a long integer option . [CODESPLIT] public final Option addLongOption ( char shortForm , String longForm ) { return addOption ( new Option . LongOption ( shortForm , longForm ) ) ; }


Input: Convenience method for adding a double option . [CODESPLIT] public final Option addDoubleOption ( char shortForm , String longForm ) { return addOption ( new Option . DoubleOption ( shortForm , longForm ) ) ; }


Input: Convenience method for adding a boolean option . [CODESPLIT] public final Option addBooleanOption ( char shortForm , String longForm ) { return addOption ( new Option . BooleanOption ( shortForm , longForm ) ) ; }


Input: Extract the options and non - option arguments from the given list of command - line arguments . The specified locale is used for parsing options whose values might be locale - specific . [CODESPLIT] public final void parse ( String [ ] argv , Locale locale ) throws IllegalOptionValueException , UnknownOptionException { // It would be best if this method only threw OptionException, but for // backwards compatibility with old user code we throw the two // exceptions above instead. Vector otherArgs = new Vector ( ) ; int position = 0 ; this . values = new Hashtable ( 10 ) ; while ( position < argv . length ) { String curArg = argv [ position ] ; if ( curArg . startsWith ( "-" ) ) { if ( curArg . equals ( "--" ) ) { // end of options position += 1 ; break ; } String valueArg = null ; if ( curArg . startsWith ( "--" ) ) { // handle --arg=value int equalsPos = curArg . indexOf ( "=" ) ; if ( equalsPos != - 1 ) { valueArg = curArg . substring ( equalsPos + 1 ) ; curArg = curArg . substring ( 0 , equalsPos ) ; } } else if ( curArg . length ( ) > 2 ) { // handle -abcd for ( int i = 1 ; i < curArg . length ( ) ; i ++ ) { Option opt = ( Option ) this . options . get ( "-" + curArg . charAt ( i ) ) ; if ( opt == null ) throw new UnknownSuboptionException ( curArg , curArg . charAt ( i ) ) ; if ( opt . wantsValue ( ) ) throw new NotFlagException ( curArg , curArg . charAt ( i ) ) ; addValue ( opt , opt . getValue ( null , locale ) ) ; } position ++ ; continue ; } Option opt = ( Option ) this . options . get ( curArg ) ; if ( opt == null ) { throw new UnknownOptionException ( curArg ) ; } Object value = null ; if ( opt . wantsValue ( ) ) { if ( valueArg == null ) { position += 1 ; if ( position < argv . length ) { valueArg = argv [ position ] ; } } value = opt . getValue ( valueArg , locale ) ; } else { value = opt . getValue ( null , locale ) ; } addValue ( opt , value ) ; position += 1 ; } else { otherArgs . addElement ( curArg ) ; position += 1 ; } } for ( ; position < argv . length ; ++ position ) { otherArgs . addElement ( argv [ position ] ) ; } this . remainingArgs = new String [ otherArgs . size ( ) ] ; otherArgs . copyInto ( remainingArgs ) ; }


Input: A default delegation to { @link #detectCodepage ( java . net . URL ) } that opens the document specified by the given URL with the detected codepage . <p > [CODESPLIT] public final Reader open ( final URL url ) throws IOException { Reader ret = null ; Charset cs = this . detectCodepage ( url ) ; if ( cs != null ) { ret = new InputStreamReader ( new BufferedInputStream ( url . openStream ( ) ) , cs ) ; } return ret ; }


Input: 打印出调用堆栈 <br > 2013 - 8 - 28 下午3 : 52 : 17 [CODESPLIT] public static void printStackTrace ( ) { Throwable throwable = new Throwable ( ) ; StackTraceElement [ ] stackTraceElements = throwable . getStackTrace ( ) ; StackTraceElement [ ] stackTraceElementsTarget = new StackTraceElement [ stackTraceElements . length - 1 ] ; // for (int i = 1, j = 0; i < stackTraceElements.length; i++) { // StackTraceElement stackTraceElement = stackTraceElements[i]; // System.out.println(stackTraceElement.getClassName()); // System.out.println(stackTraceElement.getFileName()); // System.out.println(stackTraceElement.getMethodName()); // System.out.println(stackTraceElement.getLineNumber()); // System.out.println("    at " + stackTraceElement.getClassName() + "." // + stackTraceElement.getMethodName() + "(" + // stackTraceElement.getFileName() + ":" + // stackTraceElement.getLineNumber() + ")"); // } System . arraycopy ( stackTraceElements , 1 , stackTraceElementsTarget , 0 , stackTraceElementsTarget . length ) ; System . out . println ( " ----------------------- StackTrace Info ----------------------- " ) ; System . out . print ( buildStackTrace ( stackTraceElementsTarget ) ) ; }


Input: 组织堆栈信息，将堆栈数组拼接成字符串 <br > 2013 - 8 - 28 下午3 : 50 : 50 [CODESPLIT] public static String buildStackTrace ( StackTraceElement [ ] stackTraceElements ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < stackTraceElements . length ; i ++ ) { StackTraceElement stackTraceElement = stackTraceElements [ i ] ; builder . append ( "    at " ) ; builder . append ( stackTraceElement . getClassName ( ) ) ; builder . append ( "." ) ; builder . append ( stackTraceElement . getMethodName ( ) ) ; builder . append ( "(" ) ; builder . append ( stackTraceElement . getFileName ( ) ) ; builder . append ( ":" ) ; builder . append ( stackTraceElement . getLineNumber ( ) ) ; builder . append ( ")" ) ; builder . append ( StringHelper . line ( ) ) ; } return builder . toString ( ) ; }


Input: 返回不包括本类调用堆栈的当前堆栈 <br > 2013 - 7 - 26 下午6 : 09 : 09 [CODESPLIT] public static StackTraceElement [ ] getStackTrace ( ) { Throwable throwable = new Throwable ( ) ; StackTraceElement [ ] stackTraceElements = throwable . getStackTrace ( ) ; StackTraceElement [ ] stackTraceElementsTarget = new StackTraceElement [ stackTraceElements . length ] ; System . arraycopy ( stackTraceElements , 0 , stackTraceElementsTarget , 0 , stackTraceElementsTarget . length ) ; return stackTraceElementsTarget ; }


Input: 获取间接调用的类名<p > < / p > 比如A方法调用B方法，B方法再调用whoInvoke () 方法，这样B方法内就能返回A方法在那个类下 [CODESPLIT] public static Class whoInvoke ( ) { Throwable throwable = new Throwable ( ) ; StackTraceElement [ ] stackTraceElements = throwable . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; try { return Class . forName ( stackTraceElement . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; } return null ; }


Input: ---------------------------- debug ---------------------------- [CODESPLIT] public static void debug ( Object object , Object message ) { Class clazz = object . getClass ( ) ; debug ( clazz , message ) ; }


Input: 读取field的注解值（包括get、set方法） [CODESPLIT] public static < T extends Annotation > T readAnnotationValueOnField ( Field field , Class < T > annotationClass ) { if ( field . isAnnotationPresent ( annotationClass ) ) { T t = field . getAnnotation ( annotationClass ) ; return t ; } else { Method method = EntityHelper . findGetMethod ( field ) ; if ( method . isAnnotationPresent ( annotationClass ) ) { T t = method . getAnnotation ( annotationClass ) ; return t ; } return null ; } }


Input: 在类内搜索所有的字段的annotationClass注解值 [CODESPLIT] public static < T extends Annotation > Collection < T > readAnnotationsInClass ( Class < ? > clazz , Class < T > annotationClass ) { Collection < T > collection = null ; Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { T t = readAnnotationValueOnField ( field , annotationClass ) ; if ( t == null ) { continue ; } if ( collection == null ) { collection = new ArrayList < T > ( ) ; } collection . add ( t ) ; } return collection ; }


Input: 在类内搜索使用annotationClass注解的字段（包括在get、set方法上注解） [CODESPLIT] public static < T extends Annotation > Collection < Field > getFieldsWithAnnotationInClass ( Class < ? > inClazz , Class < T > annotationClass ) { Collection < Field > fieldCollection = null ; Field [ ] fields = inClazz . getDeclaredFields ( ) ; for ( Field field : fields ) { if ( Modifier . isStatic ( field . getModifiers ( ) ) || Modifier . isFinal ( field . getModifiers ( ) ) ) { continue ; } T t = readAnnotationValueOnField ( field , annotationClass ) ; if ( t == null ) { continue ; } if ( fieldCollection == null ) { fieldCollection = new ArrayList < Field > ( ) ; } fieldCollection . add ( field ) ; } return fieldCollection ; }


Input: 从第一个字符开始比较两个字符串的大小（按照单个字符的ascii码比较），例如： abc 大于 aac 、 1234 小于 2234 、 1234 大于 123 、 223 大于 1234 [CODESPLIT] public static boolean compareNumberString ( String firstString , String secondString ) { Assert . notNull ( firstString , "第一个字符串为空！");   Assert . notNull ( secondString , "第二个字符串为空！");   char [ ] chars1 = firstString . toCharArray ( ) ; char [ ] chars2 = secondString . toCharArray ( ) ; int length1 = chars1 . length ; int length2 = chars2 . length ; int maxLength = length1 > length2 ? length1 : length2 ; for ( int i = 0 ; i < maxLength ; i ++ ) { int value1 = - 1 ; int value2 = - 1 ; if ( i < length1 ) { value1 = chars1 [ i ] ; } if ( i < length2 ) { value2 = chars2 [ i ] ; } if ( value1 < value2 ) { return true ; } else { return false ; } } return false ; }


Input: 计算数组的hashCode <br > 2013 - 10 - 25 上午11 : 06 : 57 [CODESPLIT] public static int hashCodeOfStringArray ( String [ ] stringArray ) { if ( stringArray == null ) { return 0 ; } int hashCode = 17 ; for ( int i = 0 ; i < stringArray . length ; i ++ ) { String value = stringArray [ i ] ; hashCode = hashCode * 31 + ( value == null ? 0 : value . hashCode ( ) ) ; } return hashCode ; }


Input: 换行符 <br > 2013 - 8 - 14 下午1 : 20 : 06 [CODESPLIT] public static String line ( ) { String lineSeparator = java . security . AccessController . doPrivileged ( new sun . security . action . GetPropertyAction ( "line.separator" ) ) ; //		String lineSeparator = System.getProperty("line.separator"); return lineSeparator ; }


Input: <br > 2013 - 8 - 28 下午5 : 26 : 24 [CODESPLIT] public static String convertEncode ( String str ) { if ( nullOrEmpty ( str ) ) { return null ; } try { return new String ( str . getBytes ( ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return str ; }


Input: StringReader转换为字符串 <br > 2013 - 9 - 2 下午9 : 03 : 29 [CODESPLIT] public String stringReaderToString ( StringReader reader ) { StringBuilder builder = new StringBuilder ( ) ; char [ ] buffer = new char [ 128 ] ; int length = - 1 ; try { while ( ( length = reader . read ( buffer ) ) != - 1 ) { if ( buffer . length != length ) { System . arraycopy ( buffer , 0 , buffer , 0 , length ) ; } builder . append ( buffer ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { reader . close ( ) ; } return builder . toString ( ) ; }


Input: High - level method for instantiation of a new instance of the class specified by the given fully qualified class name with singleton retrieval support . Delegates to { @link #newInstance ( Class ) } . [CODESPLIT] public Object newInstance ( String fullyQualifiedClassName ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { Object ret = this . newInstance ( Class . forName ( fullyQualifiedClassName ) ) ; return ret ; }


Input: Dynamic instantiation of the given type with singleton retrieval support as described in this class description . [CODESPLIT] public Object newInstance ( Class c ) throws InstantiationException , IllegalAccessException { Object ret = null ; Method [ ] methods = c . getDeclaredMethods ( ) ; Method m ; int modifiers ; // searching for static methods: for ( int i = 0 ; i < methods . length ; i ++ ) { m = methods [ i ] ; modifiers = m . getModifiers ( ) ; if ( ( modifiers & Modifier . STATIC ) != 0 ) { // searching for public access: if ( ( modifiers & Modifier . PUBLIC ) != 0 ) { // searching for no parameters: if ( m . getParameterTypes ( ) . length == 0 ) { // searching for return type: if ( m . getReturnType ( ) == c ) { // searching for substring "instance" in method name: if ( m . getName ( ) . toLowerCase ( ) . indexOf ( "instance" ) != - 1 ) { try { // Finally we found a singleton method: // we are static and don't need an instance. ret = m . invoke ( null , dummyParameters ) ; } catch ( IllegalArgumentException e ) { // This will not happen: // we ensured that no arguments are needed. e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { // This will not happen (only in applet context perhaps or with some // SecurityManager): // we ensured public access. e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } } } } } } // check, if we found a singleton: if ( ret == null ) { // try to invoke the default constructor: Constructor [ ] constructors = c . getConstructors ( ) ; Constructor con = null ; // search for a parameterless constructor: for ( int i = 0 ; i < constructors . length ; i ++ ) { con = constructors [ i ] ; if ( con . getParameterTypes ( ) . length == 0 ) { // see, if public: modifiers = con . getModifiers ( ) ; try { if ( ( modifiers & Modifier . PUBLIC ) == 0 ) { // try to set accessible: con . setAccessible ( true ) ; } // invokes the default constructor ret = c . newInstance ( ) ; } catch ( SecurityException se ) { // damn } } } } if ( ret == null ) { System . err . println ( "Unable to instantiate: " + c . getName ( ) + ": no singleton method, no public default constructor." ) ; } return ret ; }


Input: Singleton retrieval method . <p > Be sure to configure the instance returned at a single location in your code to avoid unpredictable application - wide side effects . <p > [CODESPLIT] public static CodepageDetectorProxy getInstance ( ) { if ( CodepageDetectorProxy . instance == null ) { CodepageDetectorProxy . instance = new CodepageDetectorProxy ( ) ; } return CodepageDetectorProxy . instance ; }


Input: <p > Detects the codepage by iteratively delegating the call to all internal { @link info . monitorenter . cpdetector . io . ICodepageDetector } instances added by { @link #add ( info . monitorenter . cpdetector . io . ICodepageDetector ) } . < / p > <p > The given InputStream has to support mark such that the call { @link java . io . InputStream#mark ( int ) } with argument length does not throw an exception . This is needed as the stream has to be resetted to the beginning for each internal delegate that tries to detect . < / p > <p > If this is impossible ( large documents ) prefer using { @link #detectCodepage ( java . net . URL ) } . < / p > [CODESPLIT] public Charset detectCodepage ( final InputStream in , final int length ) throws IOException , IllegalArgumentException { if ( ! in . markSupported ( ) ) { throw new IllegalArgumentException ( "The given input stream (" + in . getClass ( ) . getName ( ) + ") has to support for marking." ) ; } Charset ret = null ; int markLimit = length ; Iterator < ICodepageDetector > detectorIt = this . detectors . iterator ( ) ; while ( detectorIt . hasNext ( ) ) { in . mark ( markLimit ) ; ret = detectorIt . next ( ) . detectCodepage ( in , length ) ; // if more bytes have been read than marked (length) this will throw an // exception: try { in . reset ( ) ; } catch ( IOException ioex ) { IllegalStateException ise = new IllegalStateException ( "More than the given length had to be read and the given stream could not be reset. Undetermined state for this detection." ) ; ise . initCause ( ioex ) ; throw ise ; } if ( ret != null ) { if ( ret != UnknownCharset . getInstance ( ) ) { if ( ret instanceof UnsupportedCharset ) { // TODO: Debug logging: found illegal charset tag or encoding // declaration. } else { break ; } } } } return ret ; }


Input: 获取 目标对象 [CODESPLIT] public static Object getTarget ( Object proxy ) throws Exception { if ( ! AopUtils . isAopProxy ( proxy ) ) { return proxy ; //不是代理对象 } if ( AopUtils . isJdkDynamicProxy ( proxy ) ) { return getJdkDynamicProxyTargetObject ( proxy ) ; } else { //cglib return getCglibProxyTargetObject ( proxy ) ; } }


Input: 返回两个日期的毫秒之差 [CODESPLIT] public static long compareDate ( Date nearDate , Date farDate ) { long nearMilli = nearDate . getTime ( ) ; long farMilli = farDate . getTime ( ) ; long result = nearMilli - farMilli ; if ( result < 0 ) { result = - result ; } return result ; }


Input: 计算指定日期到现在的时间计算 [CODESPLIT] public static String caculatorDateToString ( Date date ) { long milliSecond = compareDate ( date ) ; List dateCaculators = DateCalculator . getDateCalculators ( ) ; for ( Iterator iterator = dateCaculators . iterator ( ) ; iterator . hasNext ( ) ; ) { DateCalculator dateCalculator = ( DateCalculator ) iterator . next ( ) ; if ( milliSecond >= dateCalculator . getMinMilliSecond ( ) && milliSecond <= dateCalculator . getMaxMilliSecond ( ) ) { String displayStr = dateCalculator . getDisplayStr ( ) ; long numberOfUnit = 0 ; if ( dateCalculator . getMinMilliSecond ( ) == 0 ) { // 分母为零，则直接为0 numberOfUnit = 0 ; } else { numberOfUnit = milliSecond / dateCalculator . getMinMilliSecond ( ) ; } // 替代所有{0} Pattern p = Pattern . compile ( "(\\{.+?\\})" ) ; Matcher m = p . matcher ( displayStr ) ; displayStr = m . replaceAll ( numberOfUnit + "" ) ; // displayStr = displayStr.replace("\\{0\\}", numberOfUnit + // ""); return displayStr ; } } return milliSecond + "" ; }


Input: Sets a new value instance overwriting the old value which is returned . <p > [CODESPLIT] public K setValue ( final K value ) { final K ret = this . m_value ; this . m_value = value ; return ret ; }


Input: 生成文件 [CODESPLIT] public File generate ( ) { QRCode qrCode = new QRCode ( ) ; File file = qrCode . encode ( profile ) ; return file ; }


Input: 增加扫描的包 [CODESPLIT] public PackageScanner addPackage ( String pkg ) { Package aPackage = Package . getPackage ( pkg ) ; addPackage ( aPackage ) ; return this ; }


Input: 开始扫描 [CODESPLIT] public Collection < Class < ? > > scan ( ) { Assert . notEmpty ( packages , "待扫描的包为空！");   Collection < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; ClassLookupHelper . ClassFileFilter classFileFilter = new ClassLookupHelper . ClassFileFilter ( ) { @ Override public boolean accept ( String klassName , File file , ClassLoader loader ) { return true ; } @ Override public boolean accept ( String klassName , JarFile jar , JarEntry entry , ClassLoader loader ) { return true ; } } ; for ( Package pkg : packages ) { Set < Class < ? > > scanClasses = ClassLookupHelper . getClasses ( pkg , recursive , classFileFilter ) ; for ( Class < ? > scanClass : scanClasses ) { if ( isAnnotationPassed ( scanClass ) && isStartWithPassed ( scanClass ) && isInterfacePassed ( scanClass ) ) { classes . add ( scanClass ) ; } } } return classes ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public boolean accept ( File pathname ) { boolean ret = false ; // search for extension without dot.  StringTokenizer tokenizer = new StringTokenizer ( pathname . getAbsolutePath ( ) , "." ) ; String extension = "no.txt" ; // a dot, because verify will not allow these tokens: won't accept, if no extension in pathname. while ( tokenizer . hasMoreElements ( ) ) { extension = tokenizer . nextToken ( ) ; } for ( int i = this . m_extensions . length - 1 ; i >= 0 ; i -- ) { if ( this . m_extensions [ i ] . equals ( extension ) ) { ret = true ; break ; } } return ret ; }


Input: 生成QRCode二维码 [CODESPLIT] public File encode ( Profile profile ) { try { File isFile = new File ( profile . getPath ( ) ) ; if ( ! isFile . exists ( ) ) { isFile . mkdirs ( ) ; } SimpleDateFormat sdf = new SimpleDateFormat ( "yyyyMMddHHmmss" ) ; String fileName = UUID . randomUUID ( ) + "." + profile . getFormat ( ) ; //            String url = zxing.getPath() + fileName; File file = new File ( profile . getPath ( ) , fileName ) ; //            writeToFile(bitMatrix, profile.getFormat(), file, profile.isLogoFlag(), profile.getLogoPath()); BufferedImage bufferedImage = encodeToBufferedImage ( profile ) ; ImageIO . write ( bufferedImage , profile . getFormat ( ) , file ) ; return file ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; }


Input: 生成二维码内容 [CODESPLIT] public BufferedImage toBufferedImageContents ( BitMatrix bitMatrix ) { int width = bitMatrix . getWidth ( ) ; int height = bitMatrix . getHeight ( ) ; BufferedImage image = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { image . setRGB ( x , y , bitMatrix . get ( x , y ) == true ? BLACK : WHITE ) ; } } return image ; }


Input: 解析二维码 [CODESPLIT] public String decode ( String path ) throws IOException , NotFoundException { if ( path == null || path . equals ( "" ) ) { System . out . println ( "文件路径不能为空!");   } File file = new File ( path ) ; BufferedImage image = ImageIO . read ( file ) ; /*判断是否是图片*/ if ( image != null ) { return decode ( image ) ; } return null ; }


Input: To be invoked before the main execution logic of concrete subclasses . <p > This implementation applies the concurrency throttle . [CODESPLIT] protected void beforeAccess ( ) { if ( this . concurrencyLimit == NO_CONCURRENCY ) { throw new IllegalStateException ( "Currently no invocations allowed - concurrency limit set to NO_CONCURRENCY" ) ; } if ( this . concurrencyLimit > 0 ) { boolean debug = logger . isDebugEnabled ( ) ; synchronized ( this . monitor ) { boolean interrupted = false ; while ( this . concurrencyCount >= this . concurrencyLimit ) { if ( interrupted ) { throw new IllegalStateException ( "Thread was interrupted while waiting for invocation access, " + "but concurrency limit still does not allow for entering" ) ; } if ( debug ) { logger . debug ( "Concurrency count " + this . concurrencyCount + " has reached limit " + this . concurrencyLimit + " - blocking" ) ; } try { this . monitor . wait ( ) ; } catch ( InterruptedException ex ) { // Re-interrupt current thread, to allow other threads to react. Thread . currentThread ( ) . interrupt ( ) ; interrupted = true ; } } if ( debug ) { logger . debug ( "Entering throttle at concurrency count " + this . concurrencyCount ) ; } this . concurrencyCount ++ ; } } }


Input: To be invoked after the main execution logic of concrete subclasses . [CODESPLIT] protected void afterAccess ( ) { if ( this . concurrencyLimit >= 0 ) { synchronized ( this . monitor ) { this . concurrencyCount -- ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Returning from throttle at concurrency count " + this . concurrencyCount ) ; } this . monitor . notify ( ) ; } } }


Input: --------------------------------------------------------------------- [CODESPLIT] private void readObject ( ObjectInputStream ois ) throws IOException , ClassNotFoundException { // Rely on default serialization, just initialize state after deserialization. ois . defaultReadObject ( ) ; // Initialize transient fields. this . logger = LogFactory . getLog ( getClass ( ) ) ; this . monitor = new Object ( ) ; }


Input:
带回调函数的代理线程，本方法将创建新线程在线程池内运行
  注意：回调函数一定要是带三个参数的方法：
 第一个参数来接收代理函数执行方法的返回值，
 第二个参数用来接收代理函数执行过程中抛出的异常，
 第三个参数用来回调调用时传给代理线程的参数列表

 回调方法的获取方法

 Class . getDeclaredMethod ( &quot ; callBack&quot ; Object . class Throwable . class Object [] . class ) ;
 2013 - 9 - 16 下午9 : 30 : 29 [CODESPLIT] public static void invoke ( Object callBackInstance , Method callBackMethod , Object instance , Method method , Object ... parameters ) { if ( method != null ) { ProxyThread proxyThread = new ProxyThread ( callBackInstance , callBackMethod , instance , method , parameters ) ; pool . execute ( proxyThread ) ; } else { EntityHelper . print ( "空对象");   StackTraceHelper . printStackTrace ( ) ; } }


Input: 代理线程，本方法将创建新线程在线程池内运行 <br > 2013 - 9 - 16 下午9 : 38 : 12 [CODESPLIT] public static void invoke ( Object instance , Method method , Object ... parameters ) { invoke ( null , null , instance , method , parameters ) ; }


Input: 获取json字符串 [CODESPLIT] public static String getJsonString ( Object object ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; String json = null ; try { json = objectMapper . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { e . printStackTrace ( ) ; } return json ; }


Input: 获取格式化的json数组 [CODESPLIT] public static String getPrettyJsonString ( Object object ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; String json = null ; try { json = objectMapper . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { e . printStackTrace ( ) ; } return json ; }


Input: 增加指定字段的数量 [CODESPLIT] public CalendarBuilder next ( int field , int plus ) { calculateCalendar . set ( field , calculateCalendar . get ( field ) + plus ) ; return this ; }


Input: Delete the supplied { @link java . io . File } - for directories recursively delete any nested directories or files as well . [CODESPLIT] public static boolean deleteRecursively ( File root ) { if ( root != null && root . exists ( ) ) { if ( root . isDirectory ( ) ) { File [ ] children = root . listFiles ( ) ; if ( children != null ) { for ( File child : children ) { deleteRecursively ( child ) ; } } } return root . delete ( ) ; } return false ; }


Input: Recursively copy the contents of the { @code src } file / directory to the { @code dest } file / directory . [CODESPLIT] public static void copyRecursively ( File src , File dest ) throws IOException { Assert . isTrue ( src != null && ( src . isDirectory ( ) || src . isFile ( ) ) , "Source File must denote a directory or file" ) ; Assert . notNull ( dest , "Destination File must not be null" ) ; doCopyRecursively ( src , dest ) ; }


Input: Actually copy the contents of the { @code src } file / directory to the { @code dest } file / directory . [CODESPLIT] private static void doCopyRecursively ( File src , File dest ) throws IOException { if ( src . isDirectory ( ) ) { dest . mkdir ( ) ; File [ ] entries = src . listFiles ( ) ; if ( entries == null ) { throw new IOException ( "Could not list files in directory: " + src ) ; } for ( File entry : entries ) { doCopyRecursively ( entry , new File ( dest , entry . getName ( ) ) ) ; } } else if ( src . isFile ( ) ) { try { dest . createNewFile ( ) ; } catch ( IOException ex ) { IOException ioex = new IOException ( "Failed to create file: " + dest ) ; ioex . initCause ( ex ) ; throw ioex ; } FileCopyUtils . copy ( src , dest ) ; } else { // Special File handle: neither a file not a directory. // Simply skip it when contained in nested directory... } }


Input: <br > 2013 - 10 - 28 上午11 : 11 : 24 [CODESPLIT] private Collection < String > checkAndPutToCollection ( Collection < String > collection , String [ ] names ) { if ( collection == null ) { collection = new HashSet < String > ( ) ; } Collections . addAll ( collection , names ) ; return collection ; }


Input: 处理IgnoreProperties注解 <br > 2013 - 10 - 30 下午6 : 15 : 41 [CODESPLIT] private void processIgnorePropertiesAnnotation ( IgnoreProperties properties , Map < Class < ? > , Collection < String > > pojoAndNamesMap ) { IgnoreProperty [ ] values = properties . value ( ) ; AllowProperty [ ] allowProperties = properties . allow ( ) ; if ( allowProperties != null ) { for ( AllowProperty allowProperty : allowProperties ) { processAllowPropertyAnnotation ( allowProperty , pojoAndNamesMap ) ; } } if ( values != null ) { for ( IgnoreProperty property : values ) { processIgnorePropertyAnnotation ( property , pojoAndNamesMap ) ; } } }


Input: 处理IgnoreProperty注解 <br > 2013 - 10 - 30 下午6 : 16 : 08 [CODESPLIT] private void processIgnorePropertyAnnotation ( IgnoreProperty property , Map < Class < ? > , Collection < String > > pojoAndNamesMap ) { String [ ] names = property . name ( ) ; Class < ? > pojoClass = property . pojo ( ) ; // Class<?> proxyAnnotationInterface = createMixInAnnotation(names);// // 根据注解创建代理接口 Collection < String > nameCollection = pojoAndNamesMap . get ( pojoClass ) ; nameCollection = checkAndPutToCollection ( nameCollection , names ) ; pojoAndNamesMap . put ( pojoClass , nameCollection ) ; }


Input: 处理AllowProperty注解 <br > 2013 - 10 - 30 下午6 : 16 : 08 [CODESPLIT] private void processAllowPropertyAnnotation ( AllowProperty property , Map < Class < ? > , Collection < String > > pojoAndNamesMap ) { String [ ] allowNames = property . name ( ) ; Class < ? > pojoClass = property . pojo ( ) ; Collection < String > ignoreProperties = EntityHelper . getUnstaticClassFieldNameCollection ( pojoClass ) ; Collection < String > allowNameCollection = new ArrayList < String > ( ) ; Collections . addAll ( allowNameCollection , allowNames ) ; Collection < String > nameCollection = pojoAndNamesMap . get ( pojoClass ) ; if ( nameCollection != null ) { nameCollection . removeAll ( allowNameCollection ) ; } else { ignoreProperties . removeAll ( allowNameCollection ) ; nameCollection = ignoreProperties ; } pojoAndNamesMap . put ( pojoClass , nameCollection ) ; }


Input: 根据方法获取过滤映射表 <br > 2013 - 10 - 25 下午2 : 47 : 34 [CODESPLIT] public Map < Class < ? > , Class < ? > > getProxyMixInAnnotation ( Method method ) { //        if (isResponseBodyAnnotation && !method.isAnnotationPresent(ResponseBody.class)) { //            return null; //        } Map < Class < ? > , Class < ? > > map = proxyMethodMap . get ( method ) ; // 从缓存中查找是否存在 if ( map != null && map . entrySet ( ) . size ( ) > 0 ) { // 如果已经读取该方法的注解信息，则从缓存中读取 return map ; } else { map = new HashMap < Class < ? > , Class < ? > > ( ) ; } Class < ? > clazzOfMethodIn = method . getDeclaringClass ( ) ; // 方法所在的class Map < Class < ? > , Collection < String > > pojoAndNamesMap = new HashMap < Class < ? > , Collection < String > > ( ) ; IgnoreProperties classIgnoreProperties = clazzOfMethodIn . getAnnotation ( IgnoreProperties . class ) ; IgnoreProperty classIgnoreProperty = clazzOfMethodIn . getAnnotation ( IgnoreProperty . class ) ; AllowProperty classAllowProperty = clazzOfMethodIn . getAnnotation ( AllowProperty . class ) ; IgnoreProperties ignoreProperties = method . getAnnotation ( IgnoreProperties . class ) ; IgnoreProperty ignoreProperty = method . getAnnotation ( IgnoreProperty . class ) ; AllowProperty allowProperty = method . getAnnotation ( AllowProperty . class ) ; if ( allowProperty != null ) { // 方法上的AllowProperty注解 processAllowPropertyAnnotation ( allowProperty , pojoAndNamesMap ) ; } if ( classAllowProperty != null ) { processAllowPropertyAnnotation ( classAllowProperty , pojoAndNamesMap ) ; } if ( classIgnoreProperties != null ) { // 类上的IgnoreProperties注解 processIgnorePropertiesAnnotation ( classIgnoreProperties , pojoAndNamesMap ) ; } if ( classIgnoreProperty != null ) { // 类上的IgnoreProperty注解 processIgnorePropertyAnnotation ( classIgnoreProperty , pojoAndNamesMap ) ; } if ( ignoreProperties != null ) { // 方法上的IgnoreProperties注解 processIgnorePropertiesAnnotation ( ignoreProperties , pojoAndNamesMap ) ; } if ( ignoreProperty != null ) { // 方法上的IgnoreProperties注解 processIgnorePropertyAnnotation ( ignoreProperty , pojoAndNamesMap ) ; } Set < Entry < Class < ? > , Collection < String > > > entries = pojoAndNamesMap . entrySet ( ) ; for ( Iterator < Entry < Class < ? > , Collection < String > > > iterator = entries . iterator ( ) ; iterator . hasNext ( ) ; ) { Entry < Class < ? > , Collection < String > > entry = ( Entry < Class < ? > , Collection < String > > ) iterator . next ( ) ; Collection < String > nameCollection = entry . getValue ( ) ; nameCollection = putGlobalIgnoreProperties ( nameCollection ) ; // 将全局过滤字段放入集合内 String [ ] names = nameCollection . toArray ( new String [ ] { } ) ; // EntityHelper.print(entry.getKey()); // for (int i = 0; i < names.length; i++) { // String name = names[i]; // EntityHelper.print(name); // } Class < ? > clazz = createMixInAnnotation ( names ) ; map . put ( entry . getKey ( ) , clazz ) ; } proxyMethodMap . put ( method , map ) ; return map ; }


Input: 创建jackson的代理注解接口类 <br > 2013 - 10 - 25 上午11 : 59 : 50 [CODESPLIT] private Class < ? > createMixInAnnotation ( String [ ] names ) { Class < ? > clazz = null ; clazz = proxyMixInAnnotationMap . get ( StringHelper . hashCodeOfStringArray ( names ) ) ; if ( clazz != null ) { return clazz ; } ClassPool pool = ClassPool . getDefault ( ) ; // 创建代理接口 CtClass cc = pool . makeInterface ( "ProxyMixInAnnotation" + System . currentTimeMillis ( ) + proxyIndex ++ ) ; ClassFile ccFile = cc . getClassFile ( ) ; ConstPool constpool = ccFile . getConstPool ( ) ; // create the annotation AnnotationsAttribute attr = new AnnotationsAttribute ( constpool , AnnotationsAttribute . visibleTag ) ; // 创建JsonIgnoreProperties注解 Annotation jsonIgnorePropertiesAnnotation = new Annotation ( JsonIgnoreProperties . class . getName ( ) , constpool ) ; BooleanMemberValue ignoreUnknownMemberValue = new BooleanMemberValue ( false , constpool ) ; ArrayMemberValue arrayMemberValue = new ArrayMemberValue ( constpool ) ; // value的数组成员 Collection < MemberValue > memberValues = new HashSet < MemberValue > ( ) ; for ( int i = 0 ; i < names . length ; i ++ ) { String name = names [ i ] ; StringMemberValue memberValue = new StringMemberValue ( constpool ) ; // 将name值设入注解内 memberValue . setValue ( name ) ; memberValues . add ( memberValue ) ; } arrayMemberValue . setValue ( memberValues . toArray ( new MemberValue [ ] { } ) ) ; jsonIgnorePropertiesAnnotation . addMemberValue ( "value" , arrayMemberValue ) ; jsonIgnorePropertiesAnnotation . addMemberValue ( "ignoreUnknown" , ignoreUnknownMemberValue ) ; attr . addAnnotation ( jsonIgnorePropertiesAnnotation ) ; ccFile . addAttribute ( attr ) ; // generate the class try { clazz = cc . toClass ( ) ; proxyMixInAnnotationMap . put ( StringHelper . hashCodeOfStringArray ( names ) , clazz ) ; // JsonIgnoreProperties ignoreProperties = (JsonIgnoreProperties) // clazz // .getAnnotation(JsonIgnoreProperties.class); // EntityHelper.print(ignoreProperties); // // EntityHelper.print(clazz); // try { // Object instance = clazz.newInstance(); // EntityHelper.print(instance); // // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } } catch ( CannotCompileException e ) { e . printStackTrace ( ) ; } // right // mthd.getMethodInfo().addAttribute(attr); return clazz ; }


Input: <br > 2013 - 10 - 25 下午12 : 29 : 58 [CODESPLIT] private JsonEncoding getJsonEncoding ( String characterEncoding ) { for ( JsonEncoding encoding : JsonEncoding . values ( ) ) { if ( characterEncoding . equals ( encoding . getJavaName ( ) ) ) { return encoding ; } } return JsonEncoding . UTF8 ; }


Input: Determine whether the given method is originally declared by { [CODESPLIT] public static boolean isObjectMethod ( Method method ) { try { Object . class . getDeclaredMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; return true ; } catch ( SecurityException ex ) { return false ; } catch ( NoSuchMethodException ex ) { return false ; } }


Input: Set the target object on which to call the target method . Only necessary when the target method is not static ; else a target class is sufficient . [CODESPLIT] public void setTargetObject ( Object targetObject ) { this . targetObject = targetObject ; if ( targetObject != null ) { this . targetClass = targetObject . getClass ( ) ; } }


Input: Prepare the specified method . The method can be invoked any number of times afterwards . [CODESPLIT] public void prepare ( ) throws ClassNotFoundException , NoSuchMethodException { if ( this . staticMethod != null ) { int lastDotIndex = this . staticMethod . lastIndexOf ( ' ' ) ; if ( lastDotIndex == - 1 || lastDotIndex == this . staticMethod . length ( ) ) { throw new IllegalArgumentException ( "staticMethod must be a fully qualified class plus method name: " + "e.g. 'example.MyExampleClass.myExampleMethod'" ) ; } String className = this . staticMethod . substring ( 0 , lastDotIndex ) ; String methodName = this . staticMethod . substring ( lastDotIndex + 1 ) ; this . targetClass = resolveClassName ( className ) ; this . targetMethod = methodName ; } Class < ? > targetClass = getTargetClass ( ) ; String targetMethod = getTargetMethod ( ) ; if ( targetClass == null ) { throw new IllegalArgumentException ( "Either 'targetClass' or 'targetObject' is required" ) ; } if ( targetMethod == null ) { throw new IllegalArgumentException ( "Property 'targetMethod' is required" ) ; } Object [ ] arguments = getArguments ( ) ; Class < ? > [ ] argTypes = new Class < ? > [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; ++ i ) { argTypes [ i ] = ( arguments [ i ] != null ? arguments [ i ] . getClass ( ) : Object . class ) ; } // Try to get the exact method first. try { this . methodObject = targetClass . getMethod ( targetMethod , argTypes ) ; } catch ( NoSuchMethodException ex ) { // Just rethrow exception if we can't get any match. this . methodObject = findMatchingMethod ( ) ; if ( this . methodObject == null ) { throw ex ; } } }


Input: Resolve the given class name into a Class . <p > The default implementations uses { @code ClassUtils . forName } using the thread context class loader . [CODESPLIT] protected Class < ? > resolveClassName ( String className ) throws ClassNotFoundException { return ClassUtils . forName ( className , ClassUtils . getDefaultClassLoader ( ) ) ; }


Input: Find a matching method with the specified name for the specified arguments . [CODESPLIT] protected Method findMatchingMethod ( ) { String targetMethod = getTargetMethod ( ) ; Object [ ] arguments = getArguments ( ) ; int argCount = arguments . length ; Method [ ] candidates = ReflectionUtils . getAllDeclaredMethods ( getTargetClass ( ) ) ; int minTypeDiffWeight = Integer . MAX_VALUE ; Method matchingMethod = null ; for ( Method candidate : candidates ) { if ( candidate . getName ( ) . equals ( targetMethod ) ) { Class < ? > [ ] paramTypes = candidate . getParameterTypes ( ) ; if ( paramTypes . length == argCount ) { int typeDiffWeight = getTypeDifferenceWeight ( paramTypes , arguments ) ; if ( typeDiffWeight < minTypeDiffWeight ) { minTypeDiffWeight = typeDiffWeight ; matchingMethod = candidate ; } } } } return matchingMethod ; }


Input: Invoke the specified method . <p > The invoker needs to have been prepared before . [CODESPLIT] public Object invoke ( ) throws InvocationTargetException , IllegalAccessException { // In the static case, target will simply be {@code null}. Object targetObject = getTargetObject ( ) ; Method preparedMethod = getPreparedMethod ( ) ; if ( targetObject == null && ! Modifier . isStatic ( preparedMethod . getModifiers ( ) ) ) { throw new IllegalArgumentException ( "Target method must not be non-static without a target" ) ; } ReflectionUtils . makeAccessible ( preparedMethod ) ; return preparedMethod . invoke ( targetObject , getArguments ( ) ) ; }


Input: Algorithm that judges the match between the declared parameter types of a candidate method and a specific list of arguments that this method is supposed to be invoked with . <p > Determines a weight that represents the class hierarchy difference between types and arguments . A direct match i . e . type Integer - arg of class Integer does not increase the result - all direct matches means weight 0 . A match between type Object and arg of class Integer would increase the weight by 2 due to the superclass 2 steps up in the hierarchy ( i . e . Object ) being the last one that still matches the required type Object . Type Number and class Integer would increase the weight by 1 accordingly due to the superclass 1 step up the hierarchy ( i . e . Number ) still matching the required type Number . Therefore with an arg of type Integer a constructor ( Integer ) would be preferred to a constructor ( Number ) which would in turn be preferred to a constructor ( Object ) . All argument weights get accumulated . <p > Note : This is the algorithm used by MethodInvoker itself and also the algorithm used for constructor and factory method selection in Spring s bean container ( in case of lenient constructor resolution which is the default for regular bean definitions ) . [CODESPLIT] public static int getTypeDifferenceWeight ( Class < ? > [ ] paramTypes , Object [ ] args ) { int result = 0 ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { if ( ! ClassUtils . isAssignableValue ( paramTypes [ i ] , args [ i ] ) ) { return Integer . MAX_VALUE ; } if ( args [ i ] != null ) { Class < ? > paramType = paramTypes [ i ] ; Class < ? > superClass = args [ i ] . getClass ( ) . getSuperclass ( ) ; while ( superClass != null ) { if ( paramType . equals ( superClass ) ) { result = result + 2 ; superClass = null ; } else if ( ClassUtils . isAssignable ( paramType , superClass ) ) { result = result + 2 ; superClass = superClass . getSuperclass ( ) ; } else { superClass = null ; } } if ( paramType . isInterface ( ) ) { result = result + 1 ; } } } return result ; }


Input: Convert the integer to an unsigned number . [CODESPLIT] private static String toUnsignedString ( int i , int shift ) { char [ ] buf = new char [ 32 ] ; int charPos = 32 ; int radix = 1 << shift ; int mask = radix - 1 ; do { buf [ -- charPos ] = digits [ i & mask ] ; i >>>= shift ; } while ( i != 0 ) ; return new String ( buf , charPos , ( 32 - charPos ) ) ; }


Input: 得到上传文件的文件头 [CODESPLIT] private static String bytesToHexString ( byte [ ] src ) { StringBuilder stringBuilder = new StringBuilder ( ) ; if ( null == src || src . length <= 0 ) { return null ; } for ( int i = 0 ; i < src . length ; i ++ ) { int v = src [ i ] & 0xFF ; String hv = Integer . toHexString ( v ) ; if ( hv . length ( ) < 2 ) { stringBuilder . append ( 0 ) ; } stringBuilder . append ( hv ) ; } return stringBuilder . toString ( ) ; }


Input: 获取文件类型 [CODESPLIT] public static String getFileType ( File file ) { String res = null ; try { @ SuppressWarnings ( "resource" ) FileInputStream fis = new FileInputStream ( file ) ; byte [ ] b = new byte [ 10 ] ; fis . read ( b , 0 , b . length ) ; String fileCode = bytesToHexString ( b ) ; Iterator < String > keyIter = FILE_TYPE_MAP . keySet ( ) . iterator ( ) ; while ( keyIter . hasNext ( ) ) { String key = keyIter . next ( ) ; if ( key . toLowerCase ( ) . startsWith ( fileCode . toLowerCase ( ) ) || fileCode . toLowerCase ( ) . startsWith ( key . toLowerCase ( ) ) ) { res = FILE_TYPE_MAP . get ( key ) ; break ; } } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return res ; }


Input: Serialize the given object to a byte array . [CODESPLIT] public static byte [ ] serialize ( Object object ) { if ( object == null ) { return null ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; oos . writeObject ( object ) ; oos . flush ( ) ; } catch ( IOException ex ) { throw new IllegalArgumentException ( "Failed to serialize object of type: " + object . getClass ( ) , ex ) ; } return baos . toByteArray ( ) ; }


Input: Deserialize the byte array into an object . [CODESPLIT] public static Object deserialize ( byte [ ] bytes ) { if ( bytes == null ) { return null ; } try { ObjectInputStream ois = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; return ois . readObject ( ) ; } catch ( IOException ex ) { throw new IllegalArgumentException ( "Failed to deserialize object" , ex ) ; } catch ( ClassNotFoundException ex ) { throw new IllegalStateException ( "Failed to deserialize object type" , ex ) ; } }


Input: 打印对象同时加入注释 [CODESPLIT] public void printC ( Object object ) { StackTraceElement [ ] stackTraceElements = StackTraceHelper . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; // 调用本类的对象类型堆栈 StringBuilder builder = new StringBuilder ( ) ; builder . append ( " ------------------------------------------------------------ " ) ; builder . append ( StringHelper . line ( ) ) ; builder . append ( StackTraceHelper . buildStackTrace ( new StackTraceElement [ ] { stackTraceElement } ) ) ; builder . append ( "    " ) ; if ( object == null ) { builder . append ( "<null>" ) ; } else { builder . append ( object . getClass ( ) . getSimpleName ( ) ) ; builder . append ( " =============== " ) ; String content = buildObjectToString ( object ) ; builder . append ( buildContent ( content ) ) ; } builder . append ( StringHelper . line ( ) ) ; builder . append ( " ------------------------------------------------------------ " ) ; System . out . println ( builder . toString ( ) ) ; }