Input: 使用反射机制自动ToString <br > 2013 - 8 - 28 下午3 : 16 : 40 [CODESPLIT] public String reflectToString ( Object object ) { 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 ( ) ; }


Input: / * ( non - Javadoc ) It is assumed that the inputstream is at the start of the file or String ( in order to read the BOM ) . [CODESPLIT] public Charset detectCodepage ( InputStream in , int length ) throws IOException { 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 ( ) ; }


Input: 判断String对象是否包含字符（如果全部为空格也返回false） [CODESPLIT] public static boolean hasText ( String ... string ) { 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 ; }


Input: sn = MD5 ( urlencode ( basicString + sk )) <p > 其中 basicString 的算法如下： <p > ( 1 ) get 请求 <p > url 中 http : // 域名 { uri } <p > basicString = uri <p > ( 2 ) post 请求 <p > url 中 http : // 域名 { uri } POST 参数按照key进行从小大到字母排序 <p > 然后拼装成：k1 = v1&amp ; k2 = v2&amp ; k3 = v3&amp ; ... &amp ; kn = vn的格式 = &gt ; { params } <p > basicString = uri + ? + params [CODESPLIT] public String calculateAKSN ( String ak , String sk , String url , List < NameValuePair > nameValuePairs , String method ) { 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 ; }


Input: 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 ) . [CODESPLIT] public static List < Element > getChildElementsByTagName ( Element ele , String [ ] childEleNames ) { 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 ; }


Input: 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 ) . [CODESPLIT] public static List < Element > getChildElementsByTagName ( Element ele , String childEleName ) { return getChildElementsByTagName ( ele , new String [ ] { childEleName } ) ; }


Input: Utility method that returns the first child element identified by its name . [CODESPLIT] public static Element getChildElementByTagName ( Element ele , String childEleName ) { 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 ; }


Input: Utility method that returns the first child element value identified by its name . [CODESPLIT] public static String getChildElementValueByTagName ( Element ele , String childEleName ) { Element child = getChildElementByTagName ( ele , childEleName ) ; return ( child != null ? getTextValue ( child ) : null ) ; }


Input: Retrieves all child elements of the given DOM element [CODESPLIT] public static List < Element > getChildElements ( Element ele ) { 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 ; }


Input: 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 . [CODESPLIT] public static String getTextValue ( Element valueEle ) { 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 ( ) ; }


Input: Namespace - aware equals comparison . Returns { [CODESPLIT] public static boolean nodeNameEquals ( Node node , String desiredName ) { Assert . notNull ( node , "Node must not be null" ) ; Assert . notNull ( desiredName , "Desired name must not be null" ) ; return nodeNameMatch ( node , desiredName ) ; }


Input: Matches the given node s name and local name against the given desired name . [CODESPLIT] private static boolean nodeNameMatch ( Node node , String desiredName ) { return ( desiredName . equals ( node . getNodeName ( ) ) || desiredName . equals ( node . getLocalName ( ) ) ) ; }


Input: Matches the given node s name and local name against the given desired names . [CODESPLIT] private static boolean nodeNameMatch ( Node node , Collection < ? > desiredNames ) { return ( desiredNames . contains ( node . getNodeName ( ) ) || desiredNames . contains ( node . getLocalName ( ) ) ) ; }


Input: @throws java . io . IOException [CODESPLIT] private final void renderHeaderCell ( String columnName , int firstOrLast ) throws IOException { m_out . write ( this . HeadCellStartTag ( ( firstOrLast == FIRST_CELL_IN_ROW ) ) ) ; m_out . write ( columnName ) ; m_out . write ( this . HeadCellStopTag ( ( firstOrLast == LAST_CELL_IN_ROW ) ) ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public final void render ( TableModel model ) throws IOException { 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 ( ) ) ; }


Input: 移除主机字符，例如传入admin@xiongyingqi . com，那么该方法将截取@之前的字符返回admin [CODESPLIT] public static String removeDomain ( String str ) { if ( str != null && ! "" . equals ( str ) ) { int index = str . indexOf ( "@" ) ; if ( index >= 0 ) { str = str . substring ( 0 , index ) ; } } return str ; }


Input: Appends the given amount of spaces to the String . <p > [CODESPLIT] public static final String appendSpaces ( final String s , final int count ) { StringBuffer tmp = new StringBuffer ( s ) ; for ( int i = 0 ; i < count ; i ++ ) { tmp . append ( " " ) ; } return tmp . toString ( ) ; }


Input: 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 > [CODESPLIT] public static final String arrayToString ( final Object isArr ) { String result = StringUtil . arrayToString ( isArr , "," ) ; return result ; }


Input: 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 > [CODESPLIT] public static final String arrayToString ( final Object isArr , final String separator ) { 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 ; }


Input: Returns the singleton instance of this class . <p > [CODESPLIT] public static StringUtil instance ( ) { if ( StringUtil . instance == null ) { StringUtil . instance = new StringUtil ( ) ; } return StringUtil . instance ; }


Input: Returns true if the argument is null or consists of whitespaces only . <p > [CODESPLIT] public static boolean isEmpty ( final String test ) { boolean result ; if ( test == null ) { result = true ; } else { result = test . trim ( ) . length ( ) == 0 ; } return result ; }


Input: Little String output - helper that modifies the given LinkedList by getting it s Objects and replace them by their toString () - representation . <p > [CODESPLIT] public static final void listOfArraysToString ( final List < Object > objects ) { if ( objects == null ) { return ; } int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { objects . add ( i , StringUtil . arrayToString ( objects . remove ( i ) ) ) ; } }


Input: Returns the maximum length of a { @link Object#toString () } result in characters within the given List . <p > [CODESPLIT] public static final int longestStringRepresentation ( final List < Object > objects ) { 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 ; }


Input: 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 . [CODESPLIT] public static final String setSize ( final String s , final int length ) { 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 ; }


Input: 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 . <p > [CODESPLIT] public static final void toLongestString ( final List < Object > objects ) { 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 ) ) ; } }


Input: 增加参数，默认使用urlEncoding [CODESPLIT] public HttpBuilder param ( String name , String value ) { return param ( name , value , true ) ; }


Input: 增加参数 [CODESPLIT] public HttpBuilder param ( String name , String value , boolean urlEncoding ) { 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 ; }


Input: 根据输入的Unicode字符，获取它的GB2312编码或者ascii编码， [CODESPLIT] public static short getGB2312Id ( char ch ) { 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 ; }


Input: 获取包下所有被Controller注解的类所表示的路径 <br > 2013 - 10 - 17 下午1 : 02 : 45 [CODESPLIT] public static Collection < String > getAnnotationMappedPaths ( Package pkg ) { 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 ; }


Input: Start to monitor given handle object for becoming weakly reachable . When the handle isn t used anymore the given listener will be called . [CODESPLIT] public static void monitor ( Object handle , ReleaseListener listener ) { 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 ) ; }


Input: Add entry to internal map of tracked entries . Internal monitoring thread is started if not already running . [CODESPLIT] private static void addEntry ( Reference < ? > ref , ReleaseListener entry ) { 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 ( ) ; } } }


Input: Check whether to keep the monitoring thread alive i . e . whether there are still entries being tracked . [CODESPLIT] private static boolean keepMonitoringThreadAlive ( ) { synchronized ( WeakReferenceMonitor . class ) { if ( ! trackedEntries . isEmpty ( ) ) { return true ; } else { logger . debug ( "No entries left to track - stopping reference monitor thread" ) ; monitoringThread = null ; return false ; } } }


Input: public static final long DB = 1024 * NB ; [CODESPLIT] public static boolean checkFileSizeLessThen ( File file , long size ) { try { fileNotFullAndExists ( file ) ; } catch ( Exception e ) { return false ; } return file . length ( ) <= size ; }


Input: 获取文件类型 <br > 2013 - 9 - 2 下午9 : 08 : 51 [CODESPLIT] public static String getMimeType ( File data ) { 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 ) ; }


Input: 根据后缀名从文件夹获取文件 <br > 2013 - 9 - 6 下午3 : 15 : 56 [CODESPLIT] public static File [ ] listFilesBySuffix ( File folder , final String suffix ) { 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 ; }


Input: 从url地址读取文件信息并写入到临时文件 <br > 2013 - 9 - 2 下午2 : 57 : 15 [CODESPLIT] public static File readURL ( String urlStr ) throws IOException { 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 ) ; }


Input: 从流读取文件内容 <br > 2013 - 9 - 2 下午2 : 52 : 39 [CODESPLIT] public static File readInputStream ( InputStream inputStream ) { String filePath = System . getProperty ( "java.io.tmpdir" , "tmp/" ) ; filePath += System . currentTimeMillis ( ) + StringUtil . randomString ( 8 ) + ".tmp" ; return readInputStream ( inputStream , filePath ) ; }


Input: 将文件转换为URL地址 <br > 2013 - 9 - 2 下午10 : 07 : 14 [CODESPLIT] public static URL toURL ( File file ) { 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 ; }


Input: 将流读入到文件内 <br > 2013 - 9 - 2 下午10 : 04 : 17 [CODESPLIT] public static File readInputStream ( InputStream inputStream , File file ) { 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 ; }


Input: 读取指定文件的文件内容（以String的形式） <br > 2013 - 8 - 30 下午5 : 26 : 55 [CODESPLIT] public static String readFileToString ( File file ) { 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 ; }


Input: 将源文件剪切到目标文件 [CODESPLIT] public static boolean cutFile ( File originFile , File targetFile ) { Assert . notNull ( originFile ) ; Assert . notNull ( targetFile ) ; copyFile ( originFile , targetFile ) ; if ( originFile . length ( ) == targetFile . length ( ) ) { return originFile . delete ( ) ; } return false ; }


Input: 读取inputStream并返回字节数组 <br > 2013 - 9 - 3 下午12 : 10 : 06 [CODESPLIT] public static byte [ ] readInputStreamToBytes ( InputStream inputStream ) throws Exception { 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 ; }


Input: 读取文件内容并返回字节数组 <br > 2013 - 9 - 3 下午12 : 10 : 06 [CODESPLIT] public static byte [ ] readFileToBytes ( File iconFile ) throws Exception { 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 ; }


Input: 将字节组写入文件 <br > 2013 - 9 - 3 下午2 : 39 : 21 [CODESPLIT] public static File writeBytesToFile ( byte [ ] data , File file ) { 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 ; }


Input: 将字符串写入文件 <br > 2013 - 9 - 6 下午12 : 09 : 45 [CODESPLIT] public static File writeStringToFile ( File file , String string ) { try { byte [ ] bts = string . getBytes ( getEncode ( file ) ) ; file = writeBytesToFile ( bts , file ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; ; LOGGER . error ( e ) ; } return file ; }


Input: 将对象写入文件 <br > 2013 - 9 - 6 下午1 : 08 : 58 [CODESPLIT] public static void serializeObjectToFile ( File targetFile , Serializable serializable ) { 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 ) ; } }


Input: 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 . [CODESPLIT] public static String resolvePlaceholders ( String text , boolean ignoreUnresolvablePlaceholders ) { PropertyPlaceholderHelper helper = ( ignoreUnresolvablePlaceholders ? nonStrictHelper : strictHelper ) ; return helper . replacePlaceholders ( text , new SystemPropertyPlaceholderResolver ( text ) ) ; }


Input: ---------------------------------------- 包定义和导入包 ---------------------------------------- [CODESPLIT] private String findPackage ( ) { Matcher matcher = PATTERN_FIND_PACKAGE . matcher ( content ) ; if ( matcher . find ( ) ) { return matcher . group ( ) ; } return null ; }


Input: 检查导入包 [CODESPLIT] private void checkImport ( ) { 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 ( ) ; } }


Input: 检查class定义段 [CODESPLIT] private void checkClass ( ) { 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 ) ; } }


Input: 查找已有的接口定义 [CODESPLIT] private Set < String > findInterfaces ( String interfaceDefineString ) { 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 ; }


Input: 检查implements关键字 [CODESPLIT] private String checkInterfaces ( String classSegment ) { 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 ; }


Input: 检查extends关键字 [CODESPLIT] private String checkSuperClass ( String classSegment ) { 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 ; }


Input: ---------------------------------------- 代码段 ---------------------------------------- [CODESPLIT] private void checkCodeFragment ( ) { 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 ( ) ) ; } }


Input: -------------------------- 移除注解 -------------------------- [CODESPLIT] private void checkAnnotations ( ) { 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 ) ; } }


Input: returns the Path to the My Documents folder or <code > null< / code > [CODESPLIT] public static String getMyDocumentsFromWinRegistry ( ) { 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 ; } }


Input: Test the phone number from which the city is using Taobao API [CODESPLIT] public static String calcMobileCity ( String mobileNumber ) throws MalformedURLException { 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 ; }


Input: } [CODESPLIT] public static void main ( String [ ] args ) throws Exception { 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()); }


Input: 按照日期进行排序 <br > 2013 - 6 - 25 下午9 : 46 : 45 [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public List sortByDateTime ( Collection < ? extends T > collection , final Field field , final boolean asc ) { 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 ; }


Input: 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 . [CODESPLIT] public static void enableIndenting ( Transformer transformer , int indentAmount ) { 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 ) { } }


Input: Disable indenting for the supplied { @link javax . xml . transform . Transformer } . [CODESPLIT] public static void disableIndenting ( Transformer transformer ) { Assert . notNull ( transformer , "Transformer must not be null" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "no" ) ; }


Input:
获取与上个计时点以毫秒为单位的时差 ，如果是第一个计时点，则开始即时并返回0
 此方法是以线程和调用类来区别计时的，即：不同的类或不同的线程都会导致计时器的从0开始计时
 2013 - 7 - 26 下午6 : 21 : 40 [CODESPLIT] public static long getTime ( ) { // 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 ; }


Input: 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 . [CODESPLIT] protected String toQualifiedName ( QName qName ) { String prefix = qName . getPrefix ( ) ; if ( ! StringUtils . hasLength ( prefix ) ) { return qName . getLocalPart ( ) ; } else { return prefix + ":" + qName . getLocalPart ( ) ; } }


Input: Starts the prefix mapping for the given prefix . [CODESPLIT] protected void startPrefixMapping ( String prefix , String namespace ) throws SAXException { 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 ) ; } } }


Input: Ends the prefix mapping for the given prefix . [CODESPLIT] protected void endPrefixMapping ( String prefix ) throws SAXException { if ( getContentHandler ( ) != null ) { if ( namespaces . containsKey ( prefix ) ) { getContentHandler ( ) . endPrefixMapping ( prefix ) ; namespaces . remove ( prefix ) ; } } }


Input: Adds the given callback to this registry . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void addCallback ( ListenableFutureCallback < ? super T > callback ) { 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 ; } } }


Input: Triggers a { @link ListenableFutureCallback#onSuccess ( Object ) } call on all added callbacks with the given result [CODESPLIT] public void success ( T result ) { synchronized ( mutex ) { state = State . SUCCESS ; this . result = result ; while ( ! callbacks . isEmpty ( ) ) { callbacks . poll ( ) . onSuccess ( result ) ; } } }


Input: Triggers a { @link ListenableFutureCallback#onFailure ( Throwable ) } call on all added callbacks with the given { @code Throwable } . [CODESPLIT] public void failure ( Throwable t ) { synchronized ( mutex ) { state = State . FAILURE ; this . result = t ; while ( ! callbacks . isEmpty ( ) ) { callbacks . poll ( ) . onFailure ( t ) ; } } }


Input: MD5 加密， 结果默认为小写 <br > 2013 - 11 - 4 下午6 : 33 : 06 [CODESPLIT] public static String encrypt ( String message , String encode ) { return encrypt ( message , encode , false ) ; }


Input: MD5 加密 <br > 2013 - 11 - 4 下午6 : 33 : 06 [CODESPLIT] public static String encrypt ( String message , String encode , boolean toUpperCase ) { 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 ( ) ; }


Input: Cuts all path information of the String representation of the given URL . <p > [CODESPLIT] public static Map . Entry < String , String > cutDirectoryInformation ( final java . net . URL path ) { 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 ; }


Input: 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 . <p > [CODESPLIT] public static Map . Entry < String , String > cutDirectoryInformation ( final String path ) { 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 ) ; }


Input: 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 . <p > [CODESPLIT] public static Map . Entry < String , String > cutExtension ( final String filename ) { 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 ) ; }


Input: Finds a filename based on the given name . If a file with the given name does not exist <tt > name< / tt > will be returned . <p > [CODESPLIT] public static String getDefaultFileName ( final String name ) { 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 ; }


Input: Returns the singleton instance of this class . <p > [CODESPLIT] public static FileUtil getInstance ( ) { if ( FileUtil . instance == null ) { FileUtil . instance = new FileUtil ( ) ; } return FileUtil . instance ; }


Input: Tests wether the given input stream only contains ASCII characters if interpreted by reading bytes ( 16 bit ) . <p > 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 . <p > [CODESPLIT] public static boolean isAllASCII ( final InputStream in ) throws IOException { boolean ret = true ; int read = - 1 ; do { read = in . read ( ) ; if ( read > 0x7F ) { ret = false ; break ; } } while ( read != - 1 ) ; return ret ; }


Input: Tests wether the content of the given file is identical at character level when it is opened with both different Charsets . <p > 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 ) . <p > [CODESPLIT] public static boolean isEqual ( final File document , final Charset a , final Charset b ) throws IOException { 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 ( ) ; } } }


Input: Reads the content of the given File into an array . <p > 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 . <p > [CODESPLIT] public static byte [ ] readRAM ( final File f ) throws IOException { 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 ( ) ; } }


Input: Removes the duplicate line breaks in the given file . <p > [CODESPLIT] public static void removeDuplicateLineBreaks ( final File f ) { 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 ( ) ; } } } } } }


Input: Returns the formatted file size to Bytes KB MB or GB depending on the given value . <p > [CODESPLIT] public String formatFilesize ( final long filesize , final Locale locale ) { 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 ; }


Input: end encode3to4 [CODESPLIT] private static byte [ ] encode3to4 ( byte [ ] source , int srcOffset , int numSigBytes , byte [ ] destination , int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 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 }


Input: 随机生成指定长度字节数的密钥 <br > 2014 - 2 - 11 下午9 : 10 : 17 [CODESPLIT] public byte [ ] generateKey ( int length ) { if ( length <= 0 ) { throw new IllegalArgumentException ( "长度为：" + lengt    "， 指定 密 长度错误！");   } byte [ ] bts = new byte [ length ] ; Random random = new Random ( ) ; for ( int i = 0 ; i < length ; i ++ ) { bts [ i ] = ( byte ) random . nextInt ( 255 ) ; } return bts ; }


Input: 根据指定的时间刷新周期获取时间字节 <br > 2014 - 2 - 11 下午9 : 13 : 21 [CODESPLIT] public byte [ ] getTimeBytes ( int seconds ) { if ( seconds <= 0 ) { throw new IllegalArgumentException ( "秒数为：" + secon s  + "， 指定的密钥更新周期错误！");   } 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 ) ; }


Input: 对字节进行迭代运算，这样结果就不具备规律性 <br > 2014 - 2 - 11 下午9 : 14 : 18 [CODESPLIT] public byte [ ] generateCode ( byte [ ] key , int refreshTime ) { 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 ; }


Input: 获取最接近digit位数字的二进制表示的数（一定大于digit位的数字）的大小 例如，如果digit为6，那么表示999999最接近的二进制数字为1048576 ( 2的20次方 ) ，结果返回20 <br > 2014 - 1 - 21 下午5 : 27 : 53 [CODESPLIT] public static int minApproach ( int digit ) { 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 ; }


Input: Build a Tree from the entries . [CODESPLIT] private ITreeNode parseTree ( ) { 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 ; }


Input: Little helper that transforms ( back ) the nodes of the tree that was parsed from the entries during initialization to canonical strings for entries . [CODESPLIT] private String getSearchPath ( ITreeNode node ) { 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 ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public String [ ] list ( ) { 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 ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public File [ ] listFiles ( ) { 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 ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public File [ ] listFiles ( FileFilter filter ) { 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 ( ) ] ) ; }


Input: 根据当前MixIn集合生成objectMapper<p > <p > <b > 注意：该方法在返回mapper对象之后调用clear方法，如果再次调用builderMapper () 肯定会保存< / b > [CODESPLIT] public static ObjectMapper builderMapper ( ) { 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 ; }


Input: 根据当前MixIn集合生成objectMapper [CODESPLIT] public static org . codehaus . jackson . map . ObjectMapper builderCodehausMapper ( ) { 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 ; }


Input: 设置MixIn集合到线程内，如果线程内已经存在数据，则会先清除 [CODESPLIT] public static void setMixIns ( Set < Map . Entry < Class < ? > , Class < ? > > > resetMixIns ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder == null ) { holder = new ThreadJacksonMixInHolder ( ) ; holderThreadLocal . set ( holder ) ; } holder . mixIns = resetMixIns ; }


Input: 不同于setMixIns，addMixIns为增加MixIn集合到线程内，即不会清除已经保存的数据 <br > 2014年4月4日 下午12 : 08 : 15 [CODESPLIT] public static void addMixIns ( Set < Map . Entry < Class < ? > , Class < ? > > > toAddMixIns ) { 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 ) ; }


Input: 获取线程内的MixIn集合<p > < / p > <b > 注意：为了防止线程执行完毕之后仍然存在有数据，请务必适时调用clear () 方法< / b > [CODESPLIT] public static Set < Map . Entry < Class < ? > , Class < ? > > > getMixIns ( ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; return holder . mixIns ; }


Input: 判断当前线程是否存在MixIn集合 [CODESPLIT] public static boolean isContainsMixIn ( ) { if ( holderThreadLocal . get ( ) == null ) { return false ; } if ( holderThreadLocal . get ( ) . mixIns != null && holderThreadLocal . get ( ) . mixIns . size ( ) > 0 ) { return true ; } return false ; }


Input: Create and return a list of { [CODESPLIT] private List < Namespace > createNamespaces ( SimpleNamespaceContext namespaceContext ) { if ( namespaceContext == null ) { return null ; } List < Namespace > namespaces = new ArrayList < Namespace > ( ) ; String defaultNamespaceUri = namespaceContext . getNamespaceURI ( XMLConstants . DEFAULT_NS_PREFIX ) ; if ( StringUtils . hasLength ( defaultNamespaceUri ) ) { namespaces . add ( this . eventFactory . createNamespace ( defaultNamespaceUri ) ) ; } for ( Iterator < String > iterator = namespaceContext . getBoundPrefixes ( ) ; iterator . hasNext ( ) ; ) { String prefix = iterator . next ( ) ; String namespaceUri = namespaceContext . getNamespaceURI ( prefix ) ; namespaces . add ( this . eventFactory . createNamespace ( prefix , namespaceUri ) ) ; } return namespaces ; }


Input: 根据指定的过滤表创建jackson对象 <br > 2013 - 10 - 25 下午2 : 46 : 43 [CODESPLIT] private ObjectMapper createObjectMapper ( Map < Class < ? > , Class < ? > > map ) { ObjectMapper mapper = new ObjectMapper ( ) ; Set < Entry < Class < ? > , Class < ? > > > entries = map . entrySet ( ) ; for ( Iterator < Entry < Class < ? > , Class < ? > > > iterator = entries . iterator ( ) ; iterator . hasNext ( ) ; ) { Entry < Class < ? > , Class < ? > > entry = iterator . next ( ) ; mapper . getSerializationConfig ( ) . addMixInAnnotations ( entry . getKey ( ) , entry . getValue ( ) ) ; //            mapper.addMixInAnnotations(entry.getKey(), entry.getValue()); } return mapper ; }


Input: 将摘要信息转换为相应的编码 [CODESPLIT] private static String encode ( String code , String message ) { return encode ( code , message . getBytes ( ) ) ; }


Input: 加密方法 <pre > // 1 . 1 首先要创建一个密匙 // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom () ; // 为我们选择的DES算法生成一个KeyGenerator对象 KeyGenerator kg = KeyGenerator . getInstance ( DES ) ; kg . init ( sr ) ; // 生成密匙 SecretKey key = kg . generateKey () ; // 获取密匙数据 byte rawKeyData [] = key . getEncoded () ; // byte rawKeyData [] = sucretsa . getBytes () ; System . out . println ( 密匙长度 === + rawKeyData . length ) ; System . out . println ( 密匙Base64 === + Base64 . encodeBytes ( rawKeyData )) ; [CODESPLIT] public static byte [ ] desEncrypt ( byte rawKeyData [ ] , byte [ ] data ) throws InvalidKeyException , NoSuchAlgorithmException , IllegalBlockSizeException , BadPaddingException , NoSuchPaddingException , InvalidKeySpecException { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom ( ) ; // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec ( rawKeyData ) ; // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( "DES" ) ; SecretKey key = keyFactory . generateSecret ( dks ) ; // Cipher对象实际完成加密操作 Cipher cipher = Cipher . getInstance ( "DES" ) ; // 用密匙初始化Cipher对象 cipher . init ( Cipher . ENCRYPT_MODE , key , sr ) ; // 现在，获取数据并加密 //        byte data[] = str.getBytes(); // 正式执行加密操作 byte [ ] encryptedData = cipher . doFinal ( data ) ; //        System.out.println("加密后===>" + encryptedData); return encryptedData ; }


Input: 解密方法 [CODESPLIT] public static byte [ ] desDecrypt ( byte rawKeyData [ ] , byte [ ] encryptedData ) throws IllegalBlockSizeException , BadPaddingException , InvalidKeyException , NoSuchAlgorithmException , NoSuchPaddingException , InvalidKeySpecException { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom ( ) ; // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec ( rawKeyData ) ; // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( "DES" ) ; SecretKey key = keyFactory . generateSecret ( dks ) ; // Cipher对象实际完成解密操作 Cipher cipher = Cipher . getInstance ( "DES" ) ; // 用密匙初始化Cipher对象 cipher . init ( Cipher . DECRYPT_MODE , key , sr ) ; // 正式执行解密操作 byte decryptedData [ ] = cipher . doFinal ( encryptedData ) ; //        System.out.println("解密后===>" + new String(decryptedData)); return decryptedData ; }


Input: <p > Adds the given argument to the acceptance filter . The filter will only return true for a Class a in the following condition : [CODESPLIT] public synchronized boolean addSuperClass ( Class c ) { boolean ret = false ; if ( ( c . getModifiers ( ) & Modifier . FINAL ) != 0 ) { } else { ret = this . superclasses . add ( c ) ; } return ret ; }


Input: Tries to detect ( from the file path and the Classloaders urls ) and load the corresponding class and delegates to { @link #accept ( Class ) } . [CODESPLIT] public boolean accept ( File pathname ) { boolean ret = false ; if ( pathname . isDirectory ( ) ) { ret = true ; } else { String ext = FileUtil . cutExtension ( pathname . getName ( ) ) . getValue ( ) . toString ( ) ; if ( ext . equals ( "jar" ) ) { // is a "directory": ret = true ; } else if ( ext . equals ( "class" ) ) { Class cl = this . forFile ( pathname ) ; if ( cl != null ) { ret = this . accept ( cl ) ; } } else { ret = false ; } } return ret ; }


Input: Factory method for creating a { @link GelfTransport } provider within the plugin manager . [CODESPLIT] @ PluginFactory @ SuppressWarnings ( "unused" ) public static GelfAppender createGelfAppender ( @ PluginElement ( "Filter" ) Filter filter , @ PluginElement ( "Layout" ) Layout < ? extends Serializable > layout , @ PluginElement ( value = "AdditionalFields" ) final KeyValuePair [ ] additionalFields , @ PluginAttribute ( value = "name" ) String name , @ PluginAttribute ( value = "ignoreExceptions" , defaultBoolean = true ) Boolean ignoreExceptions , @ PluginAttribute ( value = "server" , defaultString = "localhost" ) String server , @ PluginAttribute ( value = "port" , defaultInt = 12201 ) Integer port , @ PluginAttribute ( value = "protocol" , defaultString = "UDP" ) String protocol , @ PluginAttribute ( value = "hostName" ) String hostName , @ PluginAttribute ( value = "queueSize" , defaultInt = 512 ) Integer queueSize , @ PluginAttribute ( value = "connectTimeout" , defaultInt = 1000 ) Integer connectTimeout , @ PluginAttribute ( value = "reconnectDelay" , defaultInt = 500 ) Integer reconnectDelay , @ PluginAttribute ( value = "sendBufferSize" , defaultInt = - 1 ) Integer sendBufferSize , @ PluginAttribute ( value = "tcpNoDelay" , defaultBoolean = false ) Boolean tcpNoDelay , @ PluginAttribute ( value = "tcpKeepAlive" , defaultBoolean = false ) Boolean tcpKeepAlive , @ PluginAttribute ( value = "includeSource" , defaultBoolean = true ) Boolean includeSource , @ PluginAttribute ( value = "includeThreadContext" , defaultBoolean = true ) Boolean includeThreadContext , @ PluginAttribute ( value = "includeStackTrace" , defaultBoolean = true ) Boolean includeStackTrace , @ PluginAttribute ( value = "includeExceptionCause" , defaultBoolean = false ) Boolean includeExceptionCause , @ PluginAttribute ( value = "tlsEnabled" , defaultBoolean = false ) Boolean tlsEnabled , @ PluginAttribute ( value = "tlsEnableCertificateVerification" , defaultBoolean = true ) Boolean tlsEnableCertificateVerification , @ PluginAttribute ( value = "tlsTrustCertChainFilename" ) String tlsTrustCertChainFilename ) { if ( name == null ) { LOGGER . error ( "No name provided for ConsoleAppender" ) ; return null ; } if ( ! "UDP" . equalsIgnoreCase ( protocol ) && ! "TCP" . equalsIgnoreCase ( protocol ) ) { LOG . warn ( "Invalid protocol {}, falling back to UDP" , protocol ) ; protocol = "UDP" ; } if ( hostName == null || hostName . trim ( ) . isEmpty ( ) ) { try { final String canonicalHostName = InetAddress . getLocalHost ( ) . getCanonicalHostName ( ) ; if ( isFQDN ( canonicalHostName ) ) { hostName = canonicalHostName ; } else { hostName = InetAddress . getLocalHost ( ) . getHostName ( ) ; } } catch ( UnknownHostException e ) { LOG . warn ( "Couldn't detect local host name, falling back to \"localhost\"" ) ; hostName = "localhost" ; } } final InetSocketAddress serverAddress = new InetSocketAddress ( server , port ) ; final GelfTransports gelfProtocol = GelfTransports . valueOf ( protocol . toUpperCase ( ) ) ; final GelfConfiguration gelfConfiguration = new GelfConfiguration ( serverAddress ) . transport ( gelfProtocol ) . queueSize ( queueSize ) . connectTimeout ( connectTimeout ) . reconnectDelay ( reconnectDelay ) . sendBufferSize ( sendBufferSize ) . tcpNoDelay ( tcpNoDelay ) . tcpKeepAlive ( tcpKeepAlive ) ; if ( tlsEnabled ) { if ( gelfProtocol . equals ( GelfTransports . TCP ) ) { gelfConfiguration . enableTls ( ) ; if ( ! tlsEnableCertificateVerification ) { LOG . warn ( "TLS certificate validation is disabled. This is unsecure!" ) ; gelfConfiguration . disableTlsCertVerification ( ) ; } if ( tlsEnableCertificateVerification && tlsTrustCertChainFilename != null ) { gelfConfiguration . tlsTrustCertChainFile ( new File ( tlsTrustCertChainFilename ) ) ; } } else { LOG . warn ( "Enabling of TLS is invalid for UDP Transport" ) ; } } return new GelfAppender ( name , layout , filter , ignoreExceptions , gelfConfiguration , hostName , includeSource , includeThreadContext , includeStackTrace , additionalFields , includeExceptionCause ) ; }


Input: TODO cache values [CODESPLIT] private boolean isRtl ( CharSequence text ) { if ( textDir == null ) { textDir = getTextDirectionHeuristic ( ) ; } return textDir . isRtl ( text , 0 , text . length ( ) ) ; }


Input: Calculates text color for specified item based on its position and state . [CODESPLIT] private int getTextColor ( int item ) { int scrollX = getScrollX ( ) ; // set color of text int color = textColor . getDefaultColor ( ) ; int itemWithPadding = ( int ) ( itemWidth + dividerSize ) ; if ( scrollX > itemWithPadding * item - itemWithPadding / 2 && scrollX < itemWithPadding * ( item + 1 ) - itemWithPadding / 2 ) { int position = scrollX - itemWithPadding / 2 ; color = getColor ( position , item ) ; } else if ( item == pressedItem ) { color = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed } , color ) ; } return color ; }


Input: Sets values to choose from [CODESPLIT] public void setValues ( CharSequence [ ] values ) { if ( this . values != values ) { this . values = values ; if ( this . values != null ) { layouts = new BoringLayout [ this . values . length ] ; for ( int i = 0 ; i < layouts . length ; i ++ ) { layouts [ i ] = new BoringLayout ( this . values [ i ] , textPaint , itemWidth , Layout . Alignment . ALIGN_CENTER , 1f , 1f , boringMetrics , false , ellipsize , itemWidth ) ; } } else { layouts = new BoringLayout [ 0 ] ; } // start marque only if has already been measured if ( getWidth ( ) > 0 ) { startMarqueeIfNeeded ( ) ; } requestLayout ( ) ; invalidate ( ) ; } }


Input: Calculates color for specific position on time picker [CODESPLIT] private int getColor ( int scrollX , int position ) { int itemWithPadding = ( int ) ( itemWidth + dividerSize ) ; float proportion = Math . abs ( ( ( 1f * scrollX % itemWithPadding ) / 2 ) / ( itemWithPadding / 2f ) ) ; if ( proportion > .5 ) { proportion = ( proportion - .5f ) ; } else { proportion = .5f - proportion ; } proportion *= 2 ; int defaultColor ; int selectedColor ; if ( pressedItem == position ) { defaultColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed } , textColor . getDefaultColor ( ) ) ; selectedColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed , android . R . attr . state_selected } , defaultColor ) ; } else { defaultColor = textColor . getDefaultColor ( ) ; selectedColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_selected } , defaultColor ) ; } return ( Integer ) new ArgbEvaluator ( ) . evaluate ( proportion , selectedColor , defaultColor ) ; }


Input: Sets text size for items [CODESPLIT] private void setTextSize ( float size ) { if ( size != textPaint . getTextSize ( ) ) { textPaint . setTextSize ( size ) ; requestLayout ( ) ; invalidate ( ) ; } }


Input: Calculates x scroll position that is still in range of view scroller [CODESPLIT] private int getInBoundsX ( int x ) { if ( x < 0 ) { x = 0 ; } else if ( x > ( ( itemWidth + ( int ) dividerSize ) * ( values . length - 1 ) ) ) { x = ( ( itemWidth + ( int ) dividerSize ) * ( values . length - 1 ) ) ; } return x ; }


Input: Cleans up the path of an incoming request . Repeating / s are reduced to one / . Trailing / s are removed . A <code > null< / code > or empty path is converted to / . [CODESPLIT] private static String cleanPath ( String path ) { path = path == null ? "/" : path ; if ( ! path . startsWith ( "/" ) ) { path = "/" + path ; } path = path . replaceAll ( "/+" , "/" ) ; if ( path . length ( ) > 1 && path . endsWith ( "/" ) ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } return path ; }


Input: / * Starts jrobotremoteserver with an example library and returns . The application will shutdown when all of the web server s threads exit . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { RemoteServer . configureLogging ( ) ; RemoteServer server = new RemoteServer ( ) ; server . addLibrary ( MyRemoteLibrary . class , 8270 ) ; server . start ( ) ; }


Input: The introduction is stored in a text file resource because it is easier to edit than String constants . [CODESPLIT] private String getIntro ( ) { try { InputStream introStream = MyRemoteLibrary . class . getResourceAsStream ( "__intro__.txt" ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( introStream , writer , Charset . defaultCharset ( ) ) ; return writer . toString ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }


Input: Get an array containing the names of the keywords that the library implements . [CODESPLIT] public String [ ] get_keyword_names ( ) { try { String [ ] names = servlet . getLibrary ( ) . getKeywordNames ( ) ; if ( names == null || names . length == 0 ) throw new RuntimeException ( "No keywords found in the test library" ) ; String [ ] newNames = Arrays . copyOf ( names , names . length + 1 ) ; newNames [ names . length ] = "stop_remote_server" ; return newNames ; } catch ( Throwable e ) { log . warn ( "" , e ) ; throw new RuntimeException ( e ) ; } }


Input: Run the given keyword and return the results . [CODESPLIT] public Map < String , Object > run_keyword ( String keyword , Object [ ] args , Map < String , Object > kwargs ) { Map < String , Object > result = new HashMap < String , Object > ( ) ; StdStreamRedirecter redirector = new StdStreamRedirecter ( ) ; redirector . redirectStdStreams ( ) ; try { result . put ( "status" , "PASS" ) ; Object retObj = "" ; if ( keyword . equalsIgnoreCase ( "stop_remote_server" ) ) { retObj = stopRemoteServer ( ) ; } else { try { retObj = servlet . getLibrary ( ) . runKeyword ( keyword , args , kwargs ) ; } catch ( Exception e ) { if ( illegalArgumentIn ( e ) ) { for ( int i = 0 ; i < args . length ; i ++ ) args [ i ] = arraysToLists ( args [ i ] ) ; retObj = servlet . getLibrary ( ) . runKeyword ( keyword , args , kwargs ) ; } else { throw ( e ) ; } } } if ( retObj != null && ! retObj . equals ( "" ) ) { result . put ( "return" , retObj ) ; } } catch ( Throwable e ) { result . put ( "status" , "FAIL" ) ; Throwable thrown = e . getCause ( ) == null ? e : e . getCause ( ) ; result . put ( "error" , getError ( thrown ) ) ; result . put ( "traceback" , ExceptionUtils . getStackTrace ( thrown ) ) ; boolean continuable = isFlagSet ( "ROBOT_CONTINUE_ON_FAILURE" , thrown ) ; if ( continuable ) { result . put ( "continuable" , true ) ; } boolean fatal = isFlagSet ( "ROBOT_EXIT_ON_FAILURE" , thrown ) ; if ( fatal ) { result . put ( "fatal" , true ) ; } } finally { String stdOut = StringUtils . defaultString ( redirector . getStdOutAsString ( ) ) ; String stdErr = StringUtils . defaultString ( redirector . getStdErrAsString ( ) ) ; if ( ! stdOut . isEmpty ( ) || ! stdErr . isEmpty ( ) ) { StringBuilder output = new StringBuilder ( stdOut ) ; if ( ! stdOut . isEmpty ( ) && ! stdErr . isEmpty ( ) ) { if ( ! stdOut . endsWith ( "\n" ) ) { output . append ( "\n" ) ; } boolean addLevel = true ; for ( String prefix : logLevelPrefixes ) { if ( stdErr . startsWith ( prefix ) ) { addLevel = false ; break ; } } if ( addLevel ) { output . append ( "*INFO*" ) ; } } result . put ( "output" , output . append ( stdErr ) . toString ( ) ) ; } redirector . resetStdStreams ( ) ; } return result ; }


Input: Run the given keyword and return the results . [CODESPLIT] public Map < String , Object > run_keyword ( String keyword , Object [ ] args ) { return run_keyword ( keyword , args , null ) ; }


Input: Get an array of argument specifications for the given keyword . [CODESPLIT] public String [ ] get_keyword_arguments ( String keyword ) { if ( keyword . equalsIgnoreCase ( "stop_remote_server" ) ) { return new String [ 0 ] ; } try { String [ ] args = servlet . getLibrary ( ) . getKeywordArguments ( keyword ) ; return args == null ? new String [ 0 ] : args ; } catch ( Throwable e ) { log . warn ( "" , e ) ; throw new RuntimeException ( e ) ; } }


Input: Get documentation for given keyword . [CODESPLIT] public String get_keyword_documentation ( String keyword ) { if ( keyword . equalsIgnoreCase ( "stop_remote_server" ) ) { return "Stops the remote server.\n\nThe server may be configured so that users cannot stop it." ; } try { String doc = servlet . getLibrary ( ) . getKeywordDocumentation ( keyword ) ; return doc == null ? "" : doc ; } catch ( Throwable e ) { log . warn ( "" , e ) ; throw new RuntimeException ( e ) ; } }


Input: Main method for command line usage . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { configureLogging ( ) ; CommandLineHelper helper = new CommandLineHelper ( args ) ; if ( helper . getHelpRequested ( ) ) { System . out . print ( helper . getUsage ( ) ) ; System . exit ( 0 ) ; } RemoteServer remoteServer = new RemoteServer ( ) ; String error = helper . getError ( ) ; if ( error == null ) { try { for ( String path : helper . getLibraryMap ( ) . keySet ( ) ) remoteServer . putLibrary ( path , helper . getLibraryMap ( ) . get ( path ) ) ; } catch ( IllegalPathException e ) { error = e . getMessage ( ) ; } } if ( error != null ) { System . out . println ( "Error: " + error ) ; System . out . println ( ) ; System . out . println ( helper . getUsage ( ) ) ; System . exit ( 1 ) ; } remoteServer . setPort ( helper . getPort ( ) ) ; remoteServer . setAllowStop ( helper . getAllowStop ( ) ) ; remoteServer . setHost ( helper . getHost ( ) ) ; remoteServer . start ( ) ; }


Input: Map the given test library to the specified path . Paths must : <ul > <li > start with a / < / li > <li > contain only alphanumeric characters or any of these : / - . _ ~< / li > <li > not end in a / < / li > <li > not contain a repeating sequence of / s< / li > < / ul > [CODESPLIT] public RemoteLibrary putLibrary ( String path , Object library ) { RemoteLibrary oldLibrary = servlet . putLibrary ( path , library ) ; String name = servlet . getLibraryMap ( ) . get ( path ) . getName ( ) ; log . info ( String . format ( "Mapped path %s to library %s." , path , name ) ) ; return oldLibrary ; }


Input: This has been deprecated . Please use { @link #putLibrary } and { @link #setPort } instead . [CODESPLIT] @ Deprecated public void addLibrary ( String className , int port ) { Class < ? > clazz ; try { clazz = Class . forName ( className ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } addLibrary ( clazz , port ) ; }


Input: This has been deprecated . Please use { @link #putLibrary } and { @link #setPort } instead . [CODESPLIT] @ Deprecated public void addLibrary ( Class < ? > clazz , int port ) { if ( ! server . isStopped ( ) ) // old behavior throw new IllegalStateException ( "Cannot add a library once the server is started" ) ; if ( connector . getPort ( ) != 0 && connector . getPort ( ) != port ) { throw new RuntimeException ( "Serving on multiple ports is no longer supported. Please use putLibrary with different paths instead." ) ; } if ( servlet . getLibraryMap ( ) . keySet ( ) . contains ( "/" ) ) { throw new RuntimeException ( "A library has already been mapped to /." ) ; } Object library ; try { library = clazz . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } setPort ( port ) ; putLibrary ( "/" , library ) ; }


Input: A non - blocking method for stopping the remote server that allows requests to complete within the given timeout before shutting down the server . New connections will not be accepted after calling this . [CODESPLIT] public void stop ( int timeoutMS ) throws Exception { log . info ( "Robot Framework remote server stopping" ) ; if ( timeoutMS > 0 ) { server . setGracefulShutdown ( timeoutMS ) ; Thread stopper = new Thread ( ) { @ Override public void run ( ) { try { server . stop ( ) ; } catch ( Throwable e ) { log . error ( String . format ( "Failed to stop the server: %s" , e . getMessage ( ) ) , e ) ; } } } ; stopper . start ( ) ; } else { server . stop ( ) ; } }


Input: Starts the remote server . Add test libraries first before calling this . [CODESPLIT] public void start ( ) throws Exception { log . info ( "Robot Framework remote server starting" ) ; server . start ( ) ; log . info ( String . format ( "Robot Framework remote server started on port %d." , getLocalPort ( ) ) ) ; }


Input: Configures logging systems used by <tt > RemoteServer< / tt > and its dependencies . Specifically <ul > <li > Configure Log4J to log to the console< / li > <li > Set Log4J s log level to INFO< / li > <li > Redirect the Jetty s logging to Log4J< / li > <li > Set Jakarta Commons Logging to log to Log4J< / li > < / ul > This is convenient if you do not want to configure the logging yourself . This will only affect future instances of { [CODESPLIT] public static void configureLogging ( ) { Logger root = Logger . getRootLogger ( ) ; root . removeAllAppenders ( ) ; BasicConfigurator . configure ( ) ; root . setLevel ( Level . INFO ) ; org . eclipse . jetty . util . log . Log . setLog ( new Jetty2Log4J ( ) ) ; LogFactory . releaseAll ( ) ; LogFactory . getFactory ( ) . setAttribute ( "org.apache.commons.logging.Log" , "org.apache.commons.logging.impl.Log4JLogger" ) ; log = LogFactory . getLog ( RemoteServer . class ) ; }


Input: Removes the prefixes from all keys in this handler mapping assuming a String was used as the key and period was used as a separator . Example : AccountsReceivable . Billing . getInvoice - > getInvoice [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void removePrefixes ( ) { Map < String , Object > newHandlerMap = new HashMap < String , Object > ( ) ; for ( Entry < String , Object > entry : ( Set < Entry < String , Object > > ) this . handlerMap . entrySet ( ) ) { String newKey = ( String ) entry . getKey ( ) ; if ( entry . getKey ( ) instanceof String ) { String key = ( String ) entry . getKey ( ) ; if ( key . contains ( "." ) ) { newKey = key . substring ( key . lastIndexOf ( "." ) + 1 ) ; } } newHandlerMap . put ( newKey , entry . getValue ( ) ) ; } this . handlerMap = newHandlerMap ; }


Input: Generate Json by given path to file with properties with only included domain keys . [CODESPLIT] public String convertPropertiesFromFileToJson ( String pathToFile , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { return convertPropertiesFromFileToJson ( new File ( pathToFile ) , includeDomainKeys ) ; }


Input: Generate Json by given file with properties with only included domain keys . [CODESPLIT] public String convertPropertiesFromFileToJson ( File file , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { try { InputStream targetStream = new FileInputStream ( file ) ; return convertToJson ( targetStream , includeDomainKeys ) ; } catch ( FileNotFoundException e ) { throw new ReadInputException ( e ) ; } }


Input: generate Json by given InputStream and given filter . [CODESPLIT] public String convertToJson ( InputStream inputStream , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { return convertToJson ( inputStreamToProperties ( inputStream ) , includeDomainKeys ) ; }


Input: generate Json by given Java Properties [CODESPLIT] public String convertToJson ( Properties properties ) throws ParsePropertiesException { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { if ( ! ( entry . getKey ( ) instanceof String ) ) { throw new ParsePropertiesException ( format ( PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE , entry . getKey ( ) . getClass ( ) , entry . getKey ( ) == null ? "null" : entry . getKey ( ) ) ) ; } } return convertFromValuesAsObjectMap ( propertiesToMap ( properties ) ) ; }


Input: generate Json by given Map&lt ; String String&gt ; [CODESPLIT] public String convertToJson ( Map < String , String > properties ) throws ParsePropertiesException { return convertFromValuesAsObjectMap ( stringValueMapToObjectValueMap ( properties ) ) ; }


Input: generate Json by given Map&lt ; String Object&gt ; [CODESPLIT] public String convertFromValuesAsObjectMap ( Map < String , Object > properties ) throws ParsePropertiesException { ObjectJsonType coreObjectJsonType = new ObjectJsonType ( ) ; for ( String propertiesKey : getAllKeysFromProperties ( properties ) ) { addFieldsToJsonObject ( properties , coreObjectJsonType , propertiesKey ) ; } return prettifyOfJson ( coreObjectJsonType . toStringJson ( ) ) ; }


Input: generate Json by given Map&lt ; String String&gt ; and given filter [CODESPLIT] public String convertFromValuesAsObjectMap ( Map < String , Object > properties , String ... includeDomainKeys ) throws ParsePropertiesException { Map < String , Object > filteredProperties = new HashMap <> ( ) ; for ( String key : properties . keySet ( ) ) { for ( String requiredKey : includeDomainKeys ) { checkKey ( properties , filteredProperties , key , requiredKey ) ; } } return convertFromValuesAsObjectMap ( filteredProperties ) ; }


Input: generate Json by given Java Properties and given filter [CODESPLIT] public String convertToJson ( Properties properties , String ... includeDomainKeys ) throws ParsePropertiesException { return convertFromValuesAsObjectMap ( propertiesToMap ( properties ) , includeDomainKeys ) ; }


Input: Sets background color for this button . <p / > Xml attribute : { @code app : floatingActionButtonColor } <p / > NOTE : this method sets the <code > mColorStateList< / code > field to <code > null< / code > [CODESPLIT] public void setColor ( int color ) { boolean changed = mColor != color || mColorStateList != null ; mColor = color ; mColorStateList = null ; if ( changed ) { updateBackground ( ) ; } }


Input: Sets color state list as background for this button . <p / > Xml attribute : { @code app : floatingActionButtonColor } [CODESPLIT] public void setColorStateList ( ColorStateList colorStateList ) { boolean changed = mColorStateList != colorStateList ; mColorStateList = colorStateList ; if ( changed ) { updateBackground ( ) ; } }


Input: Inflate and initialize background drawable for this view with arguments inflated from xml or specified using { [CODESPLIT] public void initBackground ( ) { final int backgroundId ; if ( mSize == SIZE_MINI ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { backgroundId = R . drawable . com_shamanland_fab_circle_mini ; } else { backgroundId = R . drawable . com_shamanland_fab_mini ; } } else { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { backgroundId = R . drawable . com_shamanland_fab_circle_normal ; } else { backgroundId = R . drawable . com_shamanland_fab_normal ; } } updateBackground ( getResources ( ) . getDrawable ( backgroundId ) ) ; }


Input: Calculates required radius of shadow . [CODESPLIT] protected static int getShadowRadius ( Drawable shadow , Drawable circle ) { int radius = 0 ; if ( shadow != null && circle != null ) { Rect rect = new Rect ( ) ; radius = ( circle . getIntrinsicWidth ( ) + ( shadow . getPadding ( rect ) ? rect . left + rect . right : 0 ) ) / 2 ; } return Math . max ( 1 , radius ) ; }


Input: Builder to create an instance of the client . [CODESPLIT] public static Builder < OcspMultiClient > builder ( ) { return new Builder <> ( new BuildHandler < OcspMultiClient > ( ) { @ Override public OcspMultiClient build ( Properties properties ) { return new OcspMultiClient ( properties ) ; } } ) ; }


Input: Builder to create an instance of OcspFetcher using Apache HttpClient for connectivity . [CODESPLIT] public static Builder < OcspFetcher > builder ( ) { return new Builder <> ( new BuildHandler < OcspFetcher > ( ) { @ Override public OcspFetcher build ( Properties properties ) { return new ApacheOcspFetcher ( properties ) ; } } ) ; }


Input: Method for finding issuer by provided issuers in properties given an issued certificate . [CODESPLIT] protected X509Certificate findIntermediate ( X509Certificate certificate ) throws OcspException { for ( X509Certificate issuer : properties . get ( INTERMEDIATES ) ) if ( issuer . getSubjectX500Principal ( ) . equals ( certificate . getIssuerX500Principal ( ) ) ) return issuer ; throw new OcspException ( "Unable to find issuer '%s'." , certificate . getIssuerX500Principal ( ) . getName ( ) ) ; }


Input: Builder to create an instance of the client . [CODESPLIT] public static Builder < OcspClient > builder ( ) { return new Builder <> ( new BuildHandler < OcspClient > ( ) { @ Override public OcspClient build ( Properties properties ) { return new OcspClient ( properties ) ; } } ) ; }


Input: Execute the maven plugin . [CODESPLIT] @ Override public void execute ( ) throws MojoExecutionException { // First, if filtering is enabled, perform that using the Maven magic if ( applyFiltering ) { performMavenPropertyFiltering ( new File ( inputDirectory ) , filteredOutputDirectory , getInputEncoding ( ) ) ; inputDirectory = filteredOutputDirectory . getAbsolutePath ( ) ; } getLog ( ) . info ( "Pre-processing markdown files from input directory: " + inputDirectory ) ; preprocessMarkdownFiles ( new File ( inputDirectory ) ) ; if ( ! markdownDTOs . isEmpty ( ) ) { getLog ( ) . info ( "Process Pegdown extension options" ) ; int options = getPegdownExtensions ( pegdownExtensions ) ; final Map < String , Attributes > attributesMap = processAttributes ( attributes ) ; getLog ( ) . info ( "Parse Markdown to HTML" ) ; processMarkdown ( markdownDTOs , options , attributesMap ) ; } // FIXME: This will possibly overwrite any filtering updates made in the maven property filtering step above if ( StringUtils . isNotEmpty ( copyDirectories ) ) { getLog ( ) . info ( "Copy files from directories" ) ; for ( String dir : copyDirectories . split ( "," ) ) { for ( Entry < String , String > copyAction : getFoldersToCopy ( inputDirectory , outputDirectory , dir ) . entrySet ( ) ) { copyFiles ( copyAction . getKey ( ) , copyAction . getValue ( ) ) ; } } } }


Input: Parse attributes of the form NodeName : attributeName = attribute value : attributeName = attribute value ... [CODESPLIT] private Map < String , Attributes > processAttributes ( String [ ] attributeList ) { HashMap < String , Attributes > nodeAttributeMap = new HashMap <> ( ) ; for ( String attribute : attributeList ) { String [ ] nodeAttributes = attribute . split ( "\\|" ) ; Attributes attributes = new Attributes ( ) ; for ( int i = 1 ; i < nodeAttributes . length ; i ++ ) { String [ ] attributeNameValue = nodeAttributes [ i ] . split ( "=" , 2 ) ; if ( attributeNameValue . length > 1 ) { String value = attributeNameValue [ 1 ] ; if ( ! value . isEmpty ( ) ) { if ( value . charAt ( 0 ) == ' ' && value . charAt ( value . length ( ) - 1 ) == ' ' ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } else if ( value . charAt ( 0 ) == ' ' && value . charAt ( value . length ( ) - 1 ) == ' ' ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } } attributes . addValue ( attributeNameValue [ 0 ] , value ) ; } else { attributes . addValue ( attributeNameValue [ 0 ] , attributeNameValue [ 0 ] ) ; } } nodeAttributeMap . put ( nodeAttributes [ 0 ] , attributes ) ; } return nodeAttributeMap ; }


Input: Read Markdown files from directory . [CODESPLIT] @ SuppressWarnings ( "UnusedReturnValue" ) private boolean preprocessMarkdownFiles ( File inputDirectory ) throws MojoExecutionException { getLog ( ) . debug ( "Read files from: " + inputDirectory ) ; try { if ( ! inputDirectory . exists ( ) ) { getLog ( ) . info ( "There is no input folder for the project. Skipping." ) ; return false ; } int baseDepth = StringUtils . countMatches ( inputDirectory . getAbsolutePath ( ) , File . separator ) ; // Reading just the markdown dir and sub dirs if recursive option set List < File > markdownFiles = getFilesAsArray ( FileUtils . iterateFiles ( inputDirectory , getInputFileExtensions ( ) , recursiveInput ) ) ; for ( File file : markdownFiles ) { getLog ( ) . debug ( "File getName() " + file . getName ( ) ) ; getLog ( ) . debug ( "File getAbsolutePath() " + file . getAbsolutePath ( ) ) ; getLog ( ) . debug ( "File getPath() " + file . getPath ( ) ) ; MarkdownDTO dto = new MarkdownDTO ( ) ; dto . markdownFile = file ; dto . folderDepth = StringUtils . countMatches ( file . getAbsolutePath ( ) , File . separator ) - ( baseDepth + 1 ) ; if ( alwaysUseDefaultTitle ) { dto . title = defaultTitle ; } else { List < String > raw = FileUtils . readLines ( file , getInputEncoding ( ) ) ; dto . title = getTitle ( raw ) ; } if ( applyFiltering ) { for ( String line : FileUtils . readLines ( file , getInputEncoding ( ) ) ) { if ( isVariableLine ( line ) ) { String key = line . replaceAll ( "(^\\{)|(=.*)" , "" ) ; String value = line . replaceAll ( "(^\\{(.*?)=)|(}$)" , "" ) ; getLog ( ) . debug ( "Substitute: '" + key + "' -> '" + value + "'" ) ; dto . substitutes . put ( key , value ) ; } } } String inputFileExtension = FilenameUtils . getExtension ( file . getName ( ) ) ; dto . htmlFile = new File ( recursiveInput ? outputDirectory + File . separator + file . getParentFile ( ) . getPath ( ) . substring ( inputDirectory . getPath ( ) . length ( ) ) + File . separator + file . getName ( ) . replaceAll ( "." + inputFileExtension , ".html" ) : outputDirectory + File . separator + file . getName ( ) . replaceAll ( "." + inputFileExtension , ".html" ) ) ; getLog ( ) . debug ( "File htmlFile() " + dto . htmlFile ) ; markdownDTOs . add ( dto ) ; } } catch ( IOException e ) { throw new MojoExecutionException ( "Unable to load file " + e . getMessage ( ) , e ) ; } return true ; }