_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2800
|
DynamicReport.getAllFields
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2801
|
ColumnsGroupVariablesRegistrationManager.registerValueFormatter
|
train
|
protected void registerValueFormatter(DJGroupVariable djVariable, String variableName) {
if ( djVariable.getValueFormatter() == null){
return;
}
JRDesignParameter dparam = new JRDesignParameter();
dparam.setName(variableName + "_vf"); //value formater suffix
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());
}
|
java
|
{
"resource": ""
}
|
q2802
|
AbstractLayoutManager.setWhenNoDataBand
|
train
|
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");
}
|
java
|
{
"resource": ""
}
|
q2803
|
AbstractLayoutManager.ensureDJStyles
|
train
|
protected void ensureDJStyles() {
//first of all, register all parent styles if any
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);
}
}
|
java
|
{
"resource": ""
}
|
q2804
|
AbstractLayoutManager.setColumnsFinalWidth
|
train
|
protected void setColumnsFinalWidth() {
log.debug("Setting columns final width.");
float factor;
int printableArea = report.getOptions().getColumnWidth();
//Create a list with only the visible columns.
List visibleColums = getVisibleColumns();
if (report.getOptions().isUseFullPageWidth()) {
int columnsWidth = 0;
int notRezisableWidth = 0;
//Store in a variable the total with of all visible columns
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;
//Select the non-resizable columns
Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {
public boolean evaluate(Object arg0) {
return !((AbstractColumn) arg0).isFixedWidth();
}
});
//Finally, set the new width to the resizable columns
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);
}
}
}
// If the columns width changed, the X position must be setted again.
int posx = 0;
for (Object visibleColum : visibleColums) {
AbstractColumn col = (AbstractColumn) visibleColum;
col.setPosX(posx);
posx += col.getWidth();
}
}
|
java
|
{
"resource": ""
}
|
q2805
|
AbstractLayoutManager.setBandsFinalHeight
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q2806
|
AbstractLayoutManager.setBandFinalHeight
|
train
|
private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {
if (band != null) {
int finalHeight = LayoutUtils.findVerticalOffset(band);
//noinspection StatementWithEmptyBody
if (finalHeight < currHeigth && !fitToContent) {
//nothing
} else {
band.setHeight(finalHeight);
}
}
}
|
java
|
{
"resource": ""
}
|
q2807
|
AbstractLayoutManager.getParent
|
train
|
protected JRDesignGroup getParent(JRDesignGroup group) {
int index = realGroups.indexOf(group);
return (index > 0) ? (JRDesignGroup) realGroups.get(index - 1) : group;
}
|
java
|
{
"resource": ""
}
|
q2808
|
LayoutUtils.findVerticalOffset
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2809
|
LayoutUtils.moveBandsElemnts
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q2810
|
LayoutUtils.getJRDesignGroup
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2811
|
ClassicLayoutManager.applyBanners
|
train
|
protected void applyBanners() {
DynamicReportOptions options = getReport().getOptions();
if (options.getFirstPageImageBanners().isEmpty() && options.getImageBanners().isEmpty()){
return;
}
/*
First create image banners for the first page only
*/
JRDesignBand title = (JRDesignBand) getDesign().getTitle();
//if there is no title band, but there are banner images for the first page, we create a title band
if (title == null && !options.getFirstPageImageBanners().isEmpty()){
title = new JRDesignBand();
getDesign().setTitle(title);
}
applyImageBannersToBand(title, options.getFirstPageImageBanners().values(), null, true);
/*
Now create image banner for the rest of the pages
*/
JRDesignBand pageHeader = (JRDesignBand) getDesign().getPageHeader();
//if there is no title band, but there are banner images for the first page, we create a title band
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);
}
|
java
|
{
"resource": ""
}
|
q2812
|
ClassicLayoutManager.generateTitleBand
|
train
|
protected void generateTitleBand() {
log.debug("Generating title band...");
JRDesignBand band = (JRDesignBand) getDesign().getPageHeader();
int yOffset = 0;
//If title is not present then subtitle will be ignored
if (getReport().getTitle() == null)
return;
if (band != null && !getDesign().isTitleNewPage()){
//Title and subtitle comes afer the page header
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);
}
}
|
java
|
{
"resource": ""
}
|
q2813
|
ClassicLayoutManager.layoutGroupFooterLabels
|
train
|
protected void layoutGroupFooterLabels(DJGroup djgroup, JRDesignGroup jgroup, int x, int y, int width, int height) {
//List footerVariables = djgroup.getFooterVariables();
DJGroupLabel label = djgroup.getFooterLabel();
//if (label == null || footerVariables.isEmpty())
//return;
//PropertyColumn col = djgroup.getColumnToGroupBy();
JRDesignBand band = LayoutUtils.getBandFromSection((JRDesignSection) jgroup.getGroupFooterSection());
// log.debug("Adding footer group label for group " + djgroup);
/*DJGroupVariable lmvar = findLeftMostColumn(footerVariables);
AbstractColumn lmColumn = lmvar.getColumnToApplyOperation();
int width = lmColumn.getPosX().intValue() - col.getPosX().intValue();
int yOffset = findYOffsetForGroupLabel(band);*/
JRDesignExpression labelExp;
if (label.isJasperExpression()) //a text with things like "$F{myField}"
labelExp = ExpressionUtils.createStringExpression(label.getText());
else if (label.getLabelExpression() != null){
labelExp = ExpressionUtils.createExpression(jgroup.getName() + "_labelExpression", label.getLabelExpression(), true);
} else //a simple text
//labelExp = ExpressionUtils.createStringExpression("\""+ Utils.escapeTextForExpression(label.getText())+ "\"");
labelExp = ExpressionUtils.createStringExpression("\""+ label.getText() + "\"");
JRDesignTextField labelTf = new JRDesignTextField();
labelTf.setExpression(labelExp);
labelTf.setWidth(width);
labelTf.setHeight(height);
labelTf.setX(x);
labelTf.setY(y);
//int yOffsetGlabel = labelTf.getHeight();
labelTf.setPositionType( PositionTypeEnum.FIX_RELATIVE_TO_TOP );
applyStyleToElement(label.getStyle(), labelTf);
band.addElement(labelTf);
}
|
java
|
{
"resource": ""
}
|
q2814
|
ClassicLayoutManager.findYOffsetForGroupLabel
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2815
|
ClassicLayoutManager.layoutGroupSubreports
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q2816
|
ClassicLayoutManager.sendPageBreakToBottom
|
train
|
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());
}
|
java
|
{
"resource": ""
}
|
q2817
|
CrosstabBuilder.build
|
train
|
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");
}
//Ensure default dimension values
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;
}
|
java
|
{
"resource": ""
}
|
q2818
|
CrosstabBuilder.useMainReportDatasource
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2819
|
CrosstabBuilder.addInvisibleMeasure
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2820
|
CrosstabBuilder.setRowStyles
|
train
|
public CrosstabBuilder setRowStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {
crosstab.setRowHeaderStyle(headerStyle);
crosstab.setRowTotalheaderStyle(totalHeaderStyle);
crosstab.setRowTotalStyle(totalStyle);
return this;
}
|
java
|
{
"resource": ""
}
|
q2821
|
CrosstabBuilder.setColumnStyles
|
train
|
public CrosstabBuilder setColumnStyles(Style headerStyle, Style totalStyle, Style totalHeaderStyle) {
crosstab.setColumnHeaderStyle(headerStyle);
crosstab.setColumnTotalheaderStyle(totalHeaderStyle);
crosstab.setColumnTotalStyle(totalStyle);
return this;
}
|
java
|
{
"resource": ""
}
|
q2822
|
FastReportBuilder.addBarcodeColumn
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2823
|
FastReportBuilder.addGroups
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2824
|
ColumnRegistrationManager.transformEntity
|
train
|
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()); //hack for XML data source
for (String key : columnProperty.getFieldProperties().keySet()) {
field.getPropertiesMap().setProperty(key, columnProperty.getFieldProperties().get(key));
}
return field;
}
|
java
|
{
"resource": ""
}
|
q2825
|
PercentageColumn.getTextForExpression
|
train
|
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())";
}
|
java
|
{
"resource": ""
}
|
q2826
|
ReportWriterFactory.getReportWriter
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q2827
|
HorizontalBandAlignment.buildAligment
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2828
|
DJResult.getParametersMap
|
train
|
protected Map getParametersMap(ActionInvocation _invocation) {
Map map = (Map) _invocation.getStack().findValue(this.parameters);
if (map == null)
map = new HashMap();
return map;
}
|
java
|
{
"resource": ""
}
|
q2829
|
DJResult.getLayOutManagerObj
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2830
|
ColumnBuilder.buildSimpleBarcodeColumn
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2831
|
ColumnBuilder.buildSimpleImageColumn
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2832
|
ColumnBuilder.buildExpressionColumn
|
train
|
protected AbstractColumn buildExpressionColumn() {
ExpressionColumn column = new ExpressionColumn();
populateCommonAttributes(column);
populateExpressionAttributes(column);
column.setExpression(customExpression);
column.setExpressionToGroupBy(customExpressionToGroupBy);
column.setExpressionForCalculation(customExpressionForCalculation);
return column;
}
|
java
|
{
"resource": ""
}
|
q2833
|
ColumnBuilder.buildSimpleColumn
|
train
|
protected AbstractColumn buildSimpleColumn() {
SimpleColumn column = new SimpleColumn();
populateCommonAttributes(column);
columnProperty.getFieldProperties().putAll(fieldProperties);
column.setColumnProperty(columnProperty);
column.setExpressionToGroupBy(customExpressionToGroupBy);
column.setFieldDescription(fieldDescription);
return column;
}
|
java
|
{
"resource": ""
}
|
q2834
|
ColumnBuilder.addFieldProperty
|
train
|
public ColumnBuilder addFieldProperty(String propertyName, String value) {
fieldProperties.put(propertyName, value);
return this;
}
|
java
|
{
"resource": ""
}
|
q2835
|
Utils.copyProperties
|
train
|
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; // No point in trying to set an object's class
}
Class propertyType = origDescriptor.getPropertyType();
if (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))
continue;
if (!putils.isReadable(orig, name)) { //because of bad convention
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);
}
}
|
java
|
{
"resource": ""
}
|
q2836
|
ConfigOptionParser.printSuggestion
|
train
|
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." );
}
|
java
|
{
"resource": ""
}
|
q2837
|
ConfigOptionParser.getFormat
|
train
|
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 );
}
// TODO properties
// TODO environment
if( !configParser.hasValue( format ) ) {
configParser.printUsageAndExit( configOptions );
}
return (ReportGenerator.Format) configParser.getValue( format );
}
|
java
|
{
"resource": ""
}
|
q2838
|
PlainTextTableWriter.handleNewLines
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2839
|
ReportGenerator.generateHtml5Report
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2840
|
StepFormatter.flushCurrentWord
|
train
|
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 );
}
}
|
java
|
{
"resource": ""
}
|
q2841
|
StepFormatter.nextIndex
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2842
|
WordUtil.capitalize
|
train
|
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() ) );
}
|
java
|
{
"resource": ""
}
|
q2843
|
Html5ReportGenerator.deleteUnusedCaseSteps
|
train
|
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() );
}
}
}
}
|
java
|
{
"resource": ""
}
|
q2844
|
CaseArgumentAnalyser.attachmentsAreStructurallyDifferent
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2845
|
CaseArgumentAnalyser.getDifferentArguments
|
train
|
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 );
// data tables have equal here, otherwise
// the cases would be structurally different
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;
}
|
java
|
{
"resource": ""
}
|
q2846
|
AbstractJGivenConfiguration.configureTag
|
train
|
public final TagConfiguration.Builder configureTag( Class<? extends Annotation> tagAnnotation ) {
TagConfiguration configuration = new TagConfiguration( tagAnnotation );
tagConfigurations.put( tagAnnotation, configuration );
return new TagConfiguration.Builder( configuration );
}
|
java
|
{
"resource": ""
}
|
q2847
|
ParameterFormattingUtil.getFormatting
|
train
|
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 );
}
|
java
|
{
"resource": ""
}
|
q2848
|
Scenario.create
|
train
|
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 );
}
|
java
|
{
"resource": ""
}
|
q2849
|
Scenario.startScenario
|
train
|
@Override
public Scenario<GIVEN, WHEN, THEN> startScenario( String description ) {
super.startScenario( description );
return this;
}
|
java
|
{
"resource": ""
}
|
q2850
|
ScenarioExecutor.wireSteps
|
train
|
public void wireSteps( CanWire canWire ) {
for( StageState steps : stages.values() ) {
canWire.wire( steps.instance );
}
}
|
java
|
{
"resource": ""
}
|
q2851
|
ScenarioExecutor.finished
|
train
|
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();
}
}
|
java
|
{
"resource": ""
}
|
q2852
|
ScenarioExecutor.startScenario
|
train
|
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;
}
}
|
java
|
{
"resource": ""
}
|
q2853
|
ConfigOptionBuilder.setCommandLineOptionWithArgument
|
train
|
public ConfigOptionBuilder setCommandLineOptionWithArgument( CommandLineOption commandLineOption, StringConverter converter ) {
co.setCommandLineOption( commandLineOption );
return setStringConverter( converter );
}
|
java
|
{
"resource": ""
}
|
q2854
|
ConfigOptionBuilder.setCommandLineOptionWithoutArgument
|
train
|
public ConfigOptionBuilder setCommandLineOptionWithoutArgument( CommandLineOption commandLineOption, Object value ) {
co.setCommandLineOption( commandLineOption );
co.setValue( value );
return this;
}
|
java
|
{
"resource": ""
}
|
q2855
|
ConfigOptionBuilder.setDefaultWith
|
train
|
public ConfigOptionBuilder setDefaultWith( Object defaultValue ) {
co.setHasDefault( true );
co.setValue( defaultValue );
return setOptional();
}
|
java
|
{
"resource": ""
}
|
q2856
|
ConfigOptionBuilder.setStringConverter
|
train
|
public ConfigOptionBuilder setStringConverter( StringConverter converter ) {
co.setConverter( converter );
co.setHasArgument( true );
return this;
}
|
java
|
{
"resource": ""
}
|
q2857
|
ArgumentReflectionUtil.getNamedArgs
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q2858
|
Attachment.fromBinaryBytes
|
train
|
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 );
}
|
java
|
{
"resource": ""
}
|
q2859
|
Attachment.fromBinaryInputStream
|
train
|
public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException {
return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType );
}
|
java
|
{
"resource": ""
}
|
q2860
|
MediaType.binary
|
train
|
public static MediaType binary( MediaType.Type type, String subType ) {
return new MediaType( type, subType, true );
}
|
java
|
{
"resource": ""
}
|
q2861
|
MediaType.nonBinary
|
train
|
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 );
}
|
java
|
{
"resource": ""
}
|
q2862
|
MediaType.nonBinaryUtf8
|
train
|
public static MediaType nonBinaryUtf8( MediaType.Type type, String subType ) {
return new MediaType( type, subType, UTF_8 );
}
|
java
|
{
"resource": ""
}
|
q2863
|
MediaType.text
|
train
|
public static MediaType text( String subType, Charset charset ) {
return nonBinary( TEXT, subType, charset );
}
|
java
|
{
"resource": ""
}
|
q2864
|
ParseVersionMojo.parseVersion
|
train
|
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 );
}
|
java
|
{
"resource": ""
}
|
q2865
|
ReserveListenerPortMojo.findAvailablePortNumber
|
train
|
private int findAvailablePortNumber( Integer portNumberStartingPoint, List<Integer> reservedPorts )
{
assert portNumberStartingPoint != null;
int candidate = portNumberStartingPoint;
while ( reservedPorts.contains( candidate ) )
{
candidate++;
}
return candidate;
}
|
java
|
{
"resource": ""
}
|
q2866
|
Values.populateFromAttributes
|
train
|
public void populateFromAttributes(
@Nonnull final Template template,
@Nonnull final Map<String, Attribute> attributes,
@Nonnull 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());
}
}
}
|
java
|
{
"resource": ""
}
|
q2867
|
Values.addRequiredValues
|
train
|
public void addRequiredValues(@Nonnull 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));
}
|
java
|
{
"resource": ""
}
|
q2868
|
Values.put
|
train
|
public void put(final String key, final Object value) {
if (TASK_DIRECTORY_KEY.equals(key) && this.values.keySet().contains(TASK_DIRECTORY_KEY)) {
// ensure that no one overwrites the task directory
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);
}
|
java
|
{
"resource": ""
}
|
q2869
|
Values.getObject
|
train
|
public <V> V getObject(final String key, final Class<V> type) {
final Object obj = this.values.get(key);
return type.cast(obj);
}
|
java
|
{
"resource": ""
}
|
q2870
|
Values.getBoolean
|
train
|
@Nullable
public Boolean getBoolean(@Nonnull final String key) {
return (Boolean) this.values.get(key);
}
|
java
|
{
"resource": ""
}
|
q2871
|
Values.find
|
train
|
@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));
}
|
java
|
{
"resource": ""
}
|
q2872
|
MfClientHttpRequestFactoryImpl.createRequest
|
train
|
@Override
public ConfigurableRequest createRequest(
@Nonnull final URI uri,
@Nonnull final HttpMethod httpMethod) throws IOException {
HttpRequestBase httpRequest = (HttpRequestBase) createHttpUriRequest(httpMethod, uri);
return new Request(getHttpClient(), httpRequest, createHttpContext(httpMethod, uri));
}
|
java
|
{
"resource": ""
}
|
q2873
|
PYamlObject.toJSON
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q2874
|
MatchInfo.fromUri
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q2875
|
MatchInfo.fromAuthScope
|
train
|
@SuppressWarnings("StringEquality")
public static MatchInfo fromAuthScope(final AuthScope authscope) {
String newScheme = StringUtils.equals(authscope.getScheme(), AuthScope.ANY_SCHEME) ? ANY_SCHEME :
authscope.getScheme();
String newHost = StringUtils.equals(authscope.getHost(), AuthScope.ANY_HOST) ? ANY_HOST :
authscope.getHost();
int newPort = authscope.getPort() == AuthScope.ANY_PORT ? ANY_PORT : authscope.getPort();
String newRealm = StringUtils.equals(authscope.getRealm(), AuthScope.ANY_REALM) ? ANY_REALM :
authscope.getRealm();
return new MatchInfo(newScheme, newHost, newPort, ANY_PATH, ANY_QUERY,
ANY_FRAGMENT, newRealm, ANY_METHOD);
}
|
java
|
{
"resource": ""
}
|
q2876
|
JsonStyleParserHelper.createStyle
|
train
|
public Style createStyle(final List<Rule> styleRules) {
final Rule[] rulesArray = styleRules.toArray(new Rule[0]);
final FeatureTypeStyle featureTypeStyle = this.styleBuilder.createFeatureTypeStyle(null, rulesArray);
final Style style = this.styleBuilder.createStyle();
style.featureTypeStyles().add(featureTypeStyle);
return style;
}
|
java
|
{
"resource": ""
}
|
q2877
|
JsonStyleParserHelper.createLineSymbolizer
|
train
|
@VisibleForTesting
@Nullable
protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) {
final Stroke stroke = createStroke(styleJson, true);
if (stroke == null) {
return null;
} else {
return this.styleBuilder.createLineSymbolizer(stroke);
}
}
|
java
|
{
"resource": ""
}
|
q2878
|
JsonStyleParserHelper.createPolygonSymbolizer
|
train
|
@Nullable
@VisibleForTesting
protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) {
if (this.allowNullSymbolizer && !styleJson.has(JSON_FILL_COLOR)) {
return null;
}
final PolygonSymbolizer symbolizer = this.styleBuilder.createPolygonSymbolizer();
symbolizer.setFill(createFill(styleJson));
symbolizer.setStroke(createStroke(styleJson, false));
return symbolizer;
}
|
java
|
{
"resource": ""
}
|
q2879
|
JsonStyleParserHelper.createTextSymbolizer
|
train
|
@VisibleForTesting
protected TextSymbolizer createTextSymbolizer(final PJsonObject styleJson) {
final TextSymbolizer textSymbolizer = this.styleBuilder.createTextSymbolizer();
// make sure that labels are also rendered if a part of the text would be outside
// the view context, see http://docs.geoserver.org/stable/en/user/styling/sld-reference/labeling
// .html#partials
textSymbolizer.getOptions().put("partials", "true");
if (styleJson.has(JSON_LABEL)) {
final Expression label =
parseExpression(null, styleJson, JSON_LABEL,
(final String labelValue) -> labelValue.replace("${", "")
.replace("}", ""));
textSymbolizer.setLabel(label);
} else {
return null;
}
textSymbolizer.setFont(createFont(textSymbolizer.getFont(), styleJson));
if (styleJson.has(JSON_LABEL_ANCHOR_POINT_X) ||
styleJson.has(JSON_LABEL_ANCHOR_POINT_Y) ||
styleJson.has(JSON_LABEL_ALIGN) ||
styleJson.has(JSON_LABEL_X_OFFSET) ||
styleJson.has(JSON_LABEL_Y_OFFSET) ||
styleJson.has(JSON_LABEL_ROTATION) ||
styleJson.has(JSON_LABEL_PERPENDICULAR_OFFSET)) {
textSymbolizer.setLabelPlacement(createLabelPlacement(styleJson));
}
if (!StringUtils.isEmpty(styleJson.optString(JSON_HALO_RADIUS)) ||
!StringUtils.isEmpty(styleJson.optString(JSON_HALO_COLOR)) ||
!StringUtils.isEmpty(styleJson.optString(JSON_HALO_OPACITY)) ||
!StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_WIDTH)) ||
!StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_COLOR))) {
textSymbolizer.setHalo(createHalo(styleJson));
}
if (!StringUtils.isEmpty(styleJson.optString(JSON_FONT_COLOR)) ||
!StringUtils.isEmpty(styleJson.optString(JSON_FONT_OPACITY))) {
textSymbolizer.setFill(addFill(
styleJson.optString(JSON_FONT_COLOR, "black"),
styleJson.optString(JSON_FONT_OPACITY, "1.0")));
}
this.addVendorOptions(JSON_LABEL_ALLOW_OVERRUNS, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_AUTO_WRAP, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_CONFLICT_RESOLUTION, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_FOLLOW_LINE, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_GOODNESS_OF_FIT, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_GROUP, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_MAX_DISPLACEMENT, styleJson, textSymbolizer);
this.addVendorOptions(JSON_LABEL_SPACE_AROUND, styleJson, textSymbolizer);
return textSymbolizer;
}
|
java
|
{
"resource": ""
}
|
q2880
|
Handler.configureProtocolHandler
|
train
|
public static void configureProtocolHandler() {
final String pkgs = System.getProperty("java.protocol.handler.pkgs");
String newValue = "org.mapfish.print.url";
if (pkgs != null && !pkgs.contains(newValue)) {
newValue = newValue + "|" + pkgs;
} else if (pkgs != null) {
newValue = pkgs;
}
System.setProperty("java.protocol.handler.pkgs", newValue);
}
|
java
|
{
"resource": ""
}
|
q2881
|
AbstractFeatureSourceLayerPlugin.createStyleFunction
|
train
|
protected final StyleSupplier<FeatureSource> createStyleFunction(
final Template template,
final String styleString) {
return new StyleSupplier<FeatureSource>() {
@Override
public Style load(
final MfClientHttpRequestFactory requestFactory,
final FeatureSource featureSource) {
if (featureSource == null) {
throw new IllegalArgumentException("Feature source cannot be null");
}
final String geomType = featureSource.getSchema() == null ?
Geometry.class.getSimpleName().toLowerCase() :
featureSource.getSchema().getGeometryDescriptor().getType().getBinding()
.getSimpleName();
final String styleRef = styleString != null ? styleString : geomType;
final StyleParser styleParser = AbstractFeatureSourceLayerPlugin.this.parser;
return OptionalUtils.or(
() -> template.getStyle(styleRef),
() -> styleParser.loadStyle(template.getConfiguration(), requestFactory, styleRef))
.orElseGet(() -> template.getConfiguration().getDefaultStyle(geomType));
}
};
}
|
java
|
{
"resource": ""
}
|
q2882
|
WmsUtilities.makeWmsGetLayerRequest
|
train
|
public static URI makeWmsGetLayerRequest(
final WmsLayerParam wmsLayerParam,
final URI commonURI,
final Dimension imageSize,
final double dpi,
final double angle,
final ReferencedEnvelope bounds) throws FactoryException, URISyntaxException, IOException {
if (commonURI == null || commonURI.getAuthority() == null) {
throw new RuntimeException("Invalid WMS URI: " + commonURI);
}
String[] authority = commonURI.getAuthority().split(":");
URL url;
if (authority.length == 2) {
url = new URL(
commonURI.getScheme(),
authority[0],
Integer.parseInt(authority[1]),
commonURI.getPath()
);
} else {
url = new URL(
commonURI.getScheme(),
authority[0],
commonURI.getPath()
);
}
final GetMapRequest getMapRequest = WmsVersion.lookup(wmsLayerParam.version).
getGetMapRequest(url);
getMapRequest.setBBox(bounds);
getMapRequest.setDimensions(imageSize.width, imageSize.height);
getMapRequest.setFormat(wmsLayerParam.imageFormat);
getMapRequest.setSRS(CRS.lookupIdentifier(bounds.getCoordinateReferenceSystem(), false));
for (int i = wmsLayerParam.layers.length - 1; i > -1; i--) {
String layer = wmsLayerParam.layers[i];
String style = "";
if (wmsLayerParam.styles != null) {
style = wmsLayerParam.styles[i];
}
getMapRequest.addLayer(layer, style);
}
final URI getMapUri = getMapRequest.getFinalURL().toURI();
Multimap<String, String> extraParams = HashMultimap.create();
if (commonURI.getQuery() != null) {
for (NameValuePair pair: URLEncodedUtils.parse(commonURI, Charset.forName("UTF-8"))) {
extraParams.put(pair.getName(), pair.getValue());
}
}
extraParams.putAll(wmsLayerParam.getMergeableParams());
extraParams.putAll(wmsLayerParam.getCustomParams());
if (wmsLayerParam.serverType != null) {
addDpiParam(extraParams, (int) Math.round(dpi), wmsLayerParam.serverType);
if (wmsLayerParam.useNativeAngle && angle != 0.0) {
addAngleParam(extraParams, angle, wmsLayerParam.serverType);
}
}
return URIUtils.addParams(getMapUri, extraParams, Collections.emptySet());
}
|
java
|
{
"resource": ""
}
|
q2883
|
WmsUtilities.isDpiSet
|
train
|
private static boolean isDpiSet(final Multimap<String, String> extraParams) {
String searchKey = "FORMAT_OPTIONS";
for (String key: extraParams.keys()) {
if (key.equalsIgnoreCase(searchKey)) {
for (String value: extraParams.get(key)) {
if (value.toLowerCase().contains("dpi:")) {
return true;
}
}
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q2884
|
WmsUtilities.setDpiValue
|
train
|
private static void setDpiValue(final Multimap<String, String> extraParams, final int dpi) {
String searchKey = "FORMAT_OPTIONS";
for (String key: extraParams.keys()) {
if (key.equalsIgnoreCase(searchKey)) {
Collection<String> values = extraParams.removeAll(key);
List<String> newValues = new ArrayList<>();
for (String value: values) {
if (!StringUtils.isEmpty(value)) {
value += ";dpi:" + Integer.toString(dpi);
newValues.add(value);
}
}
extraParams.putAll(key, newValues);
return;
}
}
}
|
java
|
{
"resource": ""
}
|
q2885
|
GridUtils.calculateBounds
|
train
|
public static Polygon calculateBounds(final MapfishMapContext context) {
double rotation = context.getRootContext().getRotation();
ReferencedEnvelope env = context.getRootContext().toReferencedEnvelope();
Coordinate centre = env.centre();
AffineTransform rotateInstance = AffineTransform.getRotateInstance(rotation, centre.x, centre.y);
double[] dstPts = new double[8];
double[] srcPts = {
env.getMinX(), env.getMinY(), env.getMinX(), env.getMaxY(),
env.getMaxX(), env.getMaxY(), env.getMaxX(), env.getMinY()
};
rotateInstance.transform(srcPts, 0, dstPts, 0, 4);
return new GeometryFactory().createPolygon(new Coordinate[]{
new Coordinate(dstPts[0], dstPts[1]), new Coordinate(dstPts[2], dstPts[3]),
new Coordinate(dstPts[4], dstPts[5]), new Coordinate(dstPts[6], dstPts[7]),
new Coordinate(dstPts[0], dstPts[1])
});
}
|
java
|
{
"resource": ""
}
|
q2886
|
GridUtils.createGridFeatureType
|
train
|
public static SimpleFeatureType createGridFeatureType(
@Nonnull final MapfishMapContext mapContext,
@Nonnull final Class<? extends Geometry> geomClass) {
final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
CoordinateReferenceSystem projection = mapContext.getBounds().getProjection();
typeBuilder.add(Constants.Style.Grid.ATT_GEOM, geomClass, projection);
typeBuilder.setName(Constants.Style.Grid.NAME_LINES);
return typeBuilder.buildFeatureType();
}
|
java
|
{
"resource": ""
}
|
q2887
|
GridUtils.createLabel
|
train
|
public static String createLabel(final double value, final String unit, final GridLabelFormat format) {
final double zero = 0.000000001;
if (format != null) {
return format.format(value, unit);
} else {
if (Math.abs(value - Math.round(value)) < zero) {
return String.format("%d %s", Math.round(value), unit);
} else if ("m".equals(unit)) {
// meter: no decimals
return String.format("%1.0f %s", value, unit);
} else if (NonSI.DEGREE_ANGLE.toString().equals(unit)) {
// degree: by default 6 decimals
return String.format("%1.6f %s", value, unit);
} else {
return String.format("%f %s", value, unit);
}
}
}
|
java
|
{
"resource": ""
}
|
q2888
|
MapfishParser.parsePrimitive
|
train
|
public static Object parsePrimitive(
final String fieldName, final PrimitiveAttribute<?> pAtt, final PObject requestData) {
Class<?> valueClass = pAtt.getValueClass();
Object value;
try {
value = parseValue(false, new String[0], valueClass, fieldName, requestData);
} catch (UnsupportedTypeException e) {
String type = e.type.getName();
if (e.type.isArray()) {
type = e.type.getComponentType().getName() + "[]";
}
throw new RuntimeException(
"The type '" + type + "' is not a supported type when parsing json. " +
"See documentation for supported types.\n\nUnsupported type found in attribute " +
fieldName
+ "\n\nTo support more types add the type to " +
"parseValue and parseArrayValue in this class and add a test to the test class",
e);
}
pAtt.validateValue(value);
return value;
}
|
java
|
{
"resource": ""
}
|
q2889
|
CustomEPSGCodes.getDefinitionsURL
|
train
|
@Override
protected URL getDefinitionsURL() {
try {
URL url = CustomEPSGCodes.class.getResource(CUSTOM_EPSG_CODES_FILE);
// quickly test url
try (InputStream stream = url.openStream()) {
//noinspection ResultOfMethodCallIgnored
stream.read();
}
return url;
} catch (Throwable e) {
throw new AssertionError("Unable to load /epsg.properties file from root of classpath.");
}
}
|
java
|
{
"resource": ""
}
|
q2890
|
ExecutionStats.addMapStats
|
train
|
public synchronized void addMapStats(
final MapfishMapContext mapContext, final MapAttribute.MapAttributeValues mapValues) {
this.mapStats.add(new MapStats(mapContext, mapValues));
}
|
java
|
{
"resource": ""
}
|
q2891
|
ExecutionStats.addEmailStats
|
train
|
public void addEmailStats(final InternetAddress[] recipients, final boolean storageUsed) {
this.storageUsed = storageUsed;
for (InternetAddress recipient: recipients) {
emailDests.add(recipient.getAddress());
}
}
|
java
|
{
"resource": ""
}
|
q2892
|
GridParam.calculateLabelUnit
|
train
|
public String calculateLabelUnit(final CoordinateReferenceSystem mapCrs) {
String unit;
if (this.labelProjection != null) {
unit = this.labelCRS.getCoordinateSystem().getAxis(0).getUnit().toString();
} else {
unit = mapCrs.getCoordinateSystem().getAxis(0).getUnit().toString();
}
return unit;
}
|
java
|
{
"resource": ""
}
|
q2893
|
GridParam.calculateLabelTransform
|
train
|
public MathTransform calculateLabelTransform(final CoordinateReferenceSystem mapCrs) {
MathTransform labelTransform;
if (this.labelProjection != null) {
try {
labelTransform = CRS.findMathTransform(mapCrs, this.labelCRS, true);
} catch (FactoryException e) {
throw new RuntimeException(e);
}
} else {
labelTransform = IdentityTransform.create(2);
}
return labelTransform;
}
|
java
|
{
"resource": ""
}
|
q2894
|
GridLabelFormat.fromConfig
|
train
|
public static GridLabelFormat fromConfig(final GridParam param) {
if (param.labelFormat != null) {
return new GridLabelFormat.Simple(param.labelFormat);
} else if (param.valueFormat != null) {
return new GridLabelFormat.Detailed(
param.valueFormat, param.unitFormat,
param.formatDecimalSeparator, param.formatGroupingSeparator);
}
return null;
}
|
java
|
{
"resource": ""
}
|
q2895
|
HttpCredential.toCredentials
|
train
|
@Nullable
public final Credentials toCredentials(final AuthScope authscope) {
try {
if (!matches(MatchInfo.fromAuthScope(authscope))) {
return null;
}
} catch (UnknownHostException | MalformedURLException | SocketException e) {
throw new RuntimeException(e);
}
if (this.username == null) {
return null;
}
final String passwordString;
if (this.password != null) {
passwordString = new String(this.password);
} else {
passwordString = null;
}
return new UsernamePasswordCredentials(this.username, passwordString);
}
|
java
|
{
"resource": ""
}
|
q2896
|
PJsonArray.getJSONObject
|
train
|
public final PJsonObject getJSONObject(final int i) {
JSONObject val = this.array.optJSONObject(i);
final String context = "[" + i + "]";
if (val == null) {
throw new ObjectMissingException(this, context);
}
return new PJsonObject(this, val, context);
}
|
java
|
{
"resource": ""
}
|
q2897
|
PJsonArray.getJSONArray
|
train
|
public final PJsonArray getJSONArray(final int i) {
JSONArray val = this.array.optJSONArray(i);
final String context = "[" + i + "]";
if (val == null) {
throw new ObjectMissingException(this, context);
}
return new PJsonArray(this, val, context);
}
|
java
|
{
"resource": ""
}
|
q2898
|
PJsonArray.getInt
|
train
|
@Override
public final int getInt(final int i) {
int val = this.array.optInt(i, Integer.MIN_VALUE);
if (val == Integer.MIN_VALUE) {
throw new ObjectMissingException(this, "[" + i + "]");
}
return val;
}
|
java
|
{
"resource": ""
}
|
q2899
|
PJsonArray.getFloat
|
train
|
@Override
public final float getFloat(final int i) {
double val = this.array.optDouble(i, Double.MAX_VALUE);
if (val == Double.MAX_VALUE) {
throw new ObjectMissingException(this, "[" + i + "]");
}
return (float) val;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.