idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
22,500 | public static JasperPrint generateJasperPrint ( DynamicReport dr , LayoutManager layoutManager , JRDataSource ds , Map < String , Object > _parameters ) throws JRException { log . info ( "generating JasperPrint" ) ; JasperPrint jp ; JasperReport jr = DynamicJasperHelper . generateJasperReport ( dr , layoutManager , _parameters ) ; jp = JasperFillManager . fillReport ( jr , _parameters , ds ) ; return jp ; } | Compiles and fills the reports design . |
22,501 | public static JasperPrint generateJasperPrint ( DynamicReport dr , LayoutManager layoutManager , Connection con , Map < String , Object > _parameters ) throws JRException { log . info ( "generating JasperPrint" ) ; JasperPrint jp ; if ( _parameters == null ) _parameters = new HashMap < String , Object > ( ) ; visitSubreports ( dr , _parameters ) ; compileOrLoadSubreports ( dr , _parameters , "r" ) ; DynamicJasperDesign jd = generateJasperDesign ( dr ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; if ( ! _parameters . isEmpty ( ) ) { registerParams ( jd , _parameters ) ; params . putAll ( _parameters ) ; } registerEntities ( jd , dr , layoutManager ) ; layoutManager . applyLayout ( jd , dr ) ; JRPropertiesUtil . getInstance ( DefaultJasperReportsContext . getInstance ( ) ) . setProperty ( JRCompiler . COMPILER_PREFIX , DJCompilerFactory . getCompilerClassName ( ) ) ; JasperReport jr = JasperCompileManager . compileReport ( jd ) ; params . putAll ( jd . getParametersWithValues ( ) ) ; jp = JasperFillManager . fillReport ( jr , params , con ) ; return jp ; } | For running queries embebed in the report design |
22,502 | public static void generateJRXML ( DynamicReport dr , LayoutManager layoutManager , Map _parameters , String xmlEncoding , OutputStream outputStream ) throws JRException { JasperReport jr = generateJasperReport ( dr , layoutManager , _parameters ) ; if ( xmlEncoding == null ) xmlEncoding = DEFAULT_XML_ENCODING ; JRXmlWriter . writeReport ( jr , outputStream , xmlEncoding ) ; } | Creates a jrxml file |
22,503 | public static void registerParams ( DynamicJasperDesign jd , Map _parameters ) { for ( Object key : _parameters . keySet ( ) ) { if ( key instanceof String ) { try { Object value = _parameters . get ( key ) ; if ( jd . getParametersMap ( ) . get ( key ) != null ) { log . warn ( "Parameter \"" + key + "\" already registered, skipping this one: " + value ) ; continue ; } JRDesignParameter parameter = new JRDesignParameter ( ) ; if ( value == null ) continue ; Class clazz = value . getClass ( ) . getComponentType ( ) ; if ( clazz == null ) clazz = value . getClass ( ) ; parameter . setValueClass ( clazz ) ; parameter . setName ( ( String ) key ) ; jd . addParameter ( parameter ) ; } catch ( JRException e ) { } } } } | For every String key it registers the object as a parameter to make it available in the report . |
22,504 | @ SuppressWarnings ( "unchecked" ) protected static void visitSubreports ( DynamicReport dr , Map _parameters ) { for ( DJGroup group : dr . getColumnsGroups ( ) ) { for ( Subreport subreport : group . getHeaderSubreports ( ) ) { if ( subreport . getDynamicReport ( ) != null ) { visitSubreport ( dr , subreport ) ; visitSubreports ( subreport . getDynamicReport ( ) , _parameters ) ; } } for ( Subreport subreport : group . getFooterSubreports ( ) ) { if ( subreport . getDynamicReport ( ) != null ) { visitSubreport ( dr , subreport ) ; visitSubreports ( subreport . getDynamicReport ( ) , _parameters ) ; } } } } | Performs any needed operation on subreports after they are built like ensuring proper subreport with if fitToParentPrintableArea flag is set to true |
22,505 | public static JRDesignExpression getDataSourceExpression ( DJDataSource ds ) { JRDesignExpression exp = new JRDesignExpression ( ) ; exp . setValueClass ( JRDataSource . class ) ; String dsType = getDataSourceTypeStr ( ds . getDataSourceType ( ) ) ; String expText = null ; if ( ds . getDataSourceOrigin ( ) == DJConstants . DATA_SOURCE_ORIGIN_FIELD ) { expText = dsType + "$F{" + ds . getDataSourceExpression ( ) + "})" ; } else if ( ds . getDataSourceOrigin ( ) == DJConstants . DATA_SOURCE_ORIGIN_PARAMETER ) { expText = dsType + REPORT_PARAMETERS_MAP + ".get( \"" + ds . getDataSourceExpression ( ) + "\" ) )" ; } else if ( ds . getDataSourceOrigin ( ) == DJConstants . DATA_SOURCE_TYPE_SQL_CONNECTION ) { expText = dsType + REPORT_PARAMETERS_MAP + ".get( \"" + ds . getDataSourceExpression ( ) + "\" ) )" ; } else if ( ds . getDataSourceOrigin ( ) == DJConstants . DATA_SOURCE_ORIGIN_REPORT_DATASOURCE ) { expText = "((" + JRDataSource . class . getName ( ) + ") $P{REPORT_DATA_SOURCE})" ; } exp . setText ( expText ) ; return exp ; } | Returns the expression string required |
22,506 | public static JRDesignExpression getReportConnectionExpression ( ) { JRDesignExpression connectionExpression = new JRDesignExpression ( ) ; connectionExpression . setText ( "$P{" + JRDesignParameter . REPORT_CONNECTION + "}" ) ; connectionExpression . setValueClass ( Connection . class ) ; return connectionExpression ; } | Returns a JRDesignExpression that points to the main report connection |
22,507 | public static String getVariablesMapExpression ( Collection variables ) { StringBuilder variablesMap = new StringBuilder ( "new " + PropertiesMap . class . getName ( ) + "()" ) ; for ( Object variable : variables ) { JRVariable jrvar = ( JRVariable ) variable ; String varname = jrvar . getName ( ) ; variablesMap . append ( ".with(\"" ) . append ( varname ) . append ( "\",$V{" ) . append ( varname ) . append ( "})" ) ; } return variablesMap . toString ( ) ; } | Collection of JRVariable |
22,508 | public static String createCustomExpressionInvocationText ( CustomExpression customExpression , String customExpName , boolean usePreviousFieldValues ) { String stringExpression ; if ( customExpression instanceof DJSimpleExpression ) { DJSimpleExpression varexp = ( DJSimpleExpression ) customExpression ; String symbol ; switch ( varexp . getType ( ) ) { case DJSimpleExpression . TYPE_FIELD : symbol = "F" ; break ; case DJSimpleExpression . TYPE_VARIABLE : symbol = "V" ; break ; case DJSimpleExpression . TYPE_PARAMATER : symbol = "P" ; break ; default : throw new DJException ( "Invalid DJSimpleExpression, type must be FIELD, VARIABLE or PARAMETER" ) ; } stringExpression = "$" + symbol + "{" + varexp . getVariableName ( ) + "}" ; } else { String fieldsMap = "((" + DJDefaultScriptlet . class . getName ( ) + ")$P{REPORT_SCRIPTLET}).getCurrentFields()" ; if ( usePreviousFieldValues ) { fieldsMap = "((" + DJDefaultScriptlet . class . getName ( ) + ")$P{REPORT_SCRIPTLET}).getPreviousFields()" ; } String parametersMap = "((" + DJDefaultScriptlet . class . getName ( ) + ")$P{REPORT_SCRIPTLET}).getCurrentParams()" ; String variablesMap = "((" + DJDefaultScriptlet . class . getName ( ) + ")$P{REPORT_SCRIPTLET}).getCurrentVariables()" ; stringExpression = "((" + CustomExpression . class . getName ( ) + ")$P{REPORT_PARAMETERS_MAP}.get(\"" + customExpName + "\"))." + CustomExpression . EVAL_METHOD_NAME + "( " + fieldsMap + ", " + variablesMap + ", " + parametersMap + " )" ; } return stringExpression ; } | If you register a CustomExpression with the name customExpName then this will create the text needed to invoke it in a JRDesignExpression |
22,509 | private void addProperties ( final PropertyDescriptor [ ] _properties ) throws ColumnBuilderException , ClassNotFoundException { for ( final PropertyDescriptor property : _properties ) { if ( isValidProperty ( property ) ) { addColumn ( getColumnTitle ( property ) , property . getName ( ) , property . getPropertyType ( ) . getName ( ) , getColumnWidth ( property ) ) ; } } setUseFullPageWidth ( true ) ; } | Adds columns for the specified properties . |
22,510 | private static String getColumnTitle ( final PropertyDescriptor _property ) { final StringBuilder buffer = new StringBuilder ( ) ; final String name = _property . getName ( ) ; buffer . append ( Character . toUpperCase ( name . charAt ( 0 ) ) ) ; for ( int i = 1 ; i < name . length ( ) ; i ++ ) { final char c = name . charAt ( i ) ; if ( Character . isUpperCase ( c ) ) { buffer . append ( ' ' ) ; } buffer . append ( c ) ; } return buffer . toString ( ) ; } | Calculates a column title using camel humps to separate words . |
22,511 | private static boolean isValidPropertyClass ( final PropertyDescriptor _property ) { final Class type = _property . getPropertyType ( ) ; return Number . class . isAssignableFrom ( type ) || type == String . class || Date . class . isAssignableFrom ( type ) || type == Boolean . class ; } | Checks if a property s type is valid to be included in the report . |
22,512 | private static int getColumnWidth ( final PropertyDescriptor _property ) { final Class type = _property . getPropertyType ( ) ; if ( Float . class . isAssignableFrom ( type ) || Double . class . isAssignableFrom ( type ) ) { return 70 ; } else if ( type == Boolean . class ) { return 10 ; } else if ( Number . class . isAssignableFrom ( type ) ) { return 60 ; } else if ( type == String . class ) { return 100 ; } else if ( Date . class . isAssignableFrom ( type ) ) { return 50 ; } else { return 50 ; } } | Calculates the column width according to its type . |
22,513 | public void addSerie ( AbstractColumn column , StringExpression labelExpression ) { series . add ( column ) ; seriesLabels . put ( column , labelExpression ) ; } | Adds the specified serie column to the dataset with custom label expression . |
22,514 | public DynamicReport build ( ) { if ( built ) { throw new DJBuilderException ( "DynamicReport already built. Cannot use more than once." ) ; } else { built = true ; } report . setOptions ( options ) ; if ( ! globalVariablesGroup . getFooterVariables ( ) . isEmpty ( ) || ! globalVariablesGroup . getHeaderVariables ( ) . isEmpty ( ) || ! globalVariablesGroup . getVariables ( ) . isEmpty ( ) || hasPercentageColumn ( ) ) { report . getColumnsGroups ( ) . add ( 0 , globalVariablesGroup ) ; } createChartGroups ( ) ; addGlobalCrosstabs ( ) ; addSubreportsToGroups ( ) ; concatenateReports ( ) ; report . setAutoTexts ( autoTexts ) ; return report ; } | Builds the DynamicReport object . Cannot be used twice since this produced undesired results on the generated DynamicReport object |
22,515 | protected void concatenateReports ( ) { if ( ! concatenatedReports . isEmpty ( ) ) { DJGroup globalGroup = createDummyGroup ( ) ; report . getColumnsGroups ( ) . add ( 0 , globalGroup ) ; } for ( Subreport subreport : concatenatedReports ) { DJGroup globalGroup = createDummyGroup ( ) ; globalGroup . getFooterSubreports ( ) . add ( subreport ) ; report . getColumnsGroups ( ) . add ( 0 , globalGroup ) ; } } | Create dummy groups for each concatenated report and in the footer of each group adds the subreport . |
22,516 | public DynamicReportBuilder setTemplateFile ( String path , boolean importFields , boolean importVariables , boolean importParameters , boolean importDatasets ) { report . setTemplateFileName ( path ) ; report . setTemplateImportFields ( importFields ) ; report . setTemplateImportParameters ( importParameters ) ; report . setTemplateImportVariables ( importVariables ) ; report . setTemplateImportDatasets ( importDatasets ) ; return this ; } | The full path of a jrxml file or the path in the classpath of a jrxml resource . |
22,517 | public DynamicReportBuilder addStyle ( Style style ) throws DJBuilderException { if ( style . getName ( ) == null ) { throw new DJBuilderException ( "Invalid style. The style must have a name" ) ; } report . addStyle ( style ) ; return this ; } | You can register styles object for later reference them directly . Parent styles should be registered this way |
22,518 | public DynamicReportBuilder setQuery ( String text , String language ) { this . report . setQuery ( new DJQuery ( text , language ) ) ; return this ; } | Adds main report query . |
22,519 | public DynamicReportBuilder setProperty ( String name , String value ) { this . report . setProperty ( name , value ) ; return this ; } | Adds a property to report design this properties are mostly used by exporters to know if any specific configuration is needed |
22,520 | public DynamicReportBuilder setColspan ( int colNumber , int colQuantity , String colspanTitle ) { this . setColspan ( colNumber , colQuantity , colspanTitle , null ) ; return this ; } | Set a colspan in a group of columns . First add the cols to the report |
22,521 | public void setTotalColorForColumn ( int column , Color color ) { int map = ( colors . length - 1 ) - column ; colors [ map ] [ colors [ 0 ] . length - 1 ] = color ; } | Set the color for each total for the column |
22,522 | public void setColorForTotal ( int row , int column , Color color ) { int mapC = ( colors . length - 1 ) - column ; int mapR = ( colors [ 0 ] . length - 1 ) - row ; colors [ mapC ] [ mapR ] = color ; } | Sets the color for the big total between the column and row |
22,523 | public static void copyThenClose ( InputStream input , OutputStream output ) throws IOException { copy ( input , output ) ; input . close ( ) ; output . close ( ) ; } | Copies information between specified streams and then closes both of the streams . |
22,524 | public SubReportBuilder setParameterMapPath ( String path ) { subreport . setParametersExpression ( path ) ; subreport . setParametersMapOrigin ( DJConstants . SUBREPORT_PARAMETER_MAP_ORIGIN_PARAMETER ) ; return this ; } | defines the KEY in the parent report parameters map where to get the subreport parameters map . |
22,525 | public List < ColumnProperty > getAllFields ( ) { ArrayList < ColumnProperty > l = new ArrayList < ColumnProperty > ( ) ; for ( AbstractColumn abstractColumn : this . getColumns ( ) ) { if ( abstractColumn instanceof SimpleColumn && ! ( abstractColumn instanceof ExpressionColumn ) ) { l . add ( ( ( SimpleColumn ) abstractColumn ) . getColumnProperty ( ) ) ; } } l . addAll ( this . getFields ( ) ) ; return l ; } | Collects all the fields from columns and also the fields not bounds to columns |
22,526 | protected void registerValueFormatter ( DJGroupVariable djVariable , String variableName ) { if ( djVariable . getValueFormatter ( ) == null ) { return ; } JRDesignParameter dparam = new JRDesignParameter ( ) ; dparam . setName ( variableName + "_vf" ) ; dparam . setValueClassName ( DJValueFormatter . class . getName ( ) ) ; log . debug ( "Registering value formatter parameter for property " + dparam . getName ( ) ) ; try { getDjd ( ) . addParameter ( dparam ) ; } catch ( JRException e ) { throw new EntitiesRegistrationException ( e . getMessage ( ) , e ) ; } getDjd ( ) . getParametersWithValues ( ) . put ( dparam . getName ( ) , djVariable . getValueFormatter ( ) ) ; } | Registers the parameter for the value formatter for the given variable and puts it s implementation in the parameters map . |
22,527 | protected void setWhenNoDataBand ( ) { log . debug ( "setting up WHEN NO DATA band" ) ; String whenNoDataText = getReport ( ) . getWhenNoDataText ( ) ; Style style = getReport ( ) . getWhenNoDataStyle ( ) ; if ( whenNoDataText == null || "" . equals ( whenNoDataText ) ) return ; JRDesignBand band = new JRDesignBand ( ) ; getDesign ( ) . setNoData ( band ) ; JRDesignTextField text = new JRDesignTextField ( ) ; JRDesignExpression expression = ExpressionUtils . createStringExpression ( "\"" + whenNoDataText + "\"" ) ; text . setExpression ( expression ) ; if ( style == null ) { style = getReport ( ) . getOptions ( ) . getDefaultDetailStyle ( ) ; } if ( getReport ( ) . isWhenNoDataShowTitle ( ) ) { LayoutUtils . copyBandElements ( band , getDesign ( ) . getTitle ( ) ) ; LayoutUtils . copyBandElements ( band , getDesign ( ) . getPageHeader ( ) ) ; } if ( getReport ( ) . isWhenNoDataShowColumnHeader ( ) ) LayoutUtils . copyBandElements ( band , getDesign ( ) . getColumnHeader ( ) ) ; int offset = LayoutUtils . findVerticalOffset ( band ) ; text . setY ( offset ) ; applyStyleToElement ( style , text ) ; text . setWidth ( getReport ( ) . getOptions ( ) . getPrintableWidth ( ) ) ; text . setHeight ( 50 ) ; band . addElement ( text ) ; log . debug ( "OK setting up WHEN NO DATA band" ) ; } | Creates the graphic element to be shown when the datasource is empty |
22,528 | protected void ensureDJStyles ( ) { for ( Style style : getReport ( ) . getStyles ( ) . values ( ) ) { addStyleToDesign ( style ) ; } Style defaultDetailStyle = getReport ( ) . getOptions ( ) . getDefaultDetailStyle ( ) ; Style defaultHeaderStyle = getReport ( ) . getOptions ( ) . getDefaultHeaderStyle ( ) ; for ( AbstractColumn column : report . getColumns ( ) ) { if ( column . getStyle ( ) == null ) column . setStyle ( defaultDetailStyle ) ; if ( column . getHeaderStyle ( ) == null ) column . setHeaderStyle ( defaultHeaderStyle ) ; } } | Sets a default style for every element that doesn t have one |
22,529 | protected void setColumnsFinalWidth ( ) { log . debug ( "Setting columns final width." ) ; float factor ; int printableArea = report . getOptions ( ) . getColumnWidth ( ) ; List visibleColums = getVisibleColumns ( ) ; if ( report . getOptions ( ) . isUseFullPageWidth ( ) ) { int columnsWidth = 0 ; int notRezisableWidth = 0 ; for ( Object visibleColum : visibleColums ) { AbstractColumn col = ( AbstractColumn ) visibleColum ; columnsWidth += col . getWidth ( ) ; if ( col . isFixedWidth ( ) ) notRezisableWidth += col . getWidth ( ) ; } factor = ( float ) ( printableArea - notRezisableWidth ) / ( float ) ( columnsWidth - notRezisableWidth ) ; log . debug ( "printableArea = " + printableArea + ", columnsWidth = " + columnsWidth + ", columnsWidth = " + columnsWidth + ", notRezisableWidth = " + notRezisableWidth + ", factor = " + factor ) ; int acumulated = 0 ; int colFinalWidth ; Collection resizableColumns = CollectionUtils . select ( visibleColums , new Predicate ( ) { public boolean evaluate ( Object arg0 ) { return ! ( ( AbstractColumn ) arg0 ) . isFixedWidth ( ) ; } } ) ; for ( Iterator iter = resizableColumns . iterator ( ) ; iter . hasNext ( ) ; ) { AbstractColumn col = ( AbstractColumn ) iter . next ( ) ; if ( ! iter . hasNext ( ) ) { col . setWidth ( printableArea - notRezisableWidth - acumulated ) ; } else { colFinalWidth = ( new Float ( col . getWidth ( ) * factor ) ) . intValue ( ) ; acumulated += colFinalWidth ; col . setWidth ( colFinalWidth ) ; } } } int posx = 0 ; for ( Object visibleColum : visibleColums ) { AbstractColumn col = ( AbstractColumn ) visibleColum ; col . setPosX ( posx ) ; posx += col . getWidth ( ) ; } } | Sets the columns width by reading some report options like the printableArea and useFullPageWidth . columns with fixedWidth property set in TRUE will not be modified |
22,530 | protected void setBandsFinalHeight ( ) { log . debug ( "Setting bands final height..." ) ; List < JRBand > bands = new ArrayList < JRBand > ( ) ; Utils . addNotNull ( bands , design . getPageHeader ( ) ) ; Utils . addNotNull ( bands , design . getPageFooter ( ) ) ; Utils . addNotNull ( bands , design . getColumnHeader ( ) ) ; Utils . addNotNull ( bands , design . getColumnFooter ( ) ) ; Utils . addNotNull ( bands , design . getSummary ( ) ) ; Utils . addNotNull ( bands , design . getBackground ( ) ) ; bands . addAll ( ( ( JRDesignSection ) design . getDetailSection ( ) ) . getBandsList ( ) ) ; Utils . addNotNull ( bands , design . getLastPageFooter ( ) ) ; Utils . addNotNull ( bands , design . getTitle ( ) ) ; Utils . addNotNull ( bands , design . getPageFooter ( ) ) ; Utils . addNotNull ( bands , design . getNoData ( ) ) ; for ( JRGroup jrgroup : design . getGroupsList ( ) ) { DJGroup djGroup = ( DJGroup ) getReferencesMap ( ) . get ( jrgroup . getName ( ) ) ; JRDesignSection headerSection = ( JRDesignSection ) jrgroup . getGroupHeaderSection ( ) ; JRDesignSection footerSection = ( JRDesignSection ) jrgroup . getGroupFooterSection ( ) ; if ( djGroup != null ) { for ( JRBand headerBand : headerSection . getBandsList ( ) ) { setBandFinalHeight ( ( JRDesignBand ) headerBand , djGroup . getHeaderHeight ( ) , djGroup . isFitHeaderHeightToContent ( ) ) ; } for ( JRBand footerBand : footerSection . getBandsList ( ) ) { setBandFinalHeight ( ( JRDesignBand ) footerBand , djGroup . getFooterHeight ( ) , djGroup . isFitFooterHeightToContent ( ) ) ; } } else { bands . addAll ( headerSection . getBandsList ( ) ) ; bands . addAll ( footerSection . getBandsList ( ) ) ; } } for ( JRBand jrDesignBand : bands ) { setBandFinalHeight ( ( JRDesignBand ) jrDesignBand ) ; } } | Sets the necessary height for all bands in the report to hold their children |
22,531 | private void setBandFinalHeight ( JRDesignBand band , int currHeigth , boolean fitToContent ) { if ( band != null ) { int finalHeight = LayoutUtils . findVerticalOffset ( band ) ; if ( finalHeight < currHeigth && ! fitToContent ) { } else { band . setHeight ( finalHeight ) ; } } } | Removes empty space when fitToContent is true and real height of object is taller than current bands height otherwise it is not modified |
22,532 | protected JRDesignGroup getParent ( JRDesignGroup group ) { int index = realGroups . indexOf ( group ) ; return ( index > 0 ) ? ( JRDesignGroup ) realGroups . get ( index - 1 ) : group ; } | Finds the parent group of the given one and returns it |
22,533 | public static int findVerticalOffset ( JRDesignBand band ) { int finalHeight = 0 ; if ( band != null ) { for ( JRChild jrChild : band . getChildren ( ) ) { JRDesignElement element = ( JRDesignElement ) jrChild ; int currentHeight = element . getY ( ) + element . getHeight ( ) ; if ( currentHeight > finalHeight ) finalHeight = currentHeight ; } return finalHeight ; } return finalHeight ; } | Finds Y coordinate value in which more elements could be added in the band |
22,534 | public static void moveBandsElemnts ( int yOffset , JRDesignBand band ) { if ( band == null ) return ; for ( JRChild jrChild : band . getChildren ( ) ) { JRDesignElement elem = ( JRDesignElement ) jrChild ; elem . setY ( elem . getY ( ) + yOffset ) ; } } | Moves the elements contained in band in the Y axis yOffset |
22,535 | public static JRDesignGroup getJRDesignGroup ( DynamicJasperDesign jd , LayoutManager layoutManager , DJGroup group ) { Map references = layoutManager . getReferencesMap ( ) ; for ( Object o : references . keySet ( ) ) { String groupName = ( String ) o ; DJGroup djGroup = ( DJGroup ) references . get ( groupName ) ; if ( group == djGroup ) { return ( JRDesignGroup ) jd . getGroupsMap ( ) . get ( groupName ) ; } } return null ; } | Returns the JRDesignGroup for the DJGroup passed |
22,536 | protected void applyBanners ( ) { DynamicReportOptions options = getReport ( ) . getOptions ( ) ; if ( options . getFirstPageImageBanners ( ) . isEmpty ( ) && options . getImageBanners ( ) . isEmpty ( ) ) { return ; } JRDesignBand title = ( JRDesignBand ) getDesign ( ) . getTitle ( ) ; if ( title == null && ! options . getFirstPageImageBanners ( ) . isEmpty ( ) ) { title = new JRDesignBand ( ) ; getDesign ( ) . setTitle ( title ) ; } applyImageBannersToBand ( title , options . getFirstPageImageBanners ( ) . values ( ) , null , true ) ; JRDesignBand pageHeader = ( JRDesignBand ) getDesign ( ) . getPageHeader ( ) ; if ( pageHeader == null && ! options . getImageBanners ( ) . isEmpty ( ) ) { pageHeader = new JRDesignBand ( ) ; getDesign ( ) . setPageHeader ( pageHeader ) ; } JRDesignExpression printWhenExpression = null ; if ( ! options . getFirstPageImageBanners ( ) . isEmpty ( ) ) { printWhenExpression = new JRDesignExpression ( ) ; printWhenExpression . setValueClass ( Boolean . class ) ; printWhenExpression . setText ( EXPRESSION_TRUE_WHEN_NOT_FIRST_PAGE ) ; } applyImageBannersToBand ( pageHeader , options . getImageBanners ( ) . values ( ) , printWhenExpression , true ) ; } | Create the image elements for the banners tha goes into the title and header bands depending on the case |
22,537 | protected void generateTitleBand ( ) { log . debug ( "Generating title band..." ) ; JRDesignBand band = ( JRDesignBand ) getDesign ( ) . getPageHeader ( ) ; int yOffset = 0 ; if ( getReport ( ) . getTitle ( ) == null ) return ; if ( band != null && ! getDesign ( ) . isTitleNewPage ( ) ) { yOffset = band . getHeight ( ) ; } else { band = ( JRDesignBand ) getDesign ( ) . getTitle ( ) ; if ( band == null ) { band = new JRDesignBand ( ) ; getDesign ( ) . setTitle ( band ) ; } } JRDesignExpression printWhenExpression = new JRDesignExpression ( ) ; printWhenExpression . setValueClass ( Boolean . class ) ; printWhenExpression . setText ( EXPRESSION_TRUE_WHEN_FIRST_PAGE ) ; JRDesignTextField title = new JRDesignTextField ( ) ; JRDesignExpression exp = new JRDesignExpression ( ) ; if ( getReport ( ) . isTitleIsJrExpression ( ) ) { exp . setText ( getReport ( ) . getTitle ( ) ) ; } else { exp . setText ( "\"" + Utils . escapeTextForExpression ( getReport ( ) . getTitle ( ) ) + "\"" ) ; } exp . setValueClass ( String . class ) ; title . setExpression ( exp ) ; title . setWidth ( getReport ( ) . getOptions ( ) . getPrintableWidth ( ) ) ; title . setHeight ( getReport ( ) . getOptions ( ) . getTitleHeight ( ) ) ; title . setY ( yOffset ) ; title . setPrintWhenExpression ( printWhenExpression ) ; title . setRemoveLineWhenBlank ( true ) ; applyStyleToElement ( getReport ( ) . getTitleStyle ( ) , title ) ; title . setStretchType ( StretchTypeEnum . NO_STRETCH ) ; band . addElement ( title ) ; JRDesignTextField subtitle = new JRDesignTextField ( ) ; if ( getReport ( ) . getSubtitle ( ) != null ) { JRDesignExpression exp2 = new JRDesignExpression ( ) ; exp2 . setText ( "\"" + getReport ( ) . getSubtitle ( ) + "\"" ) ; exp2 . setValueClass ( String . class ) ; subtitle . setExpression ( exp2 ) ; subtitle . setWidth ( getReport ( ) . getOptions ( ) . getPrintableWidth ( ) ) ; subtitle . setHeight ( getReport ( ) . getOptions ( ) . getSubtitleHeight ( ) ) ; subtitle . setY ( title . getY ( ) + title . getHeight ( ) ) ; subtitle . setPrintWhenExpression ( printWhenExpression ) ; subtitle . setRemoveLineWhenBlank ( true ) ; applyStyleToElement ( getReport ( ) . getSubtitleStyle ( ) , subtitle ) ; title . setStretchType ( StretchTypeEnum . NO_STRETCH ) ; band . addElement ( subtitle ) ; } } | Adds title and subtitle to the TitleBand when it applies . If title is not present then subtitle will be ignored |
22,538 | protected void layoutGroupFooterLabels ( DJGroup djgroup , JRDesignGroup jgroup , int x , int y , int width , int height ) { DJGroupLabel label = djgroup . getFooterLabel ( ) ; JRDesignBand band = LayoutUtils . getBandFromSection ( ( JRDesignSection ) jgroup . getGroupFooterSection ( ) ) ; JRDesignExpression labelExp ; if ( label . isJasperExpression ( ) ) labelExp = ExpressionUtils . createStringExpression ( label . getText ( ) ) ; else if ( label . getLabelExpression ( ) != null ) { labelExp = ExpressionUtils . createExpression ( jgroup . getName ( ) + "_labelExpression" , label . getLabelExpression ( ) , true ) ; } else labelExp = ExpressionUtils . createStringExpression ( "\"" + label . getText ( ) + "\"" ) ; JRDesignTextField labelTf = new JRDesignTextField ( ) ; labelTf . setExpression ( labelExp ) ; labelTf . setWidth ( width ) ; labelTf . setHeight ( height ) ; labelTf . setX ( x ) ; labelTf . setY ( y ) ; labelTf . setPositionType ( PositionTypeEnum . FIX_RELATIVE_TO_TOP ) ; applyStyleToElement ( label . getStyle ( ) , labelTf ) ; band . addElement ( labelTf ) ; } | Creates needed textfields for general label in footer groups . |
22,539 | private int findYOffsetForGroupLabel ( JRDesignBand band ) { int offset = 0 ; for ( JRChild jrChild : band . getChildren ( ) ) { JRDesignElement elem = ( JRDesignElement ) jrChild ; if ( elem . getKey ( ) != null && elem . getKey ( ) . startsWith ( "variable_for_column_" ) ) { offset = elem . getY ( ) ; break ; } } return offset ; } | Used to ensure that the general footer label will be at the same Y position as the variables in the band . |
22,540 | protected void layoutGroupSubreports ( DJGroup columnsGroup , JRDesignGroup jgroup ) { log . debug ( "Starting subreport layout..." ) ; JRDesignBand footerBand = ( JRDesignBand ) ( ( JRDesignSection ) jgroup . getGroupFooterSection ( ) ) . getBandsList ( ) . get ( 0 ) ; JRDesignBand headerBand = ( JRDesignBand ) ( ( JRDesignSection ) jgroup . getGroupHeaderSection ( ) ) . getBandsList ( ) . get ( 0 ) ; layOutSubReportInBand ( columnsGroup , headerBand , DJConstants . HEADER ) ; layOutSubReportInBand ( columnsGroup , footerBand , DJConstants . FOOTER ) ; } | If there is a SubReport on a Group we do the layout here |
22,541 | protected void sendPageBreakToBottom ( JRDesignBand band ) { JRElement [ ] elems = band . getElements ( ) ; JRElement aux = null ; for ( JRElement elem : elems ) { if ( ( "" + elem . getKey ( ) ) . startsWith ( PAGE_BREAK_FOR_ ) ) { aux = elem ; break ; } } if ( aux != null ) ( ( JRDesignElement ) aux ) . setY ( band . getHeight ( ) ) ; } | page breaks should be near the bottom of the band this method used while adding subreports which has the start on new page option . |
22,542 | public DJCrosstab build ( ) { if ( crosstab . getMeasures ( ) . isEmpty ( ) ) { throw new LayoutException ( "Crosstabs must have at least one measure" ) ; } if ( crosstab . getColumns ( ) . isEmpty ( ) ) { throw new LayoutException ( "Crosstabs must have at least one column" ) ; } if ( crosstab . getRows ( ) . isEmpty ( ) ) { throw new LayoutException ( "Crosstabs must have at least one row" ) ; } for ( DJCrosstabColumn col : crosstab . getColumns ( ) ) { if ( col . getWidth ( ) == - 1 && cellWidth != - 1 ) col . setWidth ( cellWidth ) ; if ( col . getWidth ( ) == - 1 ) col . setWidth ( DEFAULT_CELL_WIDTH ) ; if ( col . getHeaderHeight ( ) == - 1 && columnHeaderHeight != - 1 ) col . setHeaderHeight ( columnHeaderHeight ) ; if ( col . getHeaderHeight ( ) == - 1 ) col . setHeaderHeight ( DEFAULT_COLUMN_HEADER_HEIGHT ) ; } for ( DJCrosstabRow row : crosstab . getRows ( ) ) { if ( row . getHeight ( ) == - 1 && cellHeight != - 1 ) row . setHeight ( cellHeight ) ; if ( row . getHeight ( ) == - 1 ) row . setHeight ( DEFAULT_CELL_HEIGHT ) ; if ( row . getHeaderWidth ( ) == - 1 && rowHeaderWidth != - 1 ) row . setHeaderWidth ( rowHeaderWidth ) ; if ( row . getHeaderWidth ( ) == - 1 ) row . setHeaderWidth ( DEFAULT_ROW_HEADER_WIDTH ) ; } return crosstab ; } | Build the crosstab . Throws LayoutException if anything is wrong |
22,543 | public CrosstabBuilder useMainReportDatasource ( boolean preSorted ) { DJDataSource datasource = new DJDataSource ( "ds" , DJConstants . DATA_SOURCE_ORIGIN_REPORT_DATASOURCE , DJConstants . DATA_SOURCE_TYPE_JRDATASOURCE ) ; datasource . setPreSorted ( preSorted ) ; crosstab . setDatasource ( datasource ) ; return this ; } | To use main report datasource . There should be nothing else in the detail band |
22,544 | public CrosstabBuilder addInvisibleMeasure ( String property , String className , String title ) { DJCrosstabMeasure measure = new DJCrosstabMeasure ( property , className , DJCalculation . NOTHING , title ) ; measure . setVisible ( false ) ; crosstab . getMeasures ( ) . add ( measure ) ; return this ; } | Adds a measure to the crosstab . A crosstab can have many measures . DJ will lay out one measure above the other . |
22,545 | public CrosstabBuilder setRowStyles ( Style headerStyle , Style totalStyle , Style totalHeaderStyle ) { crosstab . setRowHeaderStyle ( headerStyle ) ; crosstab . setRowTotalheaderStyle ( totalHeaderStyle ) ; crosstab . setRowTotalStyle ( totalStyle ) ; return this ; } | Should be called after all rows have been created |
22,546 | public CrosstabBuilder setColumnStyles ( Style headerStyle , Style totalStyle , Style totalHeaderStyle ) { crosstab . setColumnHeaderStyle ( headerStyle ) ; crosstab . setColumnTotalheaderStyle ( totalHeaderStyle ) ; crosstab . setColumnTotalStyle ( totalStyle ) ; return this ; } | Should be called after all columns have been created |
22,547 | public FastReportBuilder addBarcodeColumn ( String title , String property , String className , int barcodeType , boolean showText , int width , boolean fixedWidth , ImageScaleMode imageScaleMode , Style style ) throws ColumnBuilderException , ClassNotFoundException { AbstractColumn column = ColumnBuilder . getNew ( ) . setColumnProperty ( property , className ) . setWidth ( width ) . setTitle ( title ) . setFixedWidth ( fixedWidth ) . setColumnType ( ColumnBuilder . COLUMN_TYPE_BARCODE ) . setStyle ( style ) . setBarcodeType ( barcodeType ) . setShowText ( showText ) . build ( ) ; if ( style == null ) guessStyle ( className , column ) ; addColumn ( column ) ; return this ; } | By default uses InputStream as the type of the image |
22,548 | public FastReportBuilder addGroups ( int numgroups ) { groupCount = numgroups ; for ( int i = 0 ; i < groupCount ; i ++ ) { GroupBuilder gb = new GroupBuilder ( ) ; PropertyColumn col = ( PropertyColumn ) report . getColumns ( ) . get ( i ) ; gb . setCriteriaColumn ( col ) ; report . getColumnsGroups ( ) . add ( gb . build ( ) ) ; } return this ; } | This method should be called after all column have been added to the report . |
22,549 | protected Object transformEntity ( Entity entity ) { PropertyColumn propertyColumn = ( PropertyColumn ) entity ; JRDesignField field = new JRDesignField ( ) ; ColumnProperty columnProperty = propertyColumn . getColumnProperty ( ) ; field . setName ( columnProperty . getProperty ( ) ) ; field . setValueClassName ( columnProperty . getValueClassName ( ) ) ; log . debug ( "Transforming column: " + propertyColumn . getName ( ) + ", property: " + columnProperty . getProperty ( ) + " (" + columnProperty . getValueClassName ( ) + ") " ) ; field . setDescription ( propertyColumn . getFieldDescription ( ) ) ; for ( String key : columnProperty . getFieldProperties ( ) . keySet ( ) ) { field . getPropertiesMap ( ) . setProperty ( key , columnProperty . getFieldProperties ( ) . get ( key ) ) ; } return field ; } | Receives a PropertyColumn and returns a JRDesignField |
22,550 | public String getTextForExpression ( DJGroup group , DJGroup childGroup , String type ) { return "new Double( $V{" + getReportName ( ) + "_" + getGroupVariableName ( childGroup ) + "}.doubleValue() / $V{" + getReportName ( ) + "_" + getGroupVariableName ( type , group . getColumnToGroupBy ( ) . getColumnProperty ( ) . getProperty ( ) ) + "}.doubleValue())" ; } | Returns the formula for the percentage |
22,551 | public ReportWriter getReportWriter ( final JasperPrint _jasperPrint , final String _format , final Map < JRExporterParameter , Object > _parameters ) { final JRExporter exporter = FormatInfoRegistry . getInstance ( ) . getExporter ( _format ) ; exporter . setParameters ( _parameters ) ; if ( _jasperPrint . getPages ( ) . size ( ) > PAGES_THRESHHOLD ) { return new FileReportWriter ( _jasperPrint , exporter ) ; } else { return new MemoryReportWriter ( _jasperPrint , exporter ) ; } } | Returns a ReportWriter that which will use memory or a file depending on the parameter PAGES_THRESHOLD |
22,552 | public static HorizontalBandAlignment buildAligment ( byte aligment ) { if ( aligment == RIGHT . getAlignment ( ) ) return RIGHT ; else if ( aligment == LEFT . getAlignment ( ) ) return LEFT ; else if ( aligment == CENTER . getAlignment ( ) ) return CENTER ; return LEFT ; } | To be used with AutoText class constants ALIGMENT_LEFT ALIGMENT_CENTER and ALIGMENT_RIGHT |
22,553 | protected Map getParametersMap ( ActionInvocation _invocation ) { Map map = ( Map ) _invocation . getStack ( ) . findValue ( this . parameters ) ; if ( map == null ) map = new HashMap ( ) ; return map ; } | Returns the object pointed by the result - type parameter parameters |
22,554 | protected LayoutManager getLayOutManagerObj ( ActionInvocation _invocation ) { if ( layoutManager == null || "" . equals ( layoutManager ) ) { LOG . warn ( "No valid LayoutManager, using ClassicLayoutManager" ) ; return new ClassicLayoutManager ( ) ; } Object los = conditionalParse ( layoutManager , _invocation ) ; if ( los instanceof LayoutManager ) { return ( LayoutManager ) los ; } LayoutManager lo = null ; if ( los instanceof String ) { if ( LAYOUT_CLASSIC . equalsIgnoreCase ( ( String ) los ) ) lo = new ClassicLayoutManager ( ) ; else if ( LAYOUT_LIST . equalsIgnoreCase ( ( String ) los ) ) lo = new ListLayoutManager ( ) ; else { try { lo = ( LayoutManager ) Class . forName ( ( String ) los ) . newInstance ( ) ; } catch ( Exception e ) { LOG . warn ( "No valid LayoutManager: " + e . getMessage ( ) , e ) ; } } } return lo ; } | Returns the export format indicated in the result - type parameter layoutManager |
22,555 | protected AbstractColumn buildSimpleBarcodeColumn ( ) { BarCodeColumn column = new BarCodeColumn ( ) ; populateCommonAttributes ( column ) ; column . setColumnProperty ( columnProperty ) ; column . setExpressionToGroupBy ( customExpressionToGroupBy ) ; column . setScaleMode ( imageScaleMode ) ; column . setApplicationIdentifier ( applicationIdentifier ) ; column . setBarcodeType ( barcodeType ) ; column . setShowText ( showText ) ; column . setCheckSum ( checkSum ) ; return column ; } | When creating barcode columns |
22,556 | protected AbstractColumn buildSimpleImageColumn ( ) { ImageColumn column = new ImageColumn ( ) ; populateCommonAttributes ( column ) ; populateExpressionAttributes ( column ) ; column . setExpression ( customExpression ) ; column . setExpressionToGroupBy ( customExpressionToGroupBy ) ; column . setExpressionForCalculation ( customExpressionForCalculation ) ; column . setScaleMode ( imageScaleMode ) ; return column ; } | When creating image columns |
22,557 | protected AbstractColumn buildExpressionColumn ( ) { ExpressionColumn column = new ExpressionColumn ( ) ; populateCommonAttributes ( column ) ; populateExpressionAttributes ( column ) ; column . setExpression ( customExpression ) ; column . setExpressionToGroupBy ( customExpressionToGroupBy ) ; column . setExpressionForCalculation ( customExpressionForCalculation ) ; return column ; } | For creating expression columns |
22,558 | protected AbstractColumn buildSimpleColumn ( ) { SimpleColumn column = new SimpleColumn ( ) ; populateCommonAttributes ( column ) ; columnProperty . getFieldProperties ( ) . putAll ( fieldProperties ) ; column . setColumnProperty ( columnProperty ) ; column . setExpressionToGroupBy ( customExpressionToGroupBy ) ; column . setFieldDescription ( fieldDescription ) ; return column ; } | For creating regular columns |
22,559 | public ColumnBuilder addFieldProperty ( String propertyName , String value ) { fieldProperties . put ( propertyName , value ) ; return this ; } | When the JRField needs properties use this method . |
22,560 | public static void copyProperties ( Object dest , Object orig ) { try { if ( orig != null && dest != null ) { BeanUtils . copyProperties ( dest , orig ) ; PropertyUtils putils = new PropertyUtils ( ) ; PropertyDescriptor origDescriptors [ ] = putils . getPropertyDescriptors ( orig ) ; for ( PropertyDescriptor origDescriptor : origDescriptors ) { String name = origDescriptor . getName ( ) ; if ( "class" . equals ( name ) ) { continue ; } Class propertyType = origDescriptor . getPropertyType ( ) ; if ( ! Boolean . class . equals ( propertyType ) && ! ( Boolean . class . equals ( propertyType ) ) ) continue ; if ( ! putils . isReadable ( orig , name ) ) { Method m = orig . getClass ( ) . getMethod ( "is" + name . substring ( 0 , 1 ) . toUpperCase ( ) + name . substring ( 1 ) , ( Class < ? > [ ] ) null ) ; Object value = m . invoke ( orig , ( Object [ ] ) null ) ; if ( putils . isWriteable ( dest , name ) ) { BeanUtilsBean . getInstance ( ) . copyProperty ( dest , name , value ) ; } } } } } catch ( Exception e ) { throw new DJException ( "Could not copy properties for shared object: " + orig + ", message: " + e . getMessage ( ) , e ) ; } } | This takes into account objects that breaks the JavaBean convention and have as getter for Boolean objects an isXXX method . |
22,561 | private void printSuggestion ( String arg , List < ConfigOption > co ) { List < ConfigOption > sortedList = new ArrayList < ConfigOption > ( co ) ; Collections . sort ( sortedList , new ConfigOptionLevenshteinDistance ( arg ) ) ; System . err . println ( "Parse error for argument \"" + arg + "\", did you mean " + sortedList . get ( 0 ) . getCommandLineOption ( ) . showFlagInfo ( ) + "? Ignoring for now." ) ; } | Prints a suggestion to stderr for the argument based on the levenshtein distance metric |
22,562 | public static ReportGenerator . Format getFormat ( String ... args ) { ConfigOptionParser configParser = new ConfigOptionParser ( ) ; List < ConfigOption > configOptions = Arrays . asList ( format , help ) ; for ( ConfigOption co : configOptions ) { if ( co . hasDefault ( ) ) { configParser . parsedOptions . put ( co . getLongName ( ) , co . getValue ( ) ) ; } } for ( String arg : args ) { configParser . commandLineLookup ( arg , format , configOptions ) ; } if ( ! configParser . hasValue ( format ) ) { configParser . printUsageAndExit ( configOptions ) ; } return ( ReportGenerator . Format ) configParser . getValue ( format ) ; } | Terminates with a help message if the parse is not successful |
22,563 | static List < List < String > > handleNewLines ( List < List < String > > tableModel ) { List < List < String > > result = Lists . newArrayListWithExpectedSize ( tableModel . size ( ) ) ; for ( List < String > row : tableModel ) { if ( hasNewline ( row ) ) { result . addAll ( splitRow ( row ) ) ; } else { result . add ( row ) ; } } return result ; } | Handles newlines by removing them and add new rows instead |
22,564 | public static AbstractReportGenerator generateHtml5Report ( ) { AbstractReportGenerator report ; try { Class < ? > aClass = new ReportGenerator ( ) . getClass ( ) . getClassLoader ( ) . loadClass ( "com.tngtech.jgiven.report.html5.Html5ReportGenerator" ) ; report = ( AbstractReportGenerator ) aClass . newInstance ( ) ; } catch ( ClassNotFoundException e ) { throw new JGivenInstallationException ( "The JGiven HTML5 Report Generator seems not to be on the classpath.\n" + "Ensure that you have a dependency to jgiven-html5-report." ) ; } catch ( Exception e ) { throw new JGivenInternalDefectException ( "The HTML5 Report Generator could not be instantiated." , e ) ; } return report ; } | Searches the Html5ReportGenerator in Java path and instantiates the report |
22,565 | private static void flushCurrentWord ( StringBuilder currentWords , List < Word > formattedWords , boolean cutWhitespace ) { if ( currentWords . length ( ) > 0 ) { if ( cutWhitespace && currentWords . charAt ( currentWords . length ( ) - 1 ) == ' ' ) { currentWords . setLength ( currentWords . length ( ) - 1 ) ; } formattedWords . add ( new Word ( currentWords . toString ( ) ) ) ; currentWords . setLength ( 0 ) ; } } | Appends the accumulated words to the resulting words . Trailing whitespace is removed because of the postprocessing that inserts custom whitespace |
22,566 | private static int nextIndex ( String description , int defaultIndex ) { Pattern startsWithNumber = Pattern . compile ( "(\\d+).*" ) ; Matcher matcher = startsWithNumber . matcher ( description ) ; if ( matcher . matches ( ) ) { return Integer . parseInt ( matcher . group ( 1 ) ) - 1 ; } return defaultIndex ; } | Returns the next index of the argument by decrementing 1 from the possibly parsed number |
22,567 | public static String capitalize ( String text ) { if ( text == null || text . isEmpty ( ) ) { return text ; } return text . substring ( 0 , 1 ) . toUpperCase ( ) . concat ( text . substring ( 1 , text . length ( ) ) ) ; } | Returns the given text with the first letter in upper case . |
22,568 | private void deleteUnusedCaseSteps ( ReportModel model ) { for ( ScenarioModel scenarioModel : model . getScenarios ( ) ) { if ( scenarioModel . isCasesAsTable ( ) && ! hasAttachment ( scenarioModel ) ) { List < ScenarioCaseModel > cases = scenarioModel . getScenarioCases ( ) ; for ( int i = 1 ; i < cases . size ( ) ; i ++ ) { ScenarioCaseModel caseModel = cases . get ( i ) ; caseModel . setSteps ( Collections . < StepModel > emptyList ( ) ) ; } } } } | Deletes all steps of scenario cases where a data table is generated to reduce the size of the data file . In this case only the steps of the first scenario case are actually needed . |
22,569 | boolean attachmentsAreStructurallyDifferent ( List < AttachmentModel > firstAttachments , List < AttachmentModel > otherAttachments ) { if ( firstAttachments . size ( ) != otherAttachments . size ( ) ) { return true ; } for ( int i = 0 ; i < firstAttachments . size ( ) ; i ++ ) { if ( attachmentIsStructurallyDifferent ( firstAttachments . get ( i ) , otherAttachments . get ( i ) ) ) { return true ; } } return false ; } | Attachments are only structurally different if one step has an inline attachment and the other step either has no inline attachment or the inline attachment is different . |
22,570 | List < List < Word > > getDifferentArguments ( List < List < Word > > argumentWords ) { List < List < Word > > result = Lists . newArrayList ( ) ; for ( int i = 0 ; i < argumentWords . size ( ) ; i ++ ) { result . add ( Lists . < Word > newArrayList ( ) ) ; } int nWords = argumentWords . get ( 0 ) . size ( ) ; for ( int iWord = 0 ; iWord < nWords ; iWord ++ ) { Word wordOfFirstCase = argumentWords . get ( 0 ) . get ( iWord ) ; if ( wordOfFirstCase . isDataTable ( ) ) { continue ; } boolean different = false ; for ( int iCase = 1 ; iCase < argumentWords . size ( ) ; iCase ++ ) { Word wordOfCase = argumentWords . get ( iCase ) . get ( iWord ) ; if ( ! wordOfCase . getFormattedValue ( ) . equals ( wordOfFirstCase . getFormattedValue ( ) ) ) { different = true ; break ; } } if ( different ) { for ( int iCase = 0 ; iCase < argumentWords . size ( ) ; iCase ++ ) { result . get ( iCase ) . add ( argumentWords . get ( iCase ) . get ( iWord ) ) ; } } } return result ; } | Returns a list with argument words that are not equal in all cases |
22,571 | public final TagConfiguration . Builder configureTag ( Class < ? extends Annotation > tagAnnotation ) { TagConfiguration configuration = new TagConfiguration ( tagAnnotation ) ; tagConfigurations . put ( tagAnnotation , configuration ) ; return new TagConfiguration . Builder ( configuration ) ; } | Configures the given annotation as a tag . |
22,572 | private StepFormatter . Formatting < ? , ? > getFormatting ( Annotation [ ] annotations , Set < Class < ? > > visitedTypes , Annotation originalAnnotation , String parameterName ) { List < StepFormatter . Formatting < ? , ? > > foundFormatting = Lists . newArrayList ( ) ; Table tableAnnotation = null ; for ( Annotation annotation : annotations ) { try { if ( annotation instanceof Format ) { Format arg = ( Format ) annotation ; foundFormatting . add ( new StepFormatter . ArgumentFormatting ( ReflectionUtil . newInstance ( arg . value ( ) ) , arg . args ( ) ) ) ; } else if ( annotation instanceof Table ) { tableAnnotation = ( Table ) annotation ; } else if ( annotation instanceof AnnotationFormat ) { AnnotationFormat arg = ( AnnotationFormat ) annotation ; foundFormatting . add ( new StepFormatter . ArgumentFormatting ( new StepFormatter . AnnotationBasedFormatter ( arg . value ( ) . newInstance ( ) , originalAnnotation ) ) ) ; } else { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; if ( ! visitedTypes . contains ( annotationType ) ) { visitedTypes . add ( annotationType ) ; StepFormatter . Formatting < ? , ? > formatting = getFormatting ( annotationType . getAnnotations ( ) , visitedTypes , annotation , parameterName ) ; if ( formatting != null ) { foundFormatting . add ( formatting ) ; } } } } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } } if ( foundFormatting . size ( ) > 1 ) { Formatting < ? , ? > innerFormatting = Iterables . getLast ( foundFormatting ) ; foundFormatting . remove ( innerFormatting ) ; ChainedFormatting < ? > chainedFormatting = new StepFormatter . ChainedFormatting < Object > ( ( ObjectFormatter < Object > ) innerFormatting ) ; for ( StepFormatter . Formatting < ? , ? > formatting : Lists . reverse ( foundFormatting ) ) { chainedFormatting . addFormatting ( ( StepFormatter . Formatting < ? , String > ) formatting ) ; } foundFormatting . clear ( ) ; foundFormatting . add ( chainedFormatting ) ; } if ( tableAnnotation != null ) { ObjectFormatter < ? > objectFormatter = foundFormatting . isEmpty ( ) ? DefaultFormatter . INSTANCE : foundFormatting . get ( 0 ) ; return getTableFormatting ( annotations , parameterName , tableAnnotation , objectFormatter ) ; } if ( foundFormatting . isEmpty ( ) ) { return null ; } return foundFormatting . get ( 0 ) ; } | Recursively searches for formatting annotations . |
22,573 | public static < GIVEN , WHEN , THEN > Scenario < GIVEN , WHEN , THEN > create ( Class < GIVEN > givenClass , Class < WHEN > whenClass , Class < THEN > thenClass ) { return new Scenario < GIVEN , WHEN , THEN > ( givenClass , whenClass , thenClass ) ; } | Creates a scenario with 3 different steps classes . |
22,574 | public Scenario < GIVEN , WHEN , THEN > startScenario ( String description ) { super . startScenario ( description ) ; return this ; } | Describes the scenario . Must be called before any step invocation . |
22,575 | public void wireSteps ( CanWire canWire ) { for ( StageState steps : stages . values ( ) ) { canWire . wire ( steps . instance ) ; } } | Used for DI frameworks to inject values into stages . |
22,576 | public void finished ( ) throws Throwable { if ( state == FINISHED ) { return ; } State previousState = state ; state = FINISHED ; methodInterceptor . enableMethodInterception ( false ) ; try { if ( previousState == STARTED ) { callFinishLifeCycleMethods ( ) ; } } finally { listener . scenarioFinished ( ) ; } } | Has to be called when the scenario is finished in order to execute after methods . |
22,577 | public void startScenario ( Class < ? > testClass , Method method , List < NamedArgument > arguments ) { listener . scenarioStarted ( testClass , method , arguments ) ; if ( method . isAnnotationPresent ( Pending . class ) ) { Pending annotation = method . getAnnotation ( Pending . class ) ; if ( annotation . failIfPass ( ) ) { failIfPass ( ) ; } else if ( ! annotation . executeSteps ( ) ) { methodInterceptor . disableMethodExecution ( ) ; executeLifeCycleMethods = false ; } suppressExceptions = true ; } else if ( method . isAnnotationPresent ( NotImplementedYet . class ) ) { NotImplementedYet annotation = method . getAnnotation ( NotImplementedYet . class ) ; if ( annotation . failIfPass ( ) ) { failIfPass ( ) ; } else if ( ! annotation . executeSteps ( ) ) { methodInterceptor . disableMethodExecution ( ) ; executeLifeCycleMethods = false ; } suppressExceptions = true ; } } | Starts the scenario with the given method and arguments . Derives the description from the method name . |
22,578 | public ConfigOptionBuilder setCommandLineOptionWithArgument ( CommandLineOption commandLineOption , StringConverter converter ) { co . setCommandLineOption ( commandLineOption ) ; return setStringConverter ( converter ) ; } | if you want to parse an argument you need a converter from String to Object |
22,579 | public ConfigOptionBuilder setCommandLineOptionWithoutArgument ( CommandLineOption commandLineOption , Object value ) { co . setCommandLineOption ( commandLineOption ) ; co . setValue ( value ) ; return this ; } | if you don t have an argument choose the value that is going to be inserted into the map instead |
22,580 | public ConfigOptionBuilder setDefaultWith ( Object defaultValue ) { co . setHasDefault ( true ) ; co . setValue ( defaultValue ) ; return setOptional ( ) ; } | if you have a default it s automatically optional |
22,581 | public ConfigOptionBuilder setStringConverter ( StringConverter converter ) { co . setConverter ( converter ) ; co . setHasArgument ( true ) ; return this ; } | if you want to convert some string to an object you have an argument to parse |
22,582 | static List < NamedArgument > getNamedArgs ( ExtensionContext context ) { List < NamedArgument > namedArgs = new ArrayList < > ( ) ; if ( context . getTestMethod ( ) . get ( ) . getParameterCount ( ) > 0 ) { try { if ( context . getClass ( ) . getCanonicalName ( ) . equals ( METHOD_EXTENSION_CONTEXT ) ) { Field field = context . getClass ( ) . getSuperclass ( ) . getDeclaredField ( "testDescriptor" ) ; Object testDescriptor = ReflectionUtil . getFieldValueOrNull ( field , context , ERROR ) ; if ( testDescriptor != null && testDescriptor . getClass ( ) . getCanonicalName ( ) . equals ( TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR ) ) { Object invocationContext = ReflectionUtil . getFieldValueOrNull ( "invocationContext" , testDescriptor , ERROR ) ; if ( invocationContext != null && invocationContext . getClass ( ) . getCanonicalName ( ) . equals ( PARAMETERIZED_TEST_INVOCATION_CONTEXT ) ) { Object arguments = ReflectionUtil . getFieldValueOrNull ( "arguments" , invocationContext , ERROR ) ; List < Object > args = Arrays . asList ( ( Object [ ] ) arguments ) ; namedArgs = ParameterNameUtil . mapArgumentsWithParameterNames ( context . getTestMethod ( ) . get ( ) , args ) ; } } } } catch ( Exception e ) { log . warn ( ERROR , e ) ; } } return namedArgs ; } | This is a very ugly workaround to get the method arguments from the JUnit 5 context via reflection . |
22,583 | public static Attachment fromBinaryBytes ( byte [ ] bytes , MediaType mediaType ) { if ( ! mediaType . isBinary ( ) ) { throw new IllegalArgumentException ( "MediaType must be binary" ) ; } return new Attachment ( BaseEncoding . base64 ( ) . encode ( bytes ) , mediaType , null ) ; } | Creates an attachment from a given array of bytes . The bytes will be Base64 encoded . |
22,584 | public static Attachment fromBinaryInputStream ( InputStream inputStream , MediaType mediaType ) throws IOException { return fromBinaryBytes ( ByteStreams . toByteArray ( inputStream ) , mediaType ) ; } | Creates an attachment from a binary input stream . The content of the stream will be transformed into a Base64 encoded string |
22,585 | public static MediaType binary ( MediaType . Type type , String subType ) { return new MediaType ( type , subType , true ) ; } | Creates a binary media type with the given type and subtype |
22,586 | public static MediaType nonBinary ( MediaType . Type type , String subType , Charset charSet ) { ApiUtil . notNull ( charSet , "charset must not be null" ) ; return new MediaType ( type , subType , charSet ) ; } | Creates a non - binary media type with the given type subtype and charSet |
22,587 | public static MediaType nonBinaryUtf8 ( MediaType . Type type , String subType ) { return new MediaType ( type , subType , UTF_8 ) ; } | Creates a non - binary media type with the given type subtype and UTF - 8 encoding |
22,588 | public static MediaType text ( String subType , Charset charset ) { return nonBinary ( TEXT , subType , charset ) ; } | Creates a non - binary text media type with the given subtype and a specified encoding |
22,589 | public void parseVersion ( String version ) { DefaultVersioning artifactVersion = new DefaultVersioning ( version ) ; getLog ( ) . debug ( "Parsed Version" ) ; getLog ( ) . debug ( " major: " + artifactVersion . getMajor ( ) ) ; getLog ( ) . debug ( " minor: " + artifactVersion . getMinor ( ) ) ; getLog ( ) . debug ( " incremental: " + artifactVersion . getPatch ( ) ) ; getLog ( ) . debug ( " buildnumber: " + artifactVersion . getBuildNumber ( ) ) ; getLog ( ) . debug ( " qualifier: " + artifactVersion . getQualifier ( ) ) ; defineVersionProperty ( "majorVersion" , artifactVersion . getMajor ( ) ) ; defineVersionProperty ( "minorVersion" , artifactVersion . getMinor ( ) ) ; defineVersionProperty ( "incrementalVersion" , artifactVersion . getPatch ( ) ) ; defineVersionProperty ( "buildNumber" , artifactVersion . getBuildNumber ( ) ) ; defineVersionProperty ( "nextMajorVersion" , artifactVersion . getMajor ( ) + 1 ) ; defineVersionProperty ( "nextMinorVersion" , artifactVersion . getMinor ( ) + 1 ) ; defineVersionProperty ( "nextIncrementalVersion" , artifactVersion . getPatch ( ) + 1 ) ; defineVersionProperty ( "nextBuildNumber" , artifactVersion . getBuildNumber ( ) + 1 ) ; defineFormattedVersionProperty ( "majorVersion" , String . format ( formatMajor , artifactVersion . getMajor ( ) ) ) ; defineFormattedVersionProperty ( "minorVersion" , String . format ( formatMinor , artifactVersion . getMinor ( ) ) ) ; defineFormattedVersionProperty ( "incrementalVersion" , String . format ( formatIncremental , artifactVersion . getPatch ( ) ) ) ; defineFormattedVersionProperty ( "buildNumber" , String . format ( formatBuildNumber , artifactVersion . getBuildNumber ( ) ) ) ; defineFormattedVersionProperty ( "nextMajorVersion" , String . format ( formatMajor , artifactVersion . getMajor ( ) + 1 ) ) ; defineFormattedVersionProperty ( "nextMinorVersion" , String . format ( formatMinor , artifactVersion . getMinor ( ) + 1 ) ) ; defineFormattedVersionProperty ( "nextIncrementalVersion" , String . format ( formatIncremental , artifactVersion . getPatch ( ) + 1 ) ) ; defineFormattedVersionProperty ( "nextBuildNumber" , String . format ( formatBuildNumber , artifactVersion . getBuildNumber ( ) + 1 ) ) ; String osgi = artifactVersion . getAsOSGiVersion ( ) ; String qualifier = artifactVersion . getQualifier ( ) ; String qualifierQuestion = "" ; if ( qualifier == null ) { qualifier = "" ; } else { qualifierQuestion = qualifierPrefix ; } defineVersionProperty ( "qualifier" , qualifier ) ; defineVersionProperty ( "qualifier?" , qualifierQuestion + qualifier ) ; defineVersionProperty ( "osgiVersion" , osgi ) ; } | Parse a version String and add the components to a properties object . |
22,590 | private int findAvailablePortNumber ( Integer portNumberStartingPoint , List < Integer > reservedPorts ) { assert portNumberStartingPoint != null ; int candidate = portNumberStartingPoint ; while ( reservedPorts . contains ( candidate ) ) { candidate ++ ; } return candidate ; } | Returns the first number available starting at portNumberStartingPoint that s not already in the reservedPorts list . |
22,591 | public void populateFromAttributes ( final Template template , final Map < String , Attribute > attributes , final PObject requestJsonAttributes ) { if ( requestJsonAttributes . has ( JSON_REQUEST_HEADERS ) && requestJsonAttributes . getObject ( JSON_REQUEST_HEADERS ) . has ( JSON_REQUEST_HEADERS ) && ! attributes . containsKey ( JSON_REQUEST_HEADERS ) ) { attributes . put ( JSON_REQUEST_HEADERS , new HttpRequestHeadersAttribute ( ) ) ; } for ( Map . Entry < String , Attribute > attribute : attributes . entrySet ( ) ) { try { put ( attribute . getKey ( ) , attribute . getValue ( ) . getValue ( template , attribute . getKey ( ) , requestJsonAttributes ) ) ; } catch ( ObjectMissingException | IllegalArgumentException e ) { throw e ; } catch ( Throwable e ) { String templateName = "unknown" ; for ( Map . Entry < String , Template > entry : template . getConfiguration ( ) . getTemplates ( ) . entrySet ( ) ) { if ( entry . getValue ( ) == template ) { templateName = entry . getKey ( ) ; break ; } } String defaults = "" ; if ( attribute instanceof ReflectiveAttribute < ? > ) { ReflectiveAttribute < ? > reflectiveAttribute = ( ReflectiveAttribute < ? > ) attribute ; defaults = "\n\n The attribute defaults are: " + reflectiveAttribute . getDefaultValue ( ) ; } String errorMsg = "An error occurred when creating a value from the '" + attribute . getKey ( ) + "' attribute for the '" + templateName + "' template.\n\nThe JSON is: \n" + requestJsonAttributes + defaults + "\n" + e . toString ( ) ; throw new AttributeParsingException ( errorMsg , e ) ; } } if ( template . getConfiguration ( ) . isThrowErrorOnExtraParameters ( ) ) { final List < String > extraProperties = new ArrayList < > ( ) ; for ( Iterator < String > it = requestJsonAttributes . keys ( ) ; it . hasNext ( ) ; ) { final String attributeName = it . next ( ) ; if ( ! attributes . containsKey ( attributeName ) ) { extraProperties . add ( attributeName ) ; } } if ( ! extraProperties . isEmpty ( ) ) { throw new ExtraPropertyException ( "Extra properties found in the request attributes" , extraProperties , attributes . keySet ( ) ) ; } } } | Process the requestJsonAttributes using the attributes and the MapfishParser and add all resulting values to this values object . |
22,592 | public void addRequiredValues ( final Values sourceValues ) { Object taskDirectory = sourceValues . getObject ( TASK_DIRECTORY_KEY , Object . class ) ; MfClientHttpRequestFactoryProvider requestFactoryProvider = sourceValues . getObject ( CLIENT_HTTP_REQUEST_FACTORY_KEY , MfClientHttpRequestFactoryProvider . class ) ; Template template = sourceValues . getObject ( TEMPLATE_KEY , Template . class ) ; PDFConfig pdfConfig = sourceValues . getObject ( PDF_CONFIG_KEY , PDFConfig . class ) ; String subReportDir = sourceValues . getString ( SUBREPORT_DIR_KEY ) ; this . values . put ( TASK_DIRECTORY_KEY , taskDirectory ) ; this . values . put ( CLIENT_HTTP_REQUEST_FACTORY_KEY , requestFactoryProvider ) ; this . values . put ( TEMPLATE_KEY , template ) ; this . values . put ( PDF_CONFIG_KEY , pdfConfig ) ; this . values . put ( SUBREPORT_DIR_KEY , subReportDir ) ; this . values . put ( VALUES_KEY , this ) ; this . values . put ( JOB_ID_KEY , sourceValues . getString ( JOB_ID_KEY ) ) ; this . values . put ( LOCALE_KEY , sourceValues . getObject ( LOCALE_KEY , Locale . class ) ) ; } | Add the elements that all values objects require from the provided values object . |
22,593 | public void put ( final String key , final Object value ) { if ( TASK_DIRECTORY_KEY . equals ( key ) && this . values . keySet ( ) . contains ( TASK_DIRECTORY_KEY ) ) { throw new IllegalArgumentException ( "Invalid key: " + key ) ; } if ( value == null ) { throw new IllegalArgumentException ( "A null value was attempted to be put into the values object under key: " + key ) ; } this . values . put ( key , value ) ; } | Put a new value in map . |
22,594 | public < V > V getObject ( final String key , final Class < V > type ) { final Object obj = this . values . get ( key ) ; return type . cast ( obj ) ; } | Get a value as a string . |
22,595 | public Boolean getBoolean ( final String key ) { return ( Boolean ) this . values . get ( key ) ; } | Get a boolean value from the values or null . |
22,596 | @ SuppressWarnings ( "unchecked" ) public < T > Map < String , T > find ( final Class < T > valueTypeToFind ) { return ( Map < String , T > ) this . values . entrySet ( ) . stream ( ) . filter ( input -> valueTypeToFind . isInstance ( input . getValue ( ) ) ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; } | Find all the values of the requested type . |
22,597 | public ConfigurableRequest createRequest ( final URI uri , final HttpMethod httpMethod ) throws IOException { HttpRequestBase httpRequest = ( HttpRequestBase ) createHttpUriRequest ( httpMethod , uri ) ; return new Request ( getHttpClient ( ) , httpRequest , createHttpContext ( httpMethod , uri ) ) ; } | allow extension only for testing |
22,598 | public final PJsonObject toJSON ( ) { try { JSONObject json = new JSONObject ( ) ; for ( String key : this . obj . keySet ( ) ) { Object opt = opt ( key ) ; if ( opt instanceof PYamlObject ) { opt = ( ( PYamlObject ) opt ) . toJSON ( ) . getInternalObj ( ) ; } else if ( opt instanceof PYamlArray ) { opt = ( ( PYamlArray ) opt ) . toJSON ( ) . getInternalArray ( ) ; } json . put ( key , opt ) ; } return new PJsonObject ( json , this . getContextName ( ) ) ; } catch ( Throwable e ) { throw ExceptionUtils . getRuntimeException ( e ) ; } } | Convert this object to a json object . |
22,599 | public static MatchInfo fromUri ( final URI uri , final HttpMethod method ) { int newPort = uri . getPort ( ) ; if ( newPort < 0 ) { try { newPort = uri . toURL ( ) . getDefaultPort ( ) ; } catch ( MalformedURLException | IllegalArgumentException e ) { newPort = ANY_PORT ; } } return new MatchInfo ( uri . getScheme ( ) , uri . getHost ( ) , newPort , uri . getPath ( ) , uri . getQuery ( ) , uri . getFragment ( ) , ANY_REALM , method ) ; } | Create an info object from a uri and the http method object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.