Input:
triggered validation process before actions like save or submit . [CODESPLIT] public boolean preValidation ( ) { String currentTabName = parent . getCurrent ( ) . getCurrentTabName ( ) ; String tabName = null ; String firstInvalidTabName = null ; boolean reload = false ; for ( Map . Entry < String , SheetConfiguration > entry : parent . getSheetConfigMap ( ) . entrySet ( ) ) { tabName = entry . getKey ( ) ; // if not reload and tabname==current then skip reloading.
 if ( reload || ( ! tabName . equals ( currentTabName ) ) ) { parent . getWebSheetLoader ( ) . prepareWorkShee ( tabName ) ; reload = true ; } if ( ! parent . getValidationHandler ( ) . validateCurrentPage ( ) && ( firstInvalidTabName == null ) ) { firstInvalidTabName = tabName ; } } if ( firstInvalidTabName != null ) { if ( ! tabName . equals ( firstInvalidTabName ) ) { parent . getHelper ( ) . getWebSheetLoader ( ) . loadWorkSheet ( firstInvalidTabName ) ; } return false ; } return true ; }


Input: clear all the related maps . [CODESPLIT] public final void clear ( ) { if ( this . templateCommentMap != null ) { this . templateCommentMap . clear ( ) ; } if ( this . cellDatePattern != null ) { this . cellDatePattern . clear ( ) ; } if ( this . cellInputAttributes != null ) { this . cellInputAttributes . clear ( ) ; } if ( this . cellInputType != null ) { this . cellInputType . clear ( ) ; } if ( this . cellSelectItemsAttributes != null ) { this . cellSelectItemsAttributes . clear ( ) ; } }


Input:
Load header rows . [CODESPLIT] private void loadHeaderRows ( final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { int top = sheetConfig . getHeaderCellRange ( ) . getTopRow ( ) ; int bottom = sheetConfig . getHeaderCellRange ( ) . getBottomRow ( ) ; int left = sheetConfig . getHeaderCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getHeaderCellRange ( ) . getRightCol ( ) ; String sheetName = sheetConfig . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; int totalWidth = CellStyleUtility . calcTotalWidth ( sheet1 , left , right , WebSheetUtility . pixel2WidthUnits ( parent . getLineNumberColumnWidth ( ) + parent . getAddRowColumnWidth ( ) ) ) ; RangeBuildRef rangeBuildRef = new RangeBuildRef ( left , right , totalWidth , sheet1 ) ; if ( sheetConfig . isFixedWidthStyle ( ) ) { parent . setTableWidthStyle ( "table-layout: fixed; width:" + WebSheetUtility . widthUnits2Pixel ( totalWidth ) + "px;" ) ; } parent . setLineNumberColumnWidthStyle ( getWidthStyle ( WebSheetUtility . pixel2WidthUnits ( parent . getLineNumberColumnWidth ( ) ) , totalWidth ) ) ; parent . setAddRowColumnWidthStyle ( "width:" + parent . getAddRowColumnWidth ( ) + "px;" ) ; parent . getHeaderRows ( ) . clear ( ) ; if ( top < 0 ) { // this is blank configuration. set column letter as header
 parent . getHeaderRows ( ) . add ( loadHeaderRowWithoutConfigurationTab ( rangeBuildRef , true ) ) ; // set showlinenumber to true as default
 parent . setShowLineNumber ( true ) ; } else { parent . getHeaderRows ( ) . add ( loadHeaderRowWithoutConfigurationTab ( rangeBuildRef , false ) ) ; for ( int i = top ; i <= bottom ; i ++ ) { parent . getHeaderRows ( ) . add ( loadHeaderRowWithConfigurationTab ( sheetConfig , rangeBuildRef , i , cellRangeMap , skippedRegionCells ) ) ; } // set showlinenumber to false as default
 parent . setShowLineNumber ( false ) ; } }


Input: Load header row without configuration tab . [CODESPLIT] private List < HeaderCell > loadHeaderRowWithoutConfigurationTab ( final RangeBuildRef rangeBuildRef , final boolean rendered ) { int firstCol = rangeBuildRef . getLeft ( ) ; int lastCol = rangeBuildRef . getRight ( ) ; double totalWidth = ( double ) rangeBuildRef . getTotalWidth ( ) ; Sheet sheet1 = rangeBuildRef . getSheet ( ) ; List < HeaderCell > headercells = new ArrayList <> ( ) ; for ( int i = firstCol ; i <= lastCol ; i ++ ) { if ( ! sheet1 . isColumnHidden ( i ) ) { String style = getHeaderColumnStyle ( parent . getWb ( ) , null , sheet1 . getColumnWidth ( i ) , totalWidth ) ; headercells . add ( new HeaderCell ( "1" , "1" , style , style , WebSheetUtility . getExcelColumnName ( i ) , rendered , true ) ) ; } } fillToMaxColumns ( headercells ) ; return headercells ; }


Input: Fill to max columns . [CODESPLIT] private void fillToMaxColumns ( final List < HeaderCell > headercells ) { if ( headercells . size ( ) < parent . getMaxColCounts ( ) ) { int fills = parent . getMaxColCounts ( ) - headercells . size ( ) ; for ( int s = 0 ; s < fills ; s ++ ) { headercells . add ( new HeaderCell ( "1" , "1" , "" , "" , "" , false , false ) ) ; } } }


Input:
Gets the header column style . [CODESPLIT] private String getHeaderColumnStyle ( final Workbook wb , final Cell cell , final double colWidth , final double totalWidth ) { String columnstyle = "" ; if ( cell != null ) { columnstyle += CellStyleUtility . getCellStyle ( wb , cell , "" ) + CellStyleUtility . getCellFontStyle ( wb , cell ) ; // +
 } columnstyle = columnstyle + getWidthStyle ( colWidth , totalWidth ) ; return columnstyle ; }


Input: Gets the width style . [CODESPLIT] private String getWidthStyle ( final double colWidth , final double totalWidth ) { double percentage = FacesUtility . round ( TieConstants . CELL_FORMAT_PERCENTAGE_VALUE * colWidth / totalWidth , 2 ) ; return "width:" + percentage + TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL + ";" ; }


Input: Load header row with configuration tab . [CODESPLIT] private List < HeaderCell > loadHeaderRowWithConfigurationTab ( final SheetConfiguration sheetConfig , final RangeBuildRef rangeBuildRef , final int currentRow , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { Sheet sheet1 = rangeBuildRef . getSheet ( ) ; int left = rangeBuildRef . getLeft ( ) ; int right = rangeBuildRef . getRight ( ) ; double totalWidth = ( double ) rangeBuildRef . getTotalWidth ( ) ; Row row = sheet1 . getRow ( currentRow ) ; List < HeaderCell > headercells = new ArrayList <> ( ) ; for ( int cindex = left ; cindex <= right ; cindex ++ ) { String cellindex = CellUtility . getCellIndexNumberKey ( cindex , currentRow ) ; if ( ! skippedRegionCells . contains ( cellindex ) && ! sheet1 . isColumnHidden ( cindex ) ) { Cell cell = null ; if ( row != null ) { cell = row . getCell ( cindex , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } int originRowIndex = ConfigurationUtility . getOriginalRowNumInHiddenColumn ( row ) ; if ( cell != null ) { FacesCell fcell = new FacesCell ( ) ; CellUtility . convertCell ( sheetConfig , fcell , cell , cellRangeMap , originRowIndex , parent . getCellAttributesMap ( ) , null ) ; parent . getPicHelper ( ) . setupFacesCellPictureCharts ( sheet1 , fcell , cell , WebSheetUtility . getFullCellRefName ( sheet1 , cell ) ) ; CellStyleUtility . setupCellStyle ( parent . getWb ( ) , fcell , cell , row . getHeightInPoints ( ) ) ; fcell . setColumnStyle ( fcell . getColumnStyle ( ) + getColumnWidthStyle ( sheet1 , cellRangeMap , cellindex , cindex , totalWidth ) ) ; fcell . setColumnIndex ( cindex ) ; headercells . add ( new HeaderCell ( Integer . toString ( fcell . getRowspan ( ) ) , Integer . toString ( fcell . getColspan ( ) ) , fcell . getStyle ( ) , fcell . getColumnStyle ( ) , CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) , true , true ) ) ; } } } fillToMaxColumns ( headercells ) ; return headercells ; }


Input:
Gets the column width style . [CODESPLIT] private String getColumnWidthStyle ( final Sheet sheet1 , final Map < String , CellRangeAddress > cellRangeMap , final String cellindex , final int cindex , final double totalWidth ) { CellRangeAddress caddress = cellRangeMap . get ( cellindex ) ; double colWidth ; // check whether the cell has rowspan or colspan
 if ( caddress != null ) { colWidth = CellStyleUtility . calcTotalWidth ( sheet1 , caddress . getFirstColumn ( ) , caddress . getLastColumn ( ) , 0 ) ; } else { colWidth = sheet1 . getColumnWidth ( cindex ) ; } return getWidthStyle ( colWidth , totalWidth ) ; }


Input: Clear workbook . [CODESPLIT] private void clearWorkbook ( ) { parent . setFormulaEvaluator ( null ) ; parent . setDataFormatter ( null ) ; parent . setSheetConfigMap ( null ) ; parent . setTabs ( null ) ; parent . getSerialDataContext ( ) . setDataContext ( null ) ; parent . setPicturesMap ( null ) ; parent . setHeaderRows ( null ) ; parent . setBodyRows ( null ) ; parent . setWb ( null ) ; parent . getHeaderRows ( ) . clear ( ) ; parent . getBodyRows ( ) . clear ( ) ; parent . getCharsData ( ) . getChartsMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartDataMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartAnchorsMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartPositionMap ( ) . clear ( ) ; parent . getCellAttributesMap ( ) . clear ( ) ; }


Input: Load workbook . [CODESPLIT] public final int loadWorkbook ( final InputStream fis , final Map < String , Object > dataContext ) { try { Workbook wb = WorkbookFactory . create ( fis ) ; int ireturn = loadWorkbook ( wb , dataContext ) ; fis . close ( ) ; return ireturn ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , "Web Form loadWorkbook Error Exception = " + e . getLocalizedMessage ( ) , e ) ; return - 1 ; } }


Input:
Load workbook . [CODESPLIT] public final int loadWorkbook ( final Workbook wb , final Map < String , Object > dataContext ) { try { clearWorkbook ( ) ; // only support xssf workbook now since 2016 July
 if ( ! ( wb instanceof XSSFWorkbook ) ) { LOG . fine ( "Error: WebSheet only support xlsx template." ) ; return - 1 ; } LOG . fine ( "Begin load work book..." ) ; parent . setWb ( wb ) ; parent . getSerialDataContext ( ) . setDataContext ( dataContext ) ; parent . setSheetConfigMap ( new ConfigurationHandler ( parent ) . buildConfiguration ( ) ) ; parent . reCalcMaxColCounts ( ) ; parent . getChartHelper ( ) . loadChartsMap ( ) ; parent . getPicHelper ( ) . loadPicturesMap ( ) ; initSheet ( ) ; initTabs ( ) ; if ( ! parent . getTabs ( ) . isEmpty ( ) ) { loadWorkSheet ( parent . getTabs ( ) . get ( 0 ) . getTitle ( ) ) ; } } catch ( Exception e ) { LOG . log ( Level . FINE , "Web Form loadWorkbook Error Exception = " + e . getLocalizedMessage ( ) , e ) ; return - 1 ; } return 1 ; }


Input: Inits the tabs . [CODESPLIT] private void initTabs ( ) { parent . setTabs ( new ArrayList < TabModel > ( ) ) ; if ( parent . getSheetConfigMap ( ) != null ) { for ( String key : parent . getSheetConfigMap ( ) . keySet ( ) ) { parent . getTabs ( ) . add ( new TabModel ( "form_" + key , key , "form" ) ) ; } } }


Input:
load data process . unfinished . [CODESPLIT] private void loadData ( ) { if ( parent . getSerialDataContext ( ) . getDataContext ( ) == null ) { // no data objects available.
 return ; } if ( parent . isAdvancedContext ( ) ) { parent . getSerialDataContext ( ) . getDataContext ( ) . put ( "tiecells" , new HashMap < String , TieCell > ( ) ) ; } for ( SheetConfiguration sheetConfig : parent . getSheetConfigMap ( ) . values ( ) ) { List < RowsMapping > currentRowsMappingList = null ; ConfigBuildRef configBuildRef = new ConfigBuildRef ( parent . getWbWrapper ( ) , parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) , parent . getExpEngine ( ) , parent . getCellHelper ( ) , sheetConfig . getCachedCells ( ) , parent . getCellAttributesMap ( ) , sheetConfig . getFinalCommentMap ( ) ) ; int length = sheetConfig . getFormCommand ( ) . buildAt ( null , configBuildRef , sheetConfig . getFormCommand ( ) . getTopRow ( ) , parent . getSerialDataContext ( ) . getDataContext ( ) , currentRowsMappingList ) ; sheetConfig . setShiftMap ( configBuildRef . getShiftMap ( ) ) ; sheetConfig . setCollectionObjNameMap ( configBuildRef . getCollectionObjNameMap ( ) ) ; sheetConfig . setCommandIndexMap ( configBuildRef . getCommandIndexMap ( ) ) ; sheetConfig . setWatchList ( configBuildRef . getWatchList ( ) ) ; sheetConfig . setBodyAllowAddRows ( configBuildRef . isBodyAllowAdd ( ) ) ; sheetConfig . getBodyCellRange ( ) . setBottomRow ( sheetConfig . getFormCommand ( ) . getTopRow ( ) + length - 1 ) ; sheetConfig . setBodyPopulated ( true ) ; } parent . getCellHelper ( ) . reCalc ( ) ; }


Input:
Refresh data . [CODESPLIT] public void refreshData ( ) { if ( parent . getSerialDataContext ( ) . getDataContext ( ) == null ) { // no data objects available.
 return ; } for ( SheetConfiguration sheetConfig : parent . getSheetConfigMap ( ) . values ( ) ) { for ( int irow = sheetConfig . getFormCommand ( ) . getTopRow ( ) ; irow < sheetConfig . getFormCommand ( ) . getLastRow ( ) ; irow ++ ) { refreshDataForRow ( parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) . getRow ( irow ) ) ; } } parent . getCellHelper ( ) . reCalc ( ) ; }


Input: Refresh data for row . [CODESPLIT] private void refreshDataForRow ( Row row ) { if ( row == null ) { return ; } String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( row ) ; if ( saveAttrList != null ) { String [ ] saveAttrs = saveAttrList . split ( "," ) ; for ( String fullSaveAttr : saveAttrs ) { refreshDataForCell ( row , fullSaveAttr ) ; } } }


Input: refresh data for single cell . [CODESPLIT] private void refreshDataForCell ( Row row , String fullSaveAttr ) { if ( fullSaveAttr != null ) { try { String fullName = ConfigurationUtility . getFullNameFromRow ( row ) ; if ( fullName != null ) { parent . getCellHelper ( ) . restoreDataContext ( fullName ) ; SaveAttrsUtility . refreshSheetRowFromContext ( parent . getSerialDataContext ( ) . getDataContext ( ) , fullSaveAttr , row , parent . getExpEngine ( ) ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , "refreshDataForCell with fullAaveAttr =" + fullSaveAttr + " error = " + ex . getMessage ( ) , ex ) ; } } }


Input: Find tab index with name . [CODESPLIT] public final int findTabIndexWithName ( final String tabname ) { for ( int i = 0 ; i < parent . getTabs ( ) . size ( ) ; i ++ ) { if ( parent . getTabs ( ) . get ( i ) . getTitle ( ) . equalsIgnoreCase ( tabname ) ) { return i ; } } return - 1 ; }


Input:
Load work sheet . [CODESPLIT] public final void loadWorkSheet ( final String tabName ) { prepareWorkShee ( tabName ) ; parent . getValidationHandler ( ) . validateCurrentPage ( ) ; createDynamicColumns ( tabName ) ; // reset datatable current page to 1
 setDataTablePage ( 0 ) ; parent . getCurrent ( ) . setCurrentDataContextName ( null ) ; saveObjs ( ) ; if ( ( RequestContext . getCurrentInstance ( ) != null ) && ( parent . getClientId ( ) != null ) ) { RequestContext . getCurrentInstance ( ) . update ( parent . getClientId ( ) + ":websheettab" ) ; } }


Input:
prepare worksheet for loading . this only load at backend without refresh gui . [CODESPLIT] public final void prepareWorkShee ( final String tabName ) { int tabIndex = findTabIndexWithName ( tabName ) ; if ( parent . getWebFormTabView ( ) != null ) { parent . getWebFormTabView ( ) . setActiveIndex ( tabIndex ) ; } parent . getCurrent ( ) . setCurrentTabName ( tabName ) ; String sheetName = parent . getSheetConfigMap ( ) . get ( tabName ) . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; parent . getWb ( ) . setActiveSheet ( parent . getWb ( ) . getSheetIndex ( sheet1 ) ) ; SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( tabName ) ; parent . setMaxRowsPerPage ( parent . getSheetConfigMap ( ) . get ( tabName ) . getMaxRowPerPage ( ) ) ; parent . setBodyAllowAddRows ( parent . getSheetConfigMap ( ) . get ( tabName ) . isBodyAllowAddRows ( ) ) ; // populate repeat rows before setup cell range map
 Map < String , CellRangeAddress > cellRangeMap = ConfigurationUtility . indexMergedRegion ( sheet1 ) ; List < String > skippedRegionCells = ConfigurationUtility . skippedRegionCells ( sheet1 ) ; loadHeaderRows ( sheetConfig , cellRangeMap , skippedRegionCells ) ; loadBodyRows ( sheetConfig , cellRangeMap , skippedRegionCells ) ; }


Input: Sets the data table page . [CODESPLIT] private void setDataTablePage ( final int first ) { if ( parent . getWebFormClientId ( ) != null ) { final DataTable d = ( DataTable ) FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . findComponent ( parent . getWebFormClientId ( ) ) ; if ( d != null ) { d . setFirst ( first ) ; } } }


Input: Save objs . [CODESPLIT] private void saveObjs ( ) { try { if ( FacesContext . getCurrentInstance ( ) != null ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; viewMap . put ( "currentTabName" , parent . getCurrent ( ) . getCurrentTabName ( ) ) ; viewMap . put ( TieConstants . SUBMITMODE , parent . getSubmitMode ( ) ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , "saveobjs in viewMap error = " + ex . getMessage ( ) , ex ) ; } }


Input: Setup row info . [CODESPLIT] private void setupRowInfo ( final FacesRow facesRow , final Sheet sheet1 , final Row row , final int rowIndex , final boolean allowAdd ) { facesRow . setAllowAdd ( allowAdd ) ; if ( row != null ) { facesRow . setRendered ( ! row . getZeroHeight ( ) ) ; facesRow . setRowheight ( row . getHeight ( ) ) ; int rowNum = ConfigurationUtility . getOriginalRowNumInHiddenColumn ( row ) ; facesRow . setOriginRowIndex ( rowNum ) ; } else { facesRow . setRendered ( true ) ; facesRow . setRowheight ( sheet1 . getDefaultRowHeight ( ) ) ; facesRow . setOriginRowIndex ( rowIndex ) ; } }


Input: Load body rows . [CODESPLIT] private void loadBodyRows ( final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int bottom = CellUtility . getBodyBottomFromConfig ( sheetConfig ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; String sheetName = sheetConfig . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; parent . getBodyRows ( ) . clear ( ) ; clearCache ( ) ; for ( int i = top ; i <= bottom ; i ++ ) { parent . getBodyRows ( ) . add ( assembleFacesBodyRow ( i , sheet1 , left , right , sheetConfig , cellRangeMap , skippedRegionCells ) ) ; } sheetConfig . setBodyPopulated ( true ) ; parent . getCurrent ( ) . setCurrentTopRow ( top ) ; parent . getCurrent ( ) . setCurrentLeftColumn ( left ) ; }


Input: Assemble faces body row . [CODESPLIT] private FacesRow assembleFacesBodyRow ( final int rowIndex , final Sheet sheet1 , final int left , final int right , final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { FacesRow facesRow = new FacesRow ( rowIndex ) ; Row row = sheet1 . getRow ( rowIndex ) ; setupRowInfo ( facesRow , sheet1 , row , rowIndex , CommandUtility . isRowAllowAdd ( row , sheetConfig ) ) ; String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( row ) ; List < FacesCell > bodycells = new ArrayList <> ( ) ; for ( int cindex = left ; cindex <= right ; cindex ++ ) { String cellindex = CellUtility . getCellIndexNumberKey ( cindex , rowIndex ) ; if ( ! skippedRegionCells . contains ( cellindex ) && ! sheet1 . isColumnHidden ( cindex ) ) { Cell cell = null ; if ( row != null ) { cell = row . getCell ( cindex , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } if ( cell != null ) { FacesCell fcell = new FacesCell ( ) ; CellUtility . convertCell ( sheetConfig , fcell , cell , cellRangeMap , facesRow . getOriginRowIndex ( ) , parent . getCellAttributesMap ( ) , saveAttrList ) ; parent . getPicHelper ( ) . setupFacesCellPictureCharts ( sheet1 , fcell , cell , WebSheetUtility . getFullCellRefName ( sheet1 , cell ) ) ; CellStyleUtility . setupCellStyle ( parent . getWb ( ) , fcell , cell , row . getHeightInPoints ( ) ) ; fcell . setColumnIndex ( cindex ) ; bodycells . add ( fcell ) ; addCache ( cell ) ; } else { bodycells . add ( null ) ; } } else { bodycells . add ( null ) ; } } facesRow . setCells ( bodycells ) ; return facesRow ; }


Input: Refresh cached cell . [CODESPLIT] public final void refreshCachedCell ( final String tblName , final int i , final int index , final Cell cell , final FacesCell fcell ) { if ( ( cell != null ) && ( cell . getCellTypeEnum ( ) == CellType . FORMULA ) && ( tblName != null ) ) { try { processRefreshCell ( tblName , i , index , cell , fcell ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , "refresh Cached Cell error : " + ex . getLocalizedMessage ( ) , ex ) ; } } }


Input: Process refresh cell . [CODESPLIT] private void processRefreshCell ( final String tblName , final int i , final int index , final Cell cell , final FacesCell fcell ) { String newValue = CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; if ( parent . getCachedCells ( ) . isValueChanged ( cell , newValue ) ) { if ( fcell . isHasSaveAttr ( ) ) { parent . getCellHelper ( ) . saveDataInContext ( cell , newValue ) ; } RequestContext . getCurrentInstance ( ) . update ( tblName + ":" + i + ":cocalc" + index ) ; parent . getCachedCells ( ) . put ( cell , CellType . FORMULA ) ; } }


Input: Creates the dynamic columns . [CODESPLIT] private void createDynamicColumns ( final String tabName ) { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( tabName ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; parent . getColumns ( ) . clear ( ) ; for ( int i = left ; i <= right ; i ++ ) { parent . getColumns ( ) . add ( "column" + ( i - left ) ) ; } }


Input:
Adds the repeat row . [CODESPLIT] public final void addRepeatRow ( final int rowIndex ) { try { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( parent . getCurrent ( ) . getCurrentTabName ( ) ) ; Sheet sheet = parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) ; ConfigBuildRef configBuildRef = new ConfigBuildRef ( parent . getWbWrapper ( ) , sheet , parent . getExpEngine ( ) , parent . getCellHelper ( ) , sheetConfig . getCachedCells ( ) , parent . getCellAttributesMap ( ) , sheetConfig . getFinalCommentMap ( ) ) ; // set add mode
 configBuildRef . setAddMode ( true ) ; configBuildRef . setCollectionObjNameMap ( sheetConfig . getCollectionObjNameMap ( ) ) ; configBuildRef . setCommandIndexMap ( sheetConfig . getCommandIndexMap ( ) ) ; configBuildRef . setShiftMap ( sheetConfig . getShiftMap ( ) ) ; configBuildRef . setWatchList ( sheetConfig . getWatchList ( ) ) ; int length = CommandUtility . addRow ( configBuildRef , rowIndex , parent . getSerialDataContext ( ) . getDataContext ( ) ) ; refreshBodyRowsInRange ( configBuildRef . getInsertPosition ( ) , length , sheet , sheetConfig ) ; parent . getCellHelper ( ) . reCalc ( ) ; } catch ( AddRowException e ) { FacesContext . getCurrentInstance ( ) . addMessage ( null , new FacesMessage ( FacesMessage . SEVERITY_ERROR , "Add Row Error" , e . getMessage ( ) ) ) ; LOG . log ( Level . SEVERE , "Add row error = " + e . getLocalizedMessage ( ) , e ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , "Add row error = " + ex . getLocalizedMessage ( ) , ex ) ; } }


Input: Refresh body rows in range . [CODESPLIT] private void refreshBodyRowsInRange ( final int insertPosition , final int length , final Sheet sheet , final SheetConfiguration sheetConfig ) { Map < String , CellRangeAddress > cellRangeMap = ConfigurationUtility . indexMergedRegion ( sheet ) ; List < String > skippedRegionCells = ConfigurationUtility . skippedRegionCells ( sheet ) ; int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; for ( int irow = insertPosition ; irow < ( insertPosition + length ) ; irow ++ ) { parent . getBodyRows ( ) . add ( irow - top , assembleFacesBodyRow ( irow , sheet , left , right , sheetConfig , cellRangeMap , skippedRegionCells ) ) ; } for ( int irow = insertPosition + length - top ; irow < parent . getBodyRows ( ) . size ( ) ; irow ++ ) { FacesRow facesrow = parent . getBodyRows ( ) . get ( irow ) ; facesrow . setRowIndex ( facesrow . getRowIndex ( ) + length ) ; } }


Input:
Sets the unsaved status . [CODESPLIT] public void setUnsavedStatus ( final RequestContext requestContext , final Boolean statusFlag ) { // in client js should have setUnsavedState method
 if ( requestContext != null ) { LOG . log ( Level . FINE , "run setUnsavedState( {} )" , statusFlag . toString ( ) ) ; requestContext . execute ( "setUnsavedState(" + statusFlag . toString ( ) + ")" ) ; } }


Input: Checks if is unsaved status . [CODESPLIT] public final Boolean isUnsavedStatus ( ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; Boolean flag = ( Boolean ) viewMap . get ( TieConstants . UNSAVEDSTATE ) ; if ( flag == null ) { return false ; } return flag ; }


Input: recover by using it s address . [CODESPLIT] public final void recover ( final Sheet sheet ) { this . getSerialFirstRowRef ( ) . recover ( sheet ) ; this . getSerialLastRowPlusRef ( ) . recover ( sheet ) ; if ( this . getUnitRowsMapping ( ) != null ) { this . getUnitRowsMapping ( ) . recover ( sheet ) ; } }


Input: <p > Converts a CEF formatted String into a { [CODESPLIT] public CommonEvent parse ( String cefString , final boolean validate ) { return this . parse ( cefString , validate , Locale . ENGLISH ) ; }


Input: Converts a CEF formatted String into a { [CODESPLIT] public CommonEvent parse ( String cefString , final boolean validate , Locale locale ) { int cefHeaderSize = 7 ; CommonEvent cefEvent = new CefRev23 ( locale ) ; // Note how split number of splits is cefHeaderSize + 1. This is because the final split // should be the body of the CEF message // Compiled pattern is equivalent to "(?<!\\\\)" + Pattern.quote("|") final String [ ] extractedMessage = cefString . split ( "(?<!\\\\)" + Pattern . quote ( "|" ) , cefHeaderSize + 1 ) ; // CEF header misses values if ( extractedMessage . length < cefHeaderSize ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "CEF message failed validation" ) ; } return null ; } final HashMap < String , Object > headers = new HashMap < String , Object > ( ) ; headers . put ( "version" , Integer . valueOf ( extractedMessage [ 0 ] . substring ( extractedMessage [ 0 ] . length ( ) - 1 ) ) ) ; headers . put ( "deviceVendor" , extractedMessage [ 1 ] ) ; headers . put ( "deviceProduct" , extractedMessage [ 2 ] ) ; headers . put ( "deviceVersion" , extractedMessage [ 3 ] ) ; headers . put ( "deviceEventClassId" , extractedMessage [ 4 ] ) ; headers . put ( "name" , extractedMessage [ 5 ] ) ; headers . put ( "severity" , extractedMessage [ 6 ] ) ; final HashMap < String , String > extensions = new HashMap < String , String > ( ) ; final String ext = extractedMessage [ 7 ] ; // Compiled pattern is equivalent to String extensionRegex = "(?<!\\\\)" + Pattern.quote("="); final Matcher matcher = extensionPattern . matcher ( ext ) ; final Matcher valueMatcher = extensionPattern . matcher ( ext ) ; int index = 0 ; while ( matcher . find ( ) ) { String key = ext . substring ( index , matcher . end ( ) - 1 ) . replace ( " " , "" ) ; // Capture the start of the value (first char after delimiter match); int valueStart = matcher . end ( ) ; // Handle all but last extension if ( valueMatcher . find ( valueStart ) ) { // FInd the next match to determine the maximum length of the value int nextMatch = valueMatcher . start ( ) ; // Find the last space prior to next match (i.e. last char before next key) int lastSpace = ext . lastIndexOf ( " " , nextMatch ) ; // Copy the value between the value start (i.e. this match) // and the lastSpace (i.e. last char prior to next key) String value = ext . substring ( valueStart , lastSpace ) ; // Put to map. extensions . put ( key , value ) ; // Update index to the last character before the next key index = lastSpace + 1 ; // Treat the last KV (if match is true) } else if ( valueMatcher . find ( valueStart - 1 ) ) { // We are handling the final character, value end if newline at the // end of string int valueEnd = ext . length ( ) ; String value = ext . substring ( valueStart , valueEnd ) ; extensions . put ( key , value ) ; // Update the index to the end of the string so no matches are possible index = valueEnd ; } } try { cefEvent . setHeader ( headers ) ; cefEvent . setExtension ( extensions ) ; } catch ( CEFHandlingException e ) { logger . error ( e . toString ( ) ) ; return null ; } if ( validate ) { if ( validator == null ) { // Since the validator wasn't initiated previously, create a new one; this . validator = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; ; } Set < ConstraintViolation < CommonEvent > > validationResult = validator . validate ( cefEvent ) ; if ( validationResult . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "CEF message failed validation" ) ; } return null ; } else { return cefEvent ; } } else { return cefEvent ; } }


Input: By convention { [CODESPLIT] @ Override public Scope supply ( Dependency < ? super Scope > dep , Injector injector ) throws UnresolvableDependency { String disk = dep . instance . name . toString ( ) ; File dir = new File ( disk . substring ( 5 ) ) ; return new DiskScope ( injector . resolve ( Config . class ) , dir , DependencyScope :: instanceName ) ; }


Input: Does this resource provide the instance wanted by the given { [CODESPLIT] public boolean isNameCompatibleWith ( Dependency < ? super T > dependency ) { return instance . name . isCompatibleWith ( dependency . instance . name ) ; }


Input: Removes those bindings that are ambiguous but also do not clash because of different { [CODESPLIT] public static Binding < ? > [ ] disambiguate ( Binding < ? > [ ] bindings ) { if ( bindings . length <= 1 ) { return bindings ; } List < Binding < ? > > uniques = new ArrayList <> ( bindings . length ) ; Arrays . sort ( bindings ) ; uniques . add ( bindings [ 0 ] ) ; int lastUniqueIndex = 0 ; Set < Type < ? > > required = new HashSet <> ( ) ; List < Binding < ? > > dropped = new ArrayList <> ( ) ; for ( int i = 1 ; i < bindings . length ; i ++ ) { Binding < ? > b_d = bindings [ lastUniqueIndex ] ; Binding < ? > b_i = bindings [ i ] ; final boolean equalResource = b_d . resource . equalTo ( b_i . resource ) ; DeclarationType t_d = b_d . source . declarationType ; DeclarationType t_i = b_i . source . declarationType ; if ( equalResource && t_d . clashesWith ( t_i ) ) { throw new InconsistentBinding ( "Duplicate binds:\n" + b_d + "\n" + b_i ) ; } if ( t_i == DeclarationType . REQUIRED ) { required . add ( b_i . resource . type ( ) ) ; } else if ( equalResource && t_d . droppedWith ( t_i ) ) { if ( i - 1 == lastUniqueIndex ) { dropped . add ( uniques . remove ( uniques . size ( ) - 1 ) ) ; } dropped . add ( b_i ) ; } else if ( ! equalResource || ! t_i . replacedBy ( t_d ) ) { uniques . add ( b_i ) ; lastUniqueIndex = i ; } } return withoutProvidedThatAreNotRequiredIn ( uniques , required , dropped ) ; }


Input: as long as there is a clear contract : namely that failure is always indicated by a EventEception [CODESPLIT] @ Override public < E , T > T compute ( Event < E , T > event ) throws Throwable { return unwrapGet ( event , submit ( event , ( ) -> doProcess ( event ) ) ) ; }


Input: Registers the given event type so that it is handled by the { @link EventProcessor } system . [CODESPLIT] protected < T > void handle ( Class < T > event ) { if ( ! event . isInterface ( ) ) throw new IllegalArgumentException ( "Event type has to be an interface but was: " + event ) ; initbind ( event ) . to ( ( Initialiser < T > ) ( listener , injector ) -> injector . resolve ( EventProcessor . class ) . register ( event , listener ) ) ; bind ( event ) . toSupplier ( ( dep , injector ) -> injector . resolve ( EventProcessor . class ) . getProxy ( event ) ) ; }


Input: Add ( accumulate ) a binding described by the 4 - tuple given . [CODESPLIT] public < T > void add ( Binding < T > complete ) { if ( ! complete . isComplete ( ) ) { throw new InconsistentBinding ( "Incomplete binding added: " + complete ) ; } // NB. #64 here we can inform post binding that about the new binding bindings . add ( complete ) ; }


Input: Uses the given { @link Macro } and derives the { @link #with ( Class Macro ) } type from its declaration . This is a utility method that can be used as long as the { @link Macro } implementation is not generic . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < T > Macros with ( Macro < T > macro ) { Class < ? > type = Type . supertype ( Macro . class , Type . raw ( macro . getClass ( ) ) ) . parameter ( 0 ) . rawType ; return with ( ( Class < ? super T > ) type , macro ) ; }


Input: Uses the given { @link Macro } for the given exact ( no super - types! ) type of values . [CODESPLIT] public < T > Macros with ( Class < T > type , Macro < ? extends T > macro ) { int index = index ( type ) ; if ( index >= 0 ) { Macro < ? > [ ] tmp = macros . clone ( ) ; tmp [ index ] = macro ; return new Macros ( types , tmp ) ; } return new Macros ( arrayPrepand ( type , types ) , arrayPrepand ( macro , macros ) ) ; }


Input: A generic version of { @link Macro#expand ( Object Binding Bindings ) } that uses the matching predefined { @link Macro } for the actual type of the value and expands it . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < T , V > void expandInto ( Bindings bindings , Binding < T > binding , V value ) { macroForValueOf ( ( Class < ? super V > ) value . getClass ( ) ) . expand ( value , binding , bindings ) ; }


Input: Example - <i > typeOf< / i > [CODESPLIT] public Type < T > parametizedAsUpperBounds ( ) { if ( ! isParameterized ( ) ) return isRawType ( ) ? parametized ( wildcards ( rawType . getTypeParameters ( ) ) ) : this ; if ( areAllTypeParametersAreUpperBounds ( ) ) return this ; return new Type <> ( upperBound , rawType , arrayMap ( params , Type :: asUpperBound ) ) ; }


Input: / * Arrays [CODESPLIT] public static < A > A [ ] arrayFilter ( A [ ] arr , Predicate < A > accept ) { if ( arr == null || arr . length == 0 ) return arr ; A [ ] accepted = newArray ( arr , arr . length ) ; int j = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) if ( accept . test ( arr [ i ] ) ) accepted [ j ++ ] = arr [ i ] ; return j == arr . length ? arr : copyOf ( accepted , j ) ; }


Input: This is a special form of flatmap where the mapping does not return zero to n Bs but always returns a B . If { [CODESPLIT] public static < A , B > B [ ] arrayFlatmap ( A [ ] as , Class < B > to , Function < A , B > flatmapOp ) { B [ ] bs = newArray ( to , as . length ) ; int j = 0 ; for ( int i = 0 ; i < as . length ; i ++ ) { B b = flatmapOp . apply ( as [ i ] ) ; if ( b != null ) bs [ j ++ ] = b ; } return j == as . length ? bs : copyOf ( bs , j ) ; }


Input: / * Annotations [CODESPLIT] public static Method annotationPropertyByType ( Class < ? > type , Class < ? extends Annotation > annotation ) { return arrayFindFirst ( annotation . getDeclaredMethods ( ) , m -> m . getReturnType ( ) == type ) ; }


Input: @return A { @link Class } counts as virtual when it is known that its not a type handled by an { @link Injector } context either because it cannot be constructed at all or it does not make sense to let the { @link Injector } take care of it . This includes value types enums collection types ( including arrays ) or any type than cannot be instantiated by its nature ( abstract types ) . [CODESPLIT] public static boolean isClassVirtual ( Class < ? > cls ) { return cls == null || cls . isInterface ( ) || cls . isEnum ( ) || cls . isAnnotation ( ) || cls . isAnonymousClass ( ) || cls . isPrimitive ( ) || cls . isArray ( ) || Modifier . isAbstract ( cls . getModifiers ( ) ) || cls == String . class || Number . class . isAssignableFrom ( cls ) || cls == Boolean . class || cls == Void . class || cls == Class . class || Collection . class . isAssignableFrom ( cls ) || Map . class . isAssignableFrom ( cls ) ; }


Input: @return A { @link Class } is monomodal if it there is just a single possible initial state . All newly created instances can just have this similar initial state but due to internal state they could ( not necessarily must ) develop ( behave ) different later on . [CODESPLIT] public static boolean isClassMonomodal ( Class < ? > cls ) { if ( cls . isInterface ( ) ) return false ; if ( cls == Object . class ) return true ; for ( Field f : cls . getDeclaredFields ( ) ) if ( ! Modifier . isStatic ( f . getModifiers ( ) ) ) return false ; for ( Constructor < ? > c : cls . getDeclaredConstructors ( ) ) // maybe arguments are passed to super-type so we check it too if ( c . getParameterTypes ( ) . length > 0 ) return isClassMonomodal ( cls . getSuperclass ( ) ) ; return true ; }


Input: / * Members [CODESPLIT] public static < T extends Member > T moreVisible ( T a , T b ) { int am = a . getModifiers ( ) ; int bm = b . getModifiers ( ) ; if ( isPublic ( am ) ) return a ; if ( isPublic ( bm ) ) return b ; if ( isProtected ( am ) ) return a ; if ( isProtected ( bm ) ) return b ; if ( isPrivate ( bm ) ) return a ; if ( isPrivate ( am ) ) return b ; return a ; // same }


Input: Returns the constructor with most visible visibility and longest argument list . Self - referencing constructors are ignored . [CODESPLIT] public static < T > Constructor < T > commonConstructor ( Class < T > type ) throws NoMethodForDependency { Constructor < ? > [ ] cs = type . getDeclaredConstructors ( ) ; if ( cs . length == 0 ) throw new NoMethodForDependency ( raw ( type ) ) ; Constructor < ? > mostParamsConstructor = null ; for ( Constructor < ? > c : cs ) { if ( ! arrayContains ( c . getParameterTypes ( ) , type , ( a , b ) -> a == b ) // avoid self referencing constructors (synthetic) as they cause endless loop && ( mostParamsConstructor == null // || ( moreVisible ( c , mostParamsConstructor ) == c && ( moreVisible ( mostParamsConstructor , c ) == c || c . getParameterCount ( ) > mostParamsConstructor . getParameterCount ( ) ) ) ) ) { mostParamsConstructor = c ; } } if ( mostParamsConstructor == null ) throw new NoMethodForDependency ( raw ( type ) ) ; @ SuppressWarnings ( "unchecked" ) Constructor < T > c = ( Constructor < T > ) mostParamsConstructor ; return c ; }


Input: / * Sequences [CODESPLIT] public static boolean seqRegionEquals ( CharSequence s1 , CharSequence s2 , int length ) { if ( s1 . length ( ) < length || s2 . length ( ) < length ) return false ; if ( s1 == s2 ) return true ; for ( int i = length - 1 ; i > 0 ; i -- ) if ( s1 . charAt ( i ) != s2 . charAt ( i ) ) return false ; return true ; }


Input: / * Exception Handling [CODESPLIT] public static < T > T orElse ( T defaultValue , Provider < T > src ) { try { return src . provide ( ) ; } catch ( UnresolvableDependency e ) { return defaultValue ; } }


Input: <pre > foo . bar . baz - > foo . bar foo . bar . - > foo . < / pre > [CODESPLIT] private static String parent ( String root ) { return root . substring ( 0 , root . lastIndexOf ( ' ' , root . length ( ) - 2 ) + ( root . endsWith ( "." ) ? 1 : 0 ) ) ; }


Input: TODO maybe extract a Plugins Extension [CODESPLIT] public static < T > Dependency < T > dependency ( Class < T > type ) { return dependency ( raw ( type ) ) ; }


Input: Utility method for transferring input stream to output . [CODESPLIT] protected static void writeInputStreamToOutput ( final Context context , final InputStream source , final OutputStream output ) throws IOException { BuffersPool pool = BeansManager . get ( context ) . getContainer ( ) . getBean ( BuffersPool . class ) ; IoUtils . transfer ( source , output , pool ) ; }


Input: Write next line as a long . [CODESPLIT] protected static void writeLong ( final Writer writer , final long value ) throws IOException { writer . write ( new StringBuilder ( ) . append ( value ) . append ( ' ' ) . toString ( ) ) ; }


Input: Write next line to the output . [CODESPLIT] protected final void writeString ( final Writer writer , final String line ) throws IOException { if ( line != null ) { writer . write ( line + ' ' ) ; } else { writer . write ( ' ' ) ; } }


Input: Make workarounds for POST requests via { [CODESPLIT] protected void doSendWorkarounds ( final URLConnection connection ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . GINGERBREAD && connection instanceof HttpURLConnection ) { try { Field resHeaderField = connection . getClass ( ) . getDeclaredField ( "resHeader" ) ; resHeaderField . setAccessible ( true ) ; resHeaderField . set ( connection , null ) ; } catch ( Exception e ) { Log . w ( "Workaround" , "Failed to make a wrokaround for Android 2.2" , e ) ; } } }


Input: Writes { @code count } bytes from the byte array { @code buffer } starting at { @code offset } to this stream . If there is room in the buffer to hold the bytes they are copied in . If not the buffered bytes plus the bytes in { @code buffer } are written to the target stream the target is flushed and the buffer is cleared . [CODESPLIT] @ Override public synchronized void write ( final byte [ ] buffer , final int offset , final int length ) throws IOException { checkNotClosed ( ) ; if ( buffer == null ) { throw new NullPointerException ( "buffer == null" ) ; } final byte [ ] internalBuffer = buf ; if ( length >= internalBuffer . length ) { flushInternal ( ) ; out . write ( buffer , offset , length ) ; return ; } if ( ( offset | length ) < 0 || offset > buffer . length || buffer . length - offset < length ) { throw new ArrayIndexOutOfBoundsException ( "length=" + buffer . length + "; regionStart=" + offset + "; regionLength=" + length ) ; } // flush the internal buffer first if we have not enough space left if ( length > ( internalBuffer . length - count ) ) { flushInternal ( ) ; } System . arraycopy ( buffer , offset , internalBuffer , count , length ) ; count += length ; }


Input: Writes one byte to this stream . Only the low order byte of the integer { @code oneByte } is written . If there is room in the buffer the byte is copied into the buffer and the count incremented . Otherwise the buffer plus { @code oneByte } are written to the target stream the target is flushed and the buffer is reset . [CODESPLIT] @ Override public synchronized void write ( final int oneByte ) throws IOException { checkNotClosed ( ) ; if ( count == buf . length ) { out . write ( buf , 0 , count ) ; count = 0 ; } buf [ count ++ ] = ( byte ) oneByte ; }


Input: Set network stats tag . Converts string tag to integer one . [CODESPLIT] protected void setConvertedTrafficStatsTag ( final String tag ) { result . statsTag = Utils . getTrafficStatsTag ( tag ) ; if ( config . isDebugRest ( ) ) { Log . d ( TAG , "TrafficStats tag <" + tag + ">=" + Integer . toHexString ( result . statsTag ) ) ; } }


Input: Setup binary content with the local file . [CODESPLIT] protected void addBinaryContent ( final String name , final Uri data , final String contentType ) { String contentName = RequestDescription . BINARY_NAME_DEFAULT ; if ( ContentResolver . SCHEME_FILE . equals ( data . getScheme ( ) ) ) { try { contentName = new File ( new URI ( data . toString ( ) ) ) . getName ( ) ; } catch ( final URISyntaxException e ) { Log . e ( TAG , "Bad file URI: " + data , e ) ; } } addBinaryContent ( name , contentName , data , contentType ) ; }


Input: Setup binary content with the local file . [CODESPLIT] protected void addBinaryContent ( final String name , final String contentName , final Uri data , final String contentType ) { final ContentUriBinaryData bdata = new ContentUriBinaryData ( ) ; bdata . setName ( name ) ; bdata . setContentUri ( data , contentName ) ; bdata . setContentType ( contentType ) ; result . addBinaryData ( bdata ) ; }


Input: Setup binary content with the bitmap . [CODESPLIT] protected void addBitmap ( final String name , final Bitmap bitmap , final String fileName ) { final BitmapBinaryData bdata = new BitmapBinaryData ( ) ; bdata . setName ( name ) ; bdata . setContentName ( fileName ) ; bdata . setBitmap ( bitmap ) ; result . addBinaryData ( bdata ) ; }


Input: Setup binary content with the file descriptor . [CODESPLIT] protected void addFileDescriptor ( final String name , final AssetFileDescriptor fd , final String contentType , final String fileName ) { final AssetFdBinaryData bdata = new AssetFdBinaryData ( ) ; bdata . setFileDescriptor ( fileName , fd ) ; bdata . setName ( name ) ; bdata . setContentType ( contentType ) ; result . addBinaryData ( bdata ) ; }


Input: Remove parameter with the specified name from request description . [CODESPLIT] protected Parameter removeParameter ( final String name ) { if ( name == null ) { throw new IllegalArgumentException ( "Parameter name cannot be null" ) ; } final Iterator < Parameter > iter = result . simpleParameters . getChildren ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { final Parameter p = iter . next ( ) ; if ( name . equals ( p . name ) ) { iter . remove ( ) ; return p ; } } return null ; }


Input: Add header to request description . [CODESPLIT] protected BaseRequestBuilder < MT > addHeader ( final String name , final String value ) { result . addHeader ( name , value ) ; return this ; }


Input: Clear the builder . [CODESPLIT] public void clear ( ) { final RequestDescription result = this . result ; result . simpleParameters . children . clear ( ) ; result . clearBinaryData ( ) ; result . contentType = null ; result . clearHeaders ( ) ; }


Input: Play the track . [CODESPLIT] protected void callPlay ( final Uri uri , final int volume , final Bundle params ) { playing = true ; paused = false ; context . startService ( createPlayIntent ( ) . setData ( uri ) . putExtra ( StreamingPlaybackService . EXTRA_VOLUME , volume ) . putExtra ( StreamingPlaybackService . EXTRA_TRACK_INFO , params ) ) ; bind ( ) ; onPlayingChanged ( ) ; preparing = true ; onPreparingChanged ( ) ; }


Input: Stop playback . [CODESPLIT] protected void callStop ( ) { playing = false ; paused = false ; context . startService ( createStopIntent ( ) ) ; onPlayingChanged ( ) ; preparing = false ; onPreparingChanged ( ) ; }


Input: Bind to the streaming service . [CODESPLIT] protected final void bind ( ) { if ( bindRequested ) { return ; } final boolean result = context . bindService ( createBindIntent ( ) , serviceConnection , 0 ) ; if ( DEBUG ) { Log . v ( TAG , "Bind to streaming service: " + result ) ; } bindRequested = result ; onBind ( result ) ; }


Input: Unbind from the streaming service . [CODESPLIT] protected final void unbind ( ) { if ( streamingPlayback != null ) { dropListener ( ) ; } try { context . unbindService ( serviceConnection ) ; } catch ( final RuntimeException e ) { if ( DEBUG ) { Log . w ( TAG , "Cannot unbind radio" , e ) ; } } bindRequested = false ; }


Input: Drop streaming service listener . [CODESPLIT] protected final void dropListener ( ) { if ( DEBUG ) { Log . v ( TAG , "Drop listener" ) ; } if ( streamingPlayback != null ) { try { streamingPlayback . removeListener ( ) ; } catch ( final RemoteException e ) { Log . e ( TAG , "Cannot remove listener" , e ) ; } bindRequested = false ; } }


Input: Store image to the disk cache . If max allowed size is set image may be rescaled on disk . [CODESPLIT] public void storeToDisk ( ) throws IOException { if ( manager . isPresentOnDisk ( url ) ) { return ; } if ( ! hasAllowedSize ( ) ) { IoUtils . consumeStream ( getRemoteInputStream ( ) , manager . getBuffersPool ( ) ) ; return ; } ImageResult result = decodeStream ( getRemoteInputStream ( ) , true ) ; if ( result . getType ( ) == ImageSourceType . NETWORK && result . getBitmap ( ) != null ) { // image was scaled writeBitmapToDisk ( result . getBitmap ( ) ) ; } }


Input: Plan an image on loading . [CODESPLIT] public ImageRequestsBuilder add ( final String url ) { requests . add ( new ImageRequest ( manager , url , defaultAllowedSize ) ) ; return this ; }


Input: Plan an image on loading . [CODESPLIT] public ImageRequestsBuilder add ( final String url , final float relativeSize ) { requests . add ( new ImageRequest ( manager , url , relativeSize ) ) ; return this ; }


Input: Composes URI builder using { [CODESPLIT] protected Uri . Builder buildUri ( ) { final Uri . Builder builder = Uri . parse ( requestDescription . getUrl ( ) ) . buildUpon ( ) ; for ( final Parameter p : requestDescription . getSimpleParameters ( ) . getChildren ( ) ) { if ( p instanceof ParameterValue ) { builder . appendQueryParameter ( p . getName ( ) , ( ( ParameterValue ) p ) . getValue ( ) ) ; } } return builder ; }


Input: Read all the bytes from input stream and convert them to a string . Input stream is closed after this method invocation . [CODESPLIT] public static String streamToString ( final InputStream stream , final String charset , final BuffersPool buffersPool ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; transfer ( stream , output , buffersPool ) ; return new String ( output . toByteArray ( ) , charset ) ; }


Input: Read all the bytes from input stream and convert them to a string using UTF - 8 charset . Input stream is closed after this method invocation . [CODESPLIT] public static String streamToString ( final InputStream stream , final BuffersPool buffersPool ) throws IOException { return streamToString ( stream , UTF_8_NAME , buffersPool ) ; }


Input: Transfers all the bytes from input to output stream . If read / write operations are successful output stream will be flushed . Input stream is always closed after this method invocation . [CODESPLIT] public static void transfer ( final InputStream input , final OutputStream output , final BuffersPool buffersPool ) throws IOException { final InputStream in = buffersPool == null ? new BufferedInputStream ( input , BUFFER_SIZE_8K ) : new PoolableBufferedInputStream ( input , BUFFER_SIZE_8K , buffersPool ) ; final byte [ ] buffer = buffersPool == null ? new byte [ BUFFER_SIZE_8K ] : buffersPool . get ( BUFFER_SIZE_8K ) ; try { int cnt ; while ( ( cnt = in . read ( buffer ) ) != EOF ) { output . write ( buffer , 0 , cnt ) ; } output . flush ( ) ; } finally { closeQuietly ( in ) ; if ( buffersPool != null ) { buffersPool . release ( buffer ) ; } } }


Input: Consume the stream and close it . This implementation calls { @link InputStream#read ( byte [] ) } method and ignores any read bytes . [CODESPLIT] public static void consumeStream ( final InputStream input , final BuffersPool buffersPool ) throws IOException { // do not use skip, just use a buffer and read it all final byte [ ] buffer = buffersPool == null ? new byte [ BUFFER_SIZE_8K ] : buffersPool . get ( BUFFER_SIZE_8K ) ; try { //noinspection StatementWithEmptyBody while ( input . read ( buffer ) != EOF ) ; } finally { closeQuietly ( input ) ; if ( buffersPool != null ) { buffersPool . release ( buffer ) ; } } }


Input: Gets stream of uncompressed bytes for the { @link URLConnection } wrapping its input stream according to what is defined in its content encoding . Supported encodings : { @link #ENCODING_GZIP } { @link #ENCODING_DEFLATE } . [CODESPLIT] public static InputStream getUncompressedInputStream ( final URLConnection connection ) throws IOException { final InputStream source = connection . getInputStream ( ) ; final String encoding = connection . getContentEncoding ( ) ; return getUncompressedInputStream ( encoding , source ) ; }


Input: Wraps the supplied stream into either { @link GZIPInputStream } or { @link InflaterInputStream } depending on { @code encoding } parameter value . [CODESPLIT] public static InputStream getUncompressedInputStream ( final String encoding , final InputStream source ) throws IOException { if ( ENCODING_GZIP . equalsIgnoreCase ( encoding ) ) { return new GZIPInputStream ( source ) ; } if ( ENCODING_DEFLATE . equalsIgnoreCase ( encoding ) ) { final Inflater inflater = new Inflater ( /*no header*/ true ) ; return new InflaterInputStream ( source , inflater ) ; } return source ; }


Input: Throw { [CODESPLIT] protected void checkBeanExists ( final String name ) { if ( name == null ) { throw new NullPointerException ( "Bean name cannot be null" ) ; } if ( ! beansManager . getContainer ( ) . containsBean ( name ) ) { throw new IllegalArgumentException ( "Bean " + name + " does not exist" ) ; } }


Input: Writes the data to the given OutputStream . [CODESPLIT] @ Override protected void sendData ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendData(OutputStream)" ) ; } out . write ( getContent ( ) ) ; }


Input:
Returns the number of bytes that are available before this stream will block . This method returns the number of bytes available in the buffer plus those available in the source stream . [CODESPLIT] @ Override public synchronized int available ( ) throws IOException { final InputStream localIn = in ; // 'in' could be invalidated by close()
 if ( buf == null || localIn == null ) { throw new IOException ( "Stream is closed" ) ; } return count - pos + localIn . available ( ) ; }


Input: Closes this stream . The source stream is closed and any resources associated with it are released . [CODESPLIT] @ Override public void close ( ) throws IOException { final byte [ ] localBuf = buf ; buf = null ; final InputStream localIn = in ; in = null ; pool . release ( localBuf ) ; if ( localIn != null ) { localIn . close ( ) ; } }


Input:
Reads a single byte from this stream and returns it as an integer in the range from 0 to 255 . Returns - 1 if the end of the source string has been reached . If the internal buffer does not contain any available bytes then it is filled from the source stream and the first byte is returned . [CODESPLIT] @ Override public synchronized int read ( ) throws IOException { // Use local refs since buf and in may be invalidated by an
 // unsynchronized close()
 byte [ ] localBuf = buf ; final InputStream localIn = in ; if ( localBuf == null || localIn == null ) { throw new IOException ( "Stream is closed" ) ; } /* Are there buffered bytes available? */ if ( pos >= count && fillbuf ( localIn , localBuf ) == - 1 ) { return - 1 ; /* no, fill buffer */ } // localBuf may have been invalidated by fillbuf
 if ( localBuf != buf ) { localBuf = buf ; if ( localBuf == null ) { throw new IOException ( "Stream is closed" ) ; } } /* Did filling the buffer fail with -1 (EOF)? */ final int mask = 0xFF ; if ( count - pos > 0 ) { return localBuf [ pos ++ ] & mask ; } return - 1 ; }


Input:
Reads at most { @code length } bytes from this stream and stores them in byte array { @code buffer } starting at offset { @code offset } . Returns the number of bytes actually read or - 1 if no bytes were read and the end of the stream was encountered . If all the buffered bytes have been used a mark has not been set and the requested number of bytes is larger than the receiver s buffer size this implementation bypasses the buffer and simply places the results directly into { @code buffer } . [CODESPLIT] @ Override public synchronized int read ( final byte [ ] buffer , final int start , final int length ) throws IOException { int offset = start ; // Use local ref since buf may be invalidated by an unsynchronized
 // close()
 byte [ ] localBuf = buf ; if ( localBuf == null ) { throw new IOException ( "Stream is closed" ) ; } // avoid int overflow
 // BEGIN android-changed
 // Exception priorities (in case of multiple errors) differ from
 // RI, but are spec-compliant.
 // made implicit null check explicit, used (offset | length) < 0
 // instead of (offset < 0) || (length < 0) to safe one operation
 if ( buffer == null ) { throw new NullPointerException ( "Buffer is null" ) ; } if ( ( offset | length ) < 0 || offset > buffer . length - length ) { throw new IndexOutOfBoundsException ( "Bad offsets" ) ; } // END android-changed
 if ( length == 0 ) { return 0 ; } final InputStream localIn = in ; if ( localIn == null ) { throw new IOException ( "Stream is closed" ) ; } int required ; if ( pos < count ) { /* There are bytes available in the buffer. */ final int copylength = count - pos >= length ? length : count - pos ; System . arraycopy ( localBuf , pos , buffer , offset , copylength ) ; pos += copylength ; if ( copylength == length || localIn . available ( ) == 0 ) { return copylength ; } offset += copylength ; required = length - copylength ; } else { required = length ; } while ( true ) { int read ; /*
       * If we're not marked and the required size is greater than the
       * buffer, simply read the bytes directly bypassing the buffer.
       */ if ( markpos == - 1 && required >= localBuf . length ) { read = localIn . read ( buffer , offset , required ) ; if ( read == - 1 ) { return required == length ? - 1 : length - required ; } } else { if ( fillbuf ( localIn , localBuf ) == - 1 ) { return required == length ? - 1 : length - required ; } // localBuf may have been invalidated by fillbuf
 if ( localBuf != buf ) { localBuf = buf ; if ( localBuf == null ) { throw new IOException ( "Stream is closed" ) ; } } read = count - pos >= required ? required : count - pos ; System . arraycopy ( localBuf , pos , buffer , offset , read ) ; pos += read ; } required -= read ; if ( required == 0 ) { return length ; } if ( localIn . available ( ) == 0 ) { return length - required ; } offset += read ; } }


Input:
Resets this stream to the last marked location . [CODESPLIT] @ Override public synchronized void reset ( ) throws IOException { // BEGIN android-changed
 /*
     * These exceptions get thrown in some "normalish" circumstances,
     * so it is preferable to avoid loading up the whole big set of
     * messages just for these cases.
     */ if ( buf == null ) { throw new IOException ( "Stream is closed" ) ; } if ( - 1 == markpos ) { throw new IOException ( "Mark has been invalidated." ) ; } // END android-changed
 pos = markpos ; }


Input:
Skips { @code amount } number of bytes in this stream . Subsequent { @code read () } s will not return these bytes unless { @code reset () } is used . [CODESPLIT] @ Override public synchronized long skip ( final long amount ) throws IOException { // Use local refs since buf and in may be invalidated by an
 // unsynchronized close()
 final byte [ ] localBuf = buf ; final InputStream localIn = in ; if ( localBuf == null ) { throw new IOException ( "Stream is closed" ) ; } if ( amount < 1 ) { return 0 ; } if ( localIn == null ) { throw new IOException ( "Stream is closed" ) ; } if ( count - pos >= amount ) { pos += amount ; return amount ; } long read = count - pos ; pos = count ; if ( markpos != - 1 && amount <= marklimit ) { if ( fillbuf ( localIn , localBuf ) == - 1 ) { return read ; } if ( count - pos >= amount - read ) { pos += amount - read ; return amount ; } // Couldn't get all the bytes, skip what we read
 read += ( count - pos ) ; pos = count ; return read ; } return read + localIn . skip ( amount - read ) ; }


Input: Write the start to the specified output stream . [CODESPLIT] protected void sendStart ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendStart(OutputStream out)" ) ; } out . write ( EXTRA_BYTES ) ; out . write ( getPartBoundary ( ) ) ; out . write ( CRLF_BYTES ) ; }


Input: Write the content disposition header to the specified output stream . [CODESPLIT] protected void sendDispositionHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendDispositionHeader(OutputStream out)" ) ; } out . write ( CONTENT_DISPOSITION_BYTES ) ; out . write ( QUOTE_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( getName ( ) ) ) ; out . write ( QUOTE_BYTES ) ; }


Input: Write the content type header to the specified output stream . [CODESPLIT] protected void sendContentTypeHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendContentTypeHeader(OutputStream out)" ) ; } final String contentType = getContentType ( ) ; if ( contentType != null ) { out . write ( CRLF_BYTES ) ; out . write ( CONTENT_TYPE_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( contentType ) ) ; final String charSet = getCharSet ( ) ; if ( charSet != null ) { out . write ( CHARSET_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( charSet ) ) ; } } }


Input: Write the content transfer encoding header to the specified output stream . [CODESPLIT] protected void sendTransferEncodingHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendTransferEncodingHeader(OutputStream out)" ) ; } final String transferEncoding = getTransferEncoding ( ) ; if ( transferEncoding != null ) { out . write ( CRLF_BYTES ) ; out . write ( CONTENT_TRANSFER_ENCODING_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( transferEncoding ) ) ; } }


Input: Write the end of the header to the output stream . [CODESPLIT] protected void sendEndOfHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendEndOfHeader(OutputStream out)" ) ; } out . write ( CRLF_BYTES ) ; out . write ( CRLF_BYTES ) ; }


Input: Write the end data to the output stream . [CODESPLIT] protected void sendEnd ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendEnd(OutputStream out)" ) ; } out . write ( CRLF_BYTES ) ; }


Input: Write all the data to the output stream . If you override this method make sure to override #length () as well [CODESPLIT] public void send ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter send(OutputStream out)" ) ; } sendStart ( out ) ; sendDispositionHeader ( out ) ; sendContentTypeHeader ( out ) ; sendTransferEncodingHeader ( out ) ; sendEndOfHeader ( out ) ; sendData ( out ) ; sendEnd ( out ) ; }


Input: Return the full length of all the data . If you override this method make sure to override #send ( OutputStream ) as well [CODESPLIT] public long length ( ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter length()" ) ; } if ( lengthOfData ( ) < 0 ) { return - 1 ; } final ByteArrayOutputStream overhead = new ByteArrayOutputStream ( ) ; sendStart ( overhead ) ; sendDispositionHeader ( overhead ) ; sendContentTypeHeader ( overhead ) ; sendTransferEncodingHeader ( overhead ) ; sendEndOfHeader ( overhead ) ; sendEnd ( overhead ) ; return overhead . size ( ) + lengthOfData ( ) ; }


Input: Write all parts and the last boundary to the specified output stream . [CODESPLIT] public static void sendParts ( final OutputStream out , final Part [ ] parts , final byte [ ] partBoundary ) throws IOException { if ( parts == null ) { throw new IllegalArgumentException ( "Parts may not be null" ) ; } if ( partBoundary == null || partBoundary . length == 0 ) { throw new IllegalArgumentException ( "partBoundary may not be empty" ) ; } for ( int i = 0 ; i < parts . length ; i ++ ) { // set the part boundary before the part is sent parts [ i ] . setPartBoundary ( partBoundary ) ; parts [ i ] . send ( out ) ; } out . write ( EXTRA_BYTES ) ; out . write ( partBoundary ) ; out . write ( EXTRA_BYTES ) ; out . write ( CRLF_BYTES ) ; }


Input: Gets the length of the multipart message including the given parts . [CODESPLIT] public static long getLengthOfParts ( final Part [ ] parts , final byte [ ] partBoundary ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "getLengthOfParts(Parts[])" ) ; } if ( parts == null ) { throw new IllegalArgumentException ( "Parts may not be null" ) ; } long total = 0 ; for ( int i = 0 ; i < parts . length ; i ++ ) { // set the part boundary before we calculate the part's length parts [ i ] . setPartBoundary ( partBoundary ) ; final long l = parts [ i ] . length ( ) ; if ( l < 0 ) { return - 1 ; } total += l ; } total += EXTRA_BYTES . length ; total += partBoundary . length ; total += EXTRA_BYTES . length ; total += CRLF_BYTES . length ; return total ; }


Input:
if it is it returns the url parameter [CODESPLIT] private String isRedirect ( String uri ) throws URISyntaxException , MalformedURLException { // Decode the path.
 URI url = new URI ( uri ) ; if ( REDIRECT_PATH . equals ( url . getPath ( ) ) ) { String query = url . getRawQuery ( ) ; Map < String , String > params = getQueryMap ( query ) ; String urlParam = params . get ( URL_PARAMETER ) ; if ( urlParam == null ) return null ; try { return URLDecoder . decode ( urlParam , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { Logger . getLogger ( WebsockifyProxyHandler . class . getName ( ) ) . severe ( e . getMessage ( ) ) ; } } return null ; }


Input:
When file timestamp is the same as what the browser is sending up send a 304 Not Modified [CODESPLIT] private void sendNotModified ( ChannelHandlerContext ctx ) { HttpResponse response = new DefaultHttpResponse ( HTTP_1_1 , HttpResponseStatus . NOT_MODIFIED ) ; setDateHeader ( response ) ; // Close the connection as soon as the error message is sent.
 ctx . getChannel ( ) . write ( response ) . addListener ( ChannelFutureListener . CLOSE ) ; }


Input: Sets the Date header for the HTTP response [CODESPLIT] private void setDateHeader ( HttpResponse response ) { SimpleDateFormat dateFormatter = new SimpleDateFormat ( HTTP_DATE_FORMAT , Locale . US ) ; dateFormatter . setTimeZone ( TimeZone . getTimeZone ( HTTP_DATE_GMT_TIMEZONE ) ) ; Calendar time = new GregorianCalendar ( ) ; response . setHeader ( HttpHeaders . Names . DATE , dateFormatter . format ( time . getTime ( ) ) ) ; }


Input:
Sets the Date and Cache headers for the HTTP Response [CODESPLIT] private void setDateAndCacheHeaders ( HttpResponse response , File fileToCache ) { SimpleDateFormat dateFormatter = new SimpleDateFormat ( HTTP_DATE_FORMAT , Locale . US ) ; dateFormatter . setTimeZone ( TimeZone . getTimeZone ( HTTP_DATE_GMT_TIMEZONE ) ) ; // Date header
 Calendar time = new GregorianCalendar ( ) ; response . setHeader ( HttpHeaders . Names . DATE , dateFormatter . format ( time . getTime ( ) ) ) ; // Add cache headers
 time . add ( Calendar . SECOND , HTTP_CACHE_SECONDS ) ; response . setHeader ( HttpHeaders . Names . EXPIRES , dateFormatter . format ( time . getTime ( ) ) ) ; response . setHeader ( HttpHeaders . Names . CACHE_CONTROL , "private, max-age=" + HTTP_CACHE_SECONDS ) ; response . setHeader ( HttpHeaders . Names . LAST_MODIFIED , dateFormatter . format ( new Date ( fileToCache . lastModified ( ) ) ) ) ; }


Input: Sets the content type header for the HTTP Response [CODESPLIT] private void setContentTypeHeader ( HttpResponse response , File file ) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap ( ) ; response . setHeader ( HttpHeaders . Names . CONTENT_TYPE , mimeTypesMap . getContentType ( file . getPath ( ) ) ) ; }


Input: Closes the specified channel after all queued write requests are flushed . [CODESPLIT] static void closeOnFlush ( Channel ch ) { if ( ch . isConnected ( ) ) { ch . write ( ChannelBuffers . EMPTY_BUFFER ) . addListener ( ChannelFutureListener . CLOSE ) ; } }


Input: Write the disposition header to the output stream . [CODESPLIT] @ Override protected void sendDispositionHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( "FilePart" , "enter sendDispositionHeader(OutputStream out)" ) ; } super . sendDispositionHeader ( out ) ; final String filename = this . source . getFileName ( ) ; if ( filename != null ) { out . write ( FILE_NAME_BYTES ) ; out . write ( QUOTE_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( filename ) ) ; out . write ( QUOTE_BYTES ) ; } }


Input: Write the data in source to the specified stream . [CODESPLIT] @ Override protected void sendData ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , "enter sendData(OutputStream out)" ) ; } if ( lengthOfData ( ) == 0 ) { // this file contains no data, so there is nothing to send. // we don't want to create a zero length buffer as this will // cause an infinite loop when reading. if ( DEBUG ) { Log . d ( TAG , "No data to send." ) ; } return ; } final int size = 4096 ; final byte [ ] tmp = new byte [ size ] ; final InputStream instream = source . createInputStream ( ) ; try { int len ; while ( ( len = instream . read ( tmp ) ) >= 0 ) { out . write ( tmp , 0 , len ) ; } } finally { // we're done with the stream, close it instream . close ( ) ; } }


Input: Setup cache . This operation causes disk reads . [CODESPLIT] protected void install ( final int version ) throws IOException { if ( buffersPool == null ) { throw new IllegalStateException ( "Buffers pool is not resolved" ) ; } diskCache = DiskLruCache . open ( ensureWorkingDirectory ( ) , version , ENTRIES_COUNT , getMaxSize ( ) ) ; onCacheInstalled ( ) ; }


Input: this method is synchronized in order to avoid concurrent calls to mkdir [CODESPLIT] private synchronized File ensureWorkingDirectory ( ) throws IOException { File directory = getWorkingDirectory ( ) ; if ( ! directory . exists ( ) ) { if ( ! directory . mkdirs ( ) ) { throw new IOException ( "Working directory " + directory + " cannot be created" ) ; } } else { if ( ! directory . isDirectory ( ) ) { if ( ! directory . delete ( ) ) { throw new IOException ( directory + " is not a directory and cannot be deleted" ) ; } if ( ! directory . mkdirs ( ) ) { throw new IOException ( "Working directory " + directory + " cannot be recreated" ) ; } } } return directory ; }


Input: Read cache for the specified cache entry . [CODESPLIT] protected CacheResponse get ( final CacheEntry requestInfo ) { if ( ! checkDiskCache ( ) ) { return null ; } final CacheEntry entry = newCacheEntry ( ) ; final DiskLruCache . Snapshot snapshot = readCacheInfo ( requestInfo , entry ) ; if ( snapshot == null ) { return null ; } if ( ! entry . matches ( requestInfo ) || ! entry . canBeUsed ( ) ) { snapshot . close ( ) ; return null ; } hitCount . incrementAndGet ( ) ; final InputStream body = newBodyInputStream ( snapshot ) ; return entry . newCacheResponse ( body ) ; }


Input: Returns an input stream that reads the body of a snapshot closing the snapshot when the stream is closed . [CODESPLIT] private InputStream newBodyInputStream ( final DiskLruCache . Snapshot snapshot ) { return new FilterInputStream ( snapshot . getInputStream ( ENTRY_BODY ) ) { @ Override public void close ( ) throws IOException { snapshot . close ( ) ; super . close ( ) ; } } ; }


Input: Prepare for new width and hight . [CODESPLIT] protected void reset ( final int width , final int height ) { Bitmap bitmap = this . bitmap ; // recycle old buffer if ( bitmap != null ) { bitmap . recycle ( ) ; } bitmap = Bitmap . createBitmap ( width , height , Bitmap . Config . ARGB_8888 ) ; // high quality this . bitmap = bitmap ; this . bitmapCanvas = new Canvas ( bitmap ) ; }


Input: Returns the singleton instance for this class [CODESPLIT] public static WebsockifySslContext getInstance ( String keystore , String password , String keyPassword ) { WebsockifySslContext context = SingletonHolder . INSTANCE_MAP . get ( keystore ) ; if ( context == null ) { context = new WebsockifySslContext ( keystore , password , keyPassword ) ; SingletonHolder . INSTANCE_MAP . put ( keystore , context ) ; } return context ; }


Input: Validates that a keystore with the given parameters exists and can be used for an SSL context . [CODESPLIT] public static void validateKeystore ( String keystore , String password , String keyPassword ) throws KeyManagementException , UnrecoverableKeyException , IOException , NoSuchAlgorithmException , CertificateException , KeyStoreException { getSSLContext ( keystore , password , keyPassword ) ; }


Input: This method replaces the scale type of an image view without call to layout requests . [CODESPLIT] public ScaleType replaceScaleType ( final ScaleType type ) { blockLayoutRequests = true ; final ScaleType result = getScaleType ( ) ; setScaleType ( type ) ; blockLayoutRequests = false ; return result ; }


Input: Set a scale type and store a previous one that will be restores after the next call to { [CODESPLIT] public void setTemporaryScaleType ( final ScaleType scaleType ) { final ScaleType old = replaceScaleType ( scaleType ) ; if ( storedScaleType == null ) { storedScaleType = old ; } }


Input: Please call it from the main thread ( with looper ) . [CODESPLIT] public void startListening ( final Context context ) { if ( DEBUG ) { Log . d ( TAG , "Start location listening..." ) ; } try { locationManager = ( LocationManager ) context . getSystemService ( Context . LOCATION_SERVICE ) ; if ( locationManager == null ) { return ; } } catch ( final Exception e ) { return ; } myHandler = myLooper != null ? new MyHandler ( myLooper ) : new MyHandler ( ) ; if ( listener != null ) { listener . onLocationStart ( ) ; } final Location last = getLastKnown ( locationManager ) ; if ( last != null ) { newLocation ( last ) ; } final Criteria c = new Criteria ( ) ; c . setAltitudeRequired ( false ) ; c . setSpeedRequired ( false ) ; c . setBearingRequired ( false ) ; c . setCostAllowed ( false ) ; c . setPowerRequirement ( Criteria . POWER_LOW ) ; c . setAccuracy ( Criteria . ACCURACY_COARSE ) ; final String coarseProvider = locationManager . getBestProvider ( c , false ) ; c . setPowerRequirement ( Criteria . NO_REQUIREMENT ) ; c . setAccuracy ( Criteria . ACCURACY_FINE ) ; final String fineProvider = locationManager . getBestProvider ( c , false ) ; if ( DEBUG ) { Log . d ( TAG , "Providers " + coarseProvider + "/" + fineProvider ) ; } final long minTime = 60000 ; final int minDistance = 50 ; if ( coarseProvider != null ) { if ( DEBUG ) { Log . d ( TAG , "Register for " + coarseProvider ) ; } locationManager . requestLocationUpdates ( coarseProvider , minTime , minDistance , coarseListener ) ; myHandler . sendEmptyMessageDelayed ( MSG_STOP_COARSE_PROVIDER , MAX_COARSE_PROVIDER_LISTEN_TIME ) ; } if ( fineProvider != null ) { if ( DEBUG ) { Log . d ( TAG , "Register for " + fineProvider ) ; } locationManager . requestLocationUpdates ( fineProvider , minTime , minDistance , fineListener ) ; myHandler . sendEmptyMessageDelayed ( MSG_STOP_FINE_PROVIDER , MAX_FINE_PROVIDER_LISTEN_TIME ) ; } }


Input: Stop updates . [CODESPLIT] public void stopListening ( ) { if ( locationManager == null ) { return ; } if ( DEBUG ) { Log . d ( TAG , "Stop location listening..." ) ; } if ( listener != null ) { listener . onLocationStop ( ) ; } myHandler . removeMessages ( MSG_STOP_FINE_PROVIDER ) ; locationManager . removeUpdates ( coarseListener ) ; locationManager . removeUpdates ( fineListener ) ; locationManager = null ; }


Input: Construct a pending intent that can be used for starting request processing . Note that after this method is executed executor of the request builder is always null . [CODESPLIT] public PendingIntent getPendingIntent ( final RequestBuilder < ? > requestBuilder , final int flags ) { return PendingIntent . getService ( context , 0 , getIntent ( requestBuilder ) , flags ) ; }


Input: Perform disconnect actions . [CODESPLIT] protected void disconnect ( final URLConnection connection ) { final URLConnection http = UrlConnectionWrapper . unwrap ( connection ) ; if ( http instanceof HttpURLConnection ) { ( ( HttpURLConnection ) http ) . disconnect ( ) ; } }


Input:
Create the service connection . [CODESPLIT] public void bind ( ) { if ( serviceObject != null ) { return ; } final Context context = contextRef . get ( ) ; if ( context == null ) { return ; } // TODO make it configurable
 final Intent intent = new Intent ( context , GoroService . class ) ; intent . setAction ( getInterfaceClass ( ) . getName ( ) ) ; if ( DEBUG_CALLS ) { Log . v ( TAG , "Attempt to bind to service " + this + "/" + context , new RuntimeException ( ) ) ; } // start manually, so that it will be stopped manually
 context . startService ( intent ) ; final boolean bindResult = context . bindService ( intent , this , 0 ) ; if ( DEBUG ) { Log . v ( TAG , "Binded to service: " + bindResult + ", " + context + ", interface: " + getInterfaceClass ( ) ) ; } }


Input: Destroy the service connection . [CODESPLIT] public void unbind ( ) { if ( serviceObject == null ) { return ; } serviceObject = null ; final Context context = contextRef . get ( ) ; if ( DEBUG ) { Log . v ( TAG , "Unbind " + context + " from " + getInterfaceClass ( ) ) ; } if ( context == null ) { return ; } try { context . unbindService ( this ) ; } catch ( final Exception e ) { if ( DEBUG ) { Log . e ( TAG , "Cannot unbind from application service" , e ) ; } } }


Input: Method should be called when wrapped view gets changes related to this consumer . [CODESPLIT] public void notifyAboutViewChanges ( ) { final T view = this . view ; if ( view != null && view instanceof ImagesLoadListenerProvider ) { this . listener = ( ( ImagesLoadListenerProvider ) view ) . getImagesLoadListener ( ) ; } }


Input:
The client won t send any message so connect directly on channel open [CODESPLIT] @ Override public void channelOpen ( final ChannelHandlerContext ctx , final ChannelStateEvent e ) throws Exception { try { // make the proxy connection
 ensureTargetConnection ( e . getChannel ( ) , false , null ) ; } catch ( Exception ex ) { // target connection failed, so close the client connection
 e . getChannel ( ) . close ( ) ; ex . printStackTrace ( ) ; } }


Input: Data loading has been successful we are going to accept data . Here we can implement some accumulation logic . [CODESPLIT] protected ResponseData < MT > onAcceptData ( final ResponseData < MT > previousData , final ResponseData < MT > responseData ) { return responseData ; }


Input: request to completely reset the loader [CODESPLIT] @ Override protected void onReset ( ) { if ( DEBUG ) { Log . v ( TAG , "onReset " + this ) ; } super . onReset ( ) ; onStopLoading ( ) ; if ( receivedResponse != null ) { onReleaseData ( receivedResponse ) ; receivedResponse = null ; } }


Input: For testing only . [CODESPLIT] void waitForLoader ( final long time ) { try { done . await ( time , TimeUnit . MILLISECONDS ) ; } catch ( final InterruptedException e ) { Log . e ( TAG , "waitForLoader() ininterrupted" , e ) ; } }


Input: main thread [CODESPLIT] public boolean addTarget ( final ImageConsumer imageHolder ) { if ( future . isCancelled ( ) ) { return false ; } // we should start a new task imageHolder . onStart ( this , request . url ) ; synchronized ( targets ) { if ( result != null ) { imagesManager . setResultImage ( imageHolder , result , false ) ; imageHolder . onFinish ( request . url , result ) ; } else if ( error != null ) { imageHolder . onError ( request . url , error ) ; } else { imageHolder . currentLoader = this ; targets . add ( imageHolder ) ; } } return true ; }


Input: main thread [CODESPLIT] public void removeTarget ( final ImageConsumer consumer ) { if ( imagesManager . debug ) { Log . d ( TAG , "Cancel request: " + request . getKey ( ) + "\nLoader: " + this ) ; } consumer . onCancel ( request . url ) ; synchronized ( targets ) { targets . remove ( consumer ) ; if ( targets . isEmpty ( ) ) { if ( ! future . cancel ( true ) ) { if ( imagesManager . debug ) { Log . d ( TAG , "Can't cancel task so let's try to remove loader manually" ) ; } imagesManager . currentLoads . remove ( request . getKey ( ) , this ) ; } } } }


Input: worker thread [CODESPLIT] private void safeImageSet ( final ImageResult result ) { if ( imagesManager . debug ) { Log . v ( ImagesManager . TAG , "Post setting drawable for " + request . getKey ( ) ) ; } synchronized ( targets ) { if ( this . result != null ) { throw new IllegalStateException ( "Result is already set" ) ; } memCacheImage ( result ) ; this . result = result ; } post ( new Runnable ( ) { @ Override public void run ( ) { if ( imagesManager . debug ) { Log . v ( TAG , "Set drawable for " + request . getKey ( ) ) ; } final ArrayList < ImageConsumer > targets = ImageLoader . this . targets ; final int count = targets . size ( ) ; if ( count > 0 ) { //noinspection ForLoopReplaceableByForEach for ( int i = 0 ; i < count ; i ++ ) { final ImageConsumer imageHolder = targets . get ( i ) ; if ( imagesManager . debug ) { Log . d ( TAG , "Try to set " + imageHolder + " - " + request . getKey ( ) ) ; } setToConsumer ( imageHolder , result ) ; } } else if ( imagesManager . debug ) { Log . w ( TAG , "set drawable: have no targets in list" ) ; } } } ) ; }


Input: main thread [CODESPLIT] private void setToConsumer ( final ImageConsumer consumer , final ImageResult result ) { if ( consumer . currentLoader == this ) { imagesManager . setResultImage ( consumer , result , true ) ; } else { if ( imagesManager . debug ) { Log . d ( TAG , "Skip set for " + consumer ) ; } } }


Input: Set text view value or set its visibility to { [CODESPLIT] public static void setTextOrHide ( final TextView view , final CharSequence text ) { setTextOrHide ( view , text , View . GONE ) ; }


Input: Set text view value or change its visibility in case of empty value . [CODESPLIT] public static void setTextOrHide ( final TextView view , final CharSequence text , final int hvisibility ) { if ( TextUtils . isEmpty ( text ) ) { view . setVisibility ( hvisibility ) ; } else { view . setText ( text ) ; view . setVisibility ( View . VISIBLE ) ; } }


Input: Hide soft keyboard . [CODESPLIT] public static void hideSoftInput ( final View textView ) { try { final InputMethodManager imm = ( InputMethodManager ) textView . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . hideSoftInputFromWindow ( textView . getWindowToken ( ) , 0 ) ; } catch ( final Exception e ) { Log . w ( TAG , "Ignore exception" , e ) ; } }


Input: Show soft keyboard . [CODESPLIT] public static void showSoftInput ( final View textView ) { try { final InputMethodManager imm = ( InputMethodManager ) textView . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . showSoftInput ( textView , InputMethodManager . SHOW_FORCED ) ; } catch ( final Exception e ) { Log . w ( TAG , "Ignore exception" , e ) ; } }


Input: Toggles keyboard visibility . [CODESPLIT] public static void toggleSoftInput ( final View textView ) { try { final InputMethodManager imm = ( InputMethodManager ) textView . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . toggleSoftInputFromWindow ( textView . getWindowToken ( ) , 0 , 0 ) ; } catch ( final Exception e ) { Log . w ( TAG , "Ignore exception" , e ) ; } }


Input: Converts device independent points to actual pixels . [CODESPLIT] public static int pixelsWidth ( final DisplayMetrics displayMetrics , final int dip ) { final float scale = displayMetrics . density ; final float alpha = 0.5f ; return ( int ) ( dip * scale + alpha ) ; }


Input: Find view by ID . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < T extends View > T find ( final View view , final int id ) { final View result = view . findViewById ( id ) ; return ( T ) result ; }


Input: Find view by ID . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static < T extends View > T find ( final Activity activity , final int id ) { final View result = activity . findViewById ( id ) ; return ( T ) result ; }


Input: cancel the timer if exception is caught - prevents useless stack traces [CODESPLIT] @ Override public void exceptionCaught ( ChannelHandlerContext ctx , ExceptionEvent e ) throws Exception { cancelDirectConnectionTimer ( ) ; Logger . getLogger ( PortUnificationHandler . class . getName ( ) ) . severe ( "Exception on connection to " + ctx . getChannel ( ) . getRemoteAddress ( ) + ": " + e . getCause ( ) . getMessage ( ) ) ; }


Input: Returns an opaque token representing the current position in the stream . Call { [CODESPLIT] public long savePosition ( int readLimit ) { long offsetLimit = offset + readLimit ; if ( limit < offsetLimit ) { setLimit ( offsetLimit ) ; } return offset ; }


Input: Makes sure that the underlying stream can backtrack the full range from { [CODESPLIT] private void setLimit ( long limit ) { try { if ( reset < offset && offset <= this . limit ) { in . reset ( ) ; in . mark ( ( int ) ( limit - reset ) ) ; skip ( reset , offset ) ; } else { reset = offset ; in . mark ( ( int ) ( limit - offset ) ) ; } this . limit = limit ; } catch ( IOException e ) { throw new IllegalStateException ( "Unable to mark: " + e ) ; } }


Input: Resets the stream to the position recorded by { [CODESPLIT] public void reset ( long token ) throws IOException { if ( offset > limit || token < reset ) { throw new IOException ( "Cannot reset" ) ; } in . reset ( ) ; skip ( reset , token ) ; offset = token ; }


Input: Skips { [CODESPLIT] private void skip ( long current , long target ) throws IOException { while ( current < target ) { long skipped = in . skip ( target - current ) ; current += skipped ; } }


Input: Clear the cached entities . [CODESPLIT] public boolean clearCache ( final String url ) { memCache . remove ( url ) ; try { return imagesResponseCache . deleteGetEntry ( url ) ; } catch ( final IOException e ) { Log . w ( TAG , "Cannot clear disk cache for " + url , e ) ; return false ; } }


Input: Populate the requested image to the specified view . Called from the GUI thread . [CODESPLIT] public void populateImage ( final View view , final String url ) { final Object tag = view . getTag ( ) ; ImageConsumer consumer = null ; if ( tag == null ) { consumer = createImageConsumer ( view ) ; view . setTag ( consumer ) ; } else { if ( ! ( tag instanceof ImageConsumer ) ) { throw new IllegalStateException ( "View already has a tag " + tag + ". Cannot store consumer" ) ; } consumer = ( ImageConsumer ) tag ; } populateImage ( consumer , url ) ; }


Input: Cancel image loading for a view . [CODESPLIT] public void cancelImageLoading ( final View view ) { checkThread ( ) ; final Object tag = view . getTag ( ) ; if ( tag != null && tag instanceof ImageConsumer ) { cancelImageLoading ( ( ImageConsumer ) tag ) ; } }


Input: Create an image holder instance for the defined view . [CODESPLIT] protected ImageConsumer createImageConsumer ( final View view ) { if ( this . consumerFactory == null ) { throw new IllegalStateException ( "Image consumers factory bean not found in container. Take a look at DefaultBeansManager.edit().images() method in assist package." ) ; } return consumerFactory . createConsumer ( view ) ; }


Input: It must be executed in the main thread . [CODESPLIT] protected final void setResultImage ( final ImageConsumer consumer , final ImageResult result , final boolean animate ) { decorateResult ( consumer , result ) ; consumer . setImage ( createDrawable ( result . getBitmap ( ) ) , animate ) ; consumer . reset ( ) ; }


Input: Set preloader . [CODESPLIT] private void setLoadingImage ( final ImageConsumer consumer ) { if ( ! consumer . skipLoadingImage ( ) ) { Drawable d = getLoadingDrawable ( consumer ) ; if ( ! consumer . hasUndefinedSize ( ) || ( d . getIntrinsicWidth ( ) != 0 && d . getIntrinsicHeight ( ) != 0 ) ) { consumer . setLoadingImage ( d ) ; } } }


Input: Executed in the main thread . [CODESPLIT] private void startImageLoaderTask ( final ImageConsumer consumer , final ImageRequest request ) { final String key = request . getKey ( ) ; if ( debug ) { Log . d ( TAG , "Key " + key ) ; } ImageLoader loader = currentLoads . get ( key ) ; if ( loader != null ) { final boolean added = loader . addTarget ( consumer ) ; if ( ! added ) { loader = null ; } } if ( loader == null ) { if ( debug ) { Log . d ( TAG , "Start a new task" ) ; } loader = new ImageLoader ( request , this ) ; if ( ! loader . addTarget ( consumer ) ) { throw new IllegalStateException ( "Cannot add target to the new loader" ) ; } currentLoads . put ( key , loader ) ; if ( debug ) { Log . d ( TAG , "Current loaders count: " + currentLoads . size ( ) ) ; } final Executor executor = getImageTaskExecutor ( ) ; executor . execute ( loader . future ) ; } else if ( debug ) { Log . d ( TAG , "Joined to the existing task " + key ) ; } }


Input: Add image to memory cache . [CODESPLIT] protected void memCacheImage ( final String url , final Bitmap bitmap ) { if ( debug ) { Log . d ( TAG , "Memcache for " + url ) ; } memCache . putElement ( url , bitmap ) ; }


Input: Checks the raw type provided by the token an presence of { [CODESPLIT] protected Type getModelType ( final EntityTypeToken modelType ) { final Class < ? > modelClass = modelType . getRawClass ( ) ; // check for wrappers final Model modelAnnotation = modelClass . getAnnotation ( Model . class ) ; if ( modelAnnotation == null ) { return modelType . getType ( ) ; } final Class < ? > wrapper = modelAnnotation . wrapper ( ) ; return wrapper != null && wrapper != Model . class ? wrapper : modelType . getType ( ) ; }


Input: Recycle the buffer . [CODESPLIT] public void release ( final byte [ ] buffer ) { if ( buffer == null ) { return ; } final int capacity = buffer . length ; if ( capacity == 0 ) { return ; } synchronized ( lock ) { List < Object > bList = buffers . get ( capacity ) ; if ( bList == null ) { bList = new LinkedList < Object > ( ) ; buffers . put ( capacity , bList ) ; } bList . add ( buffer ) ; usedBuffersCount -- ; } }


Input: A good place to set custom request headers . [CODESPLIT] protected void onURLConnectionPrepared ( final Context context , final URLConnection urlConnection ) { if ( contentType != null ) { urlConnection . addRequestProperty ( "Content-Type" , contentType ) ; } if ( contentLanguage != null ) { urlConnection . addRequestProperty ( "Accept-Language" , contentLanguage ) ; } urlConnection . addRequestProperty ( "Accept-Encoding" , IoUtils . ENCODING_GZIP ) ; urlConnection . addRequestProperty ( "User-Agent" , buildUserAgent ( context ) ) ; if ( headers != null ) { for ( String name : headers . keySet ( ) ) { urlConnection . addRequestProperty ( name , headers . getString ( name ) ) ; } } }


Input:
Build { [CODESPLIT] public URLConnection makeConnection ( final Context context ) throws IOException { ConverterFactory factory = CONVERTER_FACTORIES . get ( operationType ) ; if ( factory == null ) { throw new IllegalArgumentException ( "Don't know how to convert operation type " + operationType ) ; } final BaseRequestDescriptionConverter converter = factory . createConverter ( this , context ) ; // create instance
 final URLConnection connection = converter . prepareConnectionInstance ( ) ; // setup headers
 onURLConnectionPrepared ( context , connection ) ; // make a connection
 converter . connect ( connection ) ; // send data, if required
 converter . sendRequest ( connection ) ; return connection ; }


Input: Add string parameter . [CODESPLIT] public SimpleRequestBuilder < MT > addParam ( final String name , final String value ) { addSimpleParameter ( name , value ) ; return this ; }


Input: XXX on 2 . 3 we get NP exception in case of HTTPs connection and cache [CODESPLIT] private void connectWithWorkaround ( ) throws IOException { if ( Build . VERSION . SDK_INT > Build . VERSION_CODES . GINGERBREAD_MR1 ) { super . connect ( ) ; return ; } URLConnection coreConnection = UrlConnectionWrapper . unwrap ( getCore ( ) ) ; if ( coreConnection instanceof HttpsURLConnection ) { // CHECKSTYLE:OFF try { super . connect ( ) ; } catch ( NullPointerException e ) { // ignore this NP } // CHECKSTYLE:ON } else { super . connect ( ) ; } }


Input: Calculate 32 bytes length MD5 digest . [CODESPLIT] public static String getMd5 ( final String text ) { try { final MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; final byte [ ] utf8Bytes = text . getBytes ( UTF_8_NAME ) ; md . update ( utf8Bytes , 0 , utf8Bytes . length ) ; final byte [ ] md5hash = md . digest ( ) ; final int radix = 16 ; final int length = 32 ; final StringBuilder result = new StringBuilder ( length ) . append ( new BigInteger ( 1 , md5hash ) . toString ( radix ) ) ; final int zeroBeginLen = length - result . length ( ) ; if ( zeroBeginLen > 0 ) { final char [ ] zeroBegin = new char [ zeroBeginLen ] ; Arrays . fill ( zeroBegin , Character . forDigit ( 0 , radix ) ) ; result . insert ( 0 , zeroBegin ) ; } return result . toString ( ) ; } catch ( final NoSuchAlgorithmException | UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } }


Input: Check whether activity contains a sharing intent previously set with { [CODESPLIT] public boolean checkSharingIntent ( final Activity activity ) { final Intent activityIntent = activity . getIntent ( ) ; if ( activityIntent . hasExtra ( SharingHelper . EXTRA_SHARING ) ) { processSharingIntent ( activityIntent . < Intent > getParcelableExtra ( SharingHelper . EXTRA_SHARING ) ) ; activityIntent . removeExtra ( SharingHelper . EXTRA_SHARING ) ; return true ; } return false ; }


Input: / * From MultipartEntity [CODESPLIT] private static byte [ ] generateMultipartBoundary ( ) { final Random rand = new Random ( ) ; final int c11 = 11 , c30 = 30 ; final byte [ ] bytes = new byte [ rand . nextInt ( c11 ) + c30 ] ; // a random size from 30 to 40 final byte [ ] chars = getMultipartChars ( ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = chars [ rand . nextInt ( chars . length ) ] ; } return bytes ; }


Input: Returns a string representation of the given constant [CODESPLIT] public static String stringFor ( int n ) { switch ( n ) { case CUBLAS_GEMM_DEFAULT : return "CUBLAS_GEMM_DEFAULT" ; case CUBLAS_GEMM_ALGO0 : return "CUBLAS_GEMM_ALGO0" ; case CUBLAS_GEMM_ALGO1 : return "CUBLAS_GEMM_ALGO1" ; case CUBLAS_GEMM_ALGO2 : return "CUBLAS_GEMM_ALGO2" ; case CUBLAS_GEMM_ALGO3 : return "CUBLAS_GEMM_ALGO3" ; case CUBLAS_GEMM_ALGO4 : return "CUBLAS_GEMM_ALGO4" ; case CUBLAS_GEMM_ALGO5 : return "CUBLAS_GEMM_ALGO5" ; case CUBLAS_GEMM_ALGO6 : return "CUBLAS_GEMM_ALGO6" ; case CUBLAS_GEMM_ALGO7 : return "CUBLAS_GEMM_ALGO7" ; case CUBLAS_GEMM_ALGO8 : return "CUBLAS_GEMM_ALGO8" ; case CUBLAS_GEMM_ALGO9 : return "CUBLAS_GEMM_ALGO9" ; case CUBLAS_GEMM_ALGO10 : return "CUBLAS_GEMM_ALGO10" ; case CUBLAS_GEMM_ALGO11 : return "CUBLAS_GEMM_ALGO11" ; case CUBLAS_GEMM_ALGO12 : return "CUBLAS_GEMM_ALGO12" ; case CUBLAS_GEMM_ALGO13 : return "CUBLAS_GEMM_ALGO13" ; case CUBLAS_GEMM_ALGO14 : return "CUBLAS_GEMM_ALGO14" ; case CUBLAS_GEMM_ALGO15 : return "CUBLAS_GEMM_ALGO15" ; case CUBLAS_GEMM_ALGO16 : return "CUBLAS_GEMM_ALGO16" ; case CUBLAS_GEMM_ALGO17 : return "CUBLAS_GEMM_ALGO17" ; case CUBLAS_GEMM_ALGO18 : return "CUBLAS_GEMM_ALGO18" ; case CUBLAS_GEMM_ALGO19 : return "CUBLAS_GEMM_ALGO19" ; case CUBLAS_GEMM_ALGO20 : return "CUBLAS_GEMM_ALGO20" ; case CUBLAS_GEMM_ALGO21 : return "CUBLAS_GEMM_ALGO21" ; case CUBLAS_GEMM_ALGO22 : return "CUBLAS_GEMM_ALGO22" ; case CUBLAS_GEMM_ALGO23 : return "CUBLAS_GEMM_ALGO23" ; case CUBLAS_GEMM_DEFAULT_TENSOR_OP : return "CUBLAS_GEMM_DEFAULT_TENSOR_OP" ; case CUBLAS_GEMM_ALGO0_TENSOR_OP : return "CUBLAS_GEMM_ALGO0_TENSOR_OP" ; case CUBLAS_GEMM_ALGO1_TENSOR_OP : return "CUBLAS_GEMM_ALGO1_TENSOR_OP" ; case CUBLAS_GEMM_ALGO2_TENSOR_OP : return "CUBLAS_GEMM_ALGO2_TENSOR_OP" ; case CUBLAS_GEMM_ALGO3_TENSOR_OP : return "CUBLAS_GEMM_ALGO3_TENSOR_OP" ; case CUBLAS_GEMM_ALGO4_TENSOR_OP : return "CUBLAS_GEMM_ALGO4_TENSOR_OP" ; case CUBLAS_GEMM_ALGO5_TENSOR_OP : return "CUBLAS_GEMM_ALGO5_TENSOR_OP" ; case CUBLAS_GEMM_ALGO6_TENSOR_OP : return "CUBLAS_GEMM_ALGO6_TENSOR_OP" ; case CUBLAS_GEMM_ALGO7_TENSOR_OP : return "CUBLAS_GEMM_ALGO7_TENSOR_OP" ; case CUBLAS_GEMM_ALGO8_TENSOR_OP : return "CUBLAS_GEMM_ALGO8_TENSOR_OP" ; case CUBLAS_GEMM_ALGO9_TENSOR_OP : return "CUBLAS_GEMM_ALGO9_TENSOR_OP" ; case CUBLAS_GEMM_ALGO10_TENSOR_OP : return "CUBLAS_GEMM_ALGO10_TENSOR_OP" ; case CUBLAS_GEMM_ALGO11_TENSOR_OP : return "CUBLAS_GEMM_ALGO11_TENSOR_OP" ; case CUBLAS_GEMM_ALGO12_TENSOR_OP : return "CUBLAS_GEMM_ALGO12_TENSOR_OP" ; case CUBLAS_GEMM_ALGO13_TENSOR_OP : return "CUBLAS_GEMM_ALGO13_TENSOR_OP" ; case CUBLAS_GEMM_ALGO14_TENSOR_OP : return "CUBLAS_GEMM_ALGO14_TENSOR_OP" ; } return "INVALID cublasGemmAlgo: " + n ; }


Input: Returns the String identifying the given cublasStatus [CODESPLIT] public static String stringFor ( int n ) { switch ( n ) { case CUBLAS_STATUS_SUCCESS : return "CUBLAS_STATUS_SUCCESS" ; case CUBLAS_STATUS_NOT_INITIALIZED : return "CUBLAS_STATUS_NOT_INITIALIZED" ; case CUBLAS_STATUS_ALLOC_FAILED : return "CUBLAS_STATUS_ALLOC_FAILED" ; case CUBLAS_STATUS_INVALID_VALUE : return "CUBLAS_STATUS_INVALID_VALUE" ; case CUBLAS_STATUS_ARCH_MISMATCH : return "CUBLAS_STATUS_ARCH_MISMATCH" ; case CUBLAS_STATUS_MAPPING_ERROR : return "CUBLAS_STATUS_MAPPING_ERROR" ; case CUBLAS_STATUS_EXECUTION_FAILED : return "CUBLAS_STATUS_EXECUTION_FAILED" ; case CUBLAS_STATUS_INTERNAL_ERROR : return "CUBLAS_STATUS_INTERNAL_ERROR" ; case CUBLAS_STATUS_NOT_SUPPORTED : return "CUBLAS_STATUS_NOT_SUPPORTED" ; case JCUBLAS_STATUS_INTERNAL_ERROR : return "JCUBLAS_STATUS_INTERNAL_ERROR" ; } return "INVALID cublasStatus: " + n ; }


Input: If the given result is different to cublasStatus . CUBLAS_STATUS_SUCCESS and exceptions have been enabled this method will throw a CudaException with an error message that corresponds to the given result code . Otherwise the given result is simply returned . [CODESPLIT] private static int checkResult ( int result ) { if ( exceptionsEnabled && result != cublasStatus . CUBLAS_STATUS_SUCCESS ) { throw new CudaException ( cublasStatus . stringFor ( result ) ) ; } return result ; }


Input: <pre > cublasStatus_t cublasSetVector ( int n int elemSize const void * x int incx void * y int incy ) [CODESPLIT] public static int cublasSetVector ( int n , int elemSize , Pointer x , int incx , Pointer devicePtr , int incy ) { return checkResult ( cublasSetVectorNative ( n , elemSize , x , incx , devicePtr , incy ) ) ; }


Input: <pre > cublasStatus_t cublasGetVector ( int n int elemSize const void * x int incx void * y int incy ) [CODESPLIT] public static int cublasGetVector ( int n , int elemSize , Pointer x , int incx , Pointer y , int incy ) { return checkResult ( cublasGetVectorNative ( n , elemSize , x , incx , y , incy ) ) ; }


Input: <pre > cublasStatus_t cublasSetMatrix ( int rows int cols int elemSize const void * A int lda void * B int ldb ) [CODESPLIT] public static int cublasSetMatrix ( int rows , int cols , int elemSize , Pointer A , int lda , Pointer B , int ldb ) { return checkResult ( cublasSetMatrixNative ( rows , cols , elemSize , A , lda , B , ldb ) ) ; }


Input: <pre > cublasStatus_t cublasGetMatrix ( int rows int cols int elemSize const void * A int lda void * B int ldb ) [CODESPLIT] public static int cublasGetMatrix ( int rows , int cols , int elemSize , Pointer A , int lda , Pointer B , int ldb ) { return checkResult ( cublasGetMatrixNative ( rows , cols , elemSize , A , lda , B , ldb ) ) ; }


Input: <pre > cublasStatus cublasSetVectorAsync ( int n int elemSize const void * x int incx void * y int incy cudaStream_t stream ) ; [CODESPLIT] public static int cublasSetVectorAsync ( int n , int elemSize , Pointer hostPtr , int incx , Pointer devicePtr , int incy , cudaStream_t stream ) { return checkResult ( cublasSetVectorAsyncNative ( n , elemSize , hostPtr , incx , devicePtr , incy , stream ) ) ; }


Input: <pre > cublasStatus cublasGetVectorAsync ( int n int elemSize const void * x int incx void * y int incy cudaStream_t stream ) [CODESPLIT] public static int cublasGetVectorAsync ( int n , int elemSize , Pointer devicePtr , int incx , Pointer hostPtr , int incy , cudaStream_t stream ) { return checkResult ( cublasGetVectorAsyncNative ( n , elemSize , devicePtr , incx , hostPtr , incy , stream ) ) ; }