signature:
public class JavassistFilterPropertyHandler { /** * 创建jackson的代理注解接口类 < br >
 * 2013-10-25 上午11:59:50
 * @ param names 要生成的字段
 * @ return 代理接口类 */
private Class < ? > createMixInAnnotation ( String [ ] names ) { } }

implementation:
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 ;


signature:
public class JavassistFilterPropertyHandler { /** * < br >
 * 2013-10-25 下午12:29:58
 * @ param characterEncoding
 * @ return */
private JsonEncoding getJsonEncoding ( String characterEncoding ) { } }

implementation: for ( JsonEncoding encoding : JsonEncoding . values ( ) ) { if ( characterEncoding . equals ( encoding . getJavaName ( ) ) ) { return encoding ; } } return JsonEncoding . UTF8 ;


signature:
public class ReflectionUtils { /** * Determine whether the given method is originally declared by { @ link Object } . */
public static boolean isObjectMethod ( Method method ) { } }

implementation: try { Object . class . getDeclaredMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; return true ; } catch ( SecurityException ex ) { return false ; } catch ( NoSuchMethodException ex ) { return false ; }


signature:
public class MethodInvoker { /** * 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 .
 * @ see # setTargetClass
 * @ see # setTargetMethod */
public void setTargetObject ( Object targetObject ) { } }

implementation: this . targetObject = targetObject ; if ( targetObject != null ) { this . targetClass = targetObject . getClass ( ) ; }


signature:
public class MethodInvoker { /** * Prepare the specified method .
 * The method can be invoked any number of times afterwards .
 * @ see # getPreparedMethod
 * @ see # invoke */
public void prepare ( ) throws ClassNotFoundException , NoSuchMethodException { } }

implementation:
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 ; } }


signature:
public class MethodInvoker { /** * Resolve the given class name into a Class .
 * < p > The default implementations uses { @ code ClassUtils . forName } ,
 * using the thread context class loader .
 * @ param className the class name to resolve
 * @ return the resolved Class
 * @ throws ClassNotFoundException if the class name was invalid */
protected Class < ? > resolveClassName ( String className ) throws ClassNotFoundException { } }

implementation: return ClassUtils . forName ( className , ClassUtils . getDefaultClassLoader ( ) ) ;


signature:
public class MethodInvoker { /** * Find a matching method with the specified name for the specified arguments .
 * @ return a matching method , or { @ code null } if none
 * @ see # getTargetClass ( )
 * @ see # getTargetMethod ( )
 * @ see # getArguments ( ) */
protected Method findMatchingMethod ( ) { } }

implementation: 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 ;


signature:
public class MethodInvoker { /** * Invoke the specified method .
 * < p > The invoker needs to have been prepared before .
 * @ return the object ( possibly null ) returned by the method invocation ,
 * or { @ code null } if the method has a void return type
 * @ throws java . lang . reflect . InvocationTargetException if the target method threw an exception
 * @ throws IllegalAccessException if the target method couldn ' t be accessed
 * @ see # prepare */
public Object invoke ( ) throws InvocationTargetException , IllegalAccessException { } }

implementation:
// 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 ( ) ) ;


signature:
public class MethodInvoker { /** * 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 ) .
 * @ param paramTypes the parameter types to match
 * @ param args the arguments to match
 * @ return the accumulated weight for all arguments */
public static int getTypeDifferenceWeight ( Class < ? > [ ] paramTypes , Object [ ] args ) { } }

implementation: 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 ;


signature:
public class ByteHelper { /** * Convert the integer to an unsigned number . */
private static String toUnsignedString ( int i , int shift ) { } }

implementation: 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 ) ) ;


signature:
public class FileType { /** * 得到上传文件的文件头
 * @ param src
 * @ return */
private static String bytesToHexString ( byte [ ] src ) { } }

implementation: 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 ( ) ;


signature:
public class FileType { /** * 获取文件类型
 * @ param file
 * @ return */
public static String getFileType ( File file ) { } }

implementation: 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 ;


signature:
public class SerializationUtils { /** * Serialize the given object to a byte array .
 * @ param object the object to serialize
 * @ return an array of bytes representing the object in a portable fashion */
public static byte [ ] serialize ( Object object ) { } }

implementation: 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 ( ) ;


signature:
public class SerializationUtils { /** * Deserialize the byte array into an object .
 * @ param bytes a serialized object
 * @ return the result of deserializing the bytes */
public static Object deserialize ( byte [ ] bytes ) { } }

implementation: 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 ) ; }


signature:
public class PrintHelper { /** * 打印对象同时加入注释
 * @ param object */
public void printC ( Object object ) { } }

implementation:
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 ( ) ) ;


signature:
public class PrintHelper { /** * 使用反射机制自动ToString < br >
 * 2013-8-28 下午3:16:40
 * @ param object
 * @ return */
public String reflectToString ( Object object ) { } }

implementation:
if ( object == null ) { return null ; } Class clazz = object . getClass ( ) ; StringBuilder builder = new StringBuilder ( clazz . getName ( ) ) ; builder . append ( "@" ) ; builder . append ( Integer . toHexString ( object . hashCode ( ) ) ) ; builder . append ( "[" ) ; Set < Method > methods = new LinkedHashSet < Method > ( ) ; Collection < Class > classes = EntityHelper . getAllSuperClassesOfClass ( clazz ) ; for ( Iterator iterator = classes . iterator ( ) ; iterator . hasNext ( ) ; ) { Class claxx = ( Class ) iterator . next ( ) ; Method [ ] clazzMethods = claxx . getDeclaredMethods ( ) ; for ( int i = 0 ; i < clazzMethods . length ; i ++ ) { Method method = clazzMethods [ i ] ; methods . add ( method ) ; } } // for ( int i = 0 ; i < methods . length ; i + + ) {
// Method method = methods [ i ] ;
for ( Iterator iterator = methods . iterator ( ) ; iterator . hasNext ( ) ; ) { Method method = ( Method ) iterator . next ( ) ; String methodName = method . getName ( ) ; if ( methodName . startsWith ( "get" ) && ! Modifier . isStatic ( method . getModifiers ( ) ) && Modifier . isPublic ( method . getModifiers ( ) ) ) { try { Object value = method . invoke ( object ) ; String propertyName = methodName . substring ( 3 , 4 ) . toLowerCase ( ) + methodName . substring ( 4 ) ; if ( propertyName . equals ( "class" ) || ignoreProperties . contains ( propertyName ) ) { // 忽略getClass方法
continue ; } builder . append ( propertyName ) ; builder . append ( "=" ) ; if ( value == null ) { builder . append ( "<null>" ) ; } else { if ( value . getClass ( ) . isArray ( ) ) { int arraySuperLength = Array . getLength ( value ) ; builder . append ( "{" ) ; for ( int j = 0 ; j < arraySuperLength ; j ++ ) { Object object2 = Array . get ( value , j ) ; builder . append ( object2 . toString ( ) ) ; if ( j < arraySuperLength - 1 ) { builder . append ( ", " ) ; } } builder . append ( "}" ) ; } else { builder . append ( value . toString ( ) ) ; } } builder . append ( ", " ) ; } catch ( IllegalArgumentException e ) { } catch ( IllegalAccessException e ) { } catch ( InvocationTargetException e ) { } } } if ( builder . toString ( ) . contains ( ", " ) ) { builder . replace ( builder . length ( ) - 2 , builder . length ( ) , "" ) ; } builder . append ( "]" ) ; return builder . toString ( ) ;


signature:
public class UnicodeDetector { /** * ( non - Javadoc ) It is assumed that the inputstream is at the start of the file or String ( in order to read the
 * BOM ) .
 * @ see cpdetector . io . ICodepageDetector # detectCodepage ( java . io . InputStream , int ) */
public Charset detectCodepage ( InputStream in , int length ) throws IOException { } }

implementation:
byte [ ] bom = new byte [ 4 ] ; // Get the byte - order mark , if there is one
in . read ( bom , 0 , 4 ) ; // Unicode formats = > read BOM
byte b = ( byte ) 0xEF ; if ( bom [ 0 ] == ( byte ) 0x00 && bom [ 1 ] == ( byte ) 0x00 && bom [ 2 ] == ( byte ) 0xFE && bom [ 2 ] == ( byte ) 0xFF ) // utf - 32BE
return Charset . forName ( "UTF-32BE" ) ; if ( bom [ 0 ] == ( byte ) 0xFF && bom [ 1 ] == ( byte ) 0xFE && bom [ 2 ] == ( byte ) 0x00 && bom [ 2 ] == ( byte ) 0x00 ) // utf - 32BE
return Charset . forName ( "UTF-32LE" ) ; if ( bom [ 0 ] == ( byte ) 0xEF && bom [ 1 ] == ( byte ) 0xBB && bom [ 2 ] == ( byte ) 0xBF ) // utf - 8
return Charset . forName ( "UTF-8" ) ; if ( bom [ 0 ] == ( byte ) 0xff && bom [ 1 ] == ( byte ) 0xfe ) // ucs - 2le , ucs - 4le , and ucs - 16le
return Charset . forName ( "UTF-16LE" ) ; if ( bom [ 0 ] == ( byte ) 0xfe && bom [ 1 ] == ( byte ) 0xff ) // utf - 16 and ucs - 2
return Charset . forName ( "UTF-16BE" ) ; if ( bom [ 0 ] == ( byte ) 0 && bom [ 1 ] == ( byte ) 0 && bom [ 2 ] == ( byte ) 0xfe && bom [ 3 ] == ( byte ) 0xff ) // ucs - 4
return Charset . forName ( "UCS-4" ) ; return UnknownCharset . getInstance ( ) ;


signature:
public class Judgment { /** * 判断String对象是否包含字符 ( 如果全部为空格也返回false )
 * @ param string
 * @ return */
public static boolean hasText ( String ... string ) { } }

implementation: if ( string == null ) { return false ; } boolean flag = true ; for ( String s : string ) { flag = flag && ( s != null && ! "" . equals ( s . trim ( ) ) ) ; if ( ! flag ) { return false ; } } return flag ;


signature:
public class IpAddress { /** * sn = MD5 ( urlencode ( basicString + sk ) )
 * 其中 basicString 的算法如下 :
 * ( 1 ) get 请求
 * url 中 http : / / 域名 { uri }
 * basicString = uri
 * ( 2 ) post 请求
 * url 中 http : / / 域名 { uri } POST 参数按照key进行从小大到字母排序
 * 然后拼装成 : k1 = v1 & amp ; k2 = v2 & amp ; k3 = v3 & amp ; . . . & amp ; kn = vn的格式 = & gt ; { params }
 * basicString = uri + ? + params
 * @ param ak access key
 * @ param sk secret key
 * @ param url url值 , 例如 : / geosearch / nearby 不能带hostname和querstring , 也不能带 ?
 * @ param nameValuePairs $ querystring _ arrays 参数数组 , key = & gt ; value形式 。 在计算签名后不能重新排序 , 也不能添加或者删除数据元素
 * @ param method method 只能为 ' POST ' 或者 ' GET '
 * @ return 计算SN签名算法 */
public String calculateAKSN ( String ak , String sk , String url , List < NameValuePair > nameValuePairs , String method ) { } }

implementation: String params = "" ; if ( method . equals ( "POST" ) ) { Collections . sort ( nameValuePairs , new Comparator < NameValuePair > ( ) { @ Override public int compare ( NameValuePair o1 , NameValuePair o2 ) { StringComparator comparator = new StringComparator ( ) ; return comparator . compare ( o1 . getName ( ) , o2 . getName ( ) ) ; } } ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; for ( Iterator < NameValuePair > iterator = nameValuePairs . iterator ( ) ; iterator . hasNext ( ) ; ) { NameValuePair nameValuePair = iterator . next ( ) ; String name = nameValuePair . getName ( ) ; String value = nameValuePair . getValue ( ) ; stringBuilder . append ( name ) ; stringBuilder . append ( "=" ) ; stringBuilder . append ( value ) ; if ( iterator . hasNext ( ) ) { stringBuilder . append ( "&" ) ; } } params = stringBuilder . toString ( ) ; } String basicString = url + "? " + params ; String sn = null ; try { sn = MD5Helper . encrypt ( URLEncoder . encode ( basicString + sk , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return sn ;


signature:
public class DomUtils { /** * Retrieves all child elements of the given DOM element that match any of the given element names .
 * Only looks at the direct child level of the given element ; do not go into further depth
 * ( in contrast to the DOM API ' s { @ code getElementsByTagName } method ) .
 * @ param ele the DOM element to analyze
 * @ param childEleNames the child element names to look for
 * @ return a List of child { @ code org . w3c . dom . Element } instances
 * @ see org . w3c . dom . Element
 * @ see org . w3c . dom . Element # getElementsByTagName */
public static List < Element > getChildElementsByTagName ( Element ele , String [ ] childEleNames ) { } }

implementation: Assert . notNull ( ele , "Element must not be null" ) ; Assert . notNull ( childEleNames , "Element names collection must not be null" ) ; List < String > childEleNameList = Arrays . asList ( childEleNames ) ; NodeList nl = ele . getChildNodes ( ) ; List < Element > childEles = new ArrayList < Element > ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameMatch ( node , childEleNameList ) ) { childEles . add ( ( Element ) node ) ; } } return childEles ;


signature:
public class DomUtils { /** * Retrieves all child elements of the given DOM element that match the given element name .
 * Only look at the direct child level of the given element ; do not go into further depth
 * ( in contrast to the DOM API ' s { @ code getElementsByTagName } method ) .
 * @ param ele the DOM element to analyze
 * @ param childEleName the child element name to look for
 * @ return a List of child { @ code org . w3c . dom . Element } instances
 * @ see org . w3c . dom . Element
 * @ see org . w3c . dom . Element # getElementsByTagName */
public static List < Element > getChildElementsByTagName ( Element ele , String childEleName ) { } }

implementation: return getChildElementsByTagName ( ele , new String [ ] { childEleName } ) ;


signature:
public class DomUtils { /** * Utility method that returns the first child element identified by its name .
 * @ param ele the DOM element to analyze
 * @ param childEleName the child element name to look for
 * @ return the { @ code org . w3c . dom . Element } instance , or { @ code null } if none found */
public static Element getChildElementByTagName ( Element ele , String childEleName ) { } }

implementation: Assert . notNull ( ele , "Element must not be null" ) ; Assert . notNull ( childEleName , "Element name must not be null" ) ; NodeList nl = ele . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameMatch ( node , childEleName ) ) { return ( Element ) node ; } } return null ;


signature:
public class DomUtils { /** * Utility method that returns the first child element value identified by its name .
 * @ param ele the DOM element to analyze
 * @ param childEleName the child element name to look for
 * @ return the extracted text value , or { @ code null } if no child element found */
public static String getChildElementValueByTagName ( Element ele , String childEleName ) { } }

implementation: Element child = getChildElementByTagName ( ele , childEleName ) ; return ( child != null ? getTextValue ( child ) : null ) ;


signature:
public class DomUtils { /** * Retrieves all child elements of the given DOM element
 * @ param ele the DOM element to analyze
 * @ return a List of child { @ code org . w3c . dom . Element } instances */
public static List < Element > getChildElements ( Element ele ) { } }

implementation: Assert . notNull ( ele , "Element must not be null" ) ; NodeList nl = ele . getChildNodes ( ) ; List < Element > childEles = new ArrayList < Element > ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element ) { childEles . add ( ( Element ) node ) ; } } return childEles ;


signature:
public class DomUtils { /** * Extracts the text value from the given DOM element , ignoring XML comments .
 * < p > Appends all CharacterData nodes and EntityReference nodes into a single
 * String value , excluding Comment nodes . Only exposes actual user - specified
 * text , no default values of any kind .
 * @ see org . w3c . dom . CharacterData
 * @ see org . w3c . dom . EntityReference
 * @ see org . w3c . dom . Comment */
public static String getTextValue ( Element valueEle ) { } }

implementation: Assert . notNull ( valueEle , "Element must not be null" ) ; StringBuilder sb = new StringBuilder ( ) ; NodeList nl = valueEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node item = nl . item ( i ) ; if ( ( item instanceof CharacterData && ! ( item instanceof Comment ) ) || item instanceof EntityReference ) { sb . append ( item . getNodeValue ( ) ) ; } } return sb . toString ( ) ;


signature:
public class DomUtils { /** * Namespace - aware equals comparison . Returns { @ code true } if either
 * { @ link org . w3c . dom . Node # getLocalName } or { @ link org . w3c . dom . Node # getNodeName } equals
 * { @ code desiredName } , otherwise returns { @ code false } . */
public static boolean nodeNameEquals ( Node node , String desiredName ) { } }

implementation: Assert . notNull ( node , "Node must not be null" ) ; Assert . notNull ( desiredName , "Desired name must not be null" ) ; return nodeNameMatch ( node , desiredName ) ;


signature:
public class DomUtils { /** * Matches the given node ' s name and local name against the given desired name . */
private static boolean nodeNameMatch ( Node node , String desiredName ) { } }

implementation: return ( desiredName . equals ( node . getNodeName ( ) ) || desiredName . equals ( node . getLocalName ( ) ) ) ;


signature:
public class DomUtils { /** * Matches the given node ' s name and local name against the given desired names . */
private static boolean nodeNameMatch ( Node node , Collection < ? > desiredNames ) { } }

implementation: return ( desiredNames . contains ( node . getNodeName ( ) ) || desiredNames . contains ( node . getLocalName ( ) ) ) ;


signature:
public class StreamTableRenderer { /** * @ throws java . io . IOException */
private final void renderHeaderCell ( String columnName , int firstOrLast ) throws IOException { } }

implementation: m_out . write ( this . HeadCellStartTag ( ( firstOrLast == FIRST_CELL_IN_ROW ) ) ) ; m_out . write ( columnName ) ; m_out . write ( this . HeadCellStopTag ( ( firstOrLast == LAST_CELL_IN_ROW ) ) ) ;


signature:
public class StreamTableRenderer { /** * / * ( non - Javadoc )
 * @ see cpdetector . util . collections . ui . ITableRenderer # render ( javax . swing . table . TableModel ) */
public final void render ( TableModel model ) throws IOException { } }

implementation:
this . m_out . write ( this . TableStartTag ( ) ) ; int rows = model . getRowCount ( ) ; // write header
m_out . write ( this . HeadRowStartTag ( ) ) ; this . renderHeader ( model ) ; m_out . write ( this . HeadRowStopTag ( ) ) ; for ( int i = 0 ; i < rows ; i ++ ) { this . renderRow ( model , i ) ; } this . m_out . write ( this . TableStopTag ( ) ) ;


signature:
public class DomainHelper { /** * 移除主机字符 , 例如传入admin @ xiongyingqi . com , 那么该方法将截取 @ 之前的字符返回admin
 * @ param str
 * @ return */
public static String removeDomain ( String str ) { } }

implementation: if ( str != null && ! "" . equals ( str ) ) { int index = str . indexOf ( "@" ) ; if ( index >= 0 ) { str = str . substring ( 0 , index ) ; } } return str ;


signature:
public class StringUtil { /** * Appends the given amount of spaces to the String .
 * Not intended for big append - operations because in a loop alway just one
 * space is added .
 * @ param s
 * the base String to append spaces to .
 * @ param count
 * the amount of spaces to append .
 * @ return a String consisting of s and count trailing whitespaces . */
public static final String appendSpaces ( final String s , final int count ) { } }

implementation: StringBuffer tmp = new StringBuffer ( s ) ; for ( int i = 0 ; i < count ; i ++ ) { tmp . append ( " " ) ; } return tmp . toString ( ) ;


signature:
public class StringUtil { /** * If the given Object is no Array , it ' s toString - method is invoked .
 * Primitive type - Arrays and Object - Arrays are introspected using
 * java . lang . reflect . Array . Convention for creation fo String -
 * representation : < p >
 * @ see info . monitorenter . util . StringUtil # arrayToString ( Object , String )
 * @ param isArr
 * The Array to represent as String .
 * @ return a String - representation of the Object . */
public static final String arrayToString ( final Object isArr ) { } }

implementation: String result = StringUtil . arrayToString ( isArr , "," ) ; return result ;


signature:
public class StringUtil { /** * If the given Object is no Array , it ' s toString - method is invoked .
 * Primitive type - Arrays and Object - Arrays are introspected using
 * java . lang . reflect . Array . Convention for creation for String -
 * representation : < br >
 * < code >
 * / / Primitive arrays :
 * & quot ; [ & quot ; + isArr [ 0 ] + & quot ; & lt ; separator & gt ; & quot ; + isArr [ 1 ] + . . . . + isArr [ isArr . length - 1 ] + & quot ; ] & quot ;
 * / / Object arrays :
 * & quot ; [ & quot ; + isArr [ 0 ] . toString ( ) + & quot ; & lt ; separator & gt ; & quot ; + . . . . + isArr [ isArr . length - 1 ] . toString + & quot ; ] & quot ;
 * / / Two or three - dimensional Arrays are not supported
 * / / ( should be reflected in a special output method , e . g . as a field )
 * / / other Objects :
 * toString ( )
 * < / code >
 * @ param separator put in - between each array element in the resulting string .
 * @ param isArr
 * The Array to represent as String .
 * @ return a String - representation of the Object . */
public static final String arrayToString ( final Object isArr , final String separator ) { } }

implementation:
String result ; if ( isArr == null ) { result = "null" ; } else { Object element ; StringBuffer tmp = new StringBuffer ( ) ; try { int length = Array . getLength ( isArr ) ; tmp . append ( "[" ) ; for ( int i = 0 ; i < length ; i ++ ) { element = Array . get ( isArr , i ) ; if ( element == null ) { tmp . append ( "null" ) ; } else { tmp . append ( element . toString ( ) ) ; } if ( i < length - 1 ) { tmp . append ( separator ) ; } } tmp . append ( "]" ) ; result = tmp . toString ( ) ; } catch ( ArrayIndexOutOfBoundsException bound ) { // programming mistake or bad Array . getLength ( obj ) .
tmp . append ( "]" ) ; result = tmp . toString ( ) ; } catch ( IllegalArgumentException noarr ) { result = isArr . toString ( ) ; } } return result ;


signature:
public class StringUtil { /** * Returns the singleton instance of this class .
 * 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 .
 * @ return the singleton instance of this class . */
public static StringUtil instance ( ) { } }

implementation: if ( StringUtil . instance == null ) { StringUtil . instance = new StringUtil ( ) ; } return StringUtil . instance ;


signature:
public class StringUtil { /** * Returns true if the argument is null or consists of whitespaces only .
 * @ param test
 * the < code > String < / code > to test .
 * @ return true if the argument is null or consists of whitespaces only . */
public static boolean isEmpty ( final String test ) { } }

implementation: boolean result ; if ( test == null ) { result = true ; } else { result = test . trim ( ) . length ( ) == 0 ; } return result ;


signature:
public class StringUtil { /** * Little String output - helper that modifies the given LinkedList by getting
 * it ' s Objects and replace them by their toString ( ) - representation .
 * What is special ? < br >
 * If an Object in the given List is an Array ( of Objects or primitive data
 * types ) reflection will be used to create a String - representation of them .
 * The changes are reflected in the Objects that are in the given List . So
 * keep a reference to it . If you are sure , that your List does not contain
 * Arrays do not use this method to avoid overhead .
 * Avoid structural modifications ( remove ) of the list while using this
 * method . This method or better : the given List is only thread - safe if the
 * list is synchronized .
 * A clever VM ( hotspot ) will be able to inline this function because of void
 * return .
 * @ param objects
 * the List of objects that will be changed to a list of the String
 * representation of the Objects with respect to special array
 * treatment . */
public static final void listOfArraysToString ( final List < Object > objects ) { } }

implementation: if ( objects == null ) { return ; } int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { objects . add ( i , StringUtil . arrayToString ( objects . remove ( i ) ) ) ; }


signature:
public class StringUtil { /** * Returns the maximum length of a { @ link Object # toString ( ) } result in
 * characters within the given List .
 * No data is changed in the given List at all . But the String -
 * representation of all Objects , even Arrays is build to inspect . < br >
 * Convention for creation fo String - representation : < br >
 * < pre >
 * Primitive Arrays : as performed by this classes @ see # ArrayToString .
 * Object Arrays : as performed by this classes @ see # ArrayToString
 * other Objects : toString ( ) ( as performed by this classes @ see # ArrayToString ) .
 * < / pre >
 * @ param objects
 * the < code > List & lt ; Object & gt ; < / code > to inspect for the maximum
 * length of a { @ link Object # toString ( ) } result .
 * @ return The length of the longest String - representation of an Object in
 * the List < b > or 0 if objects was null or of size 0 . < / b > */
public static final int longestStringRepresentation ( final List < Object > objects ) { } }

implementation:
int result ; if ( objects == null ) { result = 0 ; } else { int maxsize = 0 ; int tint = 0 ; String tmp ; int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { tmp = StringUtil . arrayToString ( objects . get ( i ) ) ; tint = tmp . length ( ) ; if ( tint > maxsize ) { maxsize = tint ; } } // maximum size known .
result = maxsize ; } return result ;


signature:
public class StringUtil { /** * Appends the necessary amount of spaces to the string until it has the givn
 * length . No Exception is thrown , if the length of the String is shorter than
 * the given length , but nothing will happen and a message will be printed to
 * the System . out .
 * @ param s
 * the String to expand .
 * @ param length
 * the desired length of the String to be returned .
 * @ return A String that represents the content of the old String including
 * extra whitespaces . */
public static final String setSize ( final String s , final int length ) { } }

implementation: String result = s ; int oldlen = s . length ( ) ; if ( oldlen > length ) { System . err . println ( "greenpeace.util.setSize(String s,int length): length (" + length + ") is smaller than s.length(" + oldlen + ") : " + s ) ; } else { int tofill = length - oldlen ; result = StringUtil . appendSpaces ( s , tofill ) ; } return result ;


signature:
public class StringUtil { /** * Modifies the given LinkedList by getting it ' s Objects and replace them by
 * their toString ( ) - representation concatenated with the necessary amount of
 * white spaces that every String in the List will have the same amount of
 * characters .
 * Only use this method in following case : < br >
 * < ul >
 * < li > You have got an AbstractList or subclass containing Objects you do not
 * know . < / li >
 * < li > You want to transform all Elements in the List to Strings . < / li >
 * < li > There might be Array ' s in the Object ( whose toString method will return
 * only their hashcode ) . < / li >
 * < / ul >
 * What happens ?
 * < ul >
 * < li > All Objects , even primitive Arrays in your List will be turned to
 * String - representation . < / li >
 * < li > The result will replace the old position of the Object in the given
 * List . The old Objects will get lost ! < / li >
 * < li > All Strings will be filled with whitespaces until each String has the
 * same length . < / li >
 * < / ul >
 * At least this method will be speeded up by a hotspot VM by inlining this
 * method . < br >
 * < i > An example : < br >
 * You just retrieved data from a db using jdbc and a generic class
 * ( resultset . getObject ( ) ) . You want to print the data to System . out or to
 * save it to a file , but do not know , if Arrays are contained . You want the
 * output to be formatted ( each line ) . < / i >
 * @ param objects
 * contains the Objects to replace by their toString ( )
 * representation . */
public static final void toLongestString ( final List < Object > objects ) { } }

implementation:
if ( objects == null ) { return ; } int maxsize = 0 ; int tint = 0 ; String tmp ; int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { StringUtil . arrayToString ( objects . get ( i ) ) ; tmp = ( String ) objects . get ( i ) ; tint = tmp . length ( ) ; if ( tint > maxsize ) { maxsize = tint ; } objects . add ( i , tmp ) ; } // maximum size known .
for ( int i = 0 ; i < stop ; i ++ ) { objects . add ( i , StringUtil . setSize ( ( String ) objects . remove ( i ) , maxsize ) ) ; }


signature:
public class HttpBuilder { /** * 增加参数 , 默认使用urlEncoding
 * @ param name
 * @ param value
 * @ return */
public HttpBuilder param ( String name , String value ) { } }

implementation: return param ( name , value , true ) ;


signature:
public class HttpBuilder { /** * 增加参数
 * @ param name
 * @ param value
 * @ param urlEncoding
 * @ return */
public HttpBuilder param ( String name , String value , boolean urlEncoding ) { } }

implementation: String encodedValue = null ; if ( urlEncoding && value != null ) { try { encodedValue = URLEncoder . encode ( value , charset . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { Logger . error ( e ) ; } } if ( encodedValue == null ) { encodedValue = value ; } NameValuePair nameValuePair = new BasicNameValuePair ( name , encodedValue ) ; this . nameValuePairs . add ( nameValuePair ) ; return this ;


signature:
public class CosineSimilarAlgorithm { /** * 根据输入的Unicode字符 , 获取它的GB2312编码或者ascii编码 ,
 * @ param ch 输入的GB2312中文字符或者ASCII字符 ( 128个 )
 * @ return ch在GB2312中的位置 , - 1表示该字符不认识 */
public static short getGB2312Id ( char ch ) { } }

implementation:
try { byte [ ] buffer = Character . toString ( ch ) . getBytes ( "GB2312" ) ; if ( buffer . length != 2 ) { // 正常情况下buffer应该是两个字节 , 否则说明ch不属于GB2312编码 , 故返回 ' ? ' , 此时说明不认识该字符
return - 1 ; } int b0 = ( int ) ( buffer [ 0 ] & 0x0FF ) - 161 ; // 编码从A1开始 , 因此减去0xA1 = 161
int b1 = ( int ) ( buffer [ 1 ] & 0x0FF ) - 161 ; // 第一个字符和最后一个字符没有汉字 , 因此每个区只收16*6-2 = 94个汉字
return ( short ) ( b0 * 94 + b1 ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return - 1 ;


signature:
public class SpringMVCHelper { /** * 获取包下所有被Controller注解的类所表示的路径 < br >
 * 2013-10-17 下午1:02:45
 * @ param pkg
 * @ return */
public static Collection < String > getAnnotationMappedPaths ( Package pkg ) { } }

implementation: if ( pkg == null ) { return null ; } Collection < String > rs = new LinkedHashSet < String > ( ) ; Set < Class < ? > > classes = PackageUtil . getclass ( pkg ) ; for ( Iterator iterator = classes . iterator ( ) ; iterator . hasNext ( ) ; ) { Class < ? > clazz = ( Class < ? > ) iterator . next ( ) ; if ( clazz . isAnnotationPresent ( Controller . class ) ) { String [ ] clazzPaths = null ; if ( clazz . isAnnotationPresent ( RequestMapping . class ) ) { RequestMapping typeMapping = clazz . getAnnotation ( RequestMapping . class ) ; clazzPaths = typeMapping . value ( ) ; } String [ ] methodPaths = null ; Collection < String > methodPathCollection = new ArrayList < String > ( ) ; Method [ ] methods = clazz . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method method = methods [ i ] ; if ( method . isAnnotationPresent ( RequestMapping . class ) ) { RequestMapping typeMapping = method . getAnnotation ( RequestMapping . class ) ; String [ ] methodPathsVar = typeMapping . value ( ) ; Collections . addAll ( methodPathCollection , methodPathsVar ) ; } } if ( methodPathCollection . size ( ) > 0 ) { methodPaths = methodPathCollection . toArray ( new String [ ] { } ) ; } if ( clazzPaths != null && clazzPaths . length > 0 && methodPaths != null && methodPaths . length > 0 ) { for ( int i = 0 ; i < clazzPaths . length ; i ++ ) { String typePath = clazzPaths [ i ] ; typePath = checkForPath ( typePath ) ; for ( int j = 0 ; j < methodPaths . length ; j ++ ) { String methodPath = methodPaths [ j ] ; methodPath = checkForPath ( methodPath ) ; String mappedPath = typePath + methodPath ; rs . add ( mappedPath ) ; } } } else if ( ( clazzPaths != null && clazzPaths . length > 0 ) && ( methodPaths == null || methodPaths . length == 0 ) ) { for ( int i = 0 ; i < clazzPaths . length ; i ++ ) { String typePath = clazzPaths [ i ] ; typePath = checkForPath ( typePath ) ; rs . add ( typePath ) ; } } else if ( ( methodPaths != null && methodPaths . length > 0 ) && ( clazzPaths == null || clazzPaths . length == 0 ) ) { EntityHelper . print ( methodPaths ) ; for ( int i = 0 ; i < clazzPaths . length ; i ++ ) { String typePath = clazzPaths [ i ] ; typePath = checkForPath ( typePath ) ; rs . add ( typePath ) ; } } } } return rs ;


signature:
public class WeakReferenceMonitor { /** * Start to monitor given handle object for becoming weakly reachable .
 * When the handle isn ' t used anymore , the given listener will be called .
 * @ param handle the object that will be monitored
 * @ param listener the listener that will be called upon release of the handle */
public static void monitor ( Object handle , ReleaseListener listener ) { } }

implementation:
if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Monitoring handle [" + handle + "] with release listener [" + listener + "]" ) ; } // Make weak reference to this handle , so we can say when
// handle is not used any more by polling on handleQueue .
WeakReference < Object > weakRef = new WeakReference < Object > ( handle , handleQueue ) ; // Add monitored entry to internal map of all monitored entries .
addEntry ( weakRef , listener ) ;


signature:
public class WeakReferenceMonitor { /** * Add entry to internal map of tracked entries .
 * Internal monitoring thread is started if not already running .
 * @ param ref reference to tracked handle
 * @ param entry the associated entry */
private static void addEntry ( Reference < ? > ref , ReleaseListener entry ) { } }

implementation:
synchronized ( WeakReferenceMonitor . class ) { // Add entry , the key is given reference .
trackedEntries . put ( ref , entry ) ; // Start monitoring thread lazily .
if ( monitoringThread == null ) { monitoringThread = new Thread ( new MonitoringProcess ( ) , WeakReferenceMonitor . class . getName ( ) ) ; monitoringThread . setDaemon ( true ) ; monitoringThread . start ( ) ; } }


signature:
public class WeakReferenceMonitor { /** * Check whether to keep the monitoring thread alive ,
 * i . e . whether there are still entries being tracked . */
private static boolean keepMonitoringThreadAlive ( ) { } }

implementation: synchronized ( WeakReferenceMonitor . class ) { if ( ! trackedEntries . isEmpty ( ) ) { return true ; } else { logger . debug ( "No entries left to track - stopping reference monitor thread" ) ; monitoringThread = null ; return false ; } }


signature:
public class FileHelper { /** * public static final long DB = 1024 * NB ; */
public static boolean checkFileSizeLessThen ( File file , long size ) { } }

implementation: try { fileNotFullAndExists ( file ) ; } catch ( Exception e ) { return false ; } return file . length ( ) <= size ;


signature:
public class FileHelper { /** * 获取文件类型 < br >
 * 2013-9-2 下午9:08:51
 * @ param data
 * @ return */
public static String getMimeType ( File data ) { } }

implementation:
if ( ! data . exists ( ) ) { return null ; } ContentHandler contenthandler = new BodyContentHandler ( ) ; Metadata metadata = new Metadata ( ) ; metadata . set ( Metadata . RESOURCE_NAME_KEY , data . getName ( ) ) ; Parser parser = new AutoDetectParser ( ) ; try { parser . parse ( new FileInputStream ( data ) , contenthandler , metadata , null ) ; } catch ( FileNotFoundException e ) { LOGGER . error ( e ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } catch ( SAXException e ) { LOGGER . error ( e ) ; } catch ( TikaException e ) { LOGGER . error ( e ) ; } // System . out . println ( " Mime : " + metadata . get ( Metadata . CONTENT _ TYPE ) ) ;
// System . out . println ( " Mime str : " + metadata . toString ( ) ) ;
return metadata . get ( Metadata . CONTENT_TYPE ) ;


signature:
public class FileHelper { /** * 根据后缀名从文件夹获取文件 < br >
 * 2013-9-6 下午3:15:56
 * @ param folder
 * @ param suffix
 * @ return */
public static File [ ] listFilesBySuffix ( File folder , final String suffix ) { } }

implementation: File [ ] files = folder . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File paramFile , String paramString ) { String newSuffix = suffix ; if ( ! newSuffix . startsWith ( "." ) ) { newSuffix = "." + newSuffix ; } if ( paramString . endsWith ( newSuffix ) ) { return true ; } return false ; } } ) ; return files ;


signature:
public class FileHelper { /** * 从url地址读取文件信息并写入到临时文件 < br >
 * 2013-9-2 下午2:57:15
 * @ param urlStr
 * @ return
 * @ throws java . io . IOException */
public static File readURL ( String urlStr ) throws IOException { } }

implementation:
URL url = new URL ( urlStr ) ; // System . out . println ( " - - - - - url - - - - - " ) ;
// System . out . println ( urlStr ) ;
// System . out . println ( url . getPath ( ) ) ;
// System . out . println ( url . getHost ( ) ) ;
// System . out . println ( " - - - - - " ) ;
InputStream inputStream = null ; if ( url . getHost ( ) . trim ( ) . equals ( "" ) ) { // inputStream = new FileInputStream ( url . getFile ( ) ) ;
File file = new File ( url . getFile ( ) ) ; return file ; } else { inputStream = url . openStream ( ) ; } return readInputStream ( inputStream ) ;


signature:
public class FileHelper { /** * 从流读取文件内容 < br >
 * 2013-9-2 下午2:52:39
 * @ param inputStream
 * @ return */
public static File readInputStream ( InputStream inputStream ) { } }

implementation: String filePath = System . getProperty ( "java.io.tmpdir" , "tmp/" ) ; filePath += System . currentTimeMillis ( ) + StringUtil . randomString ( 8 ) + ".tmp" ; return readInputStream ( inputStream , filePath ) ;


signature:
public class FileHelper { /** * 将文件转换为URL地址 < br >
 * 2013-9-2 下午10:07:14
 * @ param file
 * @ return */
public static URL toURL ( File file ) { } }

implementation: if ( file == null || ! file . exists ( ) ) { return null ; } URI uri = file . toURI ( ) ; URL url = null ; try { url = uri . toURL ( ) ; } catch ( MalformedURLException e ) { LOGGER . error ( e ) ; } return url ;


signature:
public class FileHelper { /** * 将流读入到文件内 < br >
 * 2013-9-2 下午10:04:17
 * @ param inputStream
 * @ param file
 * @ return */
public static File readInputStream ( InputStream inputStream , File file ) { } }

implementation:
try { validateFile ( file ) ; } catch ( Exception e2 ) { e2 . printStackTrace ( ) ; } try { FileOutputStream outputStream = new FileOutputStream ( file ) ; int length = - 1 ; try { int bufferSize = 128 ; byte [ ] buffer = new byte [ bufferSize ] ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { if ( length != bufferSize ) { System . arraycopy ( buffer , 0 , buffer , 0 , length ) ; } outputStream . write ( buffer ) ; } } catch ( IOException e ) { LOGGER . error ( e ) ; } finally { // try {
// inputStream . close ( ) ;
// } catch ( IOException e1 ) {
// e1 . printStackTrace ( ) ;
try { inputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } try { outputStream . flush ( ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } try { outputStream . close ( ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } } } catch ( FileNotFoundException e1 ) { e1 . printStackTrace ( ) ; return null ; } return file ;


signature:
public class FileHelper { /** * 读取指定文件的文件内容 ( 以String的形式 ) < br >
 * 2013-8-30 下午5:26:55
 * @ param file
 * @ return */
public static String readFileToString ( File file ) { } }

implementation: byte [ ] bts = null ; try { bts = readFileToBytes ( file ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } String content = null ; try { content = new String ( bts , getEncode ( file ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return content ;


signature:
public class FileHelper { /** * 将源文件剪切到目标文件
 * @ param originFile 源文件
 * @ param targetFile 目标文件
 * @ return */
public static boolean cutFile ( File originFile , File targetFile ) { } }

implementation: Assert . notNull ( originFile ) ; Assert . notNull ( targetFile ) ; copyFile ( originFile , targetFile ) ; if ( originFile . length ( ) == targetFile . length ( ) ) { return originFile . delete ( ) ; } return false ;


signature:
public class FileHelper { /** * 读取inputStream并返回字节数组 < br >
 * 2013-9-3 下午12:10:06
 * @ param inputStream
 * @ return */
public static byte [ ] readInputStreamToBytes ( InputStream inputStream ) throws Exception { } }

implementation:
byte [ ] data = null ; try { int bufferSize = 128 ; byte [ ] buffer = new byte [ bufferSize ] ; int offset = 0 ; ByteBuffer byteBuffer = ByteBuffer . allocate ( 1024 ) ; int length = - 1 ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { // if ( length ! = bufferSize ) {
// System . arraycopy ( buffer , 0 , data , offset , length ) ;
// System . arraycopy ( buffer , 0 , data , offset , length ) ; / / 从缓冲区拷贝数组
if ( offset + length > byteBuffer . limit ( ) ) { byteBuffer = growByteBuffer ( byteBuffer , ( int ) ( byteBuffer . limit ( ) * 1.5 ) ) ; } byteBuffer . put ( buffer , 0 , length ) ; offset += length ; } byteBuffer . flip ( ) ; // byteBuffer . limit ( offset ) ;
data = new byte [ offset ] ; byteBuffer . get ( data , 0 , offset ) ; // data = byteBuffer . array ( ) ;
} catch ( IOException e ) { LOGGER . error ( e ) ; } finally { try { inputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } return data ;


signature:
public class FileHelper { /** * 读取文件内容并返回字节数组 < br >
 * 2013-9-3 下午12:10:06
 * @ param iconFile
 * @ return */
public static byte [ ] readFileToBytes ( File iconFile ) throws Exception { } }

implementation:
try { validateFile ( iconFile ) ; } catch ( Exception e2 ) { e2 . printStackTrace ( ) ; } long fileSize = iconFile . length ( ) ; if ( fileSize > Integer . MAX_VALUE ) { throw new Exception ( "读取的文件过大！" ) ; } byte [ ] data = new byte [ ( int ) fileSize ] ; // 由于文件已经确定 , 因此大小也可以确定
try { int length = - 1 ; FileInputStream inputStream = new FileInputStream ( iconFile ) ; try { int bufferSize = 128 ; byte [ ] buffer = new byte [ bufferSize ] ; int offset = 0 ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { // if ( length ! = bufferSize ) {
// System . arraycopy ( buffer , 0 , data , offset , length ) ;
System . arraycopy ( buffer , 0 , data , offset , length ) ; // 从缓冲区拷贝数组
offset += length ; } } catch ( IOException e ) { LOGGER . error ( e ) ; } finally { try { inputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } } catch ( FileNotFoundException e1 ) { e1 . printStackTrace ( ) ; return null ; } return data ;


signature:
public class FileHelper { /** * 将字节组写入文件 < br >
 * 2013-9-3 下午2:39:21
 * @ param data
 * @ param file */
public static File writeBytesToFile ( byte [ ] data , File file ) { } }

implementation: try { validateFile ( file ) ; } catch ( Exception e1 ) { e1 . printStackTrace ( ) ; } FileOutputStream outputStream = null ; try { outputStream = new FileOutputStream ( file ) ; outputStream . write ( data ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; LOGGER . error ( e ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; LOGGER . error ( e ) ; } finally { if ( outputStream != null ) { try { outputStream . flush ( ) ; outputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; LOGGER . error ( e ) ; } } } return file ;


signature:
public class FileHelper { /** * 将字符串写入文件 < br >
 * 2013-9-6 下午12:09:45
 * @ param file
 * @ param string
 * @ return */
public static File writeStringToFile ( File file , String string ) { } }

implementation: try { byte [ ] bts = string . getBytes ( getEncode ( file ) ) ; file = writeBytesToFile ( bts , file ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; ; LOGGER . error ( e ) ; } return file ;


signature:
public class FileHelper { /** * 将对象写入文件 < br >
 * 2013-9-6 下午1:08:58
 * @ param targetFile
 * @ param serializable */
public static void serializeObjectToFile ( File targetFile , Serializable serializable ) { } }

implementation: FileOutputStream fileOutputStream = null ; ObjectOutputStream objectOutputStream = null ; try { fileOutputStream = new FileOutputStream ( targetFile ) ; try { objectOutputStream = new ObjectOutputStream ( fileOutputStream ) ; objectOutputStream . writeObject ( serializable ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } } catch ( FileNotFoundException e ) { LOGGER . error ( e ) ; } finally { closeOutStream ( objectOutputStream ) ; closeOutStream ( fileOutputStream ) ; }


signature:
public class SystemPropertyUtils { /** * Resolve $ { . . . } placeholders in the given text , replacing them with corresponding system property values .
 * Unresolvable placeholders with no default value are ignored and passed through unchanged if the
 * flag is set to true .
 * @ param text the String to resolve
 * @ param ignoreUnresolvablePlaceholders flag to determine is unresolved placeholders are ignored
 * @ return the resolved String
 * @ throws IllegalArgumentException if there is an unresolvable placeholder and the flag is false
 * @ see # PLACEHOLDER _ PREFIX
 * @ see # PLACEHOLDER _ SUFFIX */
public static String resolvePlaceholders ( String text , boolean ignoreUnresolvablePlaceholders ) { } }

implementation: PropertyPlaceholderHelper helper = ( ignoreUnresolvablePlaceholders ? nonStrictHelper : strictHelper ) ; return helper . replacePlaceholders ( text , new SystemPropertyPlaceholderResolver ( text ) ) ;


signature:
public class CodeProcessor { /** * - - - - - 包定义和导入包 - - - - - */
private String findPackage ( ) { } }

implementation: Matcher matcher = PATTERN_FIND_PACKAGE . matcher ( content ) ; if ( matcher . find ( ) ) { return matcher . group ( ) ; } return null ;


signature:
public class CodeProcessor { /** * 检查导入包
 * @ return */
private void checkImport ( ) { } }

implementation:
Set < String > classImports = new HashSet < String > ( ) ; classImports . addAll ( builder . getImports ( ) ) ; classImports . removeAll ( findImports ( content ) ) ; // 移除已经导入的包
Set < String > classImportsToRemove = new HashSet < String > ( ) ; // 如果要导入的包与类所在的package一致 , 则忽略导入
final String packageStr = findPackage ( ) ; // 类所定义的包路径
if ( packageStr != null ) { // 如果定义了包路径 , 则在包路径后面新增导入
String packageName = findPackageName ( packageStr ) ; for ( String impt : classImports ) { int point = impt . lastIndexOf ( "." ) ; String pkgNameOfImport = impt . substring ( 0 , point ) ; // 截取import的类所属包
if ( pkgNameOfImport . equals ( packageName ) ) { // 如果包已经导入 , 则取消导入
classImportsToRemove . add ( impt ) ; } } classImports . removeAll ( classImportsToRemove ) ; // 如果定义了包路径 , 则在包路径后面新增导入
StringBuilder builder = new StringBuilder ( packageStr ) ; builder . append ( StringHelper . line ( ) ) ; for ( String toImport : classImports ) { builder . append ( StringHelper . line ( ) ) ; builder . append ( "import " ) ; builder . append ( toImport ) ; builder . append ( ";" ) ; } content = StringHelper . replaceFirst ( content , packageStr , builder . toString ( ) ) ; } else { // 如果没有定义包 , 则在头部导入包
StringBuilder builder = new StringBuilder ( ) ; for ( String toImport : classImports ) { builder . append ( StringHelper . line ( ) ) ; builder . append ( "import " ) ; builder . append ( toImport ) ; builder . append ( ";" ) ; } content = builder . append ( content ) . toString ( ) ; }


signature:
public class CodeProcessor { /** * 检查class定义段 */
private void checkClass ( ) { } }

implementation:
Matcher findClassMatcher = PATTERN_FIND_CLASS_SEGMENT . matcher ( content ) ; if ( findClassMatcher . find ( ) ) { final String classDefine = findClassMatcher . group ( ) ; // 查找类定义
String classDefineReplace = checkSuperClass ( classDefine ) ; classDefineReplace = checkInterfaces ( classDefineReplace ) ; content = StringHelper . replaceFirst ( content , classDefine , classDefineReplace ) ; }


signature:
public class CodeProcessor { /** * 查找已有的接口定义
 * @ param interfaceDefineString 接口定义字符串
 * @ return */
private Set < String > findInterfaces ( String interfaceDefineString ) { } }

implementation: String interfaceStrings = StringHelper . replaceFirst ( interfaceDefineString , "implements" , "" ) ; String [ ] interfaces = interfaceStrings . split ( "," ) ; Set < String > stringSet = new HashSet < String > ( ) ; for ( String interfaceString : interfaces ) { stringSet . add ( interfaceString . trim ( ) ) ; } return stringSet ;


signature:
public class CodeProcessor { /** * 检查implements关键字
 * @ param classSegment
 * @ return */
private String checkInterfaces ( String classSegment ) { } }

implementation:
if ( builder . getInterfaces ( ) == null || builder . getInterfaces ( ) . size ( ) == 0 ) { return classSegment ; } Matcher matcher = PATTERN_FIND_INTERCES . matcher ( classSegment ) ; if ( matcher . find ( ) ) { final String interfaceDefineString = matcher . group ( ) ; Set < String > interfaceSet = findInterfaces ( interfaceDefineString ) ; StringBuilder interfaceDefineStringReplace = new StringBuilder ( interfaceDefineString ) ; for ( String interfaceName : builder . getInterfaces ( ) ) { if ( interfaceSet . contains ( interfaceName ) ) { // 如果已经存在接口的定义 , 则跳过该定义
continue ; } interfaceDefineStringReplace . append ( ", " ) ; interfaceDefineStringReplace . append ( interfaceName ) ; } classSegment = StringHelper . replaceFirst ( classSegment , interfaceDefineString , interfaceDefineStringReplace . toString ( ) ) ; } else { final String interfaceDefineString = "{" ; StringBuilder interfaceDefineStringReplace = new StringBuilder ( "implements " ) ; boolean isFirstInterface = true ; for ( String interfaceName : builder . getInterfaces ( ) ) { if ( ! isFirstInterface ) { interfaceDefineStringReplace . append ( ", " ) ; } if ( isFirstInterface ) { isFirstInterface = false ; } interfaceDefineStringReplace . append ( interfaceName ) ; } interfaceDefineStringReplace . append ( interfaceDefineString ) ; classSegment = StringHelper . replaceFirst ( classSegment , interfaceDefineString , interfaceDefineStringReplace . toString ( ) ) ; } return classSegment ;


signature:
public class CodeProcessor { /** * 检查extends关键字
 * @ param classSegment
 * @ return */
private String checkSuperClass ( String classSegment ) { } }

implementation: if ( builder . isRemoveSuperClass ( ) || builder . getSuperClass ( ) != null ) { Matcher matcher = PATTERN_FIND_SUPER_CLASS . matcher ( classSegment ) ; String superClassString = "" ; if ( builder . getSuperClass ( ) != null ) { superClassString = "extends " + builder . getSuperClass ( ) + " " ; } if ( matcher . find ( ) ) { String replacement = matcher . group ( ) ; classSegment = StringHelper . replaceFirst ( classSegment , replacement , superClassString ) ; } else { Matcher classNameMatcher = PATTERN_FIND_CLASS_NAME . matcher ( classSegment ) ; if ( classNameMatcher . find ( ) ) { String className = classNameMatcher . group ( ) ; String justClassName = findClassName ( className ) ; if ( justClassName != null && justClassName . equals ( builder . getSuperClass ( ) ) ) { return classSegment ; } classSegment = StringHelper . replaceFirst ( classSegment , className , className + superClassString ) ; } } } return classSegment ;


signature:
public class CodeProcessor { /** * - - - - - 代码段 - - - - - */
private void checkCodeFragment ( ) { } }

implementation: Matcher matcher = PATTERN_FIND_CLASS_SEGMENT . matcher ( content ) ; if ( matcher . find ( ) ) { final String classDefine = matcher . group ( ) ; StringBuilder builder = new StringBuilder ( classDefine ) ; for ( String codeFragment : this . builder . getCodeFragments ( ) ) { builder . append ( StringHelper . line ( ) ) ; builder . append ( codeFragment ) ; } content = StringHelper . replaceFirst ( content , classDefine , builder . toString ( ) ) ; }


signature:
public class CodeProcessor { /** * - - - - - 移除注解 - - - - - */
private void checkAnnotations ( ) { } }

implementation:
if ( ! builder . isRemoveAnnotations ( ) ) { return ; } Matcher matcher = PATTERN_FIND_ANNOTAION . matcher ( content ) ; while ( matcher . find ( ) ) { final String annotation = matcher . group ( ) ; // StringBuilder builder = new StringBuilder ( annotation ) ;
// for ( String codeFragment : this . builder . getCodeFragments ( ) ) {
// builder . append ( StringHelper . line ( ) ) ;
// builder . append ( codeFragment ) ;
content = StringHelper . replaceFirst ( content , annotation , "" ) ; EntityHelper . print ( content ) ; }


signature:
public class GetDocumentPathDemo { /** * returns the Path to the " My Documents " folder or < code > null < / code >
 * @ return { @ link String } */
public static String getMyDocumentsFromWinRegistry ( ) { } }

implementation: try { Process process = Runtime . getRuntime ( ) . exec ( PERSONAL_FOLDER_CMD ) ; StreamReader streamreader = new StreamReader ( process . getInputStream ( ) ) ; streamreader . start ( ) ; process . waitFor ( ) ; streamreader . join ( ) ; String result = streamreader . getResult ( ) ; int p = result . indexOf ( REGSTR_TOKEN ) ; if ( p == - 1 ) return null ; return result . substring ( p + REGSTR_TOKEN . length ( ) ) . trim ( ) ; } catch ( Exception e ) { return null ; }


signature:
public class PhoneNumberAddress { /** * Test the phone number from which the city is using Taobao API
 * @ return
 * @ param mobileNumber phone number */
public static String calcMobileCity ( String mobileNumber ) throws MalformedURLException { } }

implementation:
ObjectMapper objectMapper = new ObjectMapper ( ) ; String jsonString = null ; String urlString = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobileNumber ; StringBuffer sb = new StringBuffer ( ) ; BufferedReader buffer ; URL url = new URL ( urlString ) ; try { InputStream in = url . openStream ( ) ; // solve the garbage problem
buffer = new BufferedReader ( new InputStreamReader ( in , "gb2312" ) ) ; String line = null ; while ( ( line = buffer . readLine ( ) ) != null ) { sb . append ( line ) ; } in . close ( ) ; buffer . close ( ) ; // System . out . println ( sb . toString ( ) ) ;
jsonString = sb . toString ( ) ; EntityHelper . print ( jsonString ) ; // replace \
jsonString = jsonString . replaceAll ( "^[__]\\w{14}+[_ = ]+" , "[" ) ; // System . out . println ( jsonString + " ] " ) ;
String jsonString2 = jsonString + "]" ; // json object into the STRING
// array = JSONArray . fromObject ( jsonString2 ) ;
// Get JSONArray of JSONObject object , easy to read array of key - value pairs in
// jsonObject = array . getJSONObject ( 0 ) ;
} catch ( Exception e ) { e . printStackTrace ( ) ; } // return jsonObject . getString ( " province " ) ;
return null ;


signature: public class PhoneNumberAddress { public static void main ( String [ ] args ) throws Exception { } }

implementation:
TimerHelper . getTime ( ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < 100 ; i ++ ) { long number = 13000000000L + random . nextInt ( 1000000000 ) ; String testMobileNumber = "" + number ; // System . out . println ( getMobileAddress ( testMobileNumber ) ) ;
ThreadPool . invoke ( null , PhoneNumberAddress . class . getMethod ( "getMobileAddress" , String . class ) , testMobileNumber ) ; } ThreadPool . shutDown ( ) ; System . out . println ( TimerHelper . getTime ( ) ) ; // System . out . println ( calcMobilesCities ( mobileList ) . toString ( ) ) ;


signature:
public class ComparatorHelper { /** * 按照日期进行排序 < br >
 * 2013-6-25 下午9:46:45
 * @ param collection 要排序的集合
 * @ param field 指定排序的时间字段
 * @ param asc 是否按正序排序
 * @ return List */
@ SuppressWarnings ( "unchecked" ) public List sortByDateTime ( Collection < ? extends T > collection , final Field field , final boolean asc ) { } }

implementation: if ( collection == null ) { return null ; } List list = new ArrayList ( ) ; list . addAll ( collection ) ; Collections . sort ( list , new Comparator < T > ( ) { @ Override public int compare ( T o1 , T o2 ) { Object object = invokeMethod ( o1 , field ) ; Object object2 = invokeMethod ( o2 , field ) ; if ( object == null || object2 == null ) { return 0 ; } int value = 0 ; if ( object instanceof Date ) { Date v1 = ( Date ) object ; Date v2 = ( Date ) object2 ; if ( v1 . getTime ( ) < v2 . getTime ( ) ) { value = - 1 ; } else if ( v1 . getTime ( ) > v2 . getTime ( ) ) { value = 1 ; } if ( ! asc ) { value = - value ; } } return value ; } } ) ; return list ;


signature:
public class TransformerUtils { /** * Enable indenting for the supplied { @ link javax . xml . transform . Transformer } . < p > If the underlying XSLT engine is
 * Xalan , then the special output key { @ code indent - amount } will be also be set to a value of { @ link
 * # DEFAULT _ INDENT _ AMOUNT } characters .
 * @ param transformer the target transformer
 * @ param indentAmount the size of the indent ( 2 characters , 3 characters , etc . )
 * @ see javax . xml . transform . Transformer # setOutputProperty ( String , String )
 * @ see javax . xml . transform . OutputKeys # INDENT */
public static void enableIndenting ( Transformer transformer , int indentAmount ) { } }

implementation:
Assert . notNull ( transformer , "Transformer must not be null" ) ; Assert . isTrue ( indentAmount > - 1 , "The indent amount cannot be less than zero : got " + indentAmount ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; try { // Xalan - specific , but this is the most common XSLT engine in any case
transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , String . valueOf ( indentAmount ) ) ; } catch ( IllegalArgumentException ignored ) { }


signature:
public class TransformerUtils { /** * Disable indenting for the supplied { @ link javax . xml . transform . Transformer } .
 * @ param transformer the target transformer
 * @ see javax . xml . transform . OutputKeys # INDENT */
public static void disableIndenting ( Transformer transformer ) { } }

implementation: Assert . notNull ( transformer , "Transformer must not be null" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "no" ) ;


signature:
public class TimerHelper { /** * 获取与上个计时点以毫秒为单位的时差 , 如果是第一个计时点 , 则开始即时并返回0 < br >
 * 此方法是以线程和调用类来区别计时的 , 即 : 不同的类或不同的线程都会导致计时器的从0开始计时 < br >
 * 2013-7-26 下午6:21:40
 * @ return long */
public static long getTime ( ) { } }

implementation:
// StackTraceHelper . printStackTrace ( ) ;
StackTraceElement [ ] stackTraceElements = StackTraceHelper . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; // 调用本类的对象类型堆栈
String clazz = stackTraceElement . getClassName ( ) ; // 调用本类的对象类型
Thread thread = Thread . currentThread ( ) ; TimerHolder holder = new TimerHolder ( ) ; holder . setObject ( clazz ) ; holder . setThread ( thread ) ; // String methodName = stackTraceElement . getMethodName ( ) ;
// int lineNumber = stackTraceElement . getLineNumber ( ) ;
// long hashCode = 17;
// hashCode = 37 * hashCode + clazz . hashCode ( ) ;
// hashCode = 37 * hashCode + methodName . hashCode ( ) ;
// hashCode = 37 * hashCode + lineNumber ;
// System . out . println ( " stackTraceElement . getClassName ( ) = = = = = " +
// stackTraceElement . getClassName ( ) ) ;
Long startTime = holderObjects . get ( holder ) ; // System . out . println ( stackTraceElement ) ;
if ( startTime == null ) { startTime = System . currentTimeMillis ( ) ; } long time = System . currentTimeMillis ( ) - startTime ; startTime = System . currentTimeMillis ( ) ; holderObjects . put ( holder , startTime ) ; return time ;


signature:
public class AbstractStaxXMLReader { /** * Convert a { @ code QName } to a qualified name , as used by DOM and SAX .
 * The returned string has a format of { @ code prefix : localName } if the
 * prefix is set , or just { @ code localName } if not .
 * @ param qName the { @ code QName }
 * @ return the qualified name */
protected String toQualifiedName ( QName qName ) { } }

implementation: String prefix = qName . getPrefix ( ) ; if ( ! StringUtils . hasLength ( prefix ) ) { return qName . getLocalPart ( ) ; } else { return prefix + ":" + qName . getLocalPart ( ) ; }


signature:
public class AbstractStaxXMLReader { /** * Starts the prefix mapping for the given prefix .
 * @ see org . xml . sax . ContentHandler # startPrefixMapping ( String , String ) */
protected void startPrefixMapping ( String prefix , String namespace ) throws SAXException { } }

implementation: if ( getContentHandler ( ) != null ) { if ( prefix == null ) { prefix = "" ; } if ( ! StringUtils . hasLength ( namespace ) ) { return ; } if ( ! namespace . equals ( namespaces . get ( prefix ) ) ) { getContentHandler ( ) . startPrefixMapping ( prefix , namespace ) ; namespaces . put ( prefix , namespace ) ; } }


signature:
public class AbstractStaxXMLReader { /** * Ends the prefix mapping for the given prefix .
 * @ see org . xml . sax . ContentHandler # endPrefixMapping ( String ) */
protected void endPrefixMapping ( String prefix ) throws SAXException { } }

implementation: if ( getContentHandler ( ) != null ) { if ( namespaces . containsKey ( prefix ) ) { getContentHandler ( ) . endPrefixMapping ( prefix ) ; namespaces . remove ( prefix ) ; } }


signature:
public class ListenableFutureCallbackRegistry { /** * Adds the given callback to this registry .
 * @ param callback the callback to add */
@ SuppressWarnings ( "unchecked" ) public void addCallback ( ListenableFutureCallback < ? super T > callback ) { } }

implementation: Assert . notNull ( callback , "'callback' must not be null" ) ; synchronized ( mutex ) { switch ( state ) { case NEW : callbacks . add ( callback ) ; break ; case SUCCESS : callback . onSuccess ( ( T ) result ) ; break ; case FAILURE : callback . onFailure ( ( Throwable ) result ) ; break ; } }


signature:
public class ListenableFutureCallbackRegistry { /** * Triggers a { @ link ListenableFutureCallback # onSuccess ( Object ) } call on all added
 * callbacks with the given result
 * @ param result the result to trigger the callbacks with */
public void success ( T result ) { } }

implementation: synchronized ( mutex ) { state = State . SUCCESS ; this . result = result ; while ( ! callbacks . isEmpty ( ) ) { callbacks . poll ( ) . onSuccess ( result ) ; } }


signature:
public class ListenableFutureCallbackRegistry { /** * Triggers a { @ link ListenableFutureCallback # onFailure ( Throwable ) } call on all added
 * callbacks with the given { @ code Throwable } .
 * @ param t the exception to trigger the callbacks with */
public void failure ( Throwable t ) { } }

implementation: synchronized ( mutex ) { state = State . FAILURE ; this . result = t ; while ( ! callbacks . isEmpty ( ) ) { callbacks . poll ( ) . onFailure ( t ) ; } }


signature:
public class MD5Helper { /** * MD5 加密 , 结果默认为小写 < br >
 * 2013-11-4 下午6:33:06
 * @ param message 要加密的内容
 * @ param encode message的编码方式
 * @ return 加密后的信息 */
public static String encrypt ( String message , String encode ) { } }

implementation: return encrypt ( message , encode , false ) ;


signature:
public class MD5Helper { /** * MD5 加密 < br >
 * 2013-11-4 下午6:33:06
 * @ param message 要加密的内容
 * @ param encode message的编码方式
 * @ param toUpperCase 是否转换成大写
 * @ return 加密后的信息 */
public static String encrypt ( String message , String encode , boolean toUpperCase ) { } }

implementation: MessageDigest messageDigest = null ; try { messageDigest = MessageDigest . getInstance ( "MD5" ) ; messageDigest . reset ( ) ; messageDigest . update ( message . getBytes ( encode ) ) ; } catch ( NoSuchAlgorithmException e ) { e . printStackTrace ( ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } byte [ ] byteArray = messageDigest . digest ( ) ; StringBuffer md5StrBuff = new StringBuffer ( ) ; for ( int i = 0 ; i < byteArray . length ; i ++ ) { if ( Integer . toHexString ( 0xFF & byteArray [ i ] ) . length ( ) == 1 ) { md5StrBuff . append ( "0" ) . append ( Integer . toHexString ( 0xFF & byteArray [ i ] ) ) ; } else { String hex = Integer . toHexString ( 0xFF & byteArray [ i ] ) ; if ( toUpperCase ) { hex = hex . toUpperCase ( ) ; } md5StrBuff . append ( hex ) ; } } return md5StrBuff . toString ( ) ;


signature:
public class FileUtil { /** * Cuts all path information of the String representation of the given URL .
 * < pre >
 * & quot ; file / / c : / work / programming / anyfile . jar & quot ; - - & gt ; & quot ; anyfile . jar & quot ;
 * & quot ; http : / / jamwg . de & quot ; - - & gt ; & quot ; & quot ; / / No file part .
 * & quot ; ftp : / / files . com / directory2 / & quot ; - - & gt ; & quot ; & quot ; / / File part of URL denotes a directory .
 * < / pre >
 * Assuming , that ' / ' is the current file separator character .
 * @ param path
 * the absolute file path you want the mere file name of .
 * @ return the < code > { @ link java . util . Map . Entry } < / code > consisting of path
 * information and file name . */
public static Map . Entry < String , String > cutDirectoryInformation ( final java . net . URL path ) { } }

implementation: Map . Entry < String , String > ret = null ; String pre ; String suf ; String parse ; final StringBuffer tmp = new StringBuffer ( ) ; parse = path . toExternalForm ( ) ; if ( parse . endsWith ( "/" ) ) { pre = parse ; suf = "" ; } else { final StringTokenizer tokenizer = new StringTokenizer ( path . getFile ( ) , "/" ) ; tmp . append ( path . getProtocol ( ) ) ; tmp . append ( ":" ) ; tmp . append ( path . getHost ( ) ) ; pre = "" ; while ( tokenizer . hasMoreElements ( ) ) { tmp . append ( pre ) ; pre = tokenizer . nextToken ( ) ; tmp . append ( "/" ) ; } suf = pre ; pre = tmp . toString ( ) ; } ret = new Entry < String , String > ( pre , suf ) ; return ret ;


signature:
public class FileUtil { /** * Cuts the path information of the String that is interpreted as a filename
 * into the directory part and the file part . The current operating system ' s
 * path separator is used to cut all path information from the String .
 * < pre >
 * & quot ; c : / work / programming / anyfile . jar & quot ; - - & gt ; Map . Entry ( & quot ; c : / work / programming / & quot ; , & quot ; anyfile . jar & quot ; ) ;
 * & quot ; anyfile . jar & quot ; - - & gt ; Map . Entry ( new File ( & quot ; . & quot ; ) . getAbsolutePath ( ) , & quot ; anyfile . jar & quot ; ) ;
 * & quot ; c : / directory1 / directory2 / & quot ; - - & gt ; Map . Entry ( & quot ; c : / directory1 / directory2 / & quot ; , & quot ; & quot ; ) ;
 * & quot ; c : / directory1 / directory2 & quot ; - - & gt ; Map . Entry ( & quot ; c : / directory1 / directory2 / & quot ; , & quot ; & quot ; ) ; / / directory2 is a dir !
 * & quot ; c : / directory1 / file2 & quot ; - - & gt ; Map . Entry ( & quot ; c : / directory1 / & quot ; , & quot ; file2 & quot ; ) ; / / file2 is a file !
 * & quot ; c : / & quot ; - - & gt ; Map . Entry ( & quot ; c : / & quot ; , & quot ; & quot ; ) ;
 * < / pre >
 * Assuming , that ' / ' is the current file separator character .
 * < b > If your string is retrieved from an < tt > URL < / tt > instance , use
 * < tt > cutDirectoryInformation ( URL path ) < / tt > instead , because URL ' s do not
 * depend on the operating systems file separator ! < / b >
 * @ param path
 * the absolute file path you want the mere file name of .
 * @ return the < code > { @ link java . util . Map . Entry } < / code > consisting of path
 * information and file name . */
public static Map . Entry < String , String > cutDirectoryInformation ( final String path ) { } }

implementation:
final StringBuffer dir = new StringBuffer ( ) ; String file = "" ; final String fileseparator = System . getProperty ( "file.separator" ) ; final StringTokenizer tokenizer = new StringTokenizer ( path , fileseparator ) ; final int size = tokenizer . countTokens ( ) ; switch ( size ) { case 0 : dir . append ( new File ( "." ) . getAbsolutePath ( ) ) ; break ; case 1 : final File test = new File ( tokenizer . nextToken ( ) ) ; if ( new File ( path ) . isDirectory ( ) ) { dir . append ( test . getAbsolutePath ( ) ) ; } else { dir . append ( new File ( "." ) . getAbsolutePath ( ) ) ; file = path ; } break ; default : String token ; while ( tokenizer . hasMoreElements ( ) ) { // reuse String file separator : bad style . . .
token = tokenizer . nextToken ( ) ; if ( tokenizer . hasMoreTokens ( ) ) { dir . append ( token ) ; dir . append ( fileseparator ) ; } else { if ( new File ( path ) . isFile ( ) ) { file = token ; } else { dir . append ( token ) ; } } } } return new Entry < String , String > ( dir . toString ( ) , file ) ;


signature:
public class FileUtil { /** * Cuts a String into the part before the last dot and after the last dot . If
 * only one dot is contained on the first position , it will completely be used
 * as prefix part .
 * < pre >
 * Map . Entry entry = FileUtil . getPotentialExtension ( & quot ; A . Very . Strange . Name . txt & quot ; ) ;
 * String prefix = ( String ) entry . getKey ( ) ; / / prefix is & quot ; A . Very . Strange . Name & quot ; .
 * String suffix = ( String ) entry . getValue ( ) ; / / suffix is & quot ; txt & quot ; ;
 * entry = FileUtil . getPotentialExtension ( & quot ; . profile & quot ; ) ;
 * String prefix = ( String ) entry . getKey ( ) ; / / prefix is & quot ; . profile & quot ; .
 * String suffix = ( String ) entry . getValue ( ) ; / / suffix is & quot ; & quot ; ;
 * entry = FileUtil . getPotentialExtension ( & quot ; bash & quot ; ) ;
 * String prefix = ( String ) entry . getKey ( ) ; / / prefix is & quot ; bash & quot ; .
 * String suffix = ( String ) entry . getValue ( ) ; / / suffix is & quot ; & quot ; ;
 * < / pre >
 * @ param filename
 * A String that is interpreted to be a file name : The last dot ( ' . ' )
 * is interpreted to be the extension delimiter .
 * @ return A < tt > java . util . Map . Entry < / tt > instance containing a String for
 * the filename at the key side and a String for the extension at the
 * value side . */
public static Map . Entry < String , String > cutExtension ( final String filename ) { } }

implementation: String prefix ; String suffix = null ; final StringTokenizer tokenizer = new StringTokenizer ( filename , "." ) ; int tokenCount = tokenizer . countTokens ( ) ; if ( tokenCount > 1 ) { final StringBuffer prefCollect = new StringBuffer ( ) ; while ( tokenCount > 1 ) { tokenCount -- ; prefCollect . append ( tokenizer . nextToken ( ) ) ; if ( tokenCount > 1 ) { prefCollect . append ( "." ) ; } } prefix = prefCollect . toString ( ) ; suffix = tokenizer . nextToken ( ) ; } else { prefix = filename ; suffix = "" ; } return new Entry < String , String > ( prefix , suffix ) ;


signature:
public class FileUtil { /** * Finds a filename based on the given name . If a file with the given name
 * does not exist , < tt > name < / tt > will be returned .
 * Else :
 * < pre >
 * & quot ; myFile . out & quot ; - - & gt ; & quot ; myFile _ 0 . out & quot ;
 * & quot ; myFile _ 0 . out & quot ; - - & gt ; & quot ; myFile _ 1 . out & quot ;
 * & quot ; myFile _ 1 . out & quot ; - - & gt ; & quot ; myFile _ 2 . out & quot ;
 * < / pre >
 * The potential extension is preserved , but a number is appended to the
 * prefix name .
 * @ param name
 * A desired file name .
 * @ return A String that sticks to the naming convention of the given String
 * but is unique in the directory scope of argument < tt > name < / tt > . */
public static String getDefaultFileName ( final String name ) { } }

implementation: String result ; File f = new File ( name ) ; if ( ! f . exists ( ) ) { result = f . getAbsolutePath ( ) ; } else { final Map . Entry < String , String > cut = FileUtil . cutExtension ( name ) ; final String prefix = cut . getKey ( ) ; final String suffix = cut . getValue ( ) ; int num = 0 ; while ( f . exists ( ) ) { f = new File ( prefix + '_' + num + '.' + suffix ) ; num ++ ; } result = f . getAbsolutePath ( ) ; } return result ;


signature:
public class FileUtil { /** * Returns the singleton instance of this class .
 * @ return the singleton instance of this class . */
public static FileUtil getInstance ( ) { } }

implementation: if ( FileUtil . instance == null ) { FileUtil . instance = new FileUtil ( ) ; } return FileUtil . instance ;


signature:
public class FileUtil { /** * Tests wether the given input stream only contains ASCII characters if
 * interpreted by reading bytes ( 16 bit ) .
 * This does not mean that the underlying content is really an ASCII text
 * file . It just might be viewed with an editor showing only valid ASCII
 * characters .
 * @ param in
 * the stream to test .
 * @ return true if all bytes in the given input stream are in the ASCII range .
 * @ throws java . io . IOException
 * on a bad day . */
public static boolean isAllASCII ( final InputStream in ) throws IOException { } }

implementation: boolean ret = true ; int read = - 1 ; do { read = in . read ( ) ; if ( read > 0x7F ) { ret = false ; break ; } } while ( read != - 1 ) ; return ret ;


signature:
public class FileUtil { /** * Tests , wether the content of the given file is identical at character
 * level , when it is opened with both different Charsets .
 * This is most often the case , if the given file only contains ASCII codes
 * but may also occur , when both codepages cover common ranges and the
 * document only contains values m _ out of those ranges ( like the EUC - CN
 * charset contains all mappings from BIG5 ) .
 * @ param document
 * the file to test .
 * @ param a
 * the first character set to interpret the document in .
 * @ param b
 * the 2nd character set to interpret the document in .
 * @ throws java . io . IOException
 * if something goes wrong .
 * @ return true if both files have all equal contents if they are interpreted
 * as character data in both given encodings ( they may differ at
 * binary level if both charsets are different ) . */
public static boolean isEqual ( final File document , final Charset a , final Charset b ) throws IOException { } }

implementation:
boolean ret = true ; FileInputStream aIn = null ; FileInputStream bIn = null ; InputStreamReader aReader = null ; InputStreamReader bReader = null ; try { aIn = new FileInputStream ( document ) ; bIn = new FileInputStream ( document ) ; aReader = new InputStreamReader ( aIn , a ) ; bReader = new InputStreamReader ( bIn , b ) ; int readA = - 1 ; int readB = - 1 ; do { readA = aReader . read ( ) ; readB = bReader . read ( ) ; if ( readA != readB ) { // also the case , if one is at the end earlier . . .
ret = false ; break ; } } while ( ( readA != - 1 ) && ( readB != - 1 ) ) ; return ret ; } finally { if ( aReader != null ) { aReader . close ( ) ; } if ( bReader != null ) { bReader . close ( ) ; } }


signature:
public class FileUtil { /** * Reads the content of the given File into an array .
 * This method currently does not check for maximum length and might cause a
 * java . lang . OutOfMemoryError . It is only intended for
 * performance - measurements of data - based algorithms that want to exclude
 * I / O - usage .
 * @ param f
 * the file to read .
 * @ throws java . io . IOException
 * if something goes wrong .
 * @ return the contents of the given file . */
public static byte [ ] readRAM ( final File f ) throws IOException { } }

implementation: final int total = ( int ) f . length ( ) ; final byte [ ] ret = new byte [ total ] ; final InputStream in = new FileInputStream ( f ) ; try { int offset = 0 ; int read = 0 ; do { read = in . read ( ret , offset , total - read ) ; if ( read > 0 ) { offset += read ; } } while ( ( read != - 1 ) && ( offset != total ) ) ; return ret ; } finally { in . close ( ) ; }


signature:
public class FileUtil { /** * Removes the duplicate line breaks in the given file .
 * Be careful with big files : In order to avoid having to write a tmpfile
 * ( cannot read and directly write to the same file ) a StringBuffer is used
 * for manipulation . Big files will cost all RAM and terminate VM hard .
 * @ param f
 * the file to remove duplicate line breaks in . */
public static void removeDuplicateLineBreaks ( final File f ) { } }

implementation:
final String sep = StringUtil . getNewLine ( ) ; if ( ! f . exists ( ) ) { System . err . println ( "FileUtil.removeDuplicateLineBreak(File f): " + f . getAbsolutePath ( ) + " does not exist!" ) ; } else { if ( f . isDirectory ( ) ) { System . err . println ( "FileUtil.removeDuplicateLineBreak(File f): " + f . getAbsolutePath ( ) + " is a directory!" ) ; } else { // real file
FileInputStream inStream = null ; BufferedInputStream in = null ; FileWriter out = null ; try { inStream = new FileInputStream ( f ) ; in = new BufferedInputStream ( inStream , 1024 ) ; StringBuffer result = new StringBuffer ( ) ; int tmpread ; while ( ( tmpread = in . read ( ) ) != - 1 ) { result . append ( ( char ) tmpread ) ; } String tmpstring ; final StringTokenizer toke = new StringTokenizer ( result . toString ( ) , sep , true ) ; result = new StringBuffer ( ) ; int breaks = 0 ; while ( toke . hasMoreTokens ( ) ) { tmpstring = toke . nextToken ( ) . trim ( ) ; if ( tmpstring . equals ( "" ) && ( breaks > 0 ) ) { breaks ++ ; // if ( breaks < = 2 ) result . append ( sep ) ;
continue ; } if ( tmpstring . equals ( "" ) ) { tmpstring = sep ; breaks ++ ; } else { breaks = 0 ; } result . append ( tmpstring ) ; } // delete original file and write it new from tmpfile .
f . delete ( ) ; f . createNewFile ( ) ; out = new FileWriter ( f ) ; out . write ( result . toString ( ) ) ; } catch ( final FileNotFoundException e ) { // does never happen .
} catch ( final IOException g ) { g . printStackTrace ( System . err ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } if ( out != null ) { try { out . flush ( ) ; out . close ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } } } }


signature:
public class FileUtil { /** * Returns the formatted file size to Bytes , KB , MB or GB depending on the
 * given value .
 * @ param filesize
 * in bytes
 * @ param locale
 * the locale to translate the result to ( e . g . in France they us
 * @ return the formatted filesize to Bytes , KB , MB or GB depending on the
 * given value . */
public String formatFilesize ( final long filesize , final Locale locale ) { } }

implementation:
String result ; final long filesizeNormal = Math . abs ( filesize ) ; if ( Math . abs ( filesize ) < 1024 ) { result = MessageFormat . format ( this . m_bundle . getString ( "GUI_FILEUTIL_FILESIZE_BYTES_1" ) , new Object [ ] { new Long ( filesizeNormal ) } ) ; } else if ( filesizeNormal < 1048576 ) { // 1048576 = 1024.0 * 1024.0
result = MessageFormat . format ( this . m_bundle . getString ( "GUI_FILEUTIL_FILESIZE_KBYTES_1" ) , new Object [ ] { new Double ( filesizeNormal / 1024.0 ) } ) ; } else if ( filesizeNormal < 1073741824 ) { // 1024.0 ^ 3 = 1073741824
result = MessageFormat . format ( this . m_bundle . getString ( "GUI_FILEUTIL_FILESIZE_MBYTES_1" ) , new Object [ ] { new Double ( filesize / 1048576.0 ) } ) ; } else { result = MessageFormat . format ( this . m_bundle . getString ( "GUI_FILEUTIL_FILESIZE_GBYTES_1" ) , new Object [ ] { new Double ( filesizeNormal / 1073741824.0 ) } ) ; } return result ;


signature:
public class Base64 { /** * end encode3to4 */
private static byte [ ] encode3to4 ( byte [ ] source , int srcOffset , int numSigBytes , byte [ ] destination , int destOffset ) { } }

implementation:
// 1 2 3
// 01234567890123456789012345678901 Bit position
// - - - - - 000001111122222 Array position from threeBytes
// - - - - - | | | | | | | | Six bit groups to index ALPHABET
// > > 18 > > 12 > > 6 > > 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero - padding if there are only one or two
// significant bytes passed in the array .
// We have to shift left 24 in order to flush out the 1 ' s that appear
// when Java treats a value as negative that is cast from a byte to an
// int .
int inBuff = ( numSigBytes > 0 ? ( ( source [ srcOffset ] << 24 ) >>> 8 ) : 0 ) | ( numSigBytes > 1 ? ( ( source [ srcOffset + 1 ] << 24 ) >>> 16 ) : 0 ) | ( numSigBytes > 2 ? ( ( source [ srcOffset + 2 ] << 24 ) >>> 24 ) : 0 ) ; switch ( numSigBytes ) { case 3 : destination [ destOffset ] = ALPHABET [ ( inBuff >>> 18 ) ] ; destination [ destOffset + 1 ] = ALPHABET [ ( inBuff >>> 12 ) & 0x3f ] ; destination [ destOffset + 2 ] = ALPHABET [ ( inBuff >>> 6 ) & 0x3f ] ; destination [ destOffset + 3 ] = ALPHABET [ ( inBuff ) & 0x3f ] ; return destination ; case 2 : destination [ destOffset ] = ALPHABET [ ( inBuff >>> 18 ) ] ; destination [ destOffset + 1 ] = ALPHABET [ ( inBuff >>> 12 ) & 0x3f ] ; destination [ destOffset + 2 ] = ALPHABET [ ( inBuff >>> 6 ) & 0x3f ] ; destination [ destOffset + 3 ] = EQUALS_SIGN ; return destination ; case 1 : destination [ destOffset ] = ALPHABET [ ( inBuff >>> 18 ) ] ; destination [ destOffset + 1 ] = ALPHABET [ ( inBuff >>> 12 ) & 0x3f ] ; destination [ destOffset + 2 ] = EQUALS_SIGN ; destination [ destOffset + 3 ] = EQUALS_SIGN ; return destination ; default : return destination ; } // end switch


signature:
public class DynamicPassword { /** * 随机生成指定长度字节数的密钥
 * < br > 2014-2-11 下午9:10:17
 * @ param length
 * @ return byte [ ] */
public byte [ ] generateKey ( int length ) { } }

implementation: if ( length <= 0 ) { throw new IllegalArgumentException ( "长度为：" + length + "， 指定的密钥长度错误！" ) ; } byte [ ] bts = new byte [ length ] ; Random random = new Random ( ) ; for ( int i = 0 ; i < length ; i ++ ) { bts [ i ] = ( byte ) random . nextInt ( 255 ) ; } return bts ;


signature:
public class DynamicPassword { /** * 根据指定的时间刷新周期获取时间字节
 * < br > 2014-2-11 下午9:13:21
 * @ param seconds
 * @ return */
public byte [ ] getTimeBytes ( int seconds ) { } }

implementation:
if ( seconds <= 0 ) { throw new IllegalArgumentException ( "秒数为：" + seconds + "， 指定的密钥更新周期错误！" ) ; } long currentTimeMillis = System . currentTimeMillis ( ) ; // System . out . println ( currentTimeMillis ) ;
// 对秒数取整 , 比如seconds = 30 , 那么21点00分18秒与21点00分29秒是相同的结果
currentTimeMillis /= seconds * SECOND ; // long currentTimeMillisRs = currentTimeMillis * seconds *
// SECOND ; / / 还原时间位数
// System . out . println ( currentTimeMillisRs ) ;
// Date date = new Date ( currentTimeMillisRs ) ;
// String dateStr = DateHelper . FORMATTER _ LONG . format ( date ) ;
// System . out . println ( dateStr ) ;
return ByteHelper . longToBytes ( currentTimeMillis ) ;


signature:
public class DynamicPassword { /** * 对字节进行迭代运算 , 这样结果就不具备规律性
 * < br > 2014-2-11 下午9:14:18
 * @ param key
 * @ return */
public byte [ ] generateCode ( byte [ ] key , int refreshTime ) { } }

implementation:
byte [ ] bs = getTimeBytes ( refreshTime ) ; int length = bs . length ; for ( int i = 0 ; i < length ; i ++ ) { byte b = bs [ i ] ; for ( int j = 0 ; j < length ; j ++ ) { bs [ i ] = ( byte ) ( bs [ j ] | b ) ; bs [ i ] = ( byte ) ( bs [ j ] ^ b ) ; } } int keyLength = key . length ; byte [ ] rs = new byte [ keyLength ] ; System . arraycopy ( key , 0 , rs , 0 , keyLength ) ; for ( int i = 0 ; i < keyLength ; i ++ ) { byte k = rs [ i ] ; for ( int j = 0 ; j < length ; j ++ ) { rs [ i ] = ( byte ) ( bs [ j ] ^ k ) ; rs [ i ] = ( byte ) ( bs [ j ] | k ) ; } } // String string = Base64 . encodeBytes ( rs ) ;
// System . out . println ( string ) ;
return rs ;


signature:
public class DynamicPassword { /** * 获取最接近digit位数字的二进制表示的数 ( 一定大于digit位的数字 ) 的大小
 * 例如 , 如果digit为6 , 那么表示99999最接近的二进制数字为1048576(2的20次方 ) , 结果返回20
 * < br > 2014-1-21 下午5:27:53
 * @ param digit
 * @ return */
public static int minApproach ( int digit ) { } }

implementation:
int max = ( int ) ( Math . pow ( 10 , digit ) - 1 ) ; // System . out . println ( max ) ;
int i = 0 ; while ( max > 0 ) { max >>= 1 ; i ++ ; } // int k = 1 < < i ;
// System . out . println ( k ) ;
// System . out . println ( i ) ;
return i ;


signature:
public class JarArchive { /** * Build a Tree from the entries . */
private ITreeNode parseTree ( ) { } }

implementation: ITreeNode root = new TreeNodeUniqueChildren ( ) ; ITreeNode newnode , oldnode ; Enumeration entries = this . jar . entries ( ) ; String entry ; while ( entries . hasMoreElements ( ) ) { newnode = root ; oldnode = root ; entry = ( ( JarEntry ) entries . nextElement ( ) ) . getName ( ) ; System . out . println ( "Entry: " + entry ) ; StringTokenizer tokenizer = new StringTokenizer ( entry , "/" ) ; while ( tokenizer . hasMoreElements ( ) ) { String path = tokenizer . nextToken ( ) ; newnode = new TreeNodeUniqueChildren ( path ) ; oldnode . addChildNode ( newnode ) ; oldnode = newnode ; } } return root ;


signature:
public class JarArchive { /** * Little helper that transforms ( back ) the nodes of the tree that was parsed from the entries during initialization
 * to canonical strings for entries . */
private String getSearchPath ( ITreeNode node ) { } }

implementation:
List l = new LinkedList ( ) ; node . getUserObjectPathFromRoot ( l ) ; Iterator it = l . iterator ( ) ; StringBuffer ret = new StringBuffer ( ) ; int i = 0 ; String token ; while ( it . hasNext ( ) ) { // avoid the " root " token .
token = it . next ( ) . toString ( ) ; if ( i != 0 ) { ret . append ( token ) ; if ( it . hasNext ( ) ) { ret . append ( '/' ) ; } } i ++ ; } return ret . toString ( ) ;


signature:
public class JarArchive { /** * ( non - Javadoc )
 * @ see java . io . File # list ( ) */
public String [ ] list ( ) { } }

implementation: String [ ] ret = new String [ this . childs . size ( ) ] ; Iterator it = this . childs . iterator ( ) ; for ( int i = 0 ; it . hasNext ( ) ; i ++ ) { ret [ i ] = it . next ( ) . toString ( ) ; } return ret ;


signature:
public class JarArchive { /** * ( non - Javadoc )
 * @ see java . io . File # listFiles ( ) */
public File [ ] listFiles ( ) { } }

implementation: File [ ] ret = new File [ this . childs . size ( ) ] ; Iterator it = this . childs . iterator ( ) ; for ( int i = 0 ; it . hasNext ( ) ; i ++ ) { ret [ i ] = ( File ) it . next ( ) ; } return ret ;


signature:
public class JarArchive { /** * ( non - Javadoc )
 * @ see java . io . File # listFiles ( java . io . FileFilter ) */
public File [ ] listFiles ( FileFilter filter ) { } }

implementation: List ret = new LinkedList ( ) ; Iterator it = this . childs . iterator ( ) ; File next ; while ( it . hasNext ( ) ) { next = ( File ) it . next ( ) ; if ( filter . accept ( next ) ) { ret . add ( next ) ; } } return ( File [ ] ) ret . toArray ( new File [ ret . size ( ) ] ) ;


signature:
public class ThreadJacksonMixInHolder { /** * 根据当前MixIn集合生成objectMapper < p >
 * < b > 注意 : 该方法在返回mapper对象之后调用clear方法 , 如果再次调用builderMapper ( ) 肯定会保存 < / b >
 * @ return */
public static ObjectMapper builderMapper ( ) { } }

implementation:
ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder . mapper == null && isContainsMixIn ( ) ) { holder . mapper = new ObjectMapper ( ) ; for ( Map . Entry < Class < ? > , Class < ? > > mixIn : holder . mixIns ) { holder . mapper . addMixInAnnotations ( mixIn . getKey ( ) , mixIn . getValue ( ) ) ; } } clear ( ) ; // 如果不调用clear可能导致线程内的数据是脏的 !
return holder . mapper ;


signature:
public class ThreadJacksonMixInHolder { /** * 根据当前MixIn集合生成objectMapper
 * @ return */
public static org . codehaus . jackson . map . ObjectMapper builderCodehausMapper ( ) { } }

implementation:
ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder . codehausMapper == null && isContainsMixIn ( ) ) { holder . codehausMapper = new org . codehaus . jackson . map . ObjectMapper ( ) ; for ( Map . Entry < Class < ? > , Class < ? > > mixIn : holder . mixIns ) { holder . codehausMapper . getDeserializationConfig ( ) . addMixInAnnotations ( mixIn . getKey ( ) , mixIn . getValue ( ) ) ; holder . codehausMapper . getSerializationConfig ( ) . addMixInAnnotations ( mixIn . getKey ( ) , mixIn . getValue ( ) ) ; } } clear ( ) ; // 如果不调用clear可能导致线程内的数据是脏的 !
return holder . codehausMapper ;


signature:
public class ThreadJacksonMixInHolder { /** * 设置MixIn集合到线程内 , 如果线程内已经存在数据 , 则会先清除
 * @ param resetMixIns */
public static void setMixIns ( Set < Map . Entry < Class < ? > , Class < ? > > > resetMixIns ) { } }

implementation: ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder == null ) { holder = new ThreadJacksonMixInHolder ( ) ; holderThreadLocal . set ( holder ) ; } holder . mixIns = resetMixIns ;


signature:
public class ThreadJacksonMixInHolder { /** * 不同于setMixIns , addMixIns为增加MixIn集合到线程内 , 即不会清除已经保存的数据
 * < br > 2014年4月4日 下午12:08:15
 * @ param toAddMixIns */
public static void addMixIns ( Set < Map . Entry < Class < ? > , Class < ? > > > toAddMixIns ) { } }

implementation: ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder == null ) { holder = new ThreadJacksonMixInHolder ( ) ; holderThreadLocal . set ( holder ) ; } if ( holder . mixIns == null ) { holder . mixIns = new HashSet < Map . Entry < Class < ? > , Class < ? > > > ( ) ; } holder . mixIns . addAll ( toAddMixIns ) ;


signature:
public class ThreadJacksonMixInHolder { /** * 获取线程内的MixIn集合 < p > < / p >
 * < b > 注意 : 为了防止线程执行完毕之后仍然存在有数据 , 请务必适时调用clear ( ) 方法 < / b >
 * @ return
 * @ see com . xiongyingqi . jackson . helper . ThreadJacksonMixInHolder # builderMapper ( )
 * @ see com . xiongyingqi . jackson . helper . ThreadJacksonMixInHolder # builderCodehausMapper ( )
 * @ see com . xiongyingqi . jackson . helper . ThreadJacksonMixInHolder # clear ( ) */
public static Set < Map . Entry < Class < ? > , Class < ? > > > getMixIns ( ) { } }

implementation: ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; return holder . mixIns ;