Input: Parsing the complete XML Document Type Definition is way too complex but for many simple cases we can extract something useful from it . <p > doctypedecl :: = <!DOCTYPE S Name ( S ExternalID ) ? S? ( [ intSubset ] S? ) ? > DeclSep :: = PEReference | S intSubset :: = ( markupdecl | DeclSep ) * markupdecl :: = elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment ExternalID :: = SYSTEM S SystemLiteral | PUBLIC S PubidLiteral S SystemLiteral [CODESPLIT] @ Override public void decl ( char [ ] buff , int offset , int length ) throws SAXException { String s = new String ( buff , offset , length ) ; String name = null ; String systemid = null ; String publicid = null ; String [ ] v = split ( s ) ; if ( v . length > 0 && "DOCTYPE" . equalsIgnoreCase ( v [ 0 ] ) ) { if ( theDoctypeIsPresent ) return ; // one doctype only! theDoctypeIsPresent = true ; if ( v . length > 1 ) { name = v [ 1 ] ; if ( v . length > 3 && "SYSTEM" . equals ( v [ 2 ] ) ) { systemid = v [ 3 ] ; } else if ( v . length > 3 && "PUBLIC" . equals ( v [ 2 ] ) ) { publicid = v [ 3 ] ; if ( v . length > 4 ) { systemid = v [ 4 ] ; } else { systemid = "" ; } } } } publicid = trimquotes ( publicid ) ; systemid = trimquotes ( systemid ) ; if ( name != null ) { publicid = cleanPublicid ( publicid ) ; theLexicalHandler . startDTD ( name , publicid , systemid ) ; theLexicalHandler . endDTD ( ) ; theDoctypeName = name ; theDoctypePublicId = publicid ; if ( theScanner instanceof Locator ) { // Must resolve systemid theDoctypeSystemId = ( ( Locator ) theScanner ) . getSystemId ( ) ; try { theDoctypeSystemId = new URL ( new URL ( theDoctypeSystemId ) , systemid ) . toString ( ) ; } catch ( Exception ignore ) { } } } }


Input: If the String is quoted trim the quotes . [CODESPLIT] private static String trimquotes ( String in ) { if ( in == null ) return in ; int length = in . length ( ) ; if ( length == 0 ) return in ; char s = in . charAt ( 0 ) ; char e = in . charAt ( length - 1 ) ; if ( s == e && ( s == ' ' || s == ' ' ) ) { in = in . substring ( 1 , in . length ( ) - 1 ) ; } return in ; }


Input: Recognises quotes around a phrase and doesn t split it . [CODESPLIT] private static String [ ] split ( String val ) throws IllegalArgumentException { val = val . trim ( ) ; if ( val . length ( ) == 0 ) { return new String [ 0 ] ; } else { ArrayList < String > l = new ArrayList < String > ( ) ; int s = 0 ; int e = 0 ; boolean sq = false ; // single quote boolean dq = false ; // double quote char lastc = 0 ; int len = val . length ( ) ; for ( e = 0 ; e < len ; e ++ ) { char c = val . charAt ( e ) ; if ( ! dq && c == ' ' && lastc != ' ' ) { sq = ! sq ; if ( s < 0 ) s = e ; } else if ( ! sq && c == ' ' && lastc != ' ' ) { dq = ! dq ; if ( s < 0 ) s = e ; } else if ( ! sq && ! dq ) { if ( Character . isWhitespace ( c ) ) { if ( s >= 0 ) l . add ( val . substring ( s , e ) ) ; s = - 1 ; } else if ( s < 0 && c != ' ' ) { s = e ; } } lastc = c ; } l . add ( val . substring ( s , e ) ) ; return ( String [ ] ) l . toArray ( new String [ 0 ] ) ; } }


Input: so that the argument can be safely pushed [CODESPLIT] private void rectify ( Element e ) throws SAXException { Element sp ; while ( true ) { for ( sp = theStack ; sp != null ; sp = sp . next ( ) ) { if ( sp . canContain ( e ) ) break ; } if ( sp != null ) break ; ElementType parentType = e . parent ( ) ; if ( parentType == null ) break ; Element parent = new Element ( parentType , defaultAttributes ) ; // parent.name()); parent . setNext ( e ) ; e = parent ; } if ( sp == null ) return ; // don't know what to do while ( theStack != sp ) { if ( theStack == null || theStack . next ( ) == null || theStack . next ( ) . next ( ) == null ) break ; restartablyPop ( ) ; } while ( e != null ) { Element nexte = e . next ( ) ; if ( ! e . name ( ) . equals ( "<pcdata>" ) ) push ( e ) ; e = nexte ; restart ( e ) ; } theNewElement = null ; }


Input: canonicalize case . [CODESPLIT] private String makeName ( char [ ] buff , int offset , int length ) { StringBuffer dst = new StringBuffer ( length + 2 ) ; boolean seenColon = false ; boolean start = true ; // String src = new String(buff, offset, length); // DEBUG for ( ; length -- > 0 ; offset ++ ) { char ch = buff [ offset ] ; if ( Character . isLetter ( ch ) || ch == ' ' ) { start = false ; dst . append ( ch ) ; } else if ( Character . isDigit ( ch ) || ch == ' ' || ch == ' ' ) { if ( start ) dst . append ( ' ' ) ; start = false ; dst . append ( ch ) ; } else if ( ch == ' ' && ! seenColon ) { seenColon = true ; if ( start ) dst . append ( ' ' ) ; start = true ; dst . append ( translateColons ? ' ' : ch ) ; } } int dstLength = dst . length ( ) ; if ( dstLength == 0 || dst . charAt ( dstLength - 1 ) == ' ' ) dst . append ( ' ' ) ; return dst . toString ( ) . intern ( ) ; }


Input: Called to retrieve per - instance state before being killed so that the state can be restored in the constructor . [CODESPLIT] public void onSaveInstanceState ( Bundle outState ) { outState . putString ( "mToolbarVisibility" , mToolbarVisibility . name ( ) ) ; outState . putBoolean ( "mToolbarIsVisible" , mToolbarIsVisible ) ; outState . putInt ( "mActiveEditor" , mActiveEditor ) ; if ( mLinkSelection != null ) { outState . putSerializable ( "mLinkSelection" , mLinkSelection ) ; } }


Input: Perform any final cleanup before the component is destroyed . [CODESPLIT] public void onDestroy ( boolean isSaved ) { EventBus . getDefault ( ) . unregister ( this ) ; for ( RTEditText editor : mEditors . values ( ) ) { editor . unregister ( ) ; editor . onDestroy ( isSaved ) ; } mEditors . clear ( ) ; for ( RTToolbar toolbar : mToolbars . values ( ) ) { toolbar . removeToolbarListener ( ) ; } mToolbars . clear ( ) ; mRTApi = null ; }


Input: Register a rich text editor . <p > Before using the editor it needs to be registered to an RTManager . Using means any calls to the editor ( setText will fail if the editor isn t registered ) ! MUST be called from the ui thread . [CODESPLIT] public void registerEditor ( RTEditText editor , boolean useRichTextEditing ) { mEditors . put ( editor . getId ( ) , editor ) ; editor . register ( this , mRTApi ) ; editor . setRichTextEditing ( useRichTextEditing , false ) ; updateToolbarVisibility ( ) ; }


Input: Unregister a rich text editor . <p > This method may be called before the component is destroyed to stop any interaction with the editor . Not doing so may result in ( asynchronous ) calls coming through when the Activity / Fragment is already stopping its operation . <p > Must be called from the ui thread . <p > Important : calling this method is obsolete once the onDestroy ( boolean ) is called [CODESPLIT] public void unregisterEditor ( RTEditText editor ) { mEditors . remove ( editor . getId ( ) ) ; editor . unregister ( ) ; updateToolbarVisibility ( ) ; }


Input: Register a toolbar . <p > Only after doing that can it be used in conjunction with a rich text editor . Must be called from the ui thread . [CODESPLIT] public void registerToolbar ( ViewGroup toolbarContainer , RTToolbar toolbar ) { mToolbars . put ( toolbar . getId ( ) , toolbar ) ; toolbar . setToolbarListener ( this ) ; toolbar . setToolbarContainer ( toolbarContainer ) ; updateToolbarVisibility ( ) ; }


Input: Unregister a toolbar . <p > This method may be called before the component is destroyed to stop any interaction with the toolbar . Not doing so may result in ( asynchronous ) calls coming through when the Activity / Fragment is already stopping its operation . <p > Must be called from the ui thread . <p > Important : calling this method is obsolete once the onDestroy ( boolean ) is called [CODESPLIT] public void unregisterToolbar ( RTToolbar toolbar ) { mToolbars . remove ( toolbar . getId ( ) ) ; toolbar . removeToolbarListener ( ) ; updateToolbarVisibility ( ) ; }


Input: ****************************************** RTToolbarListener ******************************************* [CODESPLIT] @ Override /* @inheritDoc */ public < V , C extends RTSpan < V > > void onEffectSelected ( Effect < V , C > effect , V value ) { RTEditText editor = getActiveEditor ( ) ; if ( editor != null ) { editor . applyEffect ( effect , value ) ; } }


Input: / * called from onEventMainThread ( MediaEvent ) [CODESPLIT] private void insertImage ( final RTEditText editor , final RTImage image ) { if ( image != null && editor != null ) { Selection selection = new Selection ( editor ) ; Editable str = editor . getText ( ) ; // Unicode Character 'OBJECT REPLACEMENT CHARACTER' (U+FFFC) // see http://www.fileformat.info/info/unicode/char/fffc/index.htm str . insert ( selection . start ( ) , "\uFFFC" ) ; try { // now add the actual image and inform the RTOperationManager about the operation Spannable oldSpannable = editor . cloneSpannable ( ) ; ImageSpan imageSpan = new ImageSpan ( image , false ) ; str . setSpan ( imageSpan , selection . start ( ) , selection . end ( ) + 1 , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; int selStartAfter = editor . getSelectionStart ( ) ; int selEndAfter = editor . getSelectionEnd ( ) ; editor . onAddMedia ( image ) ; Spannable newSpannable = editor . cloneSpannable ( ) ; mOPManager . executed ( editor , new RTOperationManager . TextChangeOperation ( oldSpannable , newSpannable , selection . start ( ) , selection . end ( ) , selStartAfter , selEndAfter ) ) ; } catch ( OutOfMemoryError e ) { str . delete ( selection . start ( ) , selection . end ( ) + 1 ) ; mRTApi . makeText ( R . string . rte_add_image_error , Toast . LENGTH_LONG ) . show ( ) ; } } }


Input:
****************************************** RTEditTextListener ******************************************* [CODESPLIT] @ Override public void onRestoredInstanceState ( RTEditText editor ) { /*
         * We need to process pending sticky MediaEvents once the editors are registered with the
         * RTManager and are fully restored.
         */ MediaEvent event = EventBus . getDefault ( ) . getStickyEvent ( MediaEvent . class ) ; if ( event != null ) { onEventMainThread ( event ) ; } }


Input: Media file was picked - > process the result . [CODESPLIT] @ Subscribe ( sticky = true , threadMode = ThreadMode . MAIN ) public void onEventMainThread ( MediaEvent event ) { RTEditText editor = mEditors . get ( mActiveEditor ) ; RTMedia media = event . getMedia ( ) ; if ( editor != null && media instanceof RTImage ) { insertImage ( editor , ( RTImage ) media ) ; EventBus . getDefault ( ) . removeStickyEvent ( event ) ; mActiveEditor = Integer . MAX_VALUE ; } }


Input: LinkFragment has closed - > process the result . [CODESPLIT] @ Subscribe ( threadMode = ThreadMode . MAIN ) public void onEventMainThread ( LinkEvent event ) { final String fragmentTag = event . getFragmentTag ( ) ; mRTApi . removeFragment ( fragmentTag ) ; if ( ! event . wasCancelled ( ) && ID_01_LINK_FRAGMENT . equals ( fragmentTag ) ) { RTEditText editor = getActiveEditor ( ) ; if ( editor != null ) { Link link = event . getLink ( ) ; String url = null ; if ( link != null && link . isValid ( ) ) { // the mLinkSelection.end() <= editor.length() check is necessary since // the editor text can change when the link fragment is open Selection selection = mLinkSelection != null && mLinkSelection . end ( ) <= editor . length ( ) ? mLinkSelection : new Selection ( editor ) ; String linkText = link . getLinkText ( ) ; // if no text is selected this inserts the entered link text // if text is selected we replace it by the link text Editable str = editor . getText ( ) ; str . replace ( selection . start ( ) , selection . end ( ) , linkText ) ; editor . setSelection ( selection . start ( ) , selection . start ( ) + linkText . length ( ) ) ; url = link . getUrl ( ) ; } editor . applyEffect ( Effects . LINK , url ) ; // if url == null -> remove the link } } }


Input: then translate it back into view ( i . e . eliminate black bars ) . [CODESPLIT] protected void center ( boolean horizontal , boolean vertical ) { if ( mBitmapDisplayed . getBitmap ( ) == null ) { return ; } Matrix m = getImageViewMatrix ( ) ; RectF rect = new RectF ( 0 , 0 , mBitmapDisplayed . getBitmap ( ) . getWidth ( ) , mBitmapDisplayed . getBitmap ( ) . getHeight ( ) ) ; m . mapRect ( rect ) ; float height = rect . height ( ) ; float width = rect . width ( ) ; float deltaX = 0 , deltaY = 0 ; if ( vertical ) { int viewHeight = getHeight ( ) ; if ( height < viewHeight ) { deltaY = ( viewHeight - height ) / 2 - rect . top ; } else if ( rect . top > 0 ) { deltaY = - rect . top ; } else if ( rect . bottom < viewHeight ) { deltaY = getHeight ( ) - rect . bottom ; } } if ( horizontal ) { int viewWidth = getWidth ( ) ; if ( width < viewWidth ) { deltaX = ( viewWidth - width ) / 2 - rect . left ; } else if ( rect . left > 0 ) { deltaX = - rect . left ; } else if ( rect . right < viewWidth ) { deltaX = viewWidth - rect . right ; } } postTranslate ( deltaX , deltaY ) ; setImageMatrix ( getImageViewMatrix ( ) ) ; }


Input: Setup the base matrix so that the image is centered and scaled properly . [CODESPLIT] private void getProperBaseMatrix ( RotateBitmap bitmap , Matrix matrix ) { float viewWidth = getWidth ( ) ; float viewHeight = getHeight ( ) ; float w = bitmap . getWidth ( ) ; float h = bitmap . getHeight ( ) ; matrix . reset ( ) ; // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math . min ( viewWidth / w , 2.0f ) ; float heightScale = Math . min ( viewHeight / h , 2.0f ) ; float scale = Math . min ( widthScale , heightScale ) ; matrix . postConcat ( bitmap . getRotateMatrix ( ) ) ; matrix . postScale ( scale , scale ) ; matrix . postTranslate ( ( viewWidth - w * scale ) / 2F , ( viewHeight - h * scale ) / 2F ) ; }


Input: rather than the current 1024x768 this should be changed down to 200% . [CODESPLIT] protected float maxZoom ( ) { if ( mBitmapDisplayed . getBitmap ( ) == null ) { return 1F ; } float fw = ( float ) mBitmapDisplayed . getWidth ( ) / ( float ) mThisWidth ; float fh = ( float ) mBitmapDisplayed . getHeight ( ) / ( float ) mThisHeight ; float max = Math . max ( fw , fh ) * 4 ; return max ; }


Input: Check whether the effect exists in the currently selected text of the active RTEditText . [CODESPLIT] final public boolean existsInSelection ( RTEditText editor ) { Selection selection = getSelection ( editor ) ; List < RTSpan < V > > spans = getSpans ( editor . getText ( ) , selection , SpanCollectMode . SPAN_FLAGS ) ; return ! spans . isEmpty ( ) ; }


Input: Returns the value ( s ) of this effect in the currently selected text of the active RTEditText . [CODESPLIT] final public List < V > valuesInSelection ( RTEditText editor ) { List < V > result = new ArrayList < V > ( ) ; Selection selection = getSelection ( editor ) ; List < RTSpan < V > > spans = getSpans ( editor . getText ( ) , selection , SpanCollectMode . SPAN_FLAGS ) ; for ( RTSpan < V > span : spans ) { result . add ( span . getValue ( ) ) ; } return result ; }


Input: Remove all effects of this type from the currently selected text of the active RTEditText . If the selection is empty ( cursor ) formatting for the whole text is removed . [CODESPLIT] final public void clearFormattingInSelection ( RTEditText editor ) { Spannable text = editor . getText ( ) ; // if no selection --> select the whole text // otherwise use the getSelection method (implented by sub classes) Selection selection = new Selection ( editor ) ; selection = selection . isEmpty ( ) ? new Selection ( 0 , text . length ( ) ) : getSelection ( editor ) ; List < RTSpan < V > > spans = getSpans ( text , selection , SpanCollectMode . EXACT ) ; for ( Object span : spans ) { editor . getText ( ) . removeSpan ( span ) ; } }


Input: Equivalent to the Spanned . getSpans ( int int Class<T > ) method . Return the markup objects ( spans ) attached to the specified slice of a Spannable . The type of the spans is defined in the SpanCollector . [CODESPLIT] final public List < RTSpan < V > > getSpans ( Spannable str , Selection selection , SpanCollectMode mode ) { if ( mSpanCollector == null ) { // lazy initialize the SpanCollector Type [ ] types = ( ( ParameterizedType ) getClass ( ) . getGenericSuperclass ( ) ) . getActualTypeArguments ( ) ; Class < ? extends RTSpan < V > > spanClazz = ( Class < ? extends RTSpan < V > > ) types [ types . length - 1 ] ; mSpanCollector = newSpanCollector ( spanClazz ) ; } return mSpanCollector . getSpans ( str , selection , mode ) ; }


Input: Make sure applyToSelection works on whole paragraphs and call Effects . cleanupParagraphs ( RTEditText ) afterwards . [CODESPLIT] @ Override public final void applyToSelection ( RTEditText editor , V value ) { Selection selection = getSelection ( editor ) ; applyToSelection ( editor , selection , value ) ; Effects . cleanupParagraphs ( editor , this ) ; }


Input: Find spans within that paragraph and add them to the ParagraphSpanProcessor to be removed once the ParagraphSpanProcessor processes its spans . [CODESPLIT] protected void findSpans2Remove ( Spannable str , Paragraph paragraph , ParagraphSpanProcessor < V > spanProcessor ) { List < RTSpan < V >> spans = getSpans ( str , paragraph , SpanCollectMode . EXACT ) ; spanProcessor . removeSpans ( spans , paragraph ) ; }


Input: This method encodes the query part of an url [CODESPLIT] public static String encodeUrl ( String url ) { Uri uri = Uri . parse ( url ) ; try { Map < String , List < String > > splitQuery = splitQuery ( uri ) ; StringBuilder encodedQuery = new StringBuilder ( ) ; for ( String key : splitQuery . keySet ( ) ) { for ( String value : splitQuery . get ( key ) ) { if ( encodedQuery . length ( ) > 0 ) { encodedQuery . append ( "&" ) ; } encodedQuery . append ( key + "=" + URLEncoder . encode ( value , "UTF-8" ) ) ; } } String queryString = encodedQuery != null && encodedQuery . length ( ) > 0 ? "?" + encodedQuery : "" ; URI baseUri = new URI ( uri . getScheme ( ) , uri . getAuthority ( ) , uri . getPath ( ) , null , uri . getFragment ( ) ) ; return baseUri + queryString ; } catch ( UnsupportedEncodingException ignore ) { } catch ( URISyntaxException ignore ) { } return uri . toString ( ) ; }


Input: This method decodes an url with encoded query string [CODESPLIT] public static String decodeQuery ( String url ) { try { return URLDecoder . decode ( url , "UTF-8" ) ; } catch ( UnsupportedEncodingException ignore ) { } return url ; }


Input: This method determines if the direction of a substring is right - to - left . If the string is empty that determination is based on the default system language Locale . getDefault () . The method can handle invalid substring definitions ( start > end etc . ) in which case the method returns False . [CODESPLIT] public static boolean isRTL ( CharSequence s , int start , int end ) { if ( s == null || s . length ( ) == 0 ) { // empty string --> determine the direction from the default language return isRTL ( Locale . getDefault ( ) ) ; } if ( start == end ) { // if no character is selected we need to expand the selection start = Math . max ( 0 , -- start ) ; if ( start == end ) { end = Math . min ( s . length ( ) , ++ end ) ; } } try { Bidi bidi = new Bidi ( s . subSequence ( start , end ) . toString ( ) , Bidi . DIRECTION_DEFAULT_LEFT_TO_RIGHT ) ; return ! bidi . baseIsLeftToRight ( ) ; } catch ( IndexOutOfBoundsException e ) { return false ; } }


Input: Tries to open a known file browsers to pick a directory . [CODESPLIT] public static boolean pickDirectory ( Activity activity , File startPath , int requestCode ) { PackageManager packageMgr = activity . getPackageManager ( ) ; for ( String [ ] intent : PICK_DIRECTORY_INTENTS ) { String intentAction = intent [ 0 ] ; String uriPrefix = intent [ 1 ] ; Intent startIntent = new Intent ( intentAction ) . putExtra ( "org.openintents.extra.TITLE" , activity . getString ( R . string . save_as ) ) . setData ( Uri . parse ( uriPrefix + startPath . getPath ( ) ) ) ; try { if ( startIntent . resolveActivity ( packageMgr ) != null ) { activity . startActivityForResult ( startIntent , requestCode ) ; return true ; } } catch ( ActivityNotFoundException e ) { showNoFilePickerError ( activity , e ) ; } } return false ; }


Input: ****************************************** Lifecycle Methods ******************************************* [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . rte_crop_image ) ; mImageView = ( CropImageView ) findViewById ( R . id . image ) ; Intent intent = getIntent ( ) ; Bundle extras = intent . getExtras ( ) ; if ( extras != null ) { if ( extras . getString ( CIRCLE_CROP ) != null ) { mImageView . setLayerType ( View . LAYER_TYPE_SOFTWARE , null ) ; mCircleCrop = true ; mAspectX = 1 ; mAspectY = 1 ; } mImageSource = extras . getString ( IMAGE_SOURCE_FILE ) ; mBitmap = getBitmap ( mImageSource ) ; mImageDest = extras . getString ( IMAGE_DESTINATION_FILE ) ; if ( mImageDest == null ) { mImageDest = mImageSource ; } mSaveUri = Uri . fromFile ( new File ( mImageDest ) ) ; if ( extras . containsKey ( ASPECT_X ) && extras . get ( ASPECT_X ) instanceof Integer ) { mAspectX = extras . getInt ( ASPECT_X ) ; } else { throw new IllegalArgumentException ( "aspect_x must be integer" ) ; } if ( extras . containsKey ( ASPECT_Y ) && extras . get ( ASPECT_Y ) instanceof Integer ) { mAspectY = extras . getInt ( ASPECT_Y ) ; } else { throw new IllegalArgumentException ( "aspect_y must be integer" ) ; } mOutputX = extras . getInt ( OUTPUT_X ) ; mOutputY = extras . getInt ( OUTPUT_Y ) ; mScale = extras . getBoolean ( SCALE , true ) ; mScaleUp = extras . getBoolean ( SCALE_UP_IF_NEEDED , true ) ; } if ( mBitmap == null ) { finish ( ) ; return ; } startFaceDetection ( ) ; }


Input: ****************************************** Private Methods ******************************************* [CODESPLIT] private Bitmap getBitmap ( String path ) { Uri uri = MediaUtils . createFileUri ( path ) ; InputStream in = null ; try { in = getContentResolver ( ) . openInputStream ( uri ) ; // Decode image size BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; BitmapFactory . decodeStream ( in , null , options ) ; Helper . closeQuietly ( in ) ; // compute scale factor to ensure that the image is smaller than // IMAGE_MAX_SIZE float maxSize = Math . max ( options . outWidth , options . outHeight ) ; float scale = maxSize > IMAGE_MAX_SIZE ? maxSize / IMAGE_MAX_SIZE : 1.0f ; while ( ( maxSize / scale ) > 8 ) { try { return getBitmap ( in , uri , scale ) ; } catch ( Throwable e ) { Log . w ( getClass ( ) . getSimpleName ( ) , "bitmap could not be created (probably out of memory), decreasing size and retrying" ) ; scale *= 2f ; } } } catch ( IOException e ) { Log . e ( getClass ( ) . getSimpleName ( ) , "file " + path + " not found" ) ; } catch ( Exception e ) { Log . e ( getClass ( ) . getSimpleName ( ) , "error while opening image" , e ) ; } finally { Helper . closeQuietly ( in ) ; } return null ; }


Input:
/ * Compute the sample size as a function of minSideLength and maxNumOfPixels . minSideLength is used to specify that minimal width or height of a bitmap . maxNumOfPixels is used to specify the maximal size in pixels that are tolerable in terms of memory usage . [CODESPLIT] private Bitmap transform ( Matrix scaler , Bitmap source , int targetWidth , int targetHeight , boolean scaleUp ) { int deltaX = source . getWidth ( ) - targetWidth ; int deltaY = source . getHeight ( ) - targetHeight ; if ( ! scaleUp && ( deltaX < 0 || deltaY < 0 ) ) { /*
             * In this case the bitmap is smaller, at least in one dimension,
             * than the target. Transform it by placing as much of the image as
             * possible into the target and leaving the top/bottom or left/right
             * (or both) black.
             */ Bitmap b2 = Bitmap . createBitmap ( targetWidth , targetHeight , Bitmap . Config . ARGB_8888 ) ; Canvas c = new Canvas ( b2 ) ; int deltaXHalf = Math . max ( 0 , deltaX / 2 ) ; int deltaYHalf = Math . max ( 0 , deltaY / 2 ) ; Rect src = new Rect ( deltaXHalf , deltaYHalf , deltaXHalf + Math . min ( targetWidth , source . getWidth ( ) ) , deltaYHalf + Math . min ( targetHeight , source . getHeight ( ) ) ) ; int dstX = ( targetWidth - src . width ( ) ) / 2 ; int dstY = ( targetHeight - src . height ( ) ) / 2 ; Rect dst = new Rect ( dstX , dstY , targetWidth - dstX , targetHeight - dstY ) ; c . drawBitmap ( source , src , dst , null ) ; return b2 ; } float bitmapWidthF = source . getWidth ( ) ; float bitmapHeightF = source . getHeight ( ) ; float bitmapAspect = bitmapWidthF / bitmapHeightF ; float viewAspect = ( float ) targetWidth / targetHeight ; if ( bitmapAspect > viewAspect ) { float scale = targetHeight / bitmapHeightF ; if ( scale < .9F || scale > 1F ) { scaler . setScale ( scale , scale ) ; } else { scaler = null ; } } else { float scale = targetWidth / bitmapWidthF ; if ( scale < .9F || scale > 1F ) { scaler . setScale ( scale , scale ) ; } else { scaler = null ; } } Bitmap b1 ; if ( scaler != null ) { // this is used for minithumb and crop, so we want to mFilter here. b1 = Bitmap . createBitmap ( source , 0 , 0 , source . getWidth ( ) , source . getHeight ( ) , scaler , true ) ; } else { b1 = source ; } int dx1 = Math . max ( 0 , b1 . getWidth ( ) - targetWidth ) ; int dy1 = Math . max ( 0 , b1 . getHeight ( ) - targetHeight ) ; Bitmap b2 = Bitmap . createBitmap ( b1 , dx1 / 2 , dy1 / 2 , targetWidth , targetHeight ) ; if ( b1 != source ) { b1 . recycle ( ) ; } return b2 ; }


Input: Thong added for rotate [CODESPLIT] private Bitmap rotateImage ( Bitmap src , float degree ) { // create new matrix Matrix matrix = new Matrix ( ) ; // setup rotation degree matrix . postRotate ( degree ) ; Bitmap bmp = Bitmap . createBitmap ( src , 0 , 0 , src . getWidth ( ) , src . getHeight ( ) , matrix , true ) ; return bmp ; }


Input: ****************************************** Lifecycle Methods ******************************************* [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; Bundle extras = getIntent ( ) . getExtras ( ) ; if ( extras != null ) { String mediaAction = extras . getString ( EXTRA_MEDIA_ACTION ) ; mMediaAction = mediaAction == null ? null : MediaAction . valueOf ( mediaAction ) ; mMediaFactory = ( RTMediaFactory < RTImage , RTAudio , RTVideo > ) extras . getSerializable ( EXTRA_MEDIA_FACTORY ) ; } if ( mMediaAction != null ) { // retrieve parameters if ( savedInstanceState != null ) { mSelectedMedia = ( RTMedia ) savedInstanceState . getSerializable ( "mSelectedMedia" ) ; } switch ( mMediaAction ) { case PICK_PICTURE : case CAPTURE_PICTURE : mMediaChooserMgr = new ImageChooserManager ( this , mMediaAction , mMediaFactory , this , savedInstanceState ) ; break ; case PICK_VIDEO : case CAPTURE_VIDEO : mMediaChooserMgr = new VideoChooserManager ( this , mMediaAction , mMediaFactory , this , savedInstanceState ) ; break ; case PICK_AUDIO : case CAPTURE_AUDIO : mMediaChooserMgr = new AudioChooserManager ( this , mMediaAction , mMediaFactory , this , savedInstanceState ) ; break ; } if ( mMediaChooserMgr == null ) { finish ( ) ; } else if ( ! isWorkInProgress ( ) ) { setWorkInProgress ( true ) ; if ( ! mMediaChooserMgr . chooseMedia ( ) ) { finish ( ) ; } } } else { finish ( ) ; } }


Input: ****************************************** Listener Methods ******************************************* [CODESPLIT] @ Override public void onActivityResult ( int requestCode , int resultCode , Intent data ) { if ( resultCode == Activity . RESULT_OK ) { if ( requestCode == MediaAction . PICK_PICTURE . requestCode ( ) && data != null ) { mMediaChooserMgr . processMedia ( MediaAction . PICK_PICTURE , data ) ; } else if ( requestCode == MediaAction . CAPTURE_PICTURE . requestCode ( ) ) { mMediaChooserMgr . processMedia ( MediaAction . CAPTURE_PICTURE , data ) ; // data may be null here } else if ( requestCode == Constants . CROP_IMAGE ) { String path = data . getStringExtra ( CropImageActivity . IMAGE_DESTINATION_FILE ) ; if ( path != null && mSelectedMedia instanceof RTImage ) { EventBus . getDefault ( ) . postSticky ( new MediaEvent ( mSelectedMedia ) ) ; finish ( ) ; } } } else { setResult ( RESULT_CANCELED ) ; finish ( ) ; } }


Input: Set a new output destination for the document . [CODESPLIT] public void setOutput ( Writer writer ) { if ( writer == null ) { output = new OutputStreamWriter ( System . out ) ; } else { output = writer ; } }


Input: Force a Namespace declaration with a preferred prefix . <p > <p > This is a convenience method that invokes { @link #setPrefix setPrefix } then { @link #forceNSDecl ( java . lang . String ) forceNSDecl } . < / p > [CODESPLIT] public void forceNSDecl ( String uri , String prefix ) { setPrefix ( uri , prefix ) ; forceNSDecl ( uri ) ; }


Input: Write the XML declaration at the beginning of the document . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] public void startDocument ( ) throws SAXException { writeText4Links ( ) ; reset ( ) ; if ( ! ( "yes" . equals ( outputProperties . getProperty ( OMIT_XML_DECLARATION , "no" ) ) ) ) { write ( "<?xml" ) ; if ( version == null ) { write ( " version=\"1.0\"" ) ; } else { write ( " version=\"" ) ; write ( version ) ; write ( "\"" ) ; } if ( outputEncoding != null && outputEncoding != "" ) { write ( " encoding=\"" ) ; write ( outputEncoding ) ; write ( "\"" ) ; } if ( standalone == null ) { write ( " standalone=\"yes\"?>\n" ) ; } else { write ( " standalone=\"" ) ; write ( standalone ) ; write ( "\"" ) ; } } super . startDocument ( ) ; }


Input: Write a newline at the end of the document . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] public void endDocument ( ) throws SAXException { writeText4Links ( ) ; write ( ' ' ) ; super . endDocument ( ) ; try { flush ( ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }


Input: Write a start tag . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void startElement ( String uri , String localName , String qName , Attributes atts ) throws SAXException { writeText4Links ( ) ; if ( ! ignoreElement ( uri , localName , qName , atts ) ) { elementLevel ++ ; nsSupport . pushContext ( ) ; if ( forceDTD && ! hasOutputDTD ) { startDTD ( localName == null ? qName : localName , "" , "" ) ; } write ( ' ' ) ; writeName ( uri , localName , qName , true ) ; writeAttributes ( atts ) ; if ( elementLevel == 1 ) { forceNSDecls ( ) ; } if ( ! mOmitXHTMLNamespace || ! "html" . equalsIgnoreCase ( localName ) ) { writeNSDecls ( ) ; } write ( ' ' ) ; if ( htmlMode && ( qName . equals ( "script" ) || qName . equals ( "style" ) ) ) { cdataElement = true ; } if ( htmlMode && localName . equals ( "a" ) ) { mIgnoreChars = true ; } super . startElement ( uri , localName , qName , atts ) ; } }


Input: Write an end tag . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void endElement ( String uri , String localName , String qName ) throws SAXException { writeText4Links ( ) ; if ( ! mIgnoredTags . isEmpty ( ) && mIgnoredTags . peek ( ) . equalsIgnoreCase ( qName ) ) { mIgnoredTags . pop ( ) ; } else { if ( ! ( htmlMode && ( uri . equals ( "http://www.w3.org/1999/xhtml" ) || uri . equals ( "" ) ) && ( qName . equals ( "area" ) || qName . equals ( "base" ) || qName . equals ( "basefont" ) || qName . equals ( "br" ) || qName . equals ( "col" ) || qName . equals ( "frame" ) || qName . equals ( "hr" ) || qName . equals ( "img" ) || qName . equals ( "input" ) || qName . equals ( "isindex" ) || qName . equals ( "link" ) || qName . equals ( "meta" ) || qName . equals ( "param" ) ) ) ) { write ( "</" ) ; writeName ( uri , localName , qName , true ) ; write ( ' ' ) ; } if ( elementLevel == 1 ) { write ( ' ' ) ; } if ( htmlMode && localName . equals ( "a" ) ) { mIgnoreChars = false ; } cdataElement = false ; super . endElement ( uri , localName , qName ) ; nsSupport . popContext ( ) ; elementLevel -- ; } }


Input: Write character data . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void characters ( char ch [ ] , int start , int len ) throws SAXException { if ( ! cdataElement ) { if ( mIgnoreChars ) { writeText4Links ( ) ; writeEscUTF16 ( new String ( ch ) , start , len , false ) ; } else { collectText4Links ( ch , start , len ) ; } } else { writeText4Links ( ) ; for ( int i = start ; i < start + len ; i ++ ) { write ( ch [ i ] ) ; } } super . characters ( ch , start , len ) ; }


Input: Write ignorable whitespace . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void ignorableWhitespace ( char ch [ ] , int start , int length ) throws SAXException { writeText4Links ( ) ; writeEscUTF16 ( new String ( ch ) , start , length , false ) ; super . ignorableWhitespace ( ch , start , length ) ; }


Input: Write a processing instruction . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void processingInstruction ( String target , String data ) throws SAXException { writeText4Links ( ) ; write ( "<?" ) ; write ( target ) ; write ( ' ' ) ; write ( data ) ; write ( "?>" ) ; if ( elementLevel < 1 ) { write ( ' ' ) ; } super . processingInstruction ( target , data ) ; }


Input: Force all Namespaces to be declared . <p > This method is used on the root element to ensure that the predeclared Namespaces all appear . [CODESPLIT] private void forceNSDecls ( ) { Enumeration < String > prefixes = forcedDeclTable . keys ( ) ; while ( prefixes . hasMoreElements ( ) ) { String prefix = ( String ) prefixes . nextElement ( ) ; doPrefix ( prefix , null , true ) ; } }


Input: Determine the prefix for an element or attribute name . <p > [CODESPLIT] private String doPrefix ( String uri , String qName , boolean isElement ) { String defaultNS = nsSupport . getURI ( "" ) ; if ( "" . equals ( uri ) ) { if ( isElement && defaultNS != null ) nsSupport . declarePrefix ( "" , "" ) ; return null ; } String prefix ; if ( isElement && defaultNS != null && uri . equals ( defaultNS ) ) { prefix = "" ; } else { prefix = nsSupport . getPrefix ( uri ) ; } if ( prefix != null ) { return prefix ; } prefix = ( String ) doneDeclTable . get ( uri ) ; if ( prefix != null && ( ( ! isElement || defaultNS != null ) && "" . equals ( prefix ) || nsSupport . getURI ( prefix ) != null ) ) { prefix = null ; } if ( prefix == null ) { prefix = ( String ) prefixTable . get ( uri ) ; if ( prefix != null && ( ( ! isElement || defaultNS != null ) && "" . equals ( prefix ) || nsSupport . getURI ( prefix ) != null ) ) { prefix = null ; } } if ( prefix == null && qName != null && ! "" . equals ( qName ) ) { int i = qName . indexOf ( ' ' ) ; if ( i == - 1 ) { if ( isElement && defaultNS == null ) { prefix = "" ; } } else { prefix = qName . substring ( 0 , i ) ; } } for ( ; prefix == null || nsSupport . getURI ( prefix ) != null ; prefix = "__NS" + ++ prefixCounter ) ; nsSupport . declarePrefix ( prefix , uri ) ; doneDeclTable . put ( uri , prefix ) ; return prefix ; }


Input: Write a raw character . [CODESPLIT] private void write ( char c ) throws SAXException { try { output . write ( c ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }


Input: Write a raw string . [CODESPLIT] private void write ( String s ) throws SAXException { try { output . write ( s ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }


Input: Write out an attribute list escaping values . <p > The names will have prefixes added to them . [CODESPLIT] private void writeAttributes ( Attributes atts ) throws SAXException { int len = atts . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { write ( ' ' ) ; writeName ( atts . getURI ( i ) , atts . getLocalName ( i ) , atts . getQName ( i ) , false ) ; if ( htmlMode && booleanAttribute ( atts . getLocalName ( i ) , atts . getQName ( i ) , atts . getValue ( i ) ) ) break ; write ( "=\"" ) ; String s = atts . getValue ( i ) ; writeEscUTF16 ( s , 0 , s . length ( ) , true ) ; write ( ' ' ) ; } }


Input: Return true if the attribute is an HTML boolean from the above list . [CODESPLIT] private boolean booleanAttribute ( String localName , String qName , String value ) { String name = localName ; if ( name == null ) { int i = qName . indexOf ( ' ' ) ; if ( i != - 1 ) name = qName . substring ( i + 1 , qName . length ( ) ) ; } if ( ! name . equals ( value ) ) return false ; for ( int j = 0 ; j < booleans . length ; j ++ ) { if ( name . equals ( booleans [ j ] ) ) return true ; } return false ; }


Input: Write an array of data characters with escaping . [CODESPLIT] private void writeEscUTF16 ( String s , int start , int length , boolean isAttVal ) throws SAXException { String subString = s . substring ( start , start + length ) ; write ( StringEscapeUtils . escapeHtml4 ( subString ) ) ; }


Input: Write out the list of Namespace declarations . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private void writeNSDecls ( ) throws SAXException { Enumeration < String > prefixes = ( Enumeration < String > ) nsSupport . getDeclaredPrefixes ( ) ; while ( prefixes . hasMoreElements ( ) ) { String prefix = ( String ) prefixes . nextElement ( ) ; String uri = nsSupport . getURI ( prefix ) ; if ( uri == null ) { uri = "" ; } write ( ' ' ) ; if ( "" . equals ( prefix ) ) { write ( "xmlns=\"" ) ; } else { write ( "xmlns:" ) ; write ( prefix ) ; write ( "=\"" ) ; } writeEscUTF16 ( uri , 0 , uri . length ( ) , true ) ; write ( ' ' ) ; } }


Input: Write an element or attribute name . [CODESPLIT] private void writeName ( String uri , String localName , String qName , boolean isElement ) throws SAXException { String prefix = doPrefix ( uri , qName , isElement ) ; if ( prefix != null && ! "" . equals ( prefix ) ) { write ( prefix ) ; write ( ' ' ) ; } if ( localName != null && ! "" . equals ( localName ) ) { write ( localName ) ; } else { int i = qName . indexOf ( ' ' ) ; write ( qName . substring ( i + 1 , qName . length ( ) ) ) ; } }


Input: ////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public void comment ( char [ ] ch , int start , int length ) throws SAXException { write ( "<!--" ) ; for ( int i = start ; i < start + length ; i ++ ) { write ( ch [ i ] ) ; if ( ch [ i ] == ' ' && i + 1 <= start + length && ch [ i + 1 ] == ' ' ) write ( ' ' ) ; } write ( "-->" ) ; }


Input: Make this element anonymous . Remove any <tt > id< / tt > or <tt > name< / tt > attribute present in the element s attributes . [CODESPLIT] public void anonymize ( ) { for ( int i = theAtts . getLength ( ) - 1 ; i >= 0 ; i -- ) { if ( theAtts . getType ( i ) . equals ( "ID" ) || theAtts . getQName ( i ) . equals ( "name" ) ) { theAtts . removeAttribute ( i ) ; } } }


Input: Clean the attributes of this element . Attributes with null name ( the name was ill - formed ) or null value ( the attribute was present in the element type but not in this actual element ) are removed . [CODESPLIT] public void clean ( ) { for ( int i = theAtts . getLength ( ) - 1 ; i >= 0 ; i -- ) { String name = theAtts . getLocalName ( i ) ; if ( theAtts . getValue ( i ) == null || name == null || name . length ( ) == 0 ) { theAtts . removeAttribute ( i ) ; continue ; } } }


Input: Create a AmazonKinesis client configured with some optional properties ( can also be configured using environment variables ) : [CODESPLIT] public static AmazonKinesis buildKinesisClient ( @ Nullable String accessKey , @ Nullable String secretKey , // @ Nullable String endpoint , @ Nullable Integer port , @ Nullable String region ) { AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder . standard ( ) ; setAws ( builder , accessKey , secretKey , endpoint , port , region ) ; return builder . build ( ) ; }


Input: Ensure that the Kinesis Stream exists ( creates it if does not exist ) . [CODESPLIT] public static void ensureStreamExists ( AmazonKinesis kinesisClient , String streamName ) { createStreamIfNotExists ( kinesisClient , streamName , 1 ) ; waitStreamActivation ( kinesisClient , streamName , MIN_3 ) ; }


Input: Create a stream if it does not already exist . [CODESPLIT] private static void createStreamIfNotExists ( AmazonKinesis kinesis , String streamName , int shardCount ) { performAmazonActionWithRetry ( "createStream" , ( ) -> { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( streamName ) . withLimit ( 1 ) ; try { kinesis . describeStream ( describeStreamRequest ) ; } catch ( ResourceNotFoundException e ) { kinesis . createStream ( streamName , shardCount ) ; } return null ; } , DEFAULT_RETRY_COUNT , DEFAULT_RETRY_DURATION_IN_MILLIS ) ; }


Input: Waits that the stream has been created . [CODESPLIT] private static void waitStreamActivation ( AmazonKinesis consumer , String streamName , long streamCreationTimeoutMillis ) { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( streamName ) . withLimit ( 1 ) ; DescribeStreamResult describeStreamResult = null ; String streamStatus = null ; long endTime = System . currentTimeMillis ( ) + streamCreationTimeoutMillis ; do { try { describeStreamResult = consumer . describeStream ( describeStreamRequest ) ; streamStatus = describeStreamResult . getStreamDescription ( ) . getStreamStatus ( ) ; if ( ACTIVE_STREAM_STATUS . equals ( streamStatus ) ) { break ; } Thread . sleep ( 100 ) ; } catch ( ResourceNotFoundException | LimitExceededException ignored ) { // ignored } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new AwsKinesisException ( "Thread interrupted while waiting for stream activation" , args -> args . add ( "streamName" , streamName ) , e ) ; } } while ( System . currentTimeMillis ( ) < endTime ) ; if ( describeStreamResult == null || streamStatus == null || ! streamStatus . equals ( ACTIVE_STREAM_STATUS ) ) { throw new AwsKinesisException ( "Stream never went active" , args -> args . add ( "streamName" , streamName ) . add ( "streamCreationTimeoutMillis" , streamCreationTimeoutMillis ) ) ; } }


Input: TODO very ugly fix [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < T > TypeConverter < T > getTypeConverter ( Class < T > clazz ) { TypeConverter < T > converter = ( TypeConverter < T > ) TYPE_CONVERTERS . get ( clazz ) ; if ( converter == null ) { converter = value -> ( T ) value ; } return converter ; }


Input: This method has to be called in the default implementation of an entity interface to declare that a relation is the reciprocal of another relation : <ul > <li > the straight relation is defined from the { @code TAIL } entity to the { @code HEAD } entity . It must not have a default implementation< / li > <li > the reverse relation is defined from the { @code HEAD } entity to the { @code TAIL } entity . It must have a default implementation that call this method< / li > < / ul > <p > At runtime this call is only issued during the model analysis . The entity instances proxies overrides this default implementation to return the needed information . <br > [CODESPLIT] public static < TAIL , HEAD > Collection < TAIL > reciprocalManyRelation ( Class < TAIL > tailEntityClass , Accessor < TAIL , HEAD > relationAccessor ) { return THREAD_LOCAL_DSL_HELPER . get ( ) . reciprocalManyRelation ( tailEntityClass , relationAccessor ) ; }


Input: Complete snapshot N with lacking instance snapshots from snapshot N - 1 [CODESPLIT] private static void completeStoreSnapshotWithMissingInstanceSnapshots ( Path targetStoresPath ) { String transactionIdRegexAlone = "\"transactionId\"\\s*:\\s*\\d+\\s*," ; String transactionIdRegexReplace = "(.*\"transactionId\"\\s*:\\s*)\\d+(\\s*,.*)" ; Pattern transactionIdPattern = compile ( transactionIdRegexAlone ) ; Set < File > previousSnapshots = new HashSet <> ( ) ; Arrays . stream ( targetStoresPath . resolve ( SNAPSHOT_DIRECTORY_NAME ) . toFile ( ) . listFiles ( ) ) . sorted ( ) . forEach ( snapshot -> { Set < String > snapshotNames = Arrays . stream ( snapshot . listFiles ( ) ) . map ( File :: getName ) . collect ( toSet ( ) ) ; previousSnapshots . stream ( ) . filter ( previousSnapshot -> ! snapshotNames . contains ( previousSnapshot . getName ( ) ) ) . forEach ( previousSnapshot -> { try { Path targetPath = snapshot . toPath ( ) . resolve ( previousSnapshot . getName ( ) ) ; Path sourcePath = previousSnapshot . toPath ( ) ; long count = countTransactionId ( transactionIdPattern , sourcePath ) ; if ( count != 1L ) { throw new StoreException ( "transactionId not found once" , args -> args . add ( "found count" , count ) ) ; } BigInteger newTransactionId = new BigInteger ( snapshot . getName ( ) ) ; replaceTransactionIdValue ( transactionIdRegexReplace , sourcePath , targetPath , newTransactionId . toString ( ) ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } ) ; previousSnapshots . clear ( ) ; previousSnapshots . addAll ( Arrays . stream ( snapshot . listFiles ( ) ) . collect ( toSet ( ) ) ) ; } ) ; }


Input: Returns the single created shard ( stream has a single shard ) . [CODESPLIT] private Shard getUniqueShard ( ) { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( m_streamName ) . withLimit ( 1 ) ; DescribeStreamResult describeStreamResult = performAmazonActionWithRetry ( "describe stream " + m_streamName , ( ) -> m_kinesis . describeStream ( describeStreamRequest ) , DEFAULT_RETRY_COUNT , DEFAULT_RETRY_DURATION_IN_MILLIS ) ; String streamStatus = describeStreamResult . getStreamDescription ( ) . getStreamStatus ( ) ; if ( streamStatus == null || ! streamStatus . equals ( ACTIVE_STREAM_STATUS ) ) { throw new AwsKinesisException ( "Stream does not exist" , args -> args . add ( "streamName" , m_streamName ) ) ; } List < Shard > shards = describeStreamResult . getStreamDescription ( ) . getShards ( ) ; checkState ( shards . size ( ) == 1 , "Kinesis Stream should contain only one shard" , args -> args . add ( "streamName" , m_streamName ) . add ( "shardCount" , shards . size ( ) ) ) ; return shards . get ( 0 ) ; }


Input: Wait that the minimum duration between two GetShardIteratorRequests has elapsed . [CODESPLIT] private boolean waitTheMinimalDurationToExecuteTheNextProvisioningRequest ( ) { if ( m_lastGetShardIteratorRequestTime != null ) { long delay = m_durationBetweenRequests . get ( ) - ( System . currentTimeMillis ( ) - m_lastGetShardIteratorRequestTime ) ; if ( delay > 0 ) { try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } } } m_lastGetShardIteratorRequestTime = System . currentTimeMillis ( ) ; return true ; }


Input: Retrieves records corresponding to the request . [CODESPLIT] @ Nullable private List < Record > getRecords ( GetRecordsRequest getRecordsRequest ) { return tryAmazonAction ( "" , ( ) -> { GetRecordsResult getRecordsResult = m_kinesis . getRecords ( getRecordsRequest ) ; m_shardIterator = getRecordsResult . getNextShardIterator ( ) ; List < Record > records = getRecordsResult . getRecords ( ) ; LOG . trace ( "Get records" , args -> args . add ( "streamName" , m_streamName ) . add ( "record number" , records . size ( ) ) . add ( "millisBehindLatest" , getRecordsResult . getMillisBehindLatest ( ) ) ) ; return records ; } , m_durationBetweenRequests ) . orElse ( List . of ( ) ) ; }


Input: Handle retry for amazon quotas [CODESPLIT] public static < T > T performAmazonActionWithRetry ( String actionLabel , Supplier < T > action , int retryLimit , int durationInMillis ) { int retryCount = 0 ; do { try { return action . get ( ) ; } catch ( LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e ) { // We should just wait a little time before trying again int remainingRetries = retryLimit - retryCount ; LOG . debug ( "Amazon exception caught" , args -> args . add ( "exception" , e . getClass ( ) . getName ( ) ) . add ( "action" , actionLabel ) . add ( "remainingRetryCount" , remainingRetries ) ) ; } sleepUntilInterrupted ( actionLabel , durationInMillis ) ; } while ( retryCount ++ < retryLimit ) ; throw new AwsException ( "Limit exceeded, all retries failed" , args -> args . add ( "action" , actionLabel ) . add ( "retryLimit" , retryLimit ) ) ; }


Input: Try to perform an Amazon action and increase the duration between requests if some exception is exceeding resource usage exception is thrown . [CODESPLIT] public static < T > Optional < T > tryAmazonAction ( String actionLabel , Supplier < T > action , AtomicLong durationBetweenRequests ) { try { return of ( action . get ( ) ) ; } catch ( LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e ) { int durationRandomModifier = 1 + RANDOM . nextInt ( 64 ) ; // random duration to make readers out of sync, avoiding simultaneous readings long updatedDuration = durationBetweenRequests . updateAndGet ( duration -> duration * 2 // twice the duration + duration * 2 / durationRandomModifier ) ; // add random duration to avoid simultaneous reads LOG . debug ( "Update of minimal duration between two get shard iterator requests" , args -> args . add ( "actionLabel" , actionLabel ) . add ( "new minimalDurationBetweenTwoGetShardIteratorRequests" , updatedDuration ) ) ; } return empty ( ) ; }


Input: Create a AwsS3SnapshotStore with some properties set to configure S3 client : ( + ) to configure the access both access key and secret key must be provided . ( * ) to configure the endpoint URL the endpoint the port and the region must be provided . [CODESPLIT] public static AmazonS3 buildS3Client ( @ Nullable String accessKey , @ Nullable String secretKey , // @ Nullable String endpoint , @ Nullable Integer port , @ Nullable String region ) { AmazonS3ClientBuilder builder = AmazonS3ClientBuilder . standard ( ) ; setAws ( builder , accessKey , secretKey , endpoint , port , region ) ; return builder . build ( ) ; }


Input: Throws an exception if the bucket does not exist or is not readable . [CODESPLIT] static String checkBucketIsAccessible ( AmazonS3 amazonS3 , String bucketName ) { HeadBucketRequest headBucketRequest = new HeadBucketRequest ( bucketName ) ; try { amazonS3 . headBucket ( headBucketRequest ) ; } catch ( AmazonServiceException e ) { throw new AwsS3Exception ( "Bucket is not accessible" , args -> args . add ( "bucketName" , bucketName ) , e ) ; } return bucketName ; }


Input: This method don t use cache . Use with care . <br > If caching is required then use { @link #getMethodName ( Class Accessor ) } [CODESPLIT] public static < T > Method retrieveMethod ( Class < T > clazz , Accessor < T , ? > accessor ) { MethodCallRecorder methodCallRecorder = new MethodCallRecorder ( ) ; T accessorInstance = ProxyFactoryBuilder . < MethodCallRecorder > newProxyFactoryBuilder ( ) // . defaultObjectMethods ( ) // . unhandled ( ( context , proxy , method , args ) -> { context . setMethod ( method ) ; return DEFAULT_VALUES . get ( method . getReturnType ( ) ) ; } ) // . build ( clazz ) . createProxy ( methodCallRecorder ) ; accessor . get ( accessorInstance ) ; Method method = methodCallRecorder . getMethod ( ) ; if ( method == null ) { throw new StoreException ( "Method reference didn't call any method on the class" , args -> args . add ( "className" , clazz . getName ( ) ) ) ; } return method ; }


Input: Load the stores . [CODESPLIT] Optional < BigInteger > loadStores ( Function < String , EntityStores > entityStoresByStoreName , BiFunction < SerializableSnapshot , String , SerializableSnapshot > snapshotPostProcessor ) { Optional < BigInteger > latestSnapshotTxId ; try { latestSnapshotTxId = m_snapshotStore . listSnapshots ( ) . stream ( ) . max ( BigInteger :: compareTo ) ; } catch ( IOException e ) { throw new UnrecoverableStoreException ( "Error occurred when recovering from latest snapshot" , e ) ; } latestSnapshotTxId . ifPresent ( lastTx -> { LOG . info ( "Recovering store from snapshot" , args -> args . add ( "transactionId" , lastTx ) ) ; var postProcess = new SnapshotPostProcessor ( snapshotPostProcessor ) ; try { Flowable . fromPublisher ( m_snapshotStore . createSnapshotReader ( lastTx ) ) // . blockingForEach ( reader -> { String storeName = reader . storeName ( ) ; EntityStores entityStores = entityStoresByStoreName . apply ( storeName ) ; SerializableSnapshot serializableSnapshot ; try ( InputStream is = reader . inputStream ( ) ) { serializableSnapshot = m_snapshotSerializer . deserializeSnapshot ( storeName , is ) ; } if ( serializableSnapshot . getSnapshotModelVersion ( ) != SNAPSHOT_MODEL_VERSION ) { throw new UnrecoverableStoreException ( "Snapshot serializable model version is not supported" , args -> args . add ( "version" , serializableSnapshot . getSnapshotModelVersion ( ) ) . add ( "expectedVersion" , SNAPSHOT_MODEL_VERSION ) ) ; } if ( ! lastTx . equals ( serializableSnapshot . getTransactionId ( ) ) ) { throw new UnrecoverableStoreException ( "Snapshot transaction id  mismatch with request transaction id" , args -> args . add ( "snapshotTransactionId" , serializableSnapshot . getTransactionId ( ) ) . add ( "requestTransactionId" , lastTx ) ) ; } SerializableSnapshot finalSnapshot = postProcess . apply ( storeName , serializableSnapshot ) ; finalSnapshot . getEntities ( ) . forEach ( serializableEntityInstances -> { String entityName = serializableEntityInstances . getEntityName ( ) ; EntityStore < ? > entityStore = entityStores . getEntityStore ( entityName ) ; checkArgument ( entityStore != null , "Entity has not be registered in the store" , args -> args . add ( "entityName" , entityName ) ) ; entityStore . recover ( serializableEntityInstances ) ; } ) ; } ) ; } catch ( Exception e ) { throw new UnrecoverableStoreException ( "Error occurred when recovering from latest snapshot" , e ) ; } // update the applicationModelVersion if any consistent load/update m_applicationModelVersion = postProcess . getConsistentApplicationModelVersion ( ) ; } ) ; if ( ! latestSnapshotTxId . isPresent ( ) ) { LOG . info ( "Store has no snapshot, store is empty, creating it's first snapshot" ) ; } return latestSnapshotTxId ; }


Input: { [CODESPLIT] public InputStream locateStream ( final String uri , final File folder ) throws IOException { final Collection < File > files = findMatchedFiles ( new WildcardContext ( uri , folder ) ) ; final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; for ( final File file : files ) { if ( file . isFile ( ) ) { final InputStream is = new FileInputStream ( file ) ; IOUtils . copy ( is , out ) ; is . close ( ) ; } else { LOG . debug ( "Ignoring folder: " + file ) ; } } return new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; }


Input: Creates a { @link IOFileFilter } which collects found files into a collection and also populates a map with found resources and corresponding files . [CODESPLIT] @ SuppressWarnings ( "serial" ) private IOFileFilter createWildcardCollectorFileFilter ( final WildcardContext wildcardContext , final Collection < File > allFiles ) { notNull ( wildcardContext ) ; notNull ( allFiles ) ; return new WildcardFileFilter ( wildcardContext . getWildcard ( ) ) { @ Override public boolean accept ( final File file ) { final boolean accept = super . accept ( file ) ; if ( accept ) { LOG . debug ( "\tfound resource: {}" , file . getPath ( ) ) ; allFiles . add ( file ) ; } return accept ; } } ; }


Input: Validates arguments used by { @link DefaultWildcardStreamLocator#findMatchedFiles ( String File ) } method . [CODESPLIT] private void validate ( final WildcardContext wildcardContext ) throws IOException { notNull ( wildcardContext ) ; final String uri = wildcardContext . getUri ( ) ; final File folder = wildcardContext . getFolder ( ) ; if ( uri == null || folder == null || ! folder . isDirectory ( ) ) { final StringBuffer message = new StringBuffer ( "Invalid folder provided" ) ; if ( folder != null ) { message . append ( ", with path: " ) . append ( folder . getPath ( ) ) ; } message . append ( ", with fileNameWithWildcard: " ) . append ( uri ) ; throw new IOException ( message . toString ( ) ) ; } if ( ! hasWildcard ( uri ) ) { throw new IOException ( "No wildcard detected for the uri: " + uri ) ; } LOG . debug ( "uri: {}" , uri ) ; LOG . debug ( "folder: {}" , folder . getPath ( ) ) ; LOG . debug ( "wildcard: {}" , wildcardContext . getWildcard ( ) ) ; }


Input:
Uses the wildcardExpanderHandler to process all found files and directories . [CODESPLIT] void triggerWildcardExpander ( final Collection < File > allFiles , final WildcardContext wildcardContext ) throws IOException { LOG . debug ( "wildcard resources: {}" , allFiles ) ; if ( allFiles . isEmpty ( ) ) { final String message = String . format ( "No resource found for wildcard: %s" , wildcardContext . getWildcard ( ) ) ; LOG . warn ( message ) ; throw new IOException ( message ) ; } if ( wildcardExpanderHandler != null ) { try { wildcardExpanderHandler . apply ( allFiles ) ; } catch ( final IOException e ) { // preserve exception type if the exception is already an IOException
 throw e ; } catch ( final Exception e ) { LOG . debug ( "wildcard expanding error. Reporting original exception" , e ) ; throw new IOException ( "Exception during expanding wildcard: " + e . getMessage ( ) ) ; } } }


Input: Replace all occurrences of a substring within a string with another string . [CODESPLIT] private static String replace ( final String inString , final String oldPattern , final String newPattern ) { if ( ! hasLength ( inString ) || ! hasLength ( oldPattern ) || newPattern == null ) { return inString ; } final StringBuffer sbuf = new StringBuffer ( ) ; // output StringBuffer we'll build up int pos = 0 ; // our position in the old string int index = inString . indexOf ( oldPattern ) ; // the index of an occurrence we've found, or -1 final int patLen = oldPattern . length ( ) ; while ( index >= 0 ) { sbuf . append ( inString . substring ( pos , index ) ) ; sbuf . append ( newPattern ) ; pos = index + patLen ; index = inString . indexOf ( oldPattern , pos ) ; } sbuf . append ( inString . substring ( pos ) ) ; // remember to append any characters to the right of a match return sbuf . toString ( ) ; }


Input: Convenience method to return a Collection as a delimited ( e . g . CSV ) String . E . g . useful for <code > toString () < / code > implementations . [CODESPLIT] private static String collectionToDelimitedString ( final Collection < String > coll , final String delim ) { return collectionToDelimitedString ( coll , delim , EMPTY , EMPTY ) ; }


Input: Delete any character in a given String . [CODESPLIT] private static String deleteAny ( final String inString , final String charsToDelete ) { if ( ! hasLength ( inString ) || ! hasLength ( charsToDelete ) ) { return inString ; } final StringBuffer out = new StringBuffer ( ) ; for ( int i = 0 ; i < inString . length ( ) ; i ++ ) { final char c = inString . charAt ( i ) ; if ( charsToDelete . indexOf ( c ) == - 1 ) { out . append ( c ) ; } } return out . toString ( ) ; }


Input: { [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { LOG . debug ( "processing resource: {}" , resource ) ; final String content = IOUtils . toString ( reader ) ; final TypeScriptCompiler compiler = enginePool . getObject ( ) ; try { writer . write ( compiler . compile ( content ) ) ; } catch ( final Exception e ) { onException ( e , content ) ; } finally { // return for later reuse enginePool . returnObject ( compiler ) ; reader . close ( ) ; writer . close ( ) ; } }


Input: { [CODESPLIT] @ Override protected String getArgument ( final Resource resource ) { final String name = resource == null ? "" : FilenameUtils . getBaseName ( resource . getUri ( ) ) ; return String . format ( "'%s'" , name ) ; }


Input: { [CODESPLIT] private RequestHandlerFactory newRequestHandlerFactory ( ) { final SimpleRequestHandlerFactory factory = new SimpleRequestHandlerFactory ( ) ; final List < RequestHandler > requestHandlers = getConfiguredStrategies ( ) ; for ( final RequestHandler requestHandler : requestHandlers ) { factory . addHandler ( requestHandler ) ; } // use default when none provided if ( requestHandlers . isEmpty ( ) ) { LOG . debug ( "No locators configured. Using Default locator factory." ) ; return new DefaultRequestHandlerFactory ( ) ; } return factory ; }


Input: Add a single lint report to underlying collection . [CODESPLIT] public LintReport < T > addReport ( final ResourceLintReport < T > resourceLintReport ) { Validate . notNull ( resourceLintReport ) ; reports . add ( resourceLintReport ) ; return this ; }


Input: Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { if ( builder == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( DEFINE_WINDOW , "window" ) . evaluateChain ( getScriptAsStream ( ) , "linter.js" ) ; } return builder ; } catch ( final IOException e ) { throw new WroRuntimeException ( "Failed reading init script" , e ) ; } }


Input: Validates a js using jsHint and throws { @link LinterException } if the js is invalid . If no exception is thrown the js is valid . [CODESPLIT] public void validate ( final String data ) throws LinterException { final StopWatch watch = new StopWatch ( ) ; watch . start ( "init" ) ; final RhinoScriptBuilder builder = initScriptBuilder ( ) ; watch . stop ( ) ; watch . start ( "lint" ) ; final String packIt = buildLinterScript ( WroUtil . toJSMultiLineString ( data ) , getOptions ( ) ) ; final boolean valid = Boolean . parseBoolean ( builder . evaluate ( packIt , "check" ) . toString ( ) ) ; if ( ! valid ) { final String json = builder . addJSON ( ) . evaluate ( String . format ( "JSON.stringify(JSON.decycle(%s.errors))" , getLinterName ( ) ) , "stringify errors" ) . toString ( ) ; LOG . debug ( "json {}" , json ) ; final Type type = new TypeToken < List < LinterError > > ( ) { } . getType ( ) ; final List < LinterError > errors = new Gson ( ) . fromJson ( json , type ) ; LOG . debug ( "errors {}" , errors ) ; throw new LinterException ( ) . setErrors ( errors ) ; } LOG . debug ( "result: {}" , valid ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ; }


Input: TODO this method is duplicated in { @link CssLint } . Extract and reuse it . [CODESPLIT] private String buildLinterScript ( final String data , final String options ) { return String . format ( "%s(%s,%s);" , getLinterName ( ) , data , optionsBuilder . buildFromCsv ( options ) ) ; }


Input: Reuse { [CODESPLIT] @ Override protected ProcessorsFactory newProcessorsFactory ( ) { return new ConfigurableProcessorsFactory ( ) { @ Override protected Properties newProperties ( ) { final Properties props = new Properties ( ) ; updatePropertiesWithConfiguration ( props , ConfigurableProcessorsFactory . PARAM_PRE_PROCESSORS ) ; updatePropertiesWithConfiguration ( props , ConfigurableProcessorsFactory . PARAM_POST_PROCESSORS ) ; return props ; } @ Override protected Map < String , ResourcePostProcessor > getPostProcessorStrategies ( final ProcessorProvider provider ) { final Map < String , ResourcePostProcessor > map = super . getPostProcessorStrategies ( provider ) ; contributePostProcessors ( map ) ; return map ; } @ Override protected Map < String , ResourcePreProcessor > getPreProcessorStrategies ( final ProcessorProvider provider ) { final Map < String , ResourcePreProcessor > map = super . getPreProcessorStrategies ( provider ) ; contributePreProcessors ( map ) ; return map ; } } ; }


Input: Add to properties a new key with value extracted either from filterConfig or from configurable properties file . This method helps to ensure backward compatibility of the filterConfig vs configProperties configuration . [CODESPLIT] private void updatePropertiesWithConfiguration ( final Properties props , final String key ) { final FilterConfig filterConfig = Context . get ( ) . getFilterConfig ( ) ; // first, retrieve value from init-param for backward compatibility final String valuesAsString = filterConfig . getInitParameter ( key ) ; if ( valuesAsString != null ) { props . setProperty ( key , valuesAsString ) ; } else { // retrieve value from configProperties file final String value = getConfigProperties ( ) . getProperty ( key ) ; if ( value != null ) { props . setProperty ( key , value ) ; } } }


Input: Use this method rather than accessing the field directly because it will create a default one if none is provided . [CODESPLIT] private Properties getConfigProperties ( ) { if ( configProperties == null ) { configProperties = newConfigProperties ( ) ; if ( additionalConfigProperties != null ) { configProperties . putAll ( additionalConfigProperties ) ; } } return configProperties ; }


Input: Override this method to provide a different config properties file location . It is very likely that you would like it to be the same as the one used by the { @link FilterConfigWroConfigurationFactory } . The default properties file location is / WEB - INF / wro . properties . [CODESPLIT] protected Properties newConfigProperties ( ) { // default location is /WEB-INF/wro.properties final Properties props = new Properties ( ) ; try { return new ServletContextPropertyWroConfigurationFactory ( Context . get ( ) . getServletContext ( ) ) . createProperties ( ) ; } catch ( final Exception e ) { LOG . warn ( "No configuration property file found. Using default values." , e ) ; } return props ; }


Input: To be used for internal usage . Ensure that returned object is not null . [CODESPLIT] private Map < String , ResourcePreProcessor > getPreProcessorsMap ( ) { if ( this . preProcessorsMap == null ) { synchronized ( this ) { if ( this . preProcessorsMap == null ) { this . preProcessorsMap = newPreProcessorsMap ( ) ; } } } return this . preProcessorsMap ; }


Input: To be used for internal usage . Ensure that returned object is not null . [CODESPLIT] private Map < String , ResourcePostProcessor > getPostProcessorsMap ( ) { if ( this . postProcessorsMap == null ) { synchronized ( this ) { if ( this . postProcessorsMap == null ) { this . postProcessorsMap = newPostProcessorsMap ( ) ; } } } return this . postProcessorsMap ; }


Input: { [CODESPLIT] @ Override public synchronized WroModel create ( ) { final StopWatch stopWatch = new StopWatch ( "Create Wro Model from Groovy" ) ; try { stopWatch . start ( "createModel" ) ; final Type type = new TypeToken < WroModel > ( ) { } . getType ( ) ; final InputStream is = getModelResourceAsStream ( ) ; if ( is == null ) { throw new WroRuntimeException ( "Invalid model stream provided!" ) ; } final WroModel model = new Gson ( ) . fromJson ( new InputStreamReader ( new AutoCloseInputStream ( is ) ) , type ) ; LOG . debug ( "json model: {}" , model ) ; if ( model == null ) { throw new WroRuntimeException ( "Invalid content provided, cannot build model!" ) ; } return model ; } catch ( final Exception e ) { throw new WroRuntimeException ( "Invalid model found!" , e ) ; } finally { stopWatch . stop ( ) ; LOG . debug ( stopWatch . prettyPrint ( ) ) ; } }


Input: Use this factory method when you want to use the { [CODESPLIT] public static SmartWroModelFactory createFromStandaloneContext ( final StandaloneContext context ) { notNull ( context ) ; final boolean autoDetectWroFile = WroUtil . normalize ( context . getWroFile ( ) . getPath ( ) ) . contains ( WroUtil . normalize ( DEFAULT_WRO_FILE ) ) ; if ( ! autoDetectWroFile ) { LOG . debug ( "autoDetect is " + autoDetectWroFile + " because wroFile: " + context . getWroFile ( ) + " is not the same as the default one: " + DEFAULT_WRO_FILE ) ; } return new SmartWroModelFactory ( ) . setWroFile ( context . getWroFile ( ) ) . setAutoDetectWroFile ( autoDetectWroFile ) ; }


Input:
Handles the resource model auto detection . [CODESPLIT] private InputStream createAutoDetectedStream ( final String defaultFileName ) throws IOException { try { Validate . notNull ( wroFile , "Cannot call this method if wroFile is null!" ) ; if ( autoDetectWroFile ) { final File file = new File ( wroFile . getParentFile ( ) , defaultFileName ) ; LOG . debug ( "\tloading autodetected wro file: " + file ) ; return new FileInputStream ( file ) ; } LOG . debug ( "loading wroFile: " + wroFile ) ; return new FileInputStream ( wroFile ) ; } catch ( final FileNotFoundException e ) { // When auto detect is turned on, do not skip trying.. because the auto detection assume that the wro file name
 // can be wrong.
 if ( autoDetectWroFile ) { throw e ; } throw new WroRuntimeException ( "The wroFile doesn't exist. Skip trying with other wro model factories" , e ) ; } }


Input:
{ [CODESPLIT] @ Override public WroModel create ( ) { if ( factoryList == null ) { factoryList = newWroModelFactoryFactoryList ( ) ; } if ( factoryList != null ) { // Holds the details about model creation which are logged only when no model can be created
 final StringBuffer logMessageBuffer = new StringBuffer ( ) ; for ( final WroModelFactory factory : factoryList ) { try { // use injector for aggregated modelFactories
 injector . inject ( factory ) ; final Class < ? extends WroModelFactory > factoryClass = factory . getClass ( ) . asSubclass ( WroModelFactory . class ) ; logMessageBuffer . append ( " Using " + getClassName ( factoryClass ) + " for model creation..\n" ) ; return factory . create ( ) ; } catch ( final WroRuntimeException e ) { LOG . debug ( "[FAIL] creating model... will try another factory: {}" , e . getCause ( ) ) ; logMessageBuffer . append ( "[FAIL] Model creation using " + getClassName ( factory . getClass ( ) ) + " failed. Trying another ...\n" ) ; logMessageBuffer . append ( "[FAIL] Exception occured while building the model using: " + getClassName ( factory . getClass ( ) ) + " " + e . getMessage ( ) ) ; // stop trying with other factories if the reason is IOException
 if ( ! autoDetectWroFile && e . getCause ( ) instanceof IOException ) { throw e ; } } } LOG . error ( logMessageBuffer . toString ( ) ) ; } throw new WroRuntimeException ( "Cannot create model using any of provided factories" ) ; }


Input: Removes all [CODESPLIT] public final String removeImportStatements ( ) { final StringBuffer sb = new StringBuffer ( ) ; while ( matcher . find ( ) ) { // replace @import with empty string matcher . appendReplacement ( sb , StringUtils . EMPTY ) ; } matcher . appendTail ( sb ) ; return sb . toString ( ) ; }


Input: { [CODESPLIT] public Map < String , ResourcePreProcessor > providePreProcessors ( ) { final Map < String , ResourcePreProcessor > map = new HashMap < String , ResourcePreProcessor > ( ) ; populateProcessorsMap ( map ) ; return map ; }


Input: Creates a map of postProcessors form a map of preProcessors . This method will be removed in 1 . 5 . 0 release when there will be no differences between pre & post processor interface . [CODESPLIT] private Map < String , ResourcePostProcessor > toPostProcessors ( final Map < String , ResourcePreProcessor > preProcessorsMap ) { final Map < String , ResourcePostProcessor > map = new HashMap < String , ResourcePostProcessor > ( ) ; for ( final Entry < String , ResourcePreProcessor > entry : preProcessorsMap . entrySet ( ) ) { map . put ( entry . getKey ( ) , new ProcessorDecorator ( entry . getValue ( ) ) ) ; } return map ; }


Input: The implementation uses jsr166 ForkJoinPool implementation in case it is available and can be used otherwise the default { @link ExecutorService } is used . [CODESPLIT] protected ExecutorService newExecutor ( ) { try { final ExecutorService executor = ( ExecutorService ) Class . forName ( "java.util.concurrent.ForkJoinPool" ) . newInstance ( ) ; LOG . debug ( "Using ForkJoinPool as task executor." ) ; return executor ; } catch ( final Exception e ) { LOG . debug ( "ForkJoinPool class is not available, using default executor." , e ) ; return Executors . newFixedThreadPool ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; } }


Input: TODO rename to submitAll . <p / > Submits a chunk of jobs for parallel execution . This is a blocking operation - it will end execution when all submitted tasks are finished . [CODESPLIT] public void submit ( final Collection < Callable < T > > callables ) throws Exception { Validate . notNull ( callables ) ; final StopWatch watch = new StopWatch ( ) ; watch . start ( "init" ) ; final long start = System . currentTimeMillis ( ) ; final AtomicLong totalTime = new AtomicLong ( ) ; LOG . debug ( "running {} tasks" , callables . size ( ) ) ; if ( callables . size ( ) == 1 ) { final T result = callables . iterator ( ) . next ( ) . call ( ) ; onResultAvailable ( result ) ; } else { LOG . debug ( "Running tasks in parallel" ) ; watch . stop ( ) ; watch . start ( "submit tasks" ) ; for ( final Callable < T > callable : callables ) { getCompletionService ( ) . submit ( decorate ( callable , totalTime ) ) ; } watch . stop ( ) ; watch . start ( "consume results" ) ; for ( int i = 0 ; i < callables . size ( ) ; i ++ ) { doConsumeResult ( ) ; } } watch . stop ( ) ; destroy ( ) ; LOG . debug ( "Number of Tasks: {}" , callables . size ( ) ) ; final long averageExecutionTime = callables . size ( ) != 0 ? totalTime . longValue ( ) / callables . size ( ) : 0 ; LOG . debug ( "Average Execution Time: {}" , averageExecutionTime ) ; LOG . debug ( "Total Task Time: {}" , totalTime ) ; LOG . debug ( "Grand Total Execution Time: {}" , System . currentTimeMillis ( ) - start ) ; LOG . debug ( watch . prettyPrint ( ) ) ; }


Input: { [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String content = IOUtils . toString ( reader ) ; final StringBuffer result = new JawrCssMinifier ( ) . minifyCSS ( new StringBuffer ( content ) ) ; writer . write ( result . toString ( ) ) ; writer . flush ( ) ; } catch ( final Exception e ) { final String resourceUri = resource == null ? StringUtils . EMPTY : "[" + resource . getUri ( ) + "]" ; String message = "Exception while applying " + getClass ( ) . getSimpleName ( ) + " processor on the " + resourceUri + " resource" ; LOG . error ( message , e ) ; throw new IOException ( message ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }


Input: Compiles the javascript template into plain javascript . [CODESPLIT] public String compile ( final String content , final String optionalArgument ) { final RhinoScriptBuilder builder = initScriptBuilder ( ) ; final String argStr = createArgStr ( optionalArgument ) + createArgStr ( getArguments ( ) ) ; final String compileScript = String . format ( "%s(%s%s);" , getCompileCommand ( ) , WroUtil . toJSMultiLineString ( content ) , argStr ) ; return ( String ) builder . evaluate ( compileScript , getCompileCommand ( ) ) ; }


Input: { [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final AbstractJsTemplateCompiler jsCompiler = enginePool . getObject ( ) ; try { writer . write ( jsCompiler . compile ( content , getArgument ( resource ) ) ) ; } finally { enginePool . returnObject ( jsCompiler ) ; reader . close ( ) ; writer . close ( ) ; } }


Input:
Replace provided url with the new url if needed . [CODESPLIT] @ Override protected String replaceImageUrl ( final String cssUri , final String imageUrl ) { Validate . notNull ( uriLocatorFactory ) ; LOG . debug ( "replace url for image: {} from css: {}" , imageUrl , cssUri ) ; final String cleanImageUrl = cleanImageUrl ( imageUrl ) ; final String fileName = FilenameUtils . getName ( imageUrl ) ; String fullPath = cleanImageUrl ; /**
     * Allow dataUri transformation of absolute url's using http(s) protocol. All url's protocol are intentionally not
     * allowed, because it could be a potential security issue. For instance:
     *
     * <pre>
     * .class {
     *   background: url(file:/path/to/secure/file.png);
     * }
     * </pre>
     *
     * This should not be allowed.
     */ if ( isImageUrlChangeRequired ( cleanImageUrl ) ) { fullPath = WroUtil . getFullPath ( cssUri ) + cleanImageUrl ; } String result = imageUrl ; InputStream is = null ; try { is = uriLocatorFactory . locate ( fullPath ) ; final String dataUri = getDataUriGenerator ( ) . generateDataURI ( is , fileName ) ; if ( isReplaceAccepted ( dataUri ) ) { result = dataUri ; LOG . debug ( "dataUri replacement: {}" , StringUtils . abbreviate ( dataUri , 30 ) ) ; } } catch ( final IOException e ) { LOG . warn ( "[FAIL] extract dataUri from: {}, because: {}. " + "A possible cause: using CssUrlRewritingProcessor before CssDataUriPreProcessor." , fullPath , e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; } return result ; }


Input: Similar to { @link CssDataUriPreProcessor#isReplaceAccepted ( String ) } but decides whether the computed dataUri should replace the image url . It is useful when you want to limit the dataUri size . By default the size of dataUri is limited to 32KB ( because IE8 has a 32KB limitation ) . [CODESPLIT] protected boolean isReplaceAccepted ( final String dataUri ) { try { final byte [ ] bytes = dataUri . getBytes ( CharEncoding . UTF_8 ) ; final boolean exceedLimit = bytes . length >= SIZE_LIMIT ; LOG . debug ( "dataUri size: {}KB, limit exceeded: {}" , bytes . length / 1024 , exceedLimit ) ; return ! exceedLimit ; } catch ( final UnsupportedEncodingException e ) { throw new WroRuntimeException ( "Should never happen" , e ) ; } }


Input:
{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String content = IOUtils . toString ( reader ) ; final Matcher originalMatcher = PATTERN_COPYRIGHT . matcher ( content ) ; final StringBuffer copyrightBuffer = new StringBuffer ( ) ; while ( originalMatcher . find ( ) ) { LOG . debug ( "found copyright comment" ) ; // add copyright header to the buffer.
 copyrightBuffer . append ( originalMatcher . group ( ) ) ; } LOG . debug ( "buffer: {}" , copyrightBuffer ) ; final Writer processedWriter = new StringWriter ( ) ; getDecoratedObject ( ) . process ( resource , new StringReader ( content ) , processedWriter ) ; final Matcher processedMatcher = PATTERN_COPYRIGHT . matcher ( processedWriter . toString ( ) ) ; if ( ! processedMatcher . find ( ) ) { writer . write ( copyrightBuffer . toString ( ) ) ; } writer . write ( processedWriter . toString ( ) ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }


Input:
{ [CODESPLIT] @ Override protected ObjectFactory < WroConfiguration > newWroConfigurationFactory ( final FilterConfig filterConfig ) { if ( properties == null ) { // when no
 properties = new Properties ( ) ; properties . setProperty ( ConfigConstants . debug . name ( ) , String . valueOf ( debug ) ) ; properties . setProperty ( ConfigConstants . gzipResources . name ( ) , String . valueOf ( gzipEnabled ) ) ; properties . setProperty ( ConfigConstants . jmxEnabled . name ( ) , String . valueOf ( jmxEnabled ) ) ; properties . setProperty ( ConfigConstants . cacheUpdatePeriod . name ( ) , String . valueOf ( cacheUpdatePeriod ) ) ; properties . setProperty ( ConfigConstants . modelUpdatePeriod . name ( ) , String . valueOf ( modelUpdatePeriod ) ) ; properties . setProperty ( ConfigConstants . disableCache . name ( ) , String . valueOf ( disableCache ) ) ; if ( encoding != null ) { properties . setProperty ( ConfigConstants . encoding . name ( ) , encoding ) ; } if ( mbeanName != null ) { properties . setProperty ( ConfigConstants . mbeanName . name ( ) , mbeanName ) ; } } return new PropertyWroConfigurationFactory ( properties ) ; }


Input: { [CODESPLIT] @ Override public WroModel create ( ) { WroModel newModel = null ; try { newModel = super . create ( ) ; } catch ( final WroRuntimeException e ) { LOG . error ( "Error while creating the model" , e ) ; } if ( newModel == null ) { LOG . warn ( "Couldn't load new model, reusing last Valid Model!" ) ; if ( lastValidModel == null ) { throw new WroRuntimeException ( "No valid model was found!" ) ; } return lastValidModel ; } lastValidModel = newModel ; return lastValidModel ; }


Input: { [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String resourceContent = IOUtils . toString ( reader ) ; final Reader innerReader = new StringReader ( resourceContent ) ; final StringWriter innerWriter = new StringWriter ( ) ; try { super . process ( resource , innerReader , innerWriter ) ; writer . write ( innerWriter . toString ( ) ) ; } catch ( final Exception e ) { final String processorName = toString ( ) ; if ( isIgnoreFailingProcessor ( ) ) { LOG . debug ( "Ignoring failed processor. Original Exception" , e ) ; writer . write ( resourceContent ) ; // don't wrap exception unless required } else { LOG . error ( "Failed to process the resource: {} using processor: {}. Reason: {}" , resource , processorName , e . getMessage ( ) ) ; final String resourceUri = resource != null ? resource . getUri ( ) : null ; throw WroRuntimeException . wrap ( e , "The processor: " + processorName + " faile while processing uri: " + resourceUri ) . setResource ( resource ) ; } } finally { reader . close ( ) ; writer . close ( ) ; } }


Input: { [CODESPLIT] public String encodeGroupUrl ( final String groupName , final ResourceType resourceType , final boolean minimize ) { return decorated . encodeGroupUrl ( groupName , resourceType , minimize ) ; }


Input: Notify all listeners about cachePeriod property changed . If passed newValue is null the oldValue is taken as new value . This is the case when the reloadCache is invoked . [CODESPLIT] private void reloadCacheWithNewValue ( final Long newValue ) { final long newValueAsPrimitive = newValue == null ? getCacheUpdatePeriod ( ) : newValue ; LOG . debug ( "invoking {} listeners" , cacheUpdatePeriodListeners . size ( ) ) ; for ( final PropertyChangeListener listener : cacheUpdatePeriodListeners ) { final PropertyChangeEvent event = new PropertyChangeEvent ( this , "cache" , getCacheUpdatePeriod ( ) , newValueAsPrimitive ) ; listener . propertyChange ( event ) ; } }


Input: Notify all listeners about cachePeriod property changed . If passed newValue is null the oldValue is taken as new value . This is the case when the reloadModel is invoked . [CODESPLIT] private void reloadModelWithNewValue ( final Long newValue ) { final long newValueAsPrimitive = newValue == null ? getModelUpdatePeriod ( ) : newValue ; for ( final PropertyChangeListener listener : modelUpdatePeriodListeners ) { final PropertyChangeEvent event = new PropertyChangeEvent ( this , "model" , getModelUpdatePeriod ( ) , newValueAsPrimitive ) ; listener . propertyChange ( event ) ; } }


Input:
{ [CODESPLIT] @ Override public Map < String , ResourcePostProcessor > providePostProcessors ( ) { final Map < String , ResourcePostProcessor > resultMap = new HashMap < String , ResourcePostProcessor > ( ) ; /**
     * Created to overcome the difference between {@link ResourcePreProcessor} and {@link ResourcePostProcessor}
     * interfaces which will be resolved in next major version.
     */ final Map < String , ResourcePreProcessor > preProcessorsMap = createMap ( ) ; for ( final Entry < String , ResourcePreProcessor > entry : preProcessorsMap . entrySet ( ) ) { resultMap . put ( entry . getKey ( ) , new ProcessorDecorator ( entry . getValue ( ) ) ) ; } return resultMap ; }


Input: Factory method . Creates a { @link SchedulerHelper } which consumes a factory providing a runnable . This approach allows lazy runnable initialization . [CODESPLIT] public static SchedulerHelper create ( final LazyInitializer < Runnable > runnableFactory , final String name ) { return new SchedulerHelper ( runnableFactory , name ) ; }


Input: Run the scheduler with the provided period of time . If the scheduler is already started it will be stopped ( not before the running job is complete ) . [CODESPLIT] public SchedulerHelper scheduleWithPeriod ( final long period , final TimeUnit timeUnit ) { notNull ( timeUnit ) ; LOG . debug ( "period: {} [{}]" , period , timeUnit ) ; if ( this . period != period ) { this . period = period ; if ( ! poolInitializer . get ( ) . isShutdown ( ) ) { startScheduler ( period , timeUnit ) ; } else { LOG . warn ( "Cannot schedule because destroy was already called!" ) ; } } return this ; }


Input: The following method shuts down an ExecutorService in two phases first by calling shutdown to reject incoming tasks and then calling shutdownNow if necessary to cancel any lingering tasks : [CODESPLIT] private synchronized void destroyScheduler ( ) { if ( ! poolInitializer . get ( ) . isShutdown ( ) ) { // Disable new tasks from being submitted poolInitializer . get ( ) . shutdown ( ) ; if ( future != null ) { future . cancel ( true ) ; } try { while ( ! poolInitializer . get ( ) . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { LOG . debug ( "Termination awaited: {}" , name ) ; poolInitializer . get ( ) . shutdownNow ( ) ; } } catch ( final InterruptedException e ) { LOG . debug ( "Interrupted Exception occured during scheduler destroy" , e ) ; // (Re-)Cancel if current thread also interrupted poolInitializer . get ( ) . shutdownNow ( ) ; // Preserve interrupt status Thread . currentThread ( ) . interrupt ( ) ; } finally { LOG . debug ( "[STOP] Scheduler terminated successfully! {}" , name ) ; } } }


Input:
/ ** When using JBoss Portal and it has some funny quirks ... actually a portal application have several small web application behind it . So when it intercepts a requests for portal then it start bombing the the application behind the portal with multiple threads ( web requests ) that are combined with threads for wro4j . [CODESPLIT] public InputStream getInputStream ( final HttpServletRequest request , final HttpServletResponse response , final String location ) throws IOException { if ( request == null || response == null || location == null ) { throw new IOException ( "Cannot get stream for location: " + location + " because either request, response or location is not available" ) ; } // where to write the bytes of the stream
 final ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; boolean warnOnEmptyStream = false ; try { final RequestDispatcher dispatcher = request . getRequestDispatcher ( location ) ; if ( dispatcher != null ) { // Wrap request
 final ServletRequest servletRequest = getWrappedServletRequest ( request , location ) ; // Wrap response
 final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper ( os , response ) ; LOG . debug ( "dispatching request to location: {}" , location ) ; // use dispatcher
 dispatcher . include ( servletRequest , servletResponse ) ; warnOnEmptyStream = true ; // force flushing - the content will be written to BytArrayOutputStream.
 // Otherwise exactly 32K of data will be written.
 servletResponse . getWriter ( ) . flush ( ) ; os . close ( ) ; } } catch ( final Exception e ) { LOG . debug ( "Could not dispatch request for location {}" , location ) ; // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside
 // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are
 // included.
 return locateExternal ( request , location ) ; } try { // fallback to external resource locator if the dispatcher is empty
 if ( os . size ( ) == 0 ) { return locateExternal ( request , location ) ; } } finally { if ( warnOnEmptyStream && os . size ( ) == 0 ) { LOG . debug ( "Wrong or empty resource with location: {}" , location ) ; } } return new ByteArrayInputStream ( os . toByteArray ( ) ) ; }


Input:
Build a wrapped servlet request which will be used for dispatching . [CODESPLIT] private ServletRequest getWrappedServletRequest ( final HttpServletRequest request , final String location ) { final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper ( request ) { @ Override public String getRequestURI ( ) { return getContextPath ( ) + location ; } @ Override public String getPathInfo ( ) { return WroUtil . getPathInfoFromLocation ( this , location ) ; } @ Override public String getServletPath ( ) { return WroUtil . getServletPathFromLocation ( this , location ) ; } } ; // add an attribute to mark this request as included from wro
 wrappedRequest . setAttribute ( ATTRIBUTE_INCLUDED_BY_DISPATCHER , Boolean . TRUE ) ; return wrappedRequest ; }


Input: { [CODESPLIT] public void setResourcePreProcessors ( final Collection < ResourcePreProcessor > processors ) { preProcessors . clear ( ) ; if ( processors != null ) { preProcessors . addAll ( processors ) ; } }


Input: { [CODESPLIT] public void setResourcePostProcessors ( final Collection < ResourcePostProcessor > processors ) { postProcessors . clear ( ) ; if ( processors != null ) { postProcessors . addAll ( processors ) ; } }


Input:
Add a { [CODESPLIT] public SimpleProcessorsFactory addPostProcessor ( final ResourcePostProcessor processor ) { if ( processor . getClass ( ) . isAnnotationPresent ( Minimize . class ) ) { //TODO move large messages to properties file
 LOG . warn ( "It is recommended to add minimize aware processors to " + "pre processors instead of post processor, otherwise you " + "won't be able to disable minimization on specific resources " + "using minimize='false' attribute." ) ; } postProcessors . add ( processor ) ; return this ; }


Input: Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { return RhinoScriptBuilder . newClientSideAwareChain ( ) . addJSON ( ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_JS ) ; } catch ( final Exception e ) { LOG . error ( "Processing error:" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( "Processing error" , e ) ; } }


Input: Creates a { @link ProviderFinder } which will find providers of type provided as argument .. [CODESPLIT] public static < T > ProviderFinder < T > of ( final Class < T > type ) { return new ProviderFinder < T > ( type ) ; }


Input: Collects also providers of type { @link ConfigurableProvider } if the T type is a supertype of { @link ConfigurableProvider } . If the type is already { @link ConfigurableProvider } it will be ignored to avoid adding of duplicate providers . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private void collectConfigurableProviders ( final List < T > providers ) { if ( type . isAssignableFrom ( ConfigurableProvider . class ) && ( type != ConfigurableProvider . class ) ) { final Iterator < ConfigurableProvider > iterator = lookupProviders ( ConfigurableProvider . class ) ; for ( ; iterator . hasNext ( ) ; ) { final T provider = ( T ) iterator . next ( ) ; LOG . debug ( "found provider: {}" , provider ) ; providers . add ( provider ) ; } } }


Input: This method is useful for mocking the lookup operation . The implementation will try to use java . util . ServiceLoader by default ( available in jdk6 ) and will fallback to ServiceRegistry for earlier JDK versions . The reason for this is to support GAE environment which doesn t contain the ServiceRegistry in its whitelist . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) < P > Iterator < P > lookupProviders ( final Class < P > providerClass ) { LOG . debug ( "searching for providers of type : {}" , providerClass ) ; try { final Class < ? > serviceLoader = getClass ( ) . getClassLoader ( ) . loadClass ( "java.util.ServiceLoader" ) ; LOG . debug ( "using {} to lookupProviders" , serviceLoader . getName ( ) ) ; return ( ( Iterable < P > ) serviceLoader . getMethod ( "load" , Class . class ) . invoke ( serviceLoader , providerClass ) ) . iterator ( ) ; } catch ( final Exception e ) { LOG . debug ( "ServiceLoader is not available. Falling back to ServiceRegistry." , e ) ; } LOG . debug ( "using {} to lookupProviders" , ServiceRegistry . class . getName ( ) ) ; return ServiceRegistry . lookupProviders ( providerClass ) ; }


Input: { [CODESPLIT] @ Override protected void doInit ( final FilterConfig filterConfig ) throws ServletException { String targetBeanName = filterConfig . getInitParameter ( PARAM_TARGET_BEAN_NAME ) ; // apply default targetBeanName targetBeanName = StringUtils . isEmpty ( targetBeanName ) ? DEFAULT_TARGET_BEAN_NAME : targetBeanName ; final WebApplicationContext ctx = WebApplicationContextUtils . getWebApplicationContext ( filterConfig . getServletContext ( ) ) ; factory = ( WroManagerFactory ) ctx . getBean ( targetBeanName , WroManagerFactory . class ) ; if ( factory == null ) { throw new WroRuntimeException ( "Could not locate: " + WroManagerFactory . class . getName ( ) + " instance in applicationContext with bean name: " + targetBeanName ) ; } }


Input: The idea is to compute the aggregatedFolderPath based on a root folder . The root folder is determined by comparing the cssTargetFolder ( the folder where aggregated css files are located ) with build directory or contextFolder . If rootFolder is null then the result is also null ( equivalent to using the cssTargetFolder the same as the root folder . [CODESPLIT] public String resolve ( ) { notNull ( buildDirectory , "Build directory cannot be null!" ) ; notNull ( log , "Logger cannot be null!" ) ; String result = null ; final File cssTargetFolder = cssDestinationFolder == null ? destinationFolder : cssDestinationFolder ; File rootFolder = null ; notNull ( cssTargetFolder , "cssTargetFolder cannot be null!" ) ; if ( buildFinalName != null && cssTargetFolder . getPath ( ) . startsWith ( buildFinalName . getPath ( ) ) ) { rootFolder = buildFinalName ; } else if ( cssTargetFolder . getPath ( ) . startsWith ( buildDirectory . getPath ( ) ) ) { rootFolder = buildDirectory ; } else { // find first best match for ( final String contextFolder : getContextFolders ( ) ) { if ( cssTargetFolder . getPath ( ) . startsWith ( contextFolder ) ) { rootFolder = new File ( contextFolder ) ; break ; } } } log . debug ( "buildDirectory: " + buildDirectory ) ; log . debug ( "contextFolders: " + contextFoldersAsCSV ) ; log . debug ( "cssTargetFolder: " + cssTargetFolder ) ; log . debug ( "rootFolder: " + rootFolder ) ; if ( rootFolder != null ) { result = StringUtils . removeStart ( cssTargetFolder . getPath ( ) , rootFolder . getPath ( ) ) ; } log . debug ( "computedAggregatedFolderPath: " + result ) ; return result ; }


Input: Use { [CODESPLIT] private String [ ] getContextFolders ( ) { final StandaloneContext context = new StandaloneContext ( ) ; context . setContextFoldersAsCSV ( contextFoldersAsCSV ) ; return context . getContextFolders ( ) ; }


Input: Creates a { [CODESPLIT] public static Transformer < String > extensionTransformer ( final String newExtension ) { return new Transformer < String > ( ) { public String transform ( final String input ) { return FilenameUtils . getBaseName ( input ) + "." + newExtension ; } } ; }


Input: Appends a suffix to the source baseName . [CODESPLIT] public static Transformer < String > baseNameSuffixTransformer ( final String suffix ) { return new Transformer < String > ( ) { public String transform ( final String input ) { final String baseName = FilenameUtils . getBaseName ( input ) ; final String extension = FilenameUtils . getExtension ( input ) ; return baseName + suffix + "." + extension ; } } ; }


Input: action -- do something! What you do is determined by the argument : <ul > <li > 1 Output A . Copy B to A . Get the next B . < / li > <li > 2 Copy B to A . Get the next B . ( Delete A ) . < / li > <li > 3 Get the next B . ( Delete B ) . < / li > < / ul > action treats a string as a single character . Wow!<br / > action recognizes a regular expression if it is preceded by ( or or = . [CODESPLIT] void action ( final int d ) throws IOException , UnterminatedRegExpLiteralException , UnterminatedCommentException , UnterminatedStringLiteralException { switch ( d ) { case 1 : out . write ( theA ) ; if ( theA == theB && ( theA == ' ' || theA == ' ' ) && theY != theA ) { out . write ( ' ' ) ; } case 2 : theA = theB ; if ( theA == ' ' || theA == ' ' || theA == ' ' ) { for ( ; ; ) { out . write ( theA ) ; theA = get ( ) ; if ( theA == theB ) { break ; } if ( theA <= ' ' ) { throw new UnterminatedStringLiteralException ( ) ; } if ( theA == ' ' ) { out . write ( theA ) ; theA = get ( ) ; } } } case 3 : theB = next ( ) ; if ( theB == ' ' && ( theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' ) ) { out . write ( theA ) ; if ( theA == ' ' || theA == ' ' ) { out . write ( ' ' ) ; } out . write ( theB ) ; for ( ; ; ) { theA = get ( ) ; if ( theA == ' ' ) { for ( ; ; ) { out . write ( theA ) ; theA = get ( ) ; if ( theA == ' ' ) { break ; } if ( theA == ' ' ) { out . write ( theA ) ; theA = get ( ) ; } if ( theA <= ' ' ) { throw new UnterminatedRegExpLiteralException ( ) ; } } } else if ( theA == ' ' ) { switch ( peek ( ) ) { case ' ' : case ' ' : throw new UnterminatedRegExpLiteralException ( ) ; } break ; } else if ( theA == ' ' ) { out . write ( theA ) ; theA = get ( ) ; } else if ( theA <= ' ' ) { throw new UnterminatedRegExpLiteralException ( ) ; } out . write ( theA ) ; } theB = next ( ) ; } } }


Input: Returns a valid HTTP contentType s for a given filename . It first relies on the custom defaultContentTypeMap and if not found it will fall back to defaultFileTypeMap from javax . activation . FileTypeMap . Examples : - somefile . css resolves to text / css . - somefile . js . png resolves to image / png - / blah / index . html resolves to text / html . <p / > The implementation uses reflection to load <code > javax . activation . FileTypeMap< / code > class ( available in jdk6 ) in order to be compatible with jdk5 . If this class is not available the default content type is returned . [CODESPLIT] public static String get ( final String fileName ) { final String extension = FilenameUtils . getExtension ( WroUtil . removeQueryString ( fileName . toLowerCase ( ) ) ) ; if ( defaultContentTypeMap . containsKey ( extension ) ) { return defaultContentTypeMap . get ( extension ) ; } try { final Class < ? > fileTypeMapClass = ClassLoader . getSystemClassLoader ( ) . loadClass ( "javax.activation.FileTypeMap" ) ; LOG . debug ( "using {} to resolve contentType" , fileTypeMapClass . getName ( ) ) ; final Object fileTypeMap = fileTypeMapClass . getMethod ( "getDefaultFileTypeMap" ) . invoke ( fileTypeMapClass ) ; return ( String ) fileTypeMapClass . getMethod ( "getContentType" , String . class ) . invoke ( fileTypeMap , fileName ) ; } catch ( final Exception e ) { LOG . debug ( "FileTypeMap is not available (probably jdk5 is used). Exception {}, with message: {}" , e . getClass ( ) , e . getMessage ( ) ) ; LOG . debug ( "Will use default content type: {} for fileName: {}" , DEFAULT_CONTENT_TYPE , fileName ) ; } return DEFAULT_CONTENT_TYPE ; }