src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
PieChartAndGoogleOMeterLegendParameter extends AbstractParameter { void addLegend(final String legend) { this.legends.add(legend); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final PieChartAndGoogleOMeterLegendParameter p = new PieChartAndGoogleOMeterLegendParameter(); p.addLegend("foo"); p.addLegend("bar"); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chl=foo|bar"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
AxisTypesParameter extends AbstractParameter { void addAxisTypes(final AxisTypes axisTypes) { axisTypesList.add(axisTypes); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final AxisTypesParameter p = new AxisTypesParameter(); p.addAxisTypes(AxisTypes.BOTTOM_X_AXIS); p.addAxisTypes(AxisTypes.TOP_X_AXIS); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxt=x,t"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
AxisLabelPositionsParameter extends AbstractParameter { void addLabelPosition(final int index, final ImmutableList<? extends Number> positions) { labelPositions.add(new AxisLabelPositions(index, positions)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final AxisLabelPositionsParameter p = new AxisLabelPositionsParameter(); p.addLabelPosition(1, Lists.of(1, 2, 3)); p.addLabelPosition(2, Lists.of(7, 8, 9)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxp=1,1,2,3|2,7,8,9"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test2() { AxisLabelPositionsParameter p = new AxisLabelPositionsParameter(); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); p.addLabelPosition(2, Lists.of(1, 2, 3)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxp=2,1,2,3"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ColorsParameter extends AbstractParameter { void addColors(final ImmutableList<? extends ImmutableList<? extends Color>> colors) { for (ImmutableList<? extends Color> listOfColors : colors) { final List<Color> l = Lists.newLinkedList(); l.addAll(listOfColors); this.colors.add(l); } } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final ColorsParameter p = new ColorsParameter(); List<ImmutableList<Color>> colors = Lists.newLinkedList(); colors.add(Lists.of(BLUE)); p.addColors(Lists.copyOf(colors)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chco=0000FF"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test1() { final ColorsParameter p = new ColorsParameter(); List<ImmutableList<Color>> colors = Lists.newLinkedList(); colors.add(Lists.of(BLUE)); colors.add(Lists.of(RED)); p.addColors(Lists.copyOf(colors)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chco=0000FF,FF0000"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
AxisStylesParameter extends AbstractParameter { void addAxisStyle(final int index, final AxisStyle axisStyle) { axisStyles.add(new PrivateAxisStyles(index, axisStyle)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final AxisStylesParameter p = new AxisStylesParameter(); p.addAxisStyle(1, AxisStyle.newAxisStyle(BLUE, 12, AxisTextAlignment.CENTER)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxs=1,0000FF,12,0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test1() { final AxisStylesParameter p = new AxisStylesParameter(); p.addAxisStyle(1, AxisStyle.newAxisStyle(BLUE, 12, AxisTextAlignment.CENTER)); p.addAxisStyle(2, AxisStyle.newAxisStyle(RED, 12, AxisTextAlignment.CENTER)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxs=1,0000FF,12,0|2,FF0000,12,0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test4() { final AxisStylesParameter p = new AxisStylesParameter(); final AxisStyle axisStyle = AxisStyle.newAxisStyle(BLUE, 12, AxisTextAlignment.CENTER); p.addAxisStyle(1, axisStyle); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxs=1,0000FF,12,0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test5() { final AxisStylesParameter p = new AxisStylesParameter(); final AxisStyle axisStyle = AxisStyle.newAxisStyle(BLUE, 12, AxisTextAlignment.CENTER); axisStyle.setDrawTickMarks(true); axisStyle.setTickMarkColor(RED); p.addAxisStyle(1, axisStyle); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxs=1,0000FF,12,0,lt,FF0000"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test6() { final AxisStylesParameter p = new AxisStylesParameter(); final AxisStyle axisStyle = AxisStyle.newAxisStyle(BLUE, 12, AxisTextAlignment.CENTER); axisStyle.setDrawTickMarks(false); p.addAxisStyle(1, axisStyle); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxs=1,0000FF,12,0,l"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartFillsParameter extends AbstractParameter { void addLinearGradientFill(final FillType fillType, final int angle, final ImmutableList<? extends ColorAndOffset> colorAndOffsets) { fills.add(new LinearGradient(fillType, angle, colorAndOffsets)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final ChartFillsParameter p = new ChartFillsParameter(); p.addLinearGradientFill(FillType.CHART_AREA, 45, Lists.of(new ColorAndOffset(RED, 50))); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chf=c,lg,45,FF0000,0.5"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartFillsParameter extends AbstractParameter { void addLinearStripeFill(final FillType fillType, final int angle, final ImmutableList<? extends ColorAndWidth> colorAndWidths) { fills.add(new LinearStripes(fillType, angle, colorAndWidths)); } @Override String getKey(); @Override String getValue(); }
@Test public void test1() { final ChartFillsParameter p = new ChartFillsParameter(); p.addLinearStripeFill(FillType.BACKGROUND, 20, Lists.of(new ColorAndWidth(RED, 50))); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chf=bg,ls,20,FF0000,0.5"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartFillsParameter extends AbstractParameter { void addSolidFill(final SolidFillType solidFillType, final Color color) { fills.add(new Solid(solidFillType, color)); } @Override String getKey(); @Override String getValue(); }
@Test public void test2() { final ChartFillsParameter p = new ChartFillsParameter(); p.addSolidFill(SolidFillType.TRANSPARENCY, BLUE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chf=a,s,0000FF"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
AxisRangesParameter extends AbstractParameter { void addAxisRange(final int index, final double startOfRange, final double endOfRange, final double interval) { axisRanges.add(new AxisRange(index, startOfRange, endOfRange, interval)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final AxisRangesParameter p = new AxisRangesParameter(); p.addAxisRange(1, 10, 30, Double.NaN); p.addAxisRange(2, 12, 15, 1); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxr=1,10.0,30.0|2,12.0,15.0,1.0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
DataLegendsParameter extends AbstractParameter { void addLegends(final ImmutableList<? extends String> legends) { this.legends.addAll(legends); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final DataLegendsParameter p = new DataLegendsParameter(); p.addLegends(Lists.of("foo", "bar")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chdl=foo|bar"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartMarkersParameter extends AbstractParameter { void addFillAreaMarker(final FillAreaType fillAreaType, final Color color, final int startLineIndex, final int endLineIndex) { markers.add(new FillAreaMarker(fillAreaType, color, startLineIndex, endLineIndex)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final ChartMarkersParameter p = new ChartMarkersParameter(); p.addFillAreaMarker(FillAreaType.FULL, RED, 1, 3); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=B,FF0000,1,3,0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartMarkersParameter extends AbstractParameter { void addLineStyleMarker(final Color color, final int dataSetIndex, final int dataPoint, final int size, final Priority priority) { markers.add(new LineStyleMarker(color, dataSetIndex, dataPoint, size, priority)); } @Override String getKey(); @Override String getValue(); }
@Test public void test1() { final ChartMarkersParameter p = new ChartMarkersParameter(); p.addLineStyleMarker(BLUE, 1, 3, 12, Priority.HIGH); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=D,0000FF,1,3,12,1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartMarkersParameter extends AbstractParameter { void addHorizontalRangeMarker(final Color color, final double startPoint, final double endPoint) { markers.add(new RangeMarker(RangeType.HORIZONTAL, color, startPoint, endPoint)); } @Override String getKey(); @Override String getValue(); }
@Test public void test2() { final ChartMarkersParameter p = new ChartMarkersParameter(); p.addHorizontalRangeMarker(WHEAT, 0.1, 0.3); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=r,F5DEB3,0,0.10,0.30"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartMarkersParameter extends AbstractParameter { void addMarker(final Marker marker, final int dataSetIndex, final int startIndex, final int endIndex, final int n) { if (marker instanceof ShapeMarker) { markers.add(new ShapeMarkerParam((ShapeMarker) marker, dataSetIndex, startIndex, endIndex, n)); } else if (marker instanceof TextMarker) { markers.add(new TextMarkerParam((TextMarker) marker, dataSetIndex, startIndex, endIndex, n)); } } @Override String getKey(); @Override String getValue(); }
@Test public void test3() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW); p.addMarker(sm, 1, 5, 6, 1); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=o,CD853F,1,5,13,-1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test4() { final ChartMarkersParameter p = new ChartMarkersParameter(); p.addMarker(Markers.newTextMarker("foobar", BLACK, 15), 7, 5, 6, 1); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=tfoobar,000000,7,5,15,0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test5() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW); p.addMarker(sm, 1, 5, 6, 1); p.addMarker(Markers.newTextMarker("foobar", BLACK, 15), 7, 5, 6, 1); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=o,CD853F,1,5,13,-1|tfoobar,000000,7,5,15,0"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test7() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW); p.addMarker(sm, 1, 5, 10 ,2); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=o,CD853F,1,5:9:2,13,-1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test8() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW); p.addMarker(sm, 1, 5, 6 ,2); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=o,CD853F,1,5,13,-1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartMarkersParameter extends AbstractParameter { void addMarkers(final Marker marker, final int dataSetIndex) { addMarker(marker, dataSetIndex, -1, 0, 0); } @Override String getKey(); @Override String getValue(); }
@Test public void test9() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW); p.addMarkers(sm, 1); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=o,CD853F,1,-1,13,-1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
ChartMarkersParameter extends AbstractParameter { void addFreeMarker(final Marker marker, final double xPos, final double yPos) { markers.add(new FreeMarker(marker, xPos, yPos)); } @Override String getKey(); @Override String getValue(); }
@Test public void addFreeShapeMarker() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newShapeMarker(Shape.CIRCLE, PERU, 13, Priority.LOW); p.addFreeMarker(sm, 10, 20); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=@o,CD853F,0,0.1:0.2,13,-1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void addFreeTextMarker() { final ChartMarkersParameter p = new ChartMarkersParameter(); final Marker sm = Markers.newTextMarker("charts4j", PERU, 13, Priority.HIGH); p.addFreeMarker(sm, 20, 10); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chm=@tcharts4j,CD853F,0,0.2:0.1,13,1"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
GeoCodesParameter extends AbstractParameter { void addGeoCode(final String geoCodes) { this.geoCodes.add(geoCodes); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final GeoCodesParameter p = new GeoCodesParameter(); p.addGeoCode(UNITED_STATES + ""); p.addGeoCode(AFGHANISTAN + ""); p.addGeoCode(COLORADO + ""); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chld=USAFCO"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
LineChartLineStylesParameter extends AbstractParameter { void addLineStyle(final LineStyle lineStyle) { this.lineStyles.add(new LineStyleWrapper(lineStyle)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final LineChartLineStylesParameter p = new LineChartLineStylesParameter(); p.addLineStyle(LineStyle.newLineStyle(5, 3, 1)); p.addLineStyle(LineStyle.newLineStyle(1, 4, 2)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chls=5,3,1|1,4,2"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
AbstractGraphChart extends AbstractGChart implements GraphChart, TitledChart { public final void setLegendPosition(final LegendPosition legendPosition) { checkNotNull(legendPosition, "Legend position cannot be null."); this.legendPosition = legendPosition; } AbstractGraphChart(); final void setTitle(final String title); final void setTitle(final String title, final Color color, final int fontSize); final void setLegendPosition(final LegendPosition legendPosition); void setLegendMargins(final int legendWidth, final int legendHeight); final void setAreaFill(final Fill fill); }
@Test public void testSetLegendPosition0() { final Plot plot = Plots.newPlot(Data.newData(0, 50, 100), RED, "my Legend"); final LineChart chart = GCharts.newLineChart(plot); chart.setLegendPosition(LegendPosition.TOP); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } @Test public void testSetLegendPosition1() { final Plot plot0 = Plots.newPlot(Data.newData(0, 50, 100), RED, "legend 0"); final Plot plot1 = Plots.newPlot(Data.newData(100, 50, 0), BLUE, "legend 1"); final LineChart chart = GCharts.newLineChart(plot0, plot1); chart.setLegendPosition(LegendPosition.TOP_VERTICAL); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
AxisLabelsParameter extends AbstractParameter { void addAxisLabels(final int index, final ImmutableList<? extends String> labels) { axisLabels.add(new AxisLabels(index, labels)); } @Override String getKey(); @Override String getValue(); }
@Test public void test0() { final AxisLabelsParameter p = new AxisLabelsParameter(); p.addAxisLabels(1, Lists.of("foo", "bar", "zap")); p.addAxisLabels(2, Lists.of("foo2", "bar2", "zap2")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxl=1:|foo|bar|zap|2:|foo2|bar2|zap2"; assertEquals("Junit error", expectedString, p.toURLParameterString()); } @Test public void test2() { final AxisLabelsParameter p = new AxisLabelsParameter(); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); p.addAxisLabels(2, Lists.of("foo", "bar", "zap")); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(p.toURLParameterString()); final String expectedString = "chxl=2:|foo|bar|zap"; assertEquals("Junit error", expectedString, p.toURLParameterString()); }
BarChart extends AbstractAxisChart { public final void setHorizontal(final boolean horizontal) { this.horizontal = horizontal; } BarChart(final ImmutableList<? extends Plot> barChartPlots); final void setDataStacked(final boolean dataStacked); final void setHorizontal(final boolean horizontal); final void setBarWidth(final int barWidth); final void setSpaceBetweenGroupsOfBars(final int spaceBetweenGroupsOfBars); final void setSpaceWithinGroupsOfBars(final int spaceWithinGroupsOfBars); static final int AUTO_RESIZE; }
@Test public void testHorizontalBarChart() { BarChartPlot data1 = Plots.newBarChartPlot(Data.newData(35, 50, 30, 40), BLUE, "Q1"); BarChartPlot data2 = Plots.newBarChartPlot(Data.newData(10, 20, 30, 25), RED, "Q2"); BarChart chart = GCharts.newBarChart(data1, data2); chart.setSize(200, 300); chart.setHorizontal(true); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
BarChart extends AbstractAxisChart { public final void setDataStacked(final boolean dataStacked) { this.dataStacked = dataStacked; } BarChart(final ImmutableList<? extends Plot> barChartPlots); final void setDataStacked(final boolean dataStacked); final void setHorizontal(final boolean horizontal); final void setBarWidth(final int barWidth); final void setSpaceBetweenGroupsOfBars(final int spaceBetweenGroupsOfBars); final void setSpaceWithinGroupsOfBars(final int spaceWithinGroupsOfBars); static final int AUTO_RESIZE; }
@Test public void testStackedDataBarChart() { BarChartPlot data1 = Plots.newBarChartPlot(Data.newData(35, 50, 30, 40), BLUE, "Q1"); BarChartPlot data2 = Plots.newBarChartPlot(Data.newData(10, 20, 30, 25), RED, "Q2"); BarChart chart = GCharts.newBarChart(data1, data2); chart.setSize(200, 300); chart.setDataStacked(true); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
BarChart extends AbstractAxisChart { public final void setSpaceBetweenGroupsOfBars(final int spaceBetweenGroupsOfBars) { checkArgument(spaceWithinGroupsOfBars >= 0, "spaceWithinGroupsOfBars must be >= 0"); this.spaceBetweenGroupsOfBars = spaceBetweenGroupsOfBars; } BarChart(final ImmutableList<? extends Plot> barChartPlots); final void setDataStacked(final boolean dataStacked); final void setHorizontal(final boolean horizontal); final void setBarWidth(final int barWidth); final void setSpaceBetweenGroupsOfBars(final int spaceBetweenGroupsOfBars); final void setSpaceWithinGroupsOfBars(final int spaceWithinGroupsOfBars); static final int AUTO_RESIZE; }
@Test public void testSetSpaceBetweenGroupsOfBars() { BarChartPlot data1 = Plots.newBarChartPlot(Data.newData(0, 25, 50, 75, 100), BLUE); BarChartPlot data2 = Plots.newBarChartPlot(Data.newData(0, 25, 50, 75, 100), RED); BarChart chart = GCharts.newBarChart(data1, data2); chart.setSize(400, 200); chart.setSpaceBetweenGroupsOfBars(30); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
BarChart extends AbstractAxisChart { public final void setBarWidth(final int barWidth) { checkArgument(barWidth > -1, "barWidth must be > 0"); this.barWidth = barWidth; } BarChart(final ImmutableList<? extends Plot> barChartPlots); final void setDataStacked(final boolean dataStacked); final void setHorizontal(final boolean horizontal); final void setBarWidth(final int barWidth); final void setSpaceBetweenGroupsOfBars(final int spaceBetweenGroupsOfBars); final void setSpaceWithinGroupsOfBars(final int spaceWithinGroupsOfBars); static final int AUTO_RESIZE; }
@Test public void testSetBarWidth() { BarChartPlot data1 = Plots.newBarChartPlot(Data.newData(0, 25, 50, 75, 100), BLUE); BarChartPlot data2 = Plots.newBarChartPlot(Data.newData(0, 25, 50, 75, 100), RED); BarChart chart = GCharts.newBarChart(data1, data2); chart.setSize(400, 200); chart.setBarWidth(30); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); } @Test public void testAutoResize() { BarChartPlot data1 = Plots.newBarChartPlot(Data.newData(5, 25, 50, 75, 100), BLUE); BarChartPlot data2 = Plots.newBarChartPlot(Data.newData(5, 25, 50, 75, 100), RED); BarChart chart = GCharts.newBarChart(data1, data2); chart.setSize(400, 200); chart.setBarWidth(BarChart.AUTO_RESIZE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
BarChart extends AbstractAxisChart { public final void setSpaceWithinGroupsOfBars(final int spaceWithinGroupsOfBars) { checkArgument(spaceWithinGroupsOfBars >= 0, "spaceWithinGroupsOfBars must be >= 0"); this.spaceWithinGroupsOfBars = spaceWithinGroupsOfBars; } BarChart(final ImmutableList<? extends Plot> barChartPlots); final void setDataStacked(final boolean dataStacked); final void setHorizontal(final boolean horizontal); final void setBarWidth(final int barWidth); final void setSpaceBetweenGroupsOfBars(final int spaceBetweenGroupsOfBars); final void setSpaceWithinGroupsOfBars(final int spaceWithinGroupsOfBars); static final int AUTO_RESIZE; }
@Test public void testSetSpaceWithinGroupsOfBars() { BarChartPlot data1 = Plots.newBarChartPlot(Data.newData(0, 25, 50, 75, 100), BLUE); BarChartPlot data2 = Plots.newBarChartPlot(Data.newData(0, 25, 50, 75, 100), RED); BarChart chart = GCharts.newBarChart(data1, data2); chart.setSize(400, 200); chart.setSpaceWithinGroupsOfBars(30); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
AbstractGChart implements GChart { public void setSize(final int width, final int height) { checkArgument(width * height <= MAX_PIXELS, "The largest possible area for all charts except maps is 300,000 pixels."); checkArgument(width > MIN_WIDTH && width <= MAX_WIDTH, "width must be > " + MIN_WIDTH + " and <= " + MAX_WIDTH + ": %s", width); checkArgument(height > MIN_HEIGHT && height <= MAX_HEIGHT, "height must be > " + MIN_WIDTH + " and <= " + MAX_WIDTH + ": %s", height); this.width = width; this.height = height; } AbstractGChart(); void setSize(final int width, final int height); final Map<String, String> getParameters(); final String toURLString(); final String toURLForHTML(); void setBackgroundFill(final Fill fill); void setTransparency(final int opacity); final void setDataEncoding(final DataEncoding dataEncoding); void setMargins(final int leftMargin, final int rightMargin, final int topMargin, final int bottomMargin); void setURLEndpoint(final String urlEndpoint); }
@Test public void testSetSize0() { try { final LineChart chart = getBasicChart(); chart.setSize(0, 0); } catch (IllegalArgumentException e) { return; } fail(); } @Test public void testSetSize1() { try { final LineChart chart = getBasicChart(); chart.setSize(1001, 1001); } catch (IllegalArgumentException e) { return; } fail(); }
AbstractGChart implements GChart { public void setBackgroundFill(final Fill fill) { checkNotNull(fill, "The background fill cannot be null"); this.backgroundFill = fill; } AbstractGChart(); void setSize(final int width, final int height); final Map<String, String> getParameters(); final String toURLString(); final String toURLForHTML(); void setBackgroundFill(final Fill fill); void setTransparency(final int opacity); final void setDataEncoding(final DataEncoding dataEncoding); void setMargins(final int leftMargin, final int rightMargin, final int topMargin, final int bottomMargin); void setURLEndpoint(final String urlEndpoint); }
@Test public void testSetBackgroundFill() { final LineChart chart = getBasicChart(); chart.setBackgroundFill(Fills.newSolidFill(BLUE)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
AbstractGChart implements GChart { public void setTransparency(final int opacity) { checkArgument(opacity >= MIN_OPACITY && opacity <= MAX_OPACITY, "opacity must be between " + MIN_OPACITY + " and " + MAX_OPACITY + ": %s", opacity); this.opacity = opacity; } AbstractGChart(); void setSize(final int width, final int height); final Map<String, String> getParameters(); final String toURLString(); final String toURLForHTML(); void setBackgroundFill(final Fill fill); void setTransparency(final int opacity); final void setDataEncoding(final DataEncoding dataEncoding); void setMargins(final int leftMargin, final int rightMargin, final int topMargin, final int bottomMargin); void setURLEndpoint(final String urlEndpoint); }
@Test public void testSetTransparency() { final LineChart chart = getBasicChart(); chart.setTransparency(10); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
AbstractGChart implements GChart { public void setURLEndpoint(final String urlEndpoint) { checkNotNull(urlEndpoint, "The chart URL endpoint cannot be null"); this.chartURLEndpoint = urlEndpoint; } AbstractGChart(); void setSize(final int width, final int height); final Map<String, String> getParameters(); final String toURLString(); final String toURLForHTML(); void setBackgroundFill(final Fill fill); void setTransparency(final int opacity); final void setDataEncoding(final DataEncoding dataEncoding); void setMargins(final int leftMargin, final int rightMargin, final int topMargin, final int bottomMargin); void setURLEndpoint(final String urlEndpoint); }
@Test public void testSetURLEndpoint() { final LineChart chart = getBasicChart(); chart.setDataEncoding(DataEncoding.SIMPLE); chart.setURLEndpoint("http: Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
AbstractGChart implements GChart { public final Map<String, String> getParameters() { parameterManager.init(chartURLEndpoint); prepareData(); return parameterManager.getParameterMap(); } AbstractGChart(); void setSize(final int width, final int height); final Map<String, String> getParameters(); final String toURLString(); final String toURLForHTML(); void setBackgroundFill(final Fill fill); void setTransparency(final int opacity); final void setDataEncoding(final DataEncoding dataEncoding); void setMargins(final int leftMargin, final int rightMargin, final int topMargin, final int bottomMargin); void setURLEndpoint(final String urlEndpoint); }
@Test public void testGetParameters() { final LineChart chart = getBasicChart(); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); Map<String, String> parameters = chart.getParameters(); assertEquals("Junit error", "lc", parameters.get("cht")); assertEquals("Junit error", "200x125", parameters.get("chs")); assertEquals("Junit error", "e:AAgA..", parameters.get("chd")); }
Color { Color(final String color) { checkNotNull(color, "color cannot be null."); this.color = validateColor(color); opacity = "FF"; } Color(final String color); Color(final String color, final int opacity); Color(final Color color, final int opacity); @Override String toString(); static Color newColor(final String color); static Color newColor(final String color, final int opacity); static Color newColor(final Color color, final int opacity); static final Color ALICEBLUE; static final Color ANTIQUEWHITE; static final Color AQUA; static final Color AQUAMARINE; static final Color AZURE; static final Color BEIGE; static final Color BISQUE; static final Color BLACK; static final Color BLANCHEDALMOND; static final Color BLUE; static final Color BLUEVIOLET; static final Color BROWN; static final Color BURLYWOOD; static final Color CADETBLUE; static final Color CHARTREUSE; static final Color CHOCOLATE; static final Color CORAL; static final Color CORNFLOWERBLUE; static final Color CORNSILK; static final Color CRIMSON; static final Color CYAN; static final Color DARKBLUE; static final Color DARKCYAN; static final Color DARKGOLDENROD; static final Color DARKGRAY; static final Color DARKGREEN; static final Color DARKKHAKI; static final Color DARKMAGENTA; static final Color DARKOLIVEGREEN; static final Color DARKORANGE; static final Color DARKORCHID; static final Color DARKRED; static final Color DARKSALMON; static final Color DARKSEAGREEN; static final Color DARKSLATEBLUE; static final Color DARKSLATEGRAY; static final Color DARKTURQUOISE; static final Color DARKVIOLET; static final Color DEEPPINK; static final Color DEEPSKYBLUE; static final Color DIMGRAY; static final Color DODGERBLUE; static final Color FIREBRICK; static final Color FLORALWHITE; static final Color FORESTGREEN; static final Color FUCHSIA; static final Color GAINSBORO; static final Color GHOSTWHITE; static final Color GOLD; static final Color GOLDENROD; static final Color GRAY; static final Color GREEN; static final Color GREENYELLOW; static final Color HONEYDEW; static final Color HOTPINK; static final Color INDIANRED; static final Color INDIGO; static final Color IVORY; static final Color KHAKI; static final Color LAVENDER; static final Color LAVENDERBLUSH; static final Color LAWNGREEN; static final Color LEMONCHIFFON; static final Color LIGHTBLUE; static final Color LIGHTCORAL; static final Color LIGHTCYAN; static final Color LIGHTGOLDENRODYELLOW; static final Color LIGHTGREEN; static final Color LIGHTGREY; static final Color LIGHTPINK; static final Color LIGHTSALMON; static final Color LIGHTSEAGREEN; static final Color LIGHTSKYBLUE; static final Color LIGHTSLATEGRAY; static final Color LIGHTSTEELBLUE; static final Color LIGHTYELLOW; static final Color LIME; static final Color LIMEGREEN; static final Color LINEN; static final Color MAGENTA; static final Color MAROON; static final Color MEDIUMAQUAMARINE; static final Color MEDIUMBLUE; static final Color MEDIUMORCHID; static final Color MEDIUMPURPLE; static final Color MEDIUMSEAGREEN; static final Color MEDIUMSLATEBLUE; static final Color MEDIUMSPRINGGREEN; static final Color MEDIUMTURQUOISE; static final Color MEDIUMVIOLETRED; static final Color MIDNIGHTBLUE; static final Color MINTCREAM; static final Color MISTYROSE; static final Color MOCCASIN; static final Color NAVAJOWHITE; static final Color NAVY; static final Color OLDLACE; static final Color OLIVE; static final Color OLIVEDRAB; static final Color ORANGE; static final Color ORANGERED; static final Color ORCHID; static final Color PALEGOLDENROD; static final Color PALEGREEN; static final Color PALETURQUOISE; static final Color PALEVIOLETRED; static final Color PAPAYAWHIP; static final Color PEACHPUFF; static final Color PERU; static final Color PINK; static final Color PLUM; static final Color POWDERBLUE; static final Color PURPLE; static final Color RED; static final Color ROSYBROWN; static final Color ROYALBLUE; static final Color SADDLEBROWN; static final Color SALMON; static final Color SANDYBROWN; static final Color SEAGREEN; static final Color SEASHELL; static final Color SIENNA; static final Color SILVER; static final Color SKYBLUE; static final Color SLATEBLUE; static final Color SLATEGRAY; static final Color SNOW; static final Color SPRINGGREEN; static final Color STEELBLUE; static final Color TAN; static final Color TEAL; static final Color THISTLE; static final Color TOMATO; static final Color TURQUOISE; static final Color VIOLET; static final Color WHEAT; static final Color WHITE; static final Color WHITESMOKE; static final Color YELLOW; static final Color YELLOWGREEN; }
@Test public void colorTest() { final Color color = Color.newColor("000000"); assertEquals("Junit error", color.toString(), BLACK.toString()); }
Color { public static Color newColor(final String color) { return new Color(color); } Color(final String color); Color(final String color, final int opacity); Color(final Color color, final int opacity); @Override String toString(); static Color newColor(final String color); static Color newColor(final String color, final int opacity); static Color newColor(final Color color, final int opacity); static final Color ALICEBLUE; static final Color ANTIQUEWHITE; static final Color AQUA; static final Color AQUAMARINE; static final Color AZURE; static final Color BEIGE; static final Color BISQUE; static final Color BLACK; static final Color BLANCHEDALMOND; static final Color BLUE; static final Color BLUEVIOLET; static final Color BROWN; static final Color BURLYWOOD; static final Color CADETBLUE; static final Color CHARTREUSE; static final Color CHOCOLATE; static final Color CORAL; static final Color CORNFLOWERBLUE; static final Color CORNSILK; static final Color CRIMSON; static final Color CYAN; static final Color DARKBLUE; static final Color DARKCYAN; static final Color DARKGOLDENROD; static final Color DARKGRAY; static final Color DARKGREEN; static final Color DARKKHAKI; static final Color DARKMAGENTA; static final Color DARKOLIVEGREEN; static final Color DARKORANGE; static final Color DARKORCHID; static final Color DARKRED; static final Color DARKSALMON; static final Color DARKSEAGREEN; static final Color DARKSLATEBLUE; static final Color DARKSLATEGRAY; static final Color DARKTURQUOISE; static final Color DARKVIOLET; static final Color DEEPPINK; static final Color DEEPSKYBLUE; static final Color DIMGRAY; static final Color DODGERBLUE; static final Color FIREBRICK; static final Color FLORALWHITE; static final Color FORESTGREEN; static final Color FUCHSIA; static final Color GAINSBORO; static final Color GHOSTWHITE; static final Color GOLD; static final Color GOLDENROD; static final Color GRAY; static final Color GREEN; static final Color GREENYELLOW; static final Color HONEYDEW; static final Color HOTPINK; static final Color INDIANRED; static final Color INDIGO; static final Color IVORY; static final Color KHAKI; static final Color LAVENDER; static final Color LAVENDERBLUSH; static final Color LAWNGREEN; static final Color LEMONCHIFFON; static final Color LIGHTBLUE; static final Color LIGHTCORAL; static final Color LIGHTCYAN; static final Color LIGHTGOLDENRODYELLOW; static final Color LIGHTGREEN; static final Color LIGHTGREY; static final Color LIGHTPINK; static final Color LIGHTSALMON; static final Color LIGHTSEAGREEN; static final Color LIGHTSKYBLUE; static final Color LIGHTSLATEGRAY; static final Color LIGHTSTEELBLUE; static final Color LIGHTYELLOW; static final Color LIME; static final Color LIMEGREEN; static final Color LINEN; static final Color MAGENTA; static final Color MAROON; static final Color MEDIUMAQUAMARINE; static final Color MEDIUMBLUE; static final Color MEDIUMORCHID; static final Color MEDIUMPURPLE; static final Color MEDIUMSEAGREEN; static final Color MEDIUMSLATEBLUE; static final Color MEDIUMSPRINGGREEN; static final Color MEDIUMTURQUOISE; static final Color MEDIUMVIOLETRED; static final Color MIDNIGHTBLUE; static final Color MINTCREAM; static final Color MISTYROSE; static final Color MOCCASIN; static final Color NAVAJOWHITE; static final Color NAVY; static final Color OLDLACE; static final Color OLIVE; static final Color OLIVEDRAB; static final Color ORANGE; static final Color ORANGERED; static final Color ORCHID; static final Color PALEGOLDENROD; static final Color PALEGREEN; static final Color PALETURQUOISE; static final Color PALEVIOLETRED; static final Color PAPAYAWHIP; static final Color PEACHPUFF; static final Color PERU; static final Color PINK; static final Color PLUM; static final Color POWDERBLUE; static final Color PURPLE; static final Color RED; static final Color ROSYBROWN; static final Color ROYALBLUE; static final Color SADDLEBROWN; static final Color SALMON; static final Color SANDYBROWN; static final Color SEAGREEN; static final Color SEASHELL; static final Color SIENNA; static final Color SILVER; static final Color SKYBLUE; static final Color SLATEBLUE; static final Color SLATEGRAY; static final Color SNOW; static final Color SPRINGGREEN; static final Color STEELBLUE; static final Color TAN; static final Color TEAL; static final Color THISTLE; static final Color TOMATO; static final Color TURQUOISE; static final Color VIOLET; static final Color WHEAT; static final Color WHITE; static final Color WHITESMOKE; static final Color YELLOW; static final Color YELLOWGREEN; }
@Test public void colorTest2() { try { @SuppressWarnings("unused") final Color color = Color.newColor("FFFFFFFF"); } catch (RuntimeException e) { return; } fail(); } @Test public void colorTest3() { try { @SuppressWarnings("unused") final Color color = Color.newColor("foobar"); } catch (RuntimeException e) { return; } fail(); }
AbstractGraphChart extends AbstractGChart implements GraphChart, TitledChart { public void setLegendMargins(final int legendWidth, final int legendHeight) { this.legendMargins = new LegendMargins(legendWidth, legendHeight); } AbstractGraphChart(); final void setTitle(final String title); final void setTitle(final String title, final Color color, final int fontSize); final void setLegendPosition(final LegendPosition legendPosition); void setLegendMargins(final int legendWidth, final int legendHeight); final void setAreaFill(final Fill fill); }
@Test public void testSetLegendMargins() { final Plot plot = Plots.newPlot(Data.newData(0, 50, 100), RED, "my Legend"); final LineChart chart = GCharts.newLineChart(plot); chart.setLegendMargins(100, 50); chart.setBackgroundFill(Fills.newSolidFill(BLACK)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
AbstractGraphChart extends AbstractGChart implements GraphChart, TitledChart { public final void setAreaFill(final Fill fill) { areaFill = fill.klone(); } AbstractGraphChart(); final void setTitle(final String title); final void setTitle(final String title, final Color color, final int fontSize); final void setLegendPosition(final LegendPosition legendPosition); void setLegendMargins(final int legendWidth, final int legendHeight); final void setAreaFill(final Fill fill); }
@Test public void testSetAreaFill() { final LineChart chart = getBasicChart(); chart.setAreaFill(Fills.newSolidFill(RED)); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(chart.toURLString()); String expectedString = "http: assertEquals("Junit error", normalize(expectedString), normalize(chart.toURLString())); }
ClassLoaderUtil { public static String classnameFromFilename(final String filename) { Objects.requireNonNull(filename); return StreamSupport.stream( Paths.get(filename.replaceFirst("\\.class$", "")).spliterator(), false) .map(Path::toString) .collect(Collectors.joining(".")); } private ClassLoaderUtil(); static URL toUrl(final Path file); static String classnameFromFilename(final String filename); static String resourceNameFromClassName(final String className); static CT privileged( final Supplier<CT> classLoaderSupplier); }
@Test public void classnameFromFilename() { assertEquals( "com.example.Foo", ClassLoaderUtil.classnameFromFilename("com/example/Foo.class")); }
ClassLoaderUtil { public static String resourceNameFromClassName(final String className) { Objects.requireNonNull(className); return className.replace('.', '/') + ".class"; } private ClassLoaderUtil(); static URL toUrl(final Path file); static String classnameFromFilename(final String filename); static String resourceNameFromClassName(final String className); static CT privileged( final Supplier<CT> classLoaderSupplier); }
@Test public void resourceNameFromClassName() { assertEquals( "com/example/Foo.class", ClassLoaderUtil.resourceNameFromClassName("com.example.Foo")); }
LobbyPresenter extends BasePresenter<LobbyView> { String getLocalReport() { String localReport = lobbyReportUseCase.getLocalReport(); Timber.d("localReport: %s", localReport); return localReport; } @Inject LobbyPresenter(LobbyReportUseCase lobbyReportUseCase, SchedulersFacade schedulersFacade); }
@Test public void getLocalReport_returnsLocalReport() throws Exception { when(lobbyReportUseCase.getLocalReport()).thenReturn(DUMMY_REPORT_DATA); String result = testSubject.getLocalReport(); assertThat(result, is(DUMMY_REPORT_DATA)); }
LobbyActivity extends AppCompatActivity implements LobbyView { @Override public void displayReportData(CharSequence report) { displayReportTextView.setVisibility(View.VISIBLE); displayReportTextView.setText(report); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void displayReportData_setsReportTextViewVisibilityToVisible_andSetsText() throws Exception { testSubject.displayReportData(DUMMY_REPORT_DATA); verify(displayReportTextView).setVisibility(View.VISIBLE); verify(displayReportTextView).setText(DUMMY_REPORT_DATA); }
LobbyActivity extends AppCompatActivity implements LobbyView { @Override public void displayReportError() { Toast.makeText(this, R.string.lobby_report_error_text, Toast.LENGTH_LONG).show(); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void displayReportError_displaysToastWithCorrectErrorMessage() throws Exception { String expected = RuntimeEnvironment.application.getString(R.string.lobby_report_error_text); testSubject.displayReportError(); assertThat(ShadowToast.getTextOfLatestToast(), is(expected)); }
LobbyActivity extends AppCompatActivity implements LobbyView { @Override public void hideReportData() { displayReportTextView.setVisibility(View.GONE); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void hideReportData_setsReportTextViewVisibilityToGone() throws Exception { testSubject.hideReportData(); verify(displayReportTextView).setVisibility(View.GONE); }
LobbyActivity extends AppCompatActivity implements LobbyView { @Override public void displayLoadingIndicator() { loadingIndicator.setVisibility(View.VISIBLE); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void displayLoadingIndicator_setsLoadingIndicatorVisibilityToVisible() throws Exception { testSubject.displayLoadingIndicator(); verify(loadingIndicator).setVisibility(View.VISIBLE); }
LobbyActivity extends AppCompatActivity implements LobbyView { @Override public void hideLoadingIndicator() { loadingIndicator.setVisibility(View.GONE); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void hideLoadingIndicator_setsLoadingIndicatorVisibilityToGone() throws Exception { testSubject.hideLoadingIndicator(); verify(loadingIndicator).setVisibility(View.GONE); }
LobbyReportUseCase { Single<String> generateReport() { return repository.getReportAsync(); } @Inject LobbyReportUseCase(LobbyRepository repository); }
@Test public void generateReport_getsReportAsyncFromRepository() throws Exception { testSubject.generateReport(); verify(lobbyRepository).getReportAsync(); }
LobbyReportUseCase { String getLocalReport() { return repository.getReport(); } @Inject LobbyReportUseCase(LobbyRepository repository); }
@Test public void getLocalReport_getsReportFromRepository() throws Exception { testSubject.getLocalReport(); verify(lobbyRepository).getReport(); }
LobbyPresenter extends BasePresenter<LobbyView> { void generateReport() { addDisposable(lobbyReportUseCase.generateReport() .doOnSubscribe(s -> publishRequestState(RequestState.LOADING)) .subscribeOn(schedulersFacade.io()) .observeOn(schedulersFacade.ui()) .delay(REPORT_DELAY_MILLIS, TimeUnit.MILLISECONDS, schedulersFacade.ui()) .doOnSuccess(s -> publishRequestState(RequestState.COMPLETE)) .doOnError(t -> publishRequestState(RequestState.ERROR)) .subscribe(this::onReportDataAvailable, this::onReportDataError)); } @Inject LobbyPresenter(LobbyReportUseCase lobbyReportUseCase, SchedulersFacade schedulersFacade); }
@Test public void generateReport_whenReportDataAvailable_displaysReportDataInView() throws Exception { when(lobbyReportUseCase.generateReport()).thenReturn(Single.just(DUMMY_REPORT_DATA)); testSubject.generateReport(); testScheduler.advanceTimeBy(REPORT_DELAY_MILLIS, TimeUnit.MILLISECONDS); testScheduler.triggerActions(); verify(view).hideReportData(); verify(view).displayLoadingIndicator(); verify(view).hideLoadingIndicator(); verify(view).displayReportData(DUMMY_REPORT_DATA); verifyNoMoreInteractions(view); } @Test public void generateReport_whenReportDataError_displaysReportErrorInView() throws Exception { Throwable throwable = mock(Throwable.class); when(lobbyReportUseCase.generateReport()).thenReturn(Single.error(throwable)); testSubject.generateReport(); testScheduler.advanceTimeBy(REPORT_DELAY_MILLIS, TimeUnit.MILLISECONDS); testScheduler.triggerActions(); verify(view).hideReportData(); verify(view).displayLoadingIndicator(); verify(view).hideLoadingIndicator(); verify(view).displayReportError(); verifyNoMoreInteractions(view); }
LobbyPresenter extends BasePresenter<LobbyView> { void onReportDataAvailable(String report) { Timber.d("report data: %s", report); view.displayReportData(report); } @Inject LobbyPresenter(LobbyReportUseCase lobbyReportUseCase, SchedulersFacade schedulersFacade); }
@Test public void onReportDataAvailable_displaysReportDataInView() throws Exception { testSubject.onReportDataAvailable(DUMMY_REPORT_DATA); verify(view).displayReportData(DUMMY_REPORT_DATA); }
LobbyPresenter extends BasePresenter<LobbyView> { void onReportDataError(Throwable throwable) { Timber.e(throwable, "report error"); view.displayReportError(); } @Inject LobbyPresenter(LobbyReportUseCase lobbyReportUseCase, SchedulersFacade schedulersFacade); }
@Test public void onReportDataError_displaysReportErrorInView() throws Exception { testSubject.onReportDataError(null); verify(view).displayReportError(); }
LobbyRepositoryImpl implements LobbyRepository { @Override public Single<String> getReportAsync() { return Single.just(FAKE_REPORT_DATA); } @Override Single<String> getReportAsync(); @Override String getReport(); }
@Test public void getReportAsync_onSuccess_returnsReportData() throws Exception { when(testSubject.getReportAsync()) .thenReturn(Single.just(LobbyRepositoryImpl.FAKE_REPORT_DATA)); TestObserver<String> testObserver = testSubject.getReportAsync().test(); testObserver.assertResult(LobbyRepositoryImpl.FAKE_REPORT_DATA); testObserver.assertComplete(); } @Test public void getReportAsync_onError_returnsError() throws Exception { when(testSubject.getReportAsync()) .thenReturn(Single.error(new RuntimeException())); TestObserver<String> testObserver = testSubject.getReportAsync().test(); testObserver.assertError(RuntimeException.class); }
LobbyRepositoryImpl implements LobbyRepository { @Override public String getReport() { return FAKE_REPORT_DATA; } @Override Single<String> getReportAsync(); @Override String getReport(); }
@Test public void getReport_returnsReportData() throws Exception { String result = testSubject.getReport(); assertThat(result, is(LobbyRepositoryImpl.FAKE_REPORT_DATA)); }
LobbyActivity extends AppCompatActivity implements LobbyView { @Override protected void onDestroy() { presenter.onViewDestroyed(); super.onDestroy(); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void onDestroy_callsOnViewDestroyedOnPresenter() throws Exception { testSubject.onDestroy(); verify(presenter).onViewDestroyed(); }
LobbyActivity extends AppCompatActivity implements LobbyView { @OnClick(R.id.generate_report) public void onGenerateReportButtonClicked() { presenter.generateReport(); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }
@Test public void onGenerateReportButtonClicked_callsGenerateReportOnPresenter() throws Exception { testSubject.onGenerateReportButtonClicked(); verify(presenter).generateReport(); }
Validators { public static void checkTopic(String topic) throws MQClientException { if (UtilAll.isBlank(topic)) { throw new MQClientException("the specified topic is blank", null); } if (!regularExpressionMatcher(topic, PATTERN)) { throw new MQClientException(String.format( "the specified topic[%s] contains illegal characters, allowing only %s", topic, VALID_PATTERN_STR), null); } if (topic.length() > CHARACTER_MAX_LENGTH) { throw new MQClientException("the specified topic is longer than topic max length 255.", null); } if (topic.equals(MixAll.DEFAULT_TOPIC)) { throw new MQClientException( String.format("the topic[%s] is conflict with default topic.", topic), null); } } static String getGroupWithRegularExpression(String origin, String patternStr); static void checkGroup(String group); static boolean regularExpressionMatcher(String origin, Pattern pattern); static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer); static void checkTopic(String topic); static final String VALID_PATTERN_STR; static final Pattern PATTERN; static final int CHARACTER_MAX_LENGTH; }
@Test public void topicValidatorTest() { try { Validators.checkTopic("Hello"); Validators.checkTopic("%RETRY%Hello"); Validators.checkTopic("_%RETRY%Hello"); Validators.checkTopic("-%RETRY%Hello"); Validators.checkTopic("223-%RETRY%Hello"); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
ConsumerOffsetManager extends ConfigManager { public void commitOffset(final String clientHost, final String group, final String topic, final int queueId, final long offset) { String key = topic + TOPIC_GROUP_SEPARATOR + group; this.commitOffset(clientHost, key, queueId, offset); } ConsumerOffsetManager(); ConsumerOffsetManager(BrokerController brokerController); void scanUnsubscribedTopic(); Set<String> whichTopicByConsumer(final String group); Set<String> whichGroupByTopic(final String topic); void commitOffset(final String clientHost, final String group, final String topic, final int queueId, final long offset); long queryOffset(final String group, final String topic, final int queueId); String encode(); @Override String configFilePath(); @Override void decode(String jsonString); String encode(final boolean prettyFormat); ConcurrentHashMap<String, ConcurrentHashMap<Integer, Long>> getOffsetTable(); void setOffsetTable(ConcurrentHashMap<String, ConcurrentHashMap<Integer, Long>> offsetTable); Map<Integer, Long> queryMinOffsetInAllGroup(final String topic, final String filterGroups); Map<Integer, Long> queryOffset(final String group, final String topic); void cloneOffset(final String srcGroup, final String destGroup, final String topic); }
@Test public void test_flushConsumerOffset() throws Exception { BrokerController brokerController = new BrokerController( new BrokerConfig(), new NettyServerConfig(), new NettyClientConfig(), new MessageStoreConfig()); boolean initResult = brokerController.initialize(); System.out.println("initialize " + initResult); brokerController.start(); ConsumerOffsetManager consumerOffsetManager = new ConsumerOffsetManager(brokerController); Random random = new Random(); for (int i = 0; i < 100; i++) { String group = "DIANPU_GROUP_" + i; for (int id = 0; id < 16; id++) { consumerOffsetManager.commitOffset(null, group, "TOPIC_A", id, random.nextLong() % 1024 * 1024 * 1024); consumerOffsetManager.commitOffset(null, group, "TOPIC_B", id, random.nextLong() % 1024 * 1024 * 1024); consumerOffsetManager.commitOffset(null, group, "TOPIC_C", id, random.nextLong() % 1024 * 1024 * 1024); } } consumerOffsetManager.persist(); brokerController.shutdown(); }
TopicConfigManager extends ConfigManager { public TopicConfig createTopicInSendMessageMethod(final String topic, final String defaultTopic, final String remoteAddress, final int clientDefaultTopicQueueNums, final int topicSysFlag) { TopicConfig topicConfig = null; boolean createNew = false; try { if (this.lockTopicConfigTable.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)) { try { topicConfig = this.topicConfigTable.get(topic); if (topicConfig != null) return topicConfig; TopicConfig defaultTopicConfig = this.topicConfigTable.get(defaultTopic); if (defaultTopicConfig != null) { if (defaultTopic.equals(MixAll.DEFAULT_TOPIC)) { if (!this.brokerController.getBrokerConfig().isAutoCreateTopicEnable()) { defaultTopicConfig.setPerm(PermName.PERM_READ | PermName.PERM_WRITE); } } if (PermName.isInherited(defaultTopicConfig.getPerm())) { topicConfig = new TopicConfig(topic); int queueNums = clientDefaultTopicQueueNums > defaultTopicConfig.getWriteQueueNums() ? defaultTopicConfig .getWriteQueueNums() : clientDefaultTopicQueueNums; if (queueNums < 0) { queueNums = 0; } topicConfig.setReadQueueNums(queueNums); topicConfig.setWriteQueueNums(queueNums); int perm = defaultTopicConfig.getPerm(); perm &= ~PermName.PERM_INHERIT; topicConfig.setPerm(perm); topicConfig.setTopicSysFlag(topicSysFlag); topicConfig.setTopicFilterType(defaultTopicConfig.getTopicFilterType()); } else { log.warn("create new topic failed, because the default topic[" + defaultTopic + "] no perm, " + defaultTopicConfig.getPerm() + " producer: " + remoteAddress); } } else { log.warn("create new topic failed, because the default topic[" + defaultTopic + "] not exist." + " producer: " + remoteAddress); } if (topicConfig != null) { log.info("create new topic by default topic[" + defaultTopic + "], " + topicConfig + " producer: " + remoteAddress); this.topicConfigTable.put(topic, topicConfig); this.dataVersion.nextVersion(); createNew = true; this.persist(); } } finally { this.lockTopicConfigTable.unlock(); } } } catch (InterruptedException e) { log.error("createTopicInSendMessageMethod exception", e); } if (createNew) { this.brokerController.registerBrokerAll(false, true); } return topicConfig; } TopicConfigManager(); TopicConfigManager(BrokerController brokerController); boolean isSystemTopic(final String topic); Set<String> getSystemTopic(); boolean isTopicCanSendMessage(final String topic); TopicConfig selectTopicConfig(final String topic); TopicConfig createTopicInSendMessageMethod(final String topic, final String defaultTopic, final String remoteAddress, final int clientDefaultTopicQueueNums, final int topicSysFlag); TopicConfig createTopicInSendMessageBackMethod(// final String topic, // final int clientDefaultTopicQueueNums,// final int perm,// final int topicSysFlag); void updateTopicUnitFlag(final String topic, final boolean unit); void updateTopicUnitSubFlag(final String topic, final boolean hasUnitSub); void updateTopicConfig(final TopicConfig topicConfig); void updateOrderTopicConfig(final KVTable orderKVTableFromNs); boolean isOrderTopic(final String topic); void deleteTopicConfig(final String topic); TopicConfigSerializeWrapper buildTopicConfigSerializeWrapper(); @Override String encode(); @Override String configFilePath(); @Override void decode(String jsonString); String encode(final boolean prettyFormat); DataVersion getDataVersion(); ConcurrentHashMap<String, TopicConfig> getTopicConfigTable(); }
@Test public void test_flushTopicConfig() throws Exception { BrokerController brokerController = new BrokerController( new BrokerConfig(), new NettyServerConfig(), new NettyClientConfig(), new MessageStoreConfig()); boolean initResult = brokerController.initialize(); System.out.println("initialize " + initResult); brokerController.start(); TopicConfigManager topicConfigManager = new TopicConfigManager(brokerController); TopicConfig topicConfig = topicConfigManager.createTopicInSendMessageMethod("TestTopic_SEND", MixAll.DEFAULT_TOPIC, null, 4, 0); assertTrue(topicConfig != null); System.out.println(topicConfig); for (int i = 0; i < 10; i++) { String topic = "UNITTEST-" + i; topicConfig = topicConfigManager .createTopicInSendMessageMethod(topic, MixAll.DEFAULT_TOPIC, null, 4, 0); assertTrue(topicConfig != null); } topicConfigManager.persist(); brokerController.shutdown(); }
FilterAPI { public static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic, String subString) throws Exception { SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setTopic(topic); subscriptionData.setSubString(subString); if (null == subString || subString.equals(SubscriptionData.SUB_ALL) || subString.length() == 0) { subscriptionData.setSubString(SubscriptionData.SUB_ALL); } else { String[] tags = subString.split("\\|\\|"); if (tags != null && tags.length > 0) { for (String tag : tags) { if (tag.length() > 0) { String trimString = tag.trim(); if (trimString.length() > 0) { subscriptionData.getTagsSet().add(trimString); subscriptionData.getCodeSet().add(trimString.hashCode()); } } } } else { throw new Exception("subString split error"); } } return subscriptionData; } static URL classFile(final String className); static String simpleClassName(final String className); static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic, String subString); }
@Test public void testBuildSubscriptionData() throws Exception { SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData("ConsumerGroup1", "TestTopic", "TAG1 || Tag2 || tag3"); System.out.println(subscriptionData); } @Test public void testSubscriptionData() throws Exception { SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData("ConsumerGroup1", "TestTopic", "TAG1 || Tag2 || tag3"); subscriptionData.setFilterClassSource("java hello"); String json = RemotingSerializable.toJson(subscriptionData, true); System.out.println(json); }
UtilAll { public static String currentStackTrace() { StringBuilder sb = new StringBuilder(); StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement ste : stackTrace) { sb.append("\n\t"); sb.append(ste.toString()); } return sb.toString(); } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }
@Test public void test_currentStackTrace() { System.out.println(UtilAll.currentStackTrace()); }
UtilAll { public static String timeMillisToHumanString() { return timeMillisToHumanString(System.currentTimeMillis()); } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }
@Test public void test_timeMillisToHumanString() { System.out.println(UtilAll.timeMillisToHumanString()); }
UtilAll { public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { return -1; } } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }
@Test public void test_getpid() { int pid = UtilAll.getPid(); System.out.println("PID = " + pid); assertTrue(pid > 0); }
UtilAll { public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }
@Test public void test_isBlank() { { boolean result = UtilAll.isBlank("Hello "); assertTrue(!result); } { boolean result = UtilAll.isBlank(" Hello"); assertTrue(!result); } { boolean result = UtilAll.isBlank("He llo"); assertTrue(!result); } { boolean result = UtilAll.isBlank(" "); assertTrue(result); } { boolean result = UtilAll.isBlank("Hello"); assertTrue(!result); } }
MixAll { public static List<String> getLocalInetAddress() { List<String> inetAddressList = new ArrayList<String>(); try { Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { inetAddressList.add(addrs.nextElement().getHostAddress()); } } } catch (SocketException e) { throw new RuntimeException("get local inet address fail", e); } return inetAddressList; } static String getRetryTopic(final String consumerGroup); static boolean isSysConsumerGroup(final String consumerGroup); static boolean isSystemTopic(final String topic); static String getDLQTopic(final String consumerGroup); static String brokerVIPChannel(final boolean isChange, final String brokerAddr); static long getPID(); static long createBrokerId(final String ip, final int port); static final void string2File(final String str, final String fileName); static final void string2FileNotSafe(final String str, final String fileName); static final String file2String(final String fileName); static final String file2String(final File file); static final String file2String(final URL url); static String findClassPath(Class<?> c); static void printObjectProperties(final Logger log, final Object object); static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField); static String properties2String(final Properties properties); static Properties string2Properties(final String str); static Properties object2Properties(final Object object); static void properties2Object(final Properties p, final Object object); static boolean isPropertiesEqual(final Properties p1, final Properties p2); static List<String> getLocalInetAddress(); static boolean isLocalAddr(String address); static boolean compareAndIncreaseOnly(final AtomicLong target, final long value); static String localhostName(); Set<String> list2Set(List<String> values); List<String> set2List(Set<String> values); static final String ROCKETMQ_HOME_ENV; static final String ROCKETMQ_HOME_PROPERTY; static final String NAMESRV_ADDR_ENV; static final String NAMESRV_ADDR_PROPERTY; static final String MESSAGE_COMPRESS_LEVEL; static final String WS_DOMAIN_NAME; static final String WS_DOMAIN_SUBGROUP; static final String WS_ADDR; static final String DEFAULT_TOPIC; static final String BENCHMARK_TOPIC; static final String DEFAULT_PRODUCER_GROUP; static final String DEFAULT_CONSUMER_GROUP; static final String TOOLS_CONSUMER_GROUP; static final String FILTERSRV_CONSUMER_GROUP; static final String MONITOR_CONSUMER_GROUP; static final String CLIENT_INNER_PRODUCER_GROUP; static final String SELF_TEST_PRODUCER_GROUP; static final String SELF_TEST_CONSUMER_GROUP; static final String SELF_TEST_TOPIC; static final String OFFSET_MOVED_EVENT; static final String ONS_HTTP_PROXY_GROUP; static final String CID_ONSAPI_PERMISSION_GROUP; static final String CID_ONSAPI_OWNER_GROUP; static final String CID_ONSAPI_PULL_GROUP; static final String CID_RMQ_SYS_PREFIX; static final List<String> LocalInetAddrs; static final String Localhost; static final String DEFAULT_CHARSET; static final long MASTER_ID; static final long CURRENT_JVM_PID; static final String RETRY_GROUP_TOPIC_PREFIX; static final String DLQ_GROUP_TOPIC_PREFIX; static final String SYSTEM_TOPIC_PREFIX; static final String UNIQUE_MSG_QUERY_FLAG; }
@Test public void test() throws Exception { List<String> localInetAddress = MixAll.getLocalInetAddress(); String local = InetAddress.getLocalHost().getHostAddress(); Assert.assertTrue(localInetAddress.contains("127.0.0.1")); Assert.assertTrue(localInetAddress.contains(local)); }
ModelUtils { @NonNull static <T extends ModelObject> T deserializeModel(@NonNull JSONObject jsonObject, @NonNull Class<T> modelClass) { final ModelObject.Serializer<T> serializer = (ModelObject.Serializer<T>) ModelUtils.readModelSerializer(modelClass); return serializer.deserialize(jsonObject); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }
@Test public void parseModel_Pass_ParseMockedModelByClass() { JSONObject jsonObject = new JSONObject(); MockModelObject parsedResult = ModelUtils.deserializeModel(jsonObject, MockModelObject.class); assertNotNull(parsedResult); }
JsonUtils { @Nullable public static List<String> parseOptStringList(@Nullable JSONArray jsonArray) { if (jsonArray == null) { return null; } final List<String> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { final String item = jsonArray.optString(i, null); if (item != null) { list.add(item); } } return Collections.unmodifiableList(list); } private JsonUtils(); @NonNull static String indent(@Nullable JSONObject jsonObject); static void writeToParcel(@NonNull Parcel parcel, @Nullable JSONObject jsonObject); @Nullable static JSONObject readFromParcel(@NonNull Parcel parcel); @Nullable static List<String> parseOptStringList(@Nullable JSONArray jsonArray); @Nullable static JSONArray serializeOptStringList(@Nullable List<String> stringList); static final int INDENTATION_SPACES; }
@Test public void parseOptStringList_Pass_ParseEmptyArray() { JSONArray jsonArray = new JSONArray(); List<String> stringList = JsonUtils.parseOptStringList(jsonArray); Assert.assertNotNull(stringList); Assert.assertTrue(stringList.isEmpty()); } @SuppressWarnings("ConstantConditions") @Test public void parseOptStringList_Pass_ParseNull() { List<String> stringList = JsonUtils.parseOptStringList(null); Assert.assertNull(stringList); } @Test public void parseOptStringList_Pass_ParseStringArray() { JSONArray jsonArray = new JSONArray(); String testString = "Test"; jsonArray.put(testString); List<String> stringList = JsonUtils.parseOptStringList(jsonArray); Assert.assertNotNull(stringList); String first = stringList.get(0); Assert.assertEquals(testString, first); }
BaseHttpUrlConnectionFactory { @NonNull HttpURLConnection createHttpUrlConnection(@NonNull String url) throws IOException { final HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection(); if (urlConnection instanceof HttpsURLConnection) { ((HttpsURLConnection) urlConnection).setSSLSocketFactory(TLS_SOCKET_FACTORY); return urlConnection; } else { return handleInsecureConnection(urlConnection); } } }
@Test public void initBaseHttpUrl_Pass_HTTPS_ExpectSecureConnection() throws IOException { String url = "https: HttpURLConnection urlConnection = new BaseHttpUrlConnectionFactory() { @NonNull @Override HttpURLConnection handleInsecureConnection(@NonNull HttpURLConnection httpUrlConnection) { assertEquals(1, 2); return httpUrlConnection; } }.createHttpUrlConnection(url); assertEquals(urlConnection.getURL().toString(), url); } @Test public void initBaseHttpUrl_Pass_HTTPS_ExpectInsecureConnection() throws IOException { final String url = "http: HttpURLConnection urlConnection = new BaseHttpUrlConnectionFactory() { @NonNull @Override HttpURLConnection handleInsecureConnection(@NonNull HttpURLConnection httpUrlConnection) { assertEquals(httpUrlConnection.getURL().toString(), url); return httpUrlConnection; } }.createHttpUrlConnection(url); }
ModelUtils { @Nullable public static <T extends ModelObject> T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer) { return jsonObject == null ? null : serializer.deserialize(jsonObject); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }
@Test public void parseOpt_Pass_ParseMockedModel() { JSONObject jsonObject = new JSONObject(); MockModelObject parsedResult = ModelUtils.deserializeOpt(jsonObject, MockModelObject.SERIALIZER); Assert.assertNotNull(parsedResult); } @SuppressWarnings("ConstantConditions") @Test public void parseOpt_Pass_ParseNull() { MockModelObject parsedResult = ModelUtils.deserializeOpt(null, MockModelObject.SERIALIZER); Assert.assertNull(parsedResult); }
ModelUtils { @Nullable public static <T extends ModelObject> List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer) { if (jsonArray == null) { return null; } final List<T> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { final JSONObject itemJson = jsonArray.optJSONObject(i); if (itemJson != null) { final T item = serializer.deserialize(itemJson); list.add(item); } } return Collections.unmodifiableList(list); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }
@Test public void parseOptList_Pass_ParseMockedModel() { JSONArray jsonArray = new JSONArray(); List<MockModelObject> modelList = ModelUtils.deserializeOptList(jsonArray, MockModelObject.SERIALIZER); Assert.assertNotNull(modelList); } @SuppressWarnings("ConstantConditions") @Test public void parseOptList_Pass_ParseNull() { List<MockModelObject> modelList = ModelUtils.deserializeOptList(null, MockModelObject.SERIALIZER); Assert.assertNull(modelList); }
ModelUtils { @Nullable public static <T extends ModelObject> JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer) { return modelObject == null ? null : serializer.serialize(modelObject); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }
@Test public void serializeOpt_Pass_SerializeMockedModel() { MockModelObject mockModelObject = new MockModelObject(); JSONObject jsonObject = ModelUtils.serializeOpt(mockModelObject, MockModelObject.SERIALIZER); Assert.assertNotNull(jsonObject); } @SuppressWarnings("ConstantConditions") @Test public void serializeOpt_Pass_SerializeNull() { JSONObject jsonObject = ModelUtils.serializeOpt(null, MockModelObject.SERIALIZER); Assert.assertNull(jsonObject); }
ModelUtils { @Nullable public static <T extends ModelObject> JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer) { if (modelList == null || modelList.isEmpty()) { return null; } final JSONArray jsonArray = new JSONArray(); for (T model : modelList) { jsonArray.put(serializer.serialize(model)); } return jsonArray; } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }
@Test public void serializeOptList_Pass_SerializeMockedModelList() { List<MockModelObject> modelObjectList = new ArrayList<>(); modelObjectList.add(new MockModelObject()); JSONArray jsonArray = ModelUtils.serializeOptList(modelObjectList, MockModelObject.SERIALIZER); Assert.assertNotNull(jsonArray); Assert.assertTrue(!jsonArray.isNull(0)); } @SuppressWarnings("ConstantConditions") @Test public void serializeOptList_Pass_SerializeNull() { JSONArray jsonArray = ModelUtils.serializeOptList(null, MockModelObject.SERIALIZER); Assert.assertNull(jsonArray); }
XmlUtils { public static List<String> determineArrays(InputStream in) throws XMLStreamException { Set<String> arrayKeys = new HashSet<>(); XMLStreamReader sr = null; try { XMLInputFactory f = XMLInputFactory.newFactory(); sr = f.createXMLStreamReader(in); getObjectElements(null, sr, new LongAdder(), arrayKeys); if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); arrayKeys.forEach(key -> sb.append(sb.length() > 0 ? "\n" : "").append(key)); LOGGER.trace("Found arrays:\n{}", sb.toString()); } } finally { if (null != sr) { sr.close(); } } return new ArrayList<>(arrayKeys); } private XmlUtils(); static List<String> determineArrays(InputStream in); }
@Test public void testParseXml() throws FileNotFoundException, XMLStreamException { XMLInputFactory f = XMLInputFactory.newFactory(); File inputFile = new File(getClass().getResource("/SampleXml.xml").getFile()); XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(inputFile)); InputStream in = new FileInputStream(inputFile); List<String> arrays = XmlUtils.determineArrays(in); Assert.assertFalse(arrays.isEmpty()); Assert.assertEquals(2, arrays.size()); Assert.assertEquals("/root/channel", arrays.get(0)); Assert.assertEquals("/root/channel/formats/format", arrays.get(1)); sr.close(); }
CustomPatternFileFilter implements FileFilter { @Override public boolean accept(File file) { String fileNameInLowerCase = file.getName().toLowerCase(); FileTypeEnum fileType = FileTypeEnum.parseByFileName(fileNameInLowerCase); return (null != fileType) && fileNameInLowerCase.matches(pattern); } CustomPatternFileFilter(String pattern); @Override boolean accept(File file); }
@Test public void testFilteringXmlByPartialFileNamePatternFalse() { String pattern = "*Fle*.xml"; File file = new File("SomeFileWithXml.xml"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertFalse(filter.accept(file)); } @Test public void testFilteringXmlByPartialFileNamePatternCaseInsensitive() { String pattern = "*File*.xml"; File file = new File("Some FileWithXml.XML"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); } @Test public void testFilteringJsonByPattern() { String pattern = "*.json"; File file = new File("SomeFileWithJson.json"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); } @Test public void testFilteringUnsupportedExtension() { String pattern = "*.txt"; File file = new File("SomeFileWithJson.txt"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertFalse(filter.accept(file)); } @Test public void testFilteringXmlByPattern() { String pattern = "*.xml"; File file = new File("SomeFileWithXml.xml"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); } @Test public void testFilteringXmlByPatternFalse() { String pattern = "*.xml"; File file = new File("SomeFileWithXml.json"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertFalse(filter.accept(file)); } @Test public void testFilteringXmlByPartialFileNamePattern() { String pattern = "*File*.xml"; File file = new File("SomeFileWithXml.xml"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); }
ConverterService { public File convert(File sourceFile, File outputFile, IFileReadListener listener, AtomicBoolean isCanceled) throws IOException, XMLStreamException { StopWatch sw = new StopWatch(); Objects.requireNonNull(listener, "Listener must be not null"); FileTypeEnum inputFileType = FileTypeEnum.parseByFileName(sourceFile.getName()); if (null == inputFileType) { throw new UnsupportedFileType(String.format(UNSUPPORTED_FILE_TYPE_TEMPLATE, sourceFile.getName())); } File parentFolder = outputFile.getParentFile(); if (!parentFolder.exists()) { parentFolder.mkdirs(); } try (InputStream input = getWrappedInputStream(sourceFile, listener, isCanceled); OutputStream output = getOutputStream(outputFile)) { sw.start(); JsonXMLConfig config = createConfig(inputFileType); XMLEventReader reader = createReader(config, inputFileType, input); XMLEventWriter writer = createWriter(config, sourceFile, output, isCanceled, listener); writer.add(reader); listener.finished(); writer.flush(); writer.close(); reader.close(); } catch (XMLStreamException ex) { throw new XMLStreamException(ex.getMessage()); } finally { LOGGER.info("Taken time: {}", sw); sw.stop(); } return outputFile; } File convert(File sourceFile, File outputFile, IFileReadListener listener, AtomicBoolean isCanceled); }
@Test public void testConvertXmlToJson() throws IOException, XMLStreamException { File sourceFile = new File(this.getClass().getClassLoader().getResource("SampleXml.xml").getFile()); destinationFile = new File(getTempDirectory(), "ConvertedFile.json"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, new CustomFileReadListener(), isCanceled); assertTrue(destinationFile.exists()); assertTrue(destinationFile.length() > 0); System.out.println("destinationFile = " + destinationFile.getAbsolutePath()); } @Test public void testConvertXmlToJsonToNonExistingDirectory() throws IOException, XMLStreamException { File sourceFile = new File(this.getClass().getClassLoader().getResource("SampleXml.xml").getFile()); File nonExistingDirectory = new File(getTempDirectory(), "newDirectory"); filesToDelete.add(nonExistingDirectory); destinationFile = new File(nonExistingDirectory, "newDirectory/ConvertedFile.json"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, new CustomFileReadListener(), isCanceled); assertTrue(destinationFile.exists()); assertTrue(destinationFile.length() > 0); System.out.println("destinationFile = " + destinationFile.getAbsolutePath()); } @Test public void testConvertJsonToXml() throws IOException, XMLStreamException { File sourceFile = new File(this.getClass().getClassLoader().getResource("SampleJson.json").getFile()); destinationFile = new File(getTempDirectory(), "ConvertedFile.xml"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, new CustomFileReadListener(), isCanceled); assertTrue(destinationFile.exists()); assertTrue(destinationFile.length() > 0); System.out.println("destinationFile = " + destinationFile.getAbsolutePath()); } @Test(expected = XMLStreamException.class) public void testConvertCorruptedXmlToJson() throws IOException, XMLStreamException { File sourceFile = new File(this.getClass().getClassLoader().getResource("CorruptedXml.xml").getFile()); destinationFile = new File(getTempDirectory(), "ConvertedFile.json"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, new CustomFileReadListener(), isCanceled); } @Test(expected = UnsupportedFileType.class) public void testTryConvertUnsupportedFile() throws IOException, XMLStreamException { File sourceFile = new File(this.getClass().getClassLoader().getResource("Unsupported.txt").getFile()); destinationFile = new File(getTempDirectory(), "ConvertedFile.json"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, new CustomFileReadListener(), isCanceled); } @Test(expected = NullPointerException.class) public void testTryConvertWithNullListener() throws IOException, XMLStreamException { File sourceFile = new File(this.getClass().getClassLoader().getResource("SampleJson.json").getFile()); destinationFile = new File(getTempDirectory(), "ConvertedFile.xml"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, null, isCanceled); } @Test public void testConvertXmlToJsonFullProcess() throws IOException, XMLStreamException { File tempDirectory = new File(getTempDirectory(), "xml2jsonSerialize"); filesToDelete.add(tempDirectory); tempDirectory.mkdirs(); ComplexObject actualObject = new ComplexObject(); actualObject.setIntValue(555); actualObject.setText("Some Text in Complex Object"); SimpleObject so = new SimpleObject(); so.setBytePrimValue(Byte.valueOf("109")); so.setByteValue(Byte.valueOf("45")); so.setDoublePrimValue(457d); so.setDoubleValue(Double.parseDouble("256.12")); so.setFloatPrimValue(15.4f); so.setFloatValue(Float.parseFloat("852.45")); so.setIntegerValue(Integer.parseInt("400")); so.setIntValue(500); so.setLongPrimValue(32000000); so.setLongValue(Long.parseLong("4656053654")); so.setShortPrimValue((short)120); so.setShortValue(Short.parseShort("-99")); so.setSomeValue("Some text"); actualObject.getListOfObjects().add(so); so = new SimpleObject(); so.setBytePrimValue(Byte.valueOf("111")); so.setByteValue(Byte.valueOf("23")); so.setDoublePrimValue(3242d); so.setDoubleValue(Double.parseDouble("222.55")); so.setFloatPrimValue(2.2134f); so.setFloatValue(Float.parseFloat("876.44")); so.setIntegerValue(Integer.parseInt("456")); so.setIntValue(2223); so.setLongPrimValue(34534634); so.setLongValue(Long.parseLong("45856865")); so.setShortPrimValue((short)101); so.setShortValue(Short.parseShort("-44")); so.setSomeValue("Some text 2"); actualObject.getListOfObjects().add(so); File sourceFile = new File(tempDirectory, "SerializedObject.xml"); XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true); xmlMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true); xmlMapper.setDefaultUseWrapper(false); try (BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFile))) { writer.write(xmlMapper.writeValueAsString(actualObject)); } destinationFile = new File(tempDirectory, "SerializedObject.json"); ConverterService service = new ConverterService(); AtomicBoolean isCanceled = new AtomicBoolean(false); service.convert(sourceFile, destinationFile, new CustomFileReadListener(), isCanceled); assertTrue(destinationFile.exists()); assertTrue(destinationFile.length() > 0); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); ComplexObject result = mapper.readValue(destinationFile, ComplexObject.class); assertNotNull(result); }
ApplicationUtils { public static final String getVersion() { String version = getVersionFromManifest(); if (null == version || version.isEmpty()) { version = UNNOWN_VERSION; } return version; } private ApplicationUtils(); static final String getVersion(); static final String UNNOWN_VERSION; }
@Test public void testApplicationVersion() { Assert.assertEquals(ApplicationUtils.UNNOWN_VERSION, ApplicationUtils.getVersion()); } @Test public void getImplementationVersion() throws Exception { PowerMockito.spy(ApplicationUtils.class); PowerMockito.doReturn("1.0.0").when(ApplicationUtils.class, "getVersionFromManifest"); String s = ApplicationUtils.getVersion(); PowerMockito.verifyStatic(Package.class); Assert.assertEquals("1.0.0", s); } @Test public void getImplementationVersionEmptyValue() throws Exception { PowerMockito.spy(ApplicationUtils.class); PowerMockito.doReturn("").when(ApplicationUtils.class, "getVersionFromManifest"); String s = ApplicationUtils.getVersion(); PowerMockito.verifyStatic(Package.class); Assert.assertEquals(ApplicationUtils.UNNOWN_VERSION, s); }
HostServicesProvider { public HostServices getHostServices() { if (hostServices == null) { throw new IllegalStateException("Host services not initialized"); } return hostServices; } void init(HostServices hostServices); HostServices getHostServices(); static final HostServicesProvider INSTANCE; }
@Test(expected = IllegalStateException.class) public void testNotInitializedInstance() { HostServicesProvider.INSTANCE.getHostServices(); }
PropertiesLoader { public Properties load() throws IOException { Properties properties = new Properties(); LOGGER.debug("Loading properties from {}", propertiesFile.getAbsolutePath()); if (propertiesFile.exists()) { try (InputStream in = new FileInputStream(propertiesFile)) { properties.load(in); LOGGER.debug("Loaded {} properties", properties.size()); } } else { throw new FileNotFoundException("File '" + propertiesFile.getAbsolutePath() + "' is not exist"); } return properties; } PropertiesLoader(File propertiesFile); Properties load(); void saveProperties(Properties properties); }
@Test(expected = FileNotFoundException.class) public void testLoadFromNonExistingFile() throws IOException { PropertiesLoader loader = new PropertiesLoader(new File("someProperties.txt")); loader.load(); } @Test public void testLoad() throws IOException { PropertiesLoader loader = new PropertiesLoader(getPropertiesFile()); Properties props = loader.load(); Assert.assertEquals(4, props.size()); } @Test(expected = FileNotFoundException.class) public void testLoadFileNotExists() throws IOException { File propsFile = new File(getDestinationDirectory(), "someFolder" + TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); loader.load(); }
ApplicationProperties { public void setPropertiesLoader(PropertiesLoader loader) { if (loader == null) { throw new IllegalArgumentException("Properties loader cannot be null"); } this.loader = loader; } ApplicationProperties(PropertiesLoader loader); String getLastOpenedPath(); void saveLastOpenedPath(File path); void setPropertiesLoader(PropertiesLoader loader); }
@Test(expected = IllegalArgumentException.class) public void testApplicationPropertiesSetNullLoader() { File propsFile = new File(getDestinationDirectory(), TEST_FILE); ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile)); Assert.assertNotNull(props); props.setPropertiesLoader(null); } @Test public void testApplicationPropertiesSetNotNullLoader() { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile)); Assert.assertNotNull(props); props.setPropertiesLoader(loader); }
ApplicationProperties { public String getLastOpenedPath() { if (!isInitialized) { loadProperties(); } String path = properties.getProperty(Config.LAST_DIRECTORY); if (null == path || path.trim().isEmpty()) { return null; } else { File f = new File(path); if (!f.exists()) { return null; } } return path; } ApplicationProperties(PropertiesLoader loader); String getLastOpenedPath(); void saveLastOpenedPath(File path); void setPropertiesLoader(PropertiesLoader loader); }
@Test public void testGetPropertiesAndPathNotExists() { File propsFile = new File(getDestinationDirectory(), TEST_FILE); ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile)); Assert.assertNotNull(props); String path = props.getLastOpenedPath(); Assert.assertNull(path); path = props.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testGetPropertiesAndPathIsEmpty() throws IOException { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties appProps = new ApplicationProperties(loader); Properties props = loader.load(); props.put(Config.LAST_DIRECTORY, ""); loader.saveProperties(props); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testGetPropertiesAndPathWithOnlySpaces() throws IOException { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties appProps = new ApplicationProperties(loader); Properties props = loader.load(); props.put(Config.LAST_DIRECTORY, " "); loader.saveProperties(props); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testGetPropertiesAndPathIsNotExist() throws IOException { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties appProps = new ApplicationProperties(loader); Properties props = loader.load(); props.put(Config.LAST_DIRECTORY, new File(propsFile.getParentFile(), "someNameFolder/file.txt").getAbsolutePath()); loader.saveProperties(props); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testLoadWithException() throws IOException { PropertiesLoader loader = Mockito.mock(PropertiesLoader.class); BDDMockito.when(loader.load()).thenThrow(new IOException()); ApplicationProperties appProps = Mockito.spy(new ApplicationProperties(loader)); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); }
ApplicationCommandLine { public static ApplicationCommandLine parse(String[] args) throws java.text.ParseException, FileNotFoundException { CommandLineParser parser = new DefaultParser(); ApplicationCommandLine cmd = null; try { cmd = new ApplicationCommandLine(parser.parse(OPTIONS, args, true)); cmd.checkInputParameters(); } catch (ParseException ex) { throw new java.text.ParseException(ex.getMessage(), 0); } return cmd; } private ApplicationCommandLine(CommandLine cmd); static ApplicationCommandLine parse(String[] args); static void printHelp(); boolean isNoGuiEnabled(); File getSourceFolder(); File getDestinationFolder(); String getPattern(); boolean isForceOverwrite(); }
@Test(expected = ParseException.class) public void testParseNoGuiAndSourceFolderWithoutValue() throws ParseException, FileNotFoundException { String[] args = new String[]{"--noGui", "--sourceFolder", "--destinationFolder", DESTINATION_FOLDER_PATH, "--pattern", "*.json"}; ApplicationCommandLine.parse(args); }
ApplicationCommandLine { public static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(HELP_WINDOW_SIZE, "\n java -jar xml2json.jar " + PARAM_SIGN + Config.PAR_NO_GUI + " " + PARAM_SIGN + Config.PAR_SOURCE_FOLDER + "=[path_to_source_folder] " + PARAM_SIGN + Config.PAR_DESTINATION_FOLDER + "=[path_to_destination_folder] " + PARAM_SIGN + Config.PAR_SOURCE_FILE_PATTERN + "=[*.json|*.xml]", ", where:", OPTIONS, "example:\n java -jar xml2json.jar " + PARAM_SIGN + Config.PAR_NO_GUI + " " + PARAM_SIGN + Config.PAR_SOURCE_FOLDER + "=C:\\temp\\input " + PARAM_SIGN + Config.PAR_DESTINATION_FOLDER + "=C:\\temp\\output " + PARAM_SIGN + Config.PAR_SOURCE_FILE_PATTERN + "=*.json\n\n"); } private ApplicationCommandLine(CommandLine cmd); static ApplicationCommandLine parse(String[] args); static void printHelp(); boolean isNoGuiEnabled(); File getSourceFolder(); File getDestinationFolder(); String getPattern(); boolean isForceOverwrite(); }
@Test public void testPrintHelp() { ApplicationCommandLine.printHelp(); }
JsonXMLArrayProvider extends AbstractJsonXMLProvider { @Override protected boolean isReadWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (!isSupported(mediaType)) { return false; } Class<?> componentType = getComponentType(type, genericType); return componentType != null && getJsonXML(componentType, annotations) != null && isBindable(componentType); } JsonXMLArrayProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry); }
@Test public void testIsReadWriteable() throws NoSuchFieldException { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); Assert.assertTrue(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("sampleTypeList").getGenericType(); Assert.assertTrue(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("objectList").getGenericType(); Assert.assertFalse(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("sampleTypeIterable").getGenericType(); Assert.assertFalse(provider.isReadWriteable(Iterable.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("sampleTypeList").getGenericType(); Assert.assertFalse(provider.isReadWriteable(List.class, type, new Annotation[0], MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_XML_TYPE)); }
JsonXMLArrayProvider extends AbstractJsonXMLProvider { @Override public Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream) throws IOException, WebApplicationException { Class<?> componentType = getComponentType(type, genericType); JsonXML config = getJsonXML(componentType, annotations); List<?> list; try { list = readArray(componentType, config, getContext(componentType, mediaType), stream); } catch (XMLStreamException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } catch (JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } if (list == null) { return null; } else if (type.isArray()) { return toArray(list, componentType); } else { Collection<Object> collection = createCollection(type); if (collection == null) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } collection.addAll(list); return collection; } } JsonXMLArrayProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry); }
@Test public void testReadRootElementList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); String json = "{\"sampleRootElement\":[{\"@attribute\":\"hello\"},{\"@attribute\":\"world\"}]}"; @SuppressWarnings("unchecked") List<SampleRootElement> list = (List<SampleRootElement>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(2, list.size()); Assert.assertEquals("hello", list.get(0).attribute); Assert.assertEquals("world", list.get(1).attribute); } @Test public void testReadRootElementList_DocumentArray() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); String json = "[{\"sampleRootElement\":{\"@attribute\":\"hello\"}},{\"sampleRootElement\":{\"@attribute\":\"world\"}}]"; @SuppressWarnings("unchecked") List<SampleRootElement> list = (List<SampleRootElement>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(2, list.size()); Assert.assertEquals("hello", list.get(0).attribute); Assert.assertEquals("world", list.get(1).attribute); } @Test public void testReadSampleTypeList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleTypeList").getGenericType(); String json = "{\"sampleType\":[{\"element\":\"hello\"},{\"element\":\"world\"}]}"; @SuppressWarnings("unchecked") List<SampleType> list = (List<SampleType>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(2, list.size()); Assert.assertEquals("hello", list.get(0).element); Assert.assertEquals("world", list.get(1).element); } @Test public void testReadSampleTypeList_DocumentArray() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleTypeList").getGenericType(); String json = "[{\"sampleType\":{\"element\":\"hello\"}},{\"sampleType\":{\"element\":\"world\"}}]"; @SuppressWarnings("unchecked") List<SampleType> list = (List<SampleType>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(2, list.size()); Assert.assertEquals("hello", list.get(0).element); Assert.assertEquals("world", list.get(1).element); } @Test public void testReadSampleTypeListWithNullValues() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleTypeList").getGenericType(); String json = "[null,{\"sampleType\":{\"element\":\"hi!\"}},null]"; @SuppressWarnings("unchecked") List<SampleType> list = (List<SampleType>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(3, list.size()); Assert.assertNull(list.get(0)); Assert.assertEquals("hi!", list.get(1).element); Assert.assertNull(list.get(2)); } @Test public void testReadEmptyList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); String json = "{}"; @SuppressWarnings("unchecked") List<SampleRootElement> list = (List<SampleRootElement>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(0, list.size()); } @Test public void testReadEmptyList2() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); String json = "{\"sampleRootElement\":[]}"; @SuppressWarnings("unchecked") List<SampleRootElement> list = (List<SampleRootElement>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(0, list.size()); } @Test public void testReadEmptyList3() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); String json = "[]"; @SuppressWarnings("unchecked") List<SampleRootElement> list = (List<SampleRootElement>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(0, list.size()); } @Test public void testReadEmptyListWithVirtualRoot() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); String json = "[]"; @SuppressWarnings("unchecked") List<SampleRootElement> list = (List<SampleRootElement>)provider.read(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals(0, list.size()); }
JsonXMLArrayProvider extends AbstractJsonXMLProvider { @Override public void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry) throws IOException, WebApplicationException { Class<?> componentType = getComponentType(type, genericType); JsonXML config = getJsonXML(componentType, annotations); Collection<?> collection; if (entry == null) { collection = null; } else if (type.isArray()) { collection = Arrays.asList((Object[]) entry); } else { collection = (Collection<?>) entry; } try { writeArray(componentType, config, getContext(componentType, mediaType), stream, collection); } catch (XMLStreamException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } catch (JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } JsonXMLArrayProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry); }
@Test public void testWriteSampleRootElementList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<SampleRootElement>(); list.add(new SampleRootElement()); list.get(0).attribute = "hello"; list.add(new SampleRootElement()); list.get(1).attribute = "world"; StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[{\"sampleRootElement\":{\"@attribute\":\"hello\"}},{\"sampleRootElement\":{\"@attribute\":\"world\"}}]"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteSampleTypeList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleTypeList").getGenericType(); List<SampleType> list = new ArrayList<SampleType>(); list.add(new SampleType()); list.get(0).element = "hello"; list.add(new SampleType()); list.get(1).element = "world"; StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[{\"sampleType\":{\"element\":\"hello\"}},{\"sampleType\":{\"element\":\"world\"}}]"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteEmptyList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<SampleRootElement>(); StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[]"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteEmptyListWithVirtualRoot() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<SampleRootElement>(); StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[]"; Assert.assertEquals(json, writer.toString()); }
AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected static <A extends Annotation> A getAnnotation(Annotation[] annotations, Class<A> annotationType) { for (Annotation annotation : annotations) { if (annotation.annotationType() == annotationType) { return annotationType.cast(annotation); } } return null; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testGetAnnotation() { Annotation[] annotations = new Annotation[2]; annotations[0] = SampleType.class.getAnnotation(XmlType.class); annotations[1] = JsonXMLDefault.class.getAnnotation(JsonXML.class); Assert.assertEquals(XmlType.class, AbstractJsonXMLProvider.getAnnotation(annotations, XmlType.class).annotationType()); Assert.assertEquals(JsonXML.class, AbstractJsonXMLProvider.getAnnotation(annotations, JsonXML.class).annotationType()); Assert.assertNull(AbstractJsonXMLProvider.getAnnotation(annotations, XmlRootElement.class)); }
AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected String getCharset(MediaType mediaType) { Map<String, String> parameters = mediaType.getParameters(); return parameters.containsKey("charset") ? parameters.get("charset") : "UTF-8"; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testGetCharset() { Assert.assertEquals("UTF-8", new TestProvider().getCharset(MediaType.APPLICATION_JSON_TYPE)); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("charset", "ASCII"); MediaType customMediaType = new MediaType("application", "json", parameters); Assert.assertEquals("ASCII", new TestProvider().getCharset(customMediaType)); }
ConverterUtils { public static File getConvertedFile(File sourceFile, File destinationFolder) { FileTypeEnum fileType = FileTypeEnum.parseByFileName(sourceFile.getName()); String convertedFileName = ""; String fileNameWithoutExtension = sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf('.')); switch (fileType) { case JSON: convertedFileName = fileNameWithoutExtension + FileTypeEnum.XML.getExtension(); break; case XML: convertedFileName = fileNameWithoutExtension + FileTypeEnum.JSON.getExtension(); break; default: throw new UnsupportedFileType("Unsupported file's extension"); } return new File(destinationFolder, convertedFileName); } private ConverterUtils(); static File getConvertedFile(File sourceFile, File destinationFolder); }
@Test public void testGetConvertedFileForJson() { File sourceFile = new File("someJsonFile.json"); File outputDirectory = new File("."); File outFile = ConverterUtils.getConvertedFile(sourceFile, outputDirectory); Assert.assertEquals("someJsonFile.xml", outFile.getName()); } @Test public void testGetConvertedFileForXml() { File sourceFile = new File("someFile.xml"); File outputDirectory = new File("."); File outFile = ConverterUtils.getConvertedFile(sourceFile, outputDirectory); Assert.assertEquals("someFile.json", outFile.getName()); } @Test(expected = NullPointerException.class) public void testGetConvertedFileWithUnsupportedFile() { File sourceFile = new File("someIncorrectFile.txt"); File outputDirectory = new File("."); ConverterUtils.getConvertedFile(sourceFile, outputDirectory); }
AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected JsonXML getJsonXML(Class<?> type, Annotation[] resourceAnnotations) { JsonXML result = getAnnotation(resourceAnnotations, JsonXML.class); if (result == null) { result = type.getAnnotation(JsonXML.class); } return result; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testGetJsonXML() { JsonXML typeAnnotation = SampleRootElement.class.getAnnotation(JsonXML.class); Assert.assertEquals(typeAnnotation, new TestProvider().getJsonXML(SampleRootElement.class, new Annotation[0])); Annotation[] resourceAnnotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Assert.assertEquals(resourceAnnotations[0], new TestProvider().getJsonXML(SampleType.class, resourceAnnotations)); Assert.assertNull(new TestProvider().getJsonXML(SampleType.class, new Annotation[0])); }
AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { @Override public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testGetSize() { Assert.assertEquals(-1, new TestProvider().getSize(null, null, null, null, null)); }
AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected boolean isSupported(MediaType mediaType) { return "json".equalsIgnoreCase(mediaType.getSubtype()) || mediaType.getSubtype().endsWith("+json"); } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }
@Test public void testIsSupported() { Assert.assertTrue(new TestProvider().isSupported(MediaType.APPLICATION_JSON_TYPE)); Assert.assertTrue(new TestProvider().isSupported(new MediaType("text", "json"))); Assert.assertTrue(new TestProvider().isSupported(new MediaType("text", "JSON"))); Assert.assertTrue(new TestProvider().isSupported(new MediaType("text", "special+json"))); Assert.assertFalse(new TestProvider().isSupported(MediaType.APPLICATION_XML_TYPE)); }
JsonXMLObjectProvider extends AbstractJsonXMLProvider { @Override protected boolean isReadWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isSupported(mediaType) && getJsonXML(type, annotations) != null && isBindable(type); } JsonXMLObjectProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value); }
@Test public void testIsReadWriteable() { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] jsonXMLAnnotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Assert.assertTrue(provider.isReadWriteable(SampleRootElement.class, null, jsonXMLAnnotations, MediaType.APPLICATION_JSON_TYPE)); Assert.assertTrue(provider.isReadWriteable(SampleType.class, null, jsonXMLAnnotations, MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(Object.class, null, jsonXMLAnnotations, MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(SampleType.class, null, new Annotation[0], MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(SampleRootElement.class, null, jsonXMLAnnotations, MediaType.APPLICATION_XML_TYPE)); }
JsonXMLObjectProvider extends AbstractJsonXMLProvider { @Override public Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream) throws IOException, WebApplicationException { JsonXML config = getJsonXML(type, annotations); try { return readObject(type, config, getContext(type, mediaType), stream); } catch (XMLStreamException | JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } JsonXMLObjectProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value); }
@Test public void testReadSampleRootElement() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; String json = "{\"sampleRootElement\":{\"@attribute\":\"hello\",\"elements\":[\"world\"]}}"; SampleRootElement sampleRootElement = (SampleRootElement)provider.read(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals("hello", sampleRootElement.attribute); Assert.assertEquals("world", sampleRootElement.elements.get(0)); } @Test public void testReadSampleType() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; String json = "{\"sampleType\":{\"element\":\"hi!\"}}"; SampleType sampleType = (SampleType)provider.read(SampleType.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals("hi!", sampleType.element); } @Test public void testReadNull() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; String json = "null"; SampleRootElement sampleRootElement = (SampleRootElement)provider.read(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertNull(sampleRootElement); } @Test public void testReadNullWithVirtualRoot() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; String json = "null"; SampleRootElement sampleRootElement = (SampleRootElement)provider.read(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertNotNull(sampleRootElement); }
JsonXMLObjectProvider extends AbstractJsonXMLProvider { @Override public void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value) throws IOException, WebApplicationException { JsonXML config = getJsonXML(type, annotations); try { writeObject(type, config, getContext(type, mediaType), stream, value); } catch (XMLStreamException | JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } JsonXMLObjectProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value); }
@Test public void testWriteSampleRootElement() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; SampleRootElement sampleRootElement = new SampleRootElement(); sampleRootElement.attribute = "hello"; sampleRootElement.elements = Arrays.asList("world"); StringWriter writer = new StringWriter(); provider.write(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, sampleRootElement); String json = "{\"sampleRootElement\":{\"@attribute\":\"hello\",\"elements\":[\"world\"]}}"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteSampleType() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; SampleType sampleType = new SampleType(); sampleType.element = "hi!"; StringWriter writer = new StringWriter(); provider.write(SampleType.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, sampleType); String json = "{\"sampleType\":{\"element\":\"hi!\"}}"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteNull() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; StringWriter writer = new StringWriter(); provider.write(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, null); String json = "null"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteNullWithVirtualRoot() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; StringWriter writer = new StringWriter(); provider.write(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, null); String json = "null"; Assert.assertEquals(json, writer.toString()); }
WebhookAPI { @GET @Produces(MediaType.APPLICATION_JSON) public static Response get() { return Responses.ok(Webhooks.instance().hooks()); } @GET @Produces(MediaType.APPLICATION_JSON) static Response get(); @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) static Response get(@PathParam("id") long id); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response create( @Context UriInfo uriInfo, InputStream reqBody); @PATCH @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response update( @PathParam("id") long id, InputStream reqBody); @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response delete(@PathParam("id") long id); @POST @Path("/{id}/pings") @Consumes(MediaType.APPLICATION_JSON) static Response ping(@PathParam("id") long id); }
@Test public void _3_get1() throws Exception { Response res = target("").path("1").request() .get(); assertEquals(200, res.getStatus()); assertEquals( "{\"active\":false,\"callback_url\":\"" + CALLBACK_URL + "\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":1,\"message\":null}", res.readEntity(String.class)); } @Test public void _8_get_not_found() throws Exception { Response res = target("").path("1").request() .get(); assertEquals(404, res.getStatus()); } @Test public void _9_getAll() throws Exception { String body2 = "{\"callback_url\": \"" + CALLBACK_URL + "/2\"}"; String body3 = "{\"callback_url\": \"" + CALLBACK_URL + "/3\"}"; String body4 = "{\"callback_url\": \"" + CALLBACK_URL + "/4\"}"; target("").request().post(Entity.entity(body2, MediaType.APPLICATION_JSON_TYPE)); target("").request().post(Entity.entity(body3, MediaType.APPLICATION_JSON_TYPE)); target("").request().post(Entity.entity(body4, MediaType.APPLICATION_JSON_TYPE)); Response res = target("").request().get(); assertEquals(200, res.getStatus()); assertEquals("[" + "{\"active\":true,\"callback_url\":\"" + CALLBACK_URL + "/2\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":2,\"message\":null}," + "{\"active\":true,\"callback_url\":\"" + CALLBACK_URL + "/3\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":3,\"message\":null}," + "{\"active\":true,\"callback_url\":\"" + CALLBACK_URL + "/4\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":4,\"message\":null}" + "]", res.readEntity(String.class)); }
WebhookAPI { @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public static Response delete(@PathParam("id") long id) throws NotFound { boolean removed = Webhooks.instance().remove(id); if (removed) { return Responses.noContent(); } else { return Responses.badRequest(); } } @GET @Produces(MediaType.APPLICATION_JSON) static Response get(); @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) static Response get(@PathParam("id") long id); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response create( @Context UriInfo uriInfo, InputStream reqBody); @PATCH @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response update( @PathParam("id") long id, InputStream reqBody); @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response delete(@PathParam("id") long id); @POST @Path("/{id}/pings") @Consumes(MediaType.APPLICATION_JSON) static Response ping(@PathParam("id") long id); }
@Test public void _7_delete() throws Exception { Response res = target("").path("1").request() .delete(); assertEquals(204, res.getStatus()); }
Notifier implements ServletContextListener { public static URL getDtoChangesUri(TransactionId.W tx, DateTime time) throws IOException { NotifierConfig conf = NotifierConfig.instance(); String urlStr = new Formatter().format( "http: conf.naefAddr(), conf.naefRestApiPort(), conf.naefRestApiVersion()) .toString(); StringJoiner queries = new StringJoiner("&"); if (tx != null) { queries.add("version=" + tx.toString()); } if (time != null) { queries.add("time=" + time.getValue()); } if (queries.length() > 0) { urlStr += "?" + queries.toString(); } return new URL(urlStr); } Notifier(); static synchronized void start(); static void main(String[] args); @Override void contextInitialized(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce); static URL getDtoChangesUri(TransactionId.W tx, DateTime time); static Map<String, Object> getDtoChangesJson(TransactionId.W tx, DateTime time); static final String KEY_ROOT_DIR; static final String DEFAULT_ROOT_DIR_NAME; static final String BASE_DIR; }
@Test public void DtoChangesURLを生成() throws Exception { URL url = Notifier.getDtoChangesUri(tx, time); assertEquals( "http: url.toString()); }
NameUtilities { public static String getFullName(Class c) { if (c == null) { throw new IllegalArgumentException("class cannot be null"); } StringBuilder name = new StringBuilder(); name.append(c.getPackage().getName()).append("."); Class klaus = c; List<Class> enclosingClasses = new ArrayList<Class>(); while ((klaus = klaus.getEnclosingClass()) != null) { enclosingClasses.add(klaus); } for (int i = enclosingClasses.size() - 1; i >= 0; i--) { name.append(enclosingClasses.get(i).getSimpleName()).append("."); } name.append(c.getSimpleName()); return name.toString(); } static String getFullName(Class c); }
@Test public void testInnerClassNaming() { String expected = NameUtilitiesTest.class.getPackage().getName()+"." + NameUtilitiesTest.class.getSimpleName()+"." + "Inner" ; String name = NameUtilities.getFullName(Inner.class); Assert.assertEquals(expected, name); }
ElementTransformVirtualPredicates extends ElementTransformCopyBase { @Override public Element transform(ElementTriplesBlock el) { Element result = applyTransform(el, virtualPredicates, varGen); return result; } ElementTransformVirtualPredicates(); ElementTransformVirtualPredicates(Map<Node, BinaryRelation> virtualPredicates); ElementTransformVirtualPredicates(Map<Node, BinaryRelation> virtualPredicates, Generator<Var> varGen); @Override Element transform(ElementTriplesBlock el); @Override Element transform(ElementPathBlock el); static Element applyTransform(ElementTriplesBlock el, Map<Node, BinaryRelation> virtualPredicates, Generator<Var> rootVarGen); static Element applyTransform(ElementPathBlock el, Map<Node, BinaryRelation> virtualPredicates, Generator<Var> rootVarGen); static Element applyTransform(Triple triple, Map<Node, BinaryRelation> virtualPredicates, Generator<Var> varGen); static Element createElementForVariablePredicate(Var pVar, Node s, Node o, Map<Node, BinaryRelation> virtualPredicates, Generator<Var> varGen); static Element createElementForConcretePredicate(Var pVar, Node pRef, Node s, Node o, BinaryRelation relation, Generator<Var> varGen); static Query transform(Query query, Map<Node, BinaryRelation> virtualPredicates, boolean cloneOnChange); static Element transform(Element element, Map<Node, BinaryRelation> virtualPredicates); }
@Test public void test() { Prologue prologue = new Prologue(); prologue.setPrefixMapping(PrefixMapping.Extended); Model model = RDFDataMgr.loadModel("virtual-predicates-example.ttl"); RDFDataMgr.write(System.out, model, RDFFormat.TURTLE_PRETTY); Map<Node, BinaryRelation> virtualPredicates = new HashMap<Node, BinaryRelation>(); virtualPredicates.put(NodeFactory.createURI("http: BinaryRelationImpl.create("?s a eg:Person ; eg:birthDate ?start . " + "BIND(NOW() AS ?end) " + "BIND(YEAR(?end) - YEAR(?start) - IF(MONTH(?end) < MONTH(?start) || (MONTH(?end) = MONTH(?start) && DAY(?end) < DAY(?start)), 1, 0) as ?age)", "s", "age", prologue)); SparqlQueryParser parser = SparqlQueryParserImpl.create(Syntax.syntaxARQ, prologue); List<Query> queries = Arrays.asList( parser.apply("Select (year(NOW()) - year('1984-01-01'^^xsd:date) AS ?d) { }"), parser.apply("Select * { ?s ?p ?o }"), parser.apply("Select * { ?s eg:age ?o }"), parser.apply("Select * { ?s a eg:Person ; eg:age ?a }"), parser.apply("Select * { ?s a eg:Person ; ?p ?o . FILTER(?p = eg:age) }") ); for(Query query : queries) { if(query.isQueryResultStar()) { query.getProjectVars().addAll(query.getResultVars().stream().map(Var::alloc).collect(Collectors.toList())); query.setQueryResultStar(false); System.out.println(query); } Query intermediateQuery = ElementTransformVirtualPredicates.transform(query, virtualPredicates, true); Op op = Algebra.compile(intermediateQuery); Context ctx = ARQ.getContext().copy(); ctx.set(ARQ.optFilterEquality, false); ctx.put(ARQ.optFilterPlacement, true); ctx.put(ARQ.optFilterPlacementBGP, true); System.out.println(op); Query finalQuery = OpAsQuery.asQuery(op); System.out.println("Rewritten query: " + finalQuery); System.out.println(ResultSetFormatter.asText( FluentQueryExecutionFactory .from(model).create().createQueryExecution(finalQuery).execSelect())); } virtualPredicates.put(NodeFactory.createURI(RDFS.label.getURI()), BinaryRelationImpl.create("?s <skos:label> [ <skos:value> ?l]", "s", "l")); }
SparqlQcReader { public static List<Resource> loadTasks(String baseFile) throws IOException { List<Resource> testSuites = loadTestSuites(baseFile); List<Resource> testCases = extractTasks(testSuites); return testCases; } static List<Resource> loadTestSuitesSqcf(String baseFile); static List<Resource> extractTasks(Collection<Resource> testSuites); static List<Resource> loadTasksSqcf(String baseFile); static void renameProperty(Model model, Property p, String uri); static void normalizeSqcfModel(Model testSuitesModel); static List<Resource> loadTestSuites(String baseFile); static List<Resource> loadTestSuites(Model testSuitesModel, String baseFile); static List<Resource> loadTasks(String baseFile); static void enrichTestCasesWithLabels(Model model); static RDFNode resolveIoResourceRef(Resource testCase, Property property, // String basePath, Map<String, RDFNode> cache, BiFunction<String, Model, RDFNode> rdfizer); static void loadTestSuite(Resource testSuite, String basePath); static Resource processQueryRecordUnchecked( org.springframework.core.io.Resource resource, Model inout); static Long parseSchemaId(String ref); static Resource parseQueryId(String ref); static String createQueryResourceIri(String baseIri, Resource qr); static Resource createSchemaResource(Long id); static Resource processSchemaUnchecked( org.springframework.core.io.Resource resource, Model inout); static Resource processSchema(org.springframework.core.io.Resource resource, Model inout); static Resource processQueryRecord(org.springframework.core.io.Resource resource, Model inout); @Deprecated static Model readQueryFolder(String path); static final Property LSQtext; static final Pattern queryNamePattern; static final Pattern schemaNamePattern; }
@Test public void testReadSchema() throws IOException { List<Resource> tasks = SparqlQcReader.loadTasks("sparqlqc/1.4/benchmark/ucqrdfs.rdf"); for(Resource task : tasks) { RDFDataMgr.write(System.out, task.getModel(), RDFFormat.TURTLE); } }
SparqlStmtUtils { public static SparqlStmt optimizePrefixes(SparqlStmt stmt) { optimizePrefixes(stmt, null); return stmt; } static Map<String, Boolean> mentionedEnvVars(SparqlStmt stmt); static List<Var> getUnionProjectVars(Collection<? extends SparqlStmt> stmts); static SparqlStmt optimizePrefixes(SparqlStmt stmt); static SparqlStmt optimizePrefixes(SparqlStmt stmt, PrefixMapping globalPm); static SparqlStmt applyOpTransform(SparqlStmt stmt, Function<? super Op, ? extends Op> transform); static SparqlStmt applyNodeTransform(SparqlStmt stmt, NodeTransform xform); static SparqlStmtIterator processFile(PrefixMapping pm, String filenameOrURI); static URI extractBaseIri(String filenameOrURI); static String loadString(String filenameOrURI); static TypedInputStream openInputStream(String filenameOrURI); static SparqlStmtIterator processFile(PrefixMapping pm, String filenameOrURI, String baseIri); static SparqlStmtIterator processInputStream(PrefixMapping pm, String baseIri, InputStream in); static SparqlStmtIterator parse(InputStream in, Function<String, SparqlStmt> parser); static SPARQLResultEx execAny(RDFConnection conn, SparqlStmt stmt); static Sink<Quad> createSinkQuads(RDFFormat format, OutputStream out, PrefixMapping pm, Supplier<Dataset> datasetSupp); static void output( SPARQLResultEx rr, SPARQLResultVisitor sink); static void output( SPARQLResultEx rr, Consumer<Quad> sink ); static void output(SPARQLResultEx r); static void process(RDFConnection conn, SparqlStmt stmt, SPARQLResultVisitor sink); static void processOld(RDFConnection conn, SparqlStmt stmt); static Op toAlgebra(SparqlStmt stmt); static final Symbol symConnection; }
@Test public void testUsedPrefixes1() { PrefixMapping pm = RDFDataMgr.loadModel("rdf-prefixes/wikidata.jsonld"); String queryStr = "SELECT ?s ?desc WHERE {\n" + " ?s wdt:P279 wd:Q7725634 .\n" + " OPTIONAL {\n" + " ?s rdfs:label ?desc \n" + " FILTER (LANG(?desc) = \"en\").\n" + " }\n" + "}"; SparqlStmt stmt = SparqlStmtParserImpl.create(pm).apply(queryStr); SparqlStmtUtils.optimizePrefixes(stmt); Query query = stmt.getQuery(); Set<String> actual = query.getPrefixMapping().getNsPrefixMap().keySet(); Assert.assertEquals(Sets.newHashSet("rdfs", "wd", "wdt"), actual); } @Test public void testUsedPrefixes2() { PrefixMapping pm = RDFDataMgr.loadModel("rdf-prefixes/wikidata.jsonld"); String queryStr = "INSERT {" + " ?s wdt:P279 wd:Q7725634 .\n" + "}\n" + " WHERE {\n" + " ?s rdfs:label ?desc \n" + " FILTER (LANG(?desc) = \"en\").\n" + " }\n"; SparqlStmt stmt = SparqlStmtParserImpl.create(pm).apply(queryStr); SparqlStmtUtils.optimizePrefixes(stmt); UpdateRequest updateRequest = stmt.getUpdateRequest(); Set<String> actual = updateRequest.getPrefixMapping().getNsPrefixMap().keySet(); Assert.assertEquals(Sets.newHashSet("rdfs", "wd", "wdt"), actual); }
UriUtils { public static String replaceNamespace(String base, String replacement) { Matcher m = replaceNamespacePattern.matcher(base); String result = m.replaceAll(replacement); return result; } static Map<String, String> createMapFromUriQueryString(URI uri); static String getNameSpace(String s); static String getLocalName(String s); static String replaceNamespace(String base, String replacement); static Multimap<String, String> parseQueryString(String queryString); static Multimap<String, String> parseQueryStringEx(String queryString); static final Pattern replaceNamespacePattern; }
@Test public void test() { String r = UriUtils.replaceNamespace("http: Assert.assertEquals("http: }
QueryUtils { public static PrefixMapping usedPrefixes(Query query, PrefixMapping global) { PrefixMapping local = query.getPrefixMapping(); PrefixMapping pm = global == null ? local : new PrefixMapping2(global, local); PrefixMapping result = usedReferencePrefixes(query, pm); return result; } static Query applyOpTransform(Query beforeQuery, Function<? super Op, ? extends Op> transform); static Query restoreQueryForm(Query query, Query proto); static Query selectToConstruct(Query query, Template template); static Query rewrite(Query beforeQuery, Function<? super Op, ? extends Op> xform); static Element asPatternForConstruct(Query q); static boolean canActAsConstruct(Query q); static Set<Var> mentionedVars(Query query); static Set<Node> mentionedNodes(Query query); static Var freshVar(Query query); static Var freshVar(Query query, String baseVarName); static Map<String, Node> applyNodeTransform(Map<String, Node> jsonMapping, NodeTransform nodeTransform); static Query applyNodeTransform(Query query, NodeTransform nodeTransform); static PrefixMapping usedPrefixes(Query query, PrefixMapping global); static PrefixMapping usedPrefixes(Query query); static PrefixMapping usedReferencePrefixes(Query query, PrefixMapping pm); static Query optimizePrefixes(Query query, PrefixMapping globalPm); static Query optimizePrefixes(Query query); static Query randomizeVars(Query query); static Map<Var, Var> createRandomVarMap(Query query, String base); static void injectFilter(Query query, String exprStr); static void injectFilter(Query query, Expr expr); static void injectElement(Query query, Element element); static Range<Long> toRange(OpSlice op); static Op applyRange(Op op, Range<Long> range); static Query applySlice(Query query, Long offset, Long limit, boolean cloneOnChange); static void applyRange(Query query, Range<Long> range); static Range<Long> createRange(Long limit, Long offset); static long rangeToOffset(Range<Long> range); static long rangeToLimit(Range<Long> range); static Range<Long> toRange(Query query); static Range<Long> toRange(Long offset, Long limit); static Range<Long> subRange(Range<Long> parent, Range<Long> child); static void applyDatasetDescription(Query query, DatasetDescription dd); static Query fixVarNames(Query query); static Query elementToQuery(Element pattern, String resultVar); static Query elementToQuery(Element pattern); static Set<Quad> instanciate(Iterable<Quad> quads, Binding binding); }
@Test public void testReducedPrefixes() { Query query = QueryFactory.create(String.join("\n", "PREFIX rdf: <http: "PREFIX foo: <http: "PREFIX bar: <http: "PREFIX baz: <http: "SELECT * {", " { SELECT * {", " ?s a foo:Foo.", " } }", " ?s rdf:type foo:Bar", "}")); PrefixMapping pm = org.aksw.jena_sparql_api.utils.QueryUtils.usedPrefixes(query); Assert.assertEquals(pm.getNsPrefixMap().keySet(), new HashSet<>(Arrays.asList("rdf", "foo"))); }
JSONReader { public Attributes readDataset(Attributes attrs) { boolean wrappedInArray = next() == Event.START_ARRAY; if (wrappedInArray) next(); expect(Event.START_OBJECT); if (attrs == null) { attrs = new Attributes(); } fmi = null; next(); doReadDataset(attrs); if (wrappedInArray) next(); return attrs; } JSONReader(JsonParser parser); boolean isSkipBulkDataURI(); void setSkipBulkDataURI(boolean skipBulkDataURI); Attributes getFileMetaInformation(); Attributes readDataset(Attributes attrs); void readDatasets(Callback callback); }
@Test public void test() { StringReader reader = new StringReader(JSON); JsonParser parser = Json.createParser(reader); Attributes dataset = new JSONReader(parser).readDataset(null); assertArrayEquals(IS, dataset.getStrings(Tag.SelectorISValue)); assertArrayEquals(DS, dataset.getStrings(Tag.SelectorDSValue)); assertInfinityAndNaN(dataset.getDoubles(Tag.SelectorFDValue)); assertInfinityAndNaN(dataset.getFloats(Tag.SelectorFLValue)); }
ByteUtils { public static byte[] tagToBytesLE(int i, byte[] bytes, int off) { bytes[off + 1] = (byte) (i >> 24); bytes[off] = (byte) (i >> 16); bytes[off + 3] = (byte) (i >> 8); bytes[off + 2] = (byte) i; return bytes; } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }
@Test public void testTagToBytesLE() { assertArrayEquals(TAG_PIXEL_DATA_LE, ByteUtils.tagToBytesLE(Tag.PixelData, new byte[4] , 0)); }