method2testcases
stringlengths
118
6.63k
### Question: Crosshair implements Serializable { public StrokeType getStyle() { return this.style; } Crosshair setStyle(StrokeType style); StrokeType getStyle(); Crosshair setWidth(float width); Float getWidth(); Crosshair setColor(Object color); Color getColor(); @Override Object clone(); }### Answer: @Test public void createCrosshairByEmptyConstructor_hasStrokeTypeIsNull() { Crosshair crosshair = new Crosshair(); Assertions.assertThat(crosshair.getStyle()).isNull(); }
### Question: Area extends BasedXYGraphics { public Integer getInterpolation() { return this.interpolation; } void setInterpolation(Integer interpolation); Integer getInterpolation(); }### Answer: @Test public void createAreaByEmptyConstructor_hasInterpolationIsNull() { Area area = new Area(); Assertions.assertThat(area.getInterpolation()).isNull(); }
### Question: Area extends BasedXYGraphics { public void setInterpolation(Integer interpolation) { if (interpolation.intValue() < 0 || interpolation.intValue() > 1) { throw new IllegalArgumentException( "Area interpolation is limited to 0, 1"); } this.interpolation = interpolation; } void setInterpolation(Integer interpolation); Integer getInterpolation(); }### Answer: @Test(expected = IllegalArgumentException.class) public void setInterpolationWithPositive2_throwIllegalArgumentException() { Area area = new Area(); area.setInterpolation(new Integer(-2)); } @Test(expected = IllegalArgumentException.class) public void setInterpolationWithNegative2_throwIllegalArgumentException() { Area area = new Area(); area.setInterpolation(new Integer(2)); }
### Question: Text implements Serializable, Cloneable { public int getSize() { return size; } Number getX(); void setX(Object x); Number getY(); void setY(Number y); Boolean getShowPointer(); void setShowPointer(boolean showPointer); String getText(); void setText(String text); Double getPointerAngle(); void setPointerAngle(Double pointerAngle); Color getColor(); void setColor(Color color); int getSize(); void setSize(int size); Class getPlotType(); void setPlotType(Class plotType); @Override Object clone(); }### Answer: @Test public void createTextByEmptyConstructor_hasSizeValueGreaterThanZero() { Text text = new Text(); Assertions.assertThat(text.getSize()).isGreaterThan(0); }
### Question: Stems extends BasedXYGraphics { public void setStyle(Object style) { if (style instanceof StrokeType) { this.baseStyle = (StrokeType) style; } else if (style instanceof List) { @SuppressWarnings("unchecked") List<StrokeType> ss = (List<StrokeType>) style; setStyles(ss); } else { throw new IllegalArgumentException( "setStyle takes ShapeType or List of ShapeType"); } } void setWidth(Float width); Float getWidth(); void setStyle(Object style); StrokeType getStyle(); List<StrokeType> getStyles(); }### Answer: @Test(expected = IllegalArgumentException.class) public void setStyleWithShapeTypeParam_throwIllegalArgumentException() { Stems stems = new Stems(); stems.setStyle(ShapeType.DEFAULT); }
### Question: Line extends XYGraphics { public StrokeType getStyle() { return this.style; } Line(); Line(List<Number> ys); Line(List<Object> xs, List<Number> ys); void setWidth(Float width); Float getWidth(); void setStyle(StrokeType style); StrokeType getStyle(); void setInterpolation(Integer interpolation); Integer getInterpolation(); }### Answer: @Test public void createLineByEmptyConstructor_lineHasStyleIsNull() { Line line = new Line(); Assertions.assertThat(line.getStyle()).isNull(); }
### Question: TimePlot extends XYChart implements InternalCommWidget, InternalPlot { public XYChart setXBound(Date lower, Date upper) { setXBound((double) lower.getTime(), (double) upper.getTime()); return this; } TimePlot(); @Override String getModelNameValue(); @Override String getViewNameValue(); @Override Comm getComm(); @Override void close(); XYChart setXBound(Date lower, Date upper); @Override XYChart setXBound(List bound); }### Answer: @Test public void setXBoundWithTwoDatesParams_shouldSetXBoundParams() { TimePlot timePlot = new TimePlot(); timePlot.setXBound(lowerBound, upperBound); Assertions.assertThat(timePlot.getXLowerBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXUpperBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXAutoRange()).isFalse(); } @Test public void setXBoundWithListParam_shouldSetXBoundParams() { TimePlot timePlot = new TimePlot(); timePlot.setXBound(Arrays.asList(lowerBound, upperBound)); Assertions.assertThat(timePlot.getXLowerBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXUpperBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXAutoRange()).isFalse(); }
### Question: Histogram extends AbstractChart implements InternalCommWidget, InternalPlot { public DisplayMode getDisplayMode() { return displayMode; } Histogram(); @Override String getModelNameValue(); @Override String getViewNameValue(); @Override Comm getComm(); @Override void close(); Integer getRangeMin(); void setRangeMin(Integer rangeMin); Integer getRangeMax(); void setRangeMax(Integer rangeMax); int getBinCount(); void setBinCount(int binCount); boolean getRightClose(); void setRightClose(boolean rightClose); boolean getCumulative(); void setCumulative(boolean cumulative); boolean getNormed(); void setNormed(boolean normed); DisplayMode getDisplayMode(); void setDisplayMode(DisplayMode displayMode); boolean getLog(); void setLog(boolean log); @SuppressWarnings("unchecked") void setColor(Object color); List<Color> getColors(); Color getColor(); @SuppressWarnings("unchecked") void setData(Object data); List<Number> getData(); List<List<Number>> getListData(); List<String> getNames(); void setNames(List<String> names); }### Answer: @Test public void createHistogramByEmptyConstructor_hasDisplayModeIsNotNull() { Histogram histogram = new Histogram(); Assertions.assertThat(histogram.getDisplayMode()).isNotNull(); }
### Question: GradientColorProvider extends ColorProvider { @Override public Color getColor(TreeMapNode node) { double value = getValue(node); float result = (float) ((value - minValue) / (maxValue - minValue)); return ColorUtils.interpolateColor(start, end, result); } GradientColorProvider(TreeMap treeMap, Color start, Color end); GradientColorProvider(TreeMap treeMap); @Override Color getColor(TreeMapNode node); }### Answer: @Test public void createProviderWithTreeMapParam_getColorWithNodeReturnBeakerColorWithRGB() { GradientColorProvider gradientColorProvider = new GradientColorProvider(treeMap); Assertions.assertThat(gradientColorProvider.getColor(treeMap.getRoot()).getRGB()).isNotZero(); Assertions.assertThat(gradientColorProvider.getColor(node01).getRGB()).isNotZero(); } @Test public void createProviderWithTreeMapAndTwoColorsParams_getColorWithNodeReturnBeakerColorWithRGB() { GradientColorProvider gradientColorProvider = new GradientColorProvider(treeMap, Color.BLUE, Color.GREEN); Assertions.assertThat(gradientColorProvider.getColor(treeMap.getRoot()).getRGB()).isNotZero(); Assertions.assertThat(gradientColorProvider.getColor(node01).getRGB()).isNotZero(); }
### Question: RandomColorProvider extends ColorProvider { @Override public Color getColor(TreeMapNode node) { Object value; if (groupByParent && node.getParent() instanceof TreeMapNode){ value = ((TreeMapNode) node.getParent()).getLabel(); }else{ value = getValue(node); } if (!this.mapping.containsKey(value)) { mapping.put(value, colours[this.cursor]); cursor++; if (this.cursor == colours.length) { cursor = 0; } } return mapping.get(value); } RandomColorProvider(); RandomColorProvider(final Color[] colours); RandomColorProvider(List<Object> colors); @Override Color getColor(TreeMapNode node); boolean isGroupByParent(); void setGroupByParent(boolean groupByParent); }### Answer: @Test public void createProviderWithEmptyConstructor_getColorWithNodeReturnBeakerColorWithRGB() { RandomColorProvider randomColorProvider = new RandomColorProvider(); Assertions.assertThat(randomColorProvider.getColor(node01).getRGB()).isNotZero(); Assertions.assertThat(randomColorProvider.getColor(node02).getRGB()).isNotZero(); } @Test public void createProviderWithColorArrayParam_getColorWithNodeReturnBeakerColorWithRGB() { RandomColorProvider randomColorProvider = new RandomColorProvider(new Color[] {Color.BLUE, Color.GREEN}); Assertions.assertThat(randomColorProvider.getColor(node01).getRGB()).isNotZero(); Assertions.assertThat(randomColorProvider.getColor(node02).getRGB()).isNotZero(); }
### Question: ColorUtils { public static Color interpolateColor(final java.awt.Color COLOR1, final java.awt.Color COLOR2, float fraction) { final float INT_TO_FLOAT_CONST = 1f / 255f; fraction = Math.min(fraction, 1f); fraction = Math.max(fraction, 0f); final float RED1 = COLOR1.getRed() * INT_TO_FLOAT_CONST; final float GREEN1 = COLOR1.getGreen() * INT_TO_FLOAT_CONST; final float BLUE1 = COLOR1.getBlue() * INT_TO_FLOAT_CONST; final float ALPHA1 = COLOR1.getAlpha() * INT_TO_FLOAT_CONST; final float RED2 = COLOR2.getRed() * INT_TO_FLOAT_CONST; final float GREEN2 = COLOR2.getGreen() * INT_TO_FLOAT_CONST; final float BLUE2 = COLOR2.getBlue() * INT_TO_FLOAT_CONST; final float ALPHA2 = COLOR2.getAlpha() * INT_TO_FLOAT_CONST; final float DELTA_RED = RED2 - RED1; final float DELTA_GREEN = GREEN2 - GREEN1; final float DELTA_BLUE = BLUE2 - BLUE1; final float DELTA_ALPHA = ALPHA2 - ALPHA1; float red = RED1 + (DELTA_RED * fraction); float green = GREEN1 + (DELTA_GREEN * fraction); float blue = BLUE1 + (DELTA_BLUE * fraction); float alpha = ALPHA1 + (DELTA_ALPHA * fraction); red = Math.min(red, 1f); red = Math.max(red, 0f); green = Math.min(green, 1f); green = Math.max(green, 0f); blue = Math.min(blue, 1f); blue = Math.max(blue, 0f); alpha = Math.min(alpha, 1f); alpha = Math.max(alpha, 0f); return new Color((new java.awt.Color(red, green, blue, alpha)).getRGB()); } static Color interpolateColor(final java.awt.Color COLOR1, final java.awt.Color COLOR2, float fraction); }### Answer: @Test public void callInterpolateColorWithGreenBlueColors_returnBeakerColorWithRGB() { Color color = ColorUtils.interpolateColor(java.awt.Color.GREEN, java.awt.Color.BLUE, 0.1f); Assertions.assertThat(color.getRGB()).isNotZero(); } @Test public void callInterpolateColorWithGreenBlueColorsAndFractionIsZero_returnBeakerColorWithGreenValue() { Color color = ColorUtils.interpolateColor(java.awt.Color.GREEN, java.awt.Color.BLUE, 0f); Assertions.assertThat(color).isEqualTo(Color.GREEN); } @Test public void callInterpolateColorWithGreenBlueColorsAndFractionIsOne_returnBeakerColorWithBlueValue() { Color color = ColorUtils.interpolateColor(java.awt.Color.GREEN, java.awt.Color.BLUE, 1f); Assertions.assertThat(color).isEqualTo(Color.BLUE); }
### Question: RadioButtons extends SingleSelectionWidget { public RadioButtons() { super(); openComm(); } RadioButtons(); @Override String getModelNameValue(); @Override String getViewNameValue(); static String VIEW_NAME_VALUE; static String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { RadioButtons widget = radioButtons(); widget.setValue("1"); verifyMsgForProperty(groovyKernel, RadioButtons.VALUE, "1"); } @Test public void shouldSendCommMsgWhenOptionsChange() throws Exception { RadioButtons widget = radioButtons(); widget.setOptions(new String[]{"2", "3"}); verifyMsgForProperty(groovyKernel, RadioButtons.OPTIONS_LABELS, new String[]{"2", "3"}); }
### Question: Select extends SingleSelectionWidget { public Select() { super(); openComm(); } Select(); @Override String getModelNameValue(); @Override String getViewNameValue(); static String VIEW_NAME_VALUE; static String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { Select widget = select(); widget.setValue("1"); verifyMsgForProperty(groovyKernel, Select.VALUE, "1"); } @Test public void shouldSendCommMsgWhenOptionsChange() throws Exception { Select widget = select(); widget.setOptions(new String[]{"2", "3"}); verifyMsgForProperty(groovyKernel, RadioButtons.OPTIONS_LABELS, new String[]{"2", "3"}); }
### Question: Dropdown extends SingleSelectionWidget { public Dropdown() { super(); openComm(); } Dropdown(); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { Dropdown dropdown = dropdown(); dropdown.setValue("1"); verifyMsgForProperty(groovyKernel, Dropdown.VALUE, "1"); } @Test public void shouldSendCommMsgWhenOptionsChange() throws Exception { Dropdown dropdown = dropdown(); dropdown.setOptions(new String[]{"2", "3"}); verifyMsgForProperty(groovyKernel, Dropdown.OPTIONS_LABELS, new String[]{"2", "3"}); }
### Question: SelectMultipleSingle extends SingleSelectionWidget { public SelectMultipleSingle() { super(); openComm(); } SelectMultipleSingle(); @Override String getModelNameValue(); @Override String getViewNameValue(); static String VIEW_NAME_VALUE; static String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { SelectMultipleSingle widget = selectMultipleSingle(); widget.setOptions(new String[]{"1","2", "3"}); kernel.clearPublishedMessages(); widget.setValue("2"); verifyMsgForProperty(kernel, SelectMultiple.VALUE, "2"); } @Test public void shouldSendCommMsgWhenOptionsChange() throws Exception { SelectMultipleSingle widget = selectMultipleSingle(); widget.setOptions(new String[]{"2", "3"}); verifyMsgForProperty(kernel, SelectMultiple.OPTIONS_LABELS, new String[]{"2", "3"}); }
### Question: DatePicker extends ValueWidget<String> { public void setShowTime(final Boolean showTime) { this.showTime = showTime; sendUpdate(SHOW_TIME, showTime); } DatePicker(); @Override void updateValue(Object value); @Override String getValueFromObject(Object input); @Override String getModelNameValue(); @Override String getViewNameValue(); void setShowTime(final Boolean showTime); Boolean getShowTime(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; static final String SHOW_TIME; }### Answer: @Test public void shouldSendCommMsgWhenShowTimeChange() throws Exception { DatePicker widget = widget(); widget.setShowTime(true); verifyMsgForProperty(groovyKernel, DatePicker.SHOW_TIME, true); }
### Question: ColorPicker extends ValueWidget<String> { public ColorPicker() { super(); openComm(); } ColorPicker(); @Override String getValueFromObject(Object input); Boolean getConcise(); void setConcise(Boolean concise); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; static final String CONCISE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { ColorPicker widget = colorPicker(); widget.setValue("red"); TestWidgetUtils.verifyMsgForProperty(groovyKernel, ColorPicker.VALUE, "red"); }
### Question: Checkbox extends BoolWidget { public Checkbox() { super(); openComm(); } Checkbox(); @Override String getModelNameValue(); @Override String getViewNameValue(); static String VIEW_NAME_VALUE; static String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { Checkbox widget = checkbox(); widget.setValue(true); verifyMsgForProperty(groovyKernel, Checkbox.VALUE, true); }
### Question: ToggleButton extends BoolWidget { public ToggleButton() { super(); openComm(); } ToggleButton(); String getTooltip(); void setTooltip(String tooltip); @Override String getModelNameValue(); @Override String getViewNameValue(); static String VIEW_NAME_VALUE; static String MODEL_NAME_VALUE; static final String TOOLTIP; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { ToggleButton widget = toggleButton(); widget.setValue(true); verifyMsgForProperty(groovyKernel, ToggleButton.VALUE, true); }
### Question: HTML extends StringWidget { public HTML() { super(); openComm(); } HTML(); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { HTML widget = html(); widget.setValue("Hello <b>World</b>"); verifyMsgForProperty(groovyKernel, HTML.VALUE, "Hello <b>World</b>"); }
### Question: Label extends StringWidget { public Label() { super(); openComm(); } Label(); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { Label widget = label(); widget.setValue("1"); verifyMsgForProperty(groovyKernel, Label.VALUE, "1"); }
### Question: Textarea extends StringWidget { public Textarea() { super(); openComm(); } Textarea(); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { Textarea widget = textarea(); widget.setValue("Text area 1"); verifyMsgForProperty(groovyKernel, Textarea.VALUE, "Text area 1"); }
### Question: Text extends StringWidget { public Text() { super(); openComm(); } Text(); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { Text widget = text(); widget.setValue("1"); verifyMsgForProperty(groovyKernel, Text.VALUE, "1"); }
### Question: FloatSlider extends BoundedFloatWidget { public FloatSlider() { super(); openComm(); } FloatSlider(); String getOrientation(); void setOrientation(String orientation); String getSlider_color(); void setSlider_color(String slider_color); Boolean getReadOut(); void setReadOut(Object readOut); Boolean getContinuous_update(); void setContinuous_update(Boolean continuous_update); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setValue(11.1); verifyMsgForProperty(groovyKernel, FloatSlider.VALUE, 11.1); } @Test public void shouldSendCommMsgWhenStepChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setStep(12.1); verifyMsgForProperty(groovyKernel, BoundedFloatWidget.STEP, 12.1); } @Test public void shouldSendCommMsgWhenMaxChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setMax(122.3); verifyMsgForProperty(groovyKernel, BoundedFloatWidget.MAX, 122.3); } @Test public void shouldSendCommMsgWhenMinChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setMin(10.2); verifyMsgForProperty(groovyKernel, BoundedFloatWidget.MIN, 10.2); }
### Question: IntSlider extends BoundedIntWidget { public IntSlider() { super(); openComm(); } IntSlider(); String getOrientation(); void setOrientation(String orientation); String getSlider_color(); void setSlider_color(String slider_color); Boolean getReadOut(); void setReadOut(Object readOut); Boolean getContinuous_update(); void setContinuous_update(Boolean continuous_update); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }### Answer: @Test public void shouldSendCommMsgWhenValueChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setValue(11); verifyMsgForProperty(groovyKernel, IntSlider.VALUE, 11); } @Test public void shouldSendCommMsgWhenDisableChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setDisabled(true); verifyMsgForProperty(groovyKernel, Widget.DISABLED, true); } @Test public void shouldSendCommMsgWhenVisibleChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setVisible(false); verifyMsgForProperty(groovyKernel, Widget.VISIBLE, false); } @Test public void shouldSendCommMsgWhenDescriptionChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setDescription("Description 2"); verifyMsgForProperty(groovyKernel, Widget.DESCRIPTION, "Description 2"); } @Test public void shouldSendCommMsgWhenMsg_throttleChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setMsg_throttle(12); verifyMsgForProperty(groovyKernel, Widget.MSG_THROTTLE, 12); } @Test public void shouldSendCommMsgWhenStepChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setStep(12); verifyMsgForProperty(groovyKernel, BoundedIntWidget.STEP, 12); } @Test public void shouldSendCommMsgWhenMaxChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setMax(122); verifyMsgForProperty(groovyKernel, BoundedIntWidget.MAX, 122); } @Test public void shouldSendCommMsgWhenMinChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setMin(10); verifyMsgForProperty(groovyKernel, BoundedIntWidget.MIN, 10); }
### Question: ValueWidget extends DOMWidget { public Integer getInteger(Object input) { Integer ret = 0; if (input != null) { if (input instanceof Double) { ret = ((Double) input).intValue(); } else if (input instanceof Integer) { ret = (Integer) input; } else if (input instanceof String) { try { ret = Integer.parseInt((String) input); } catch (NumberFormatException e) { } } else if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length > 0) { ret = (Integer) getInteger(array[0]); } } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }### Answer: @Test public void getIntegerWithStringParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger("123"); Assertions.assertThat(value.intValue()).isEqualTo(123); } @Test public void getIntegerWithDoubleParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger(new Double(123)); Assertions.assertThat(value.intValue()).isEqualTo(123); } @Test public void getIntegerWithIntegerParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger(new Integer(123)); Assertions.assertThat(value.intValue()).isEqualTo(123); } @Test public void getIntegerWithArrayParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger(new Integer[]{123, 234}); Assertions.assertThat(value.intValue()).isEqualTo(123); }
### Question: ValueWidget extends DOMWidget { public Double getDouble(Object input) { Double ret = 0D; if (input != null) { if (input instanceof Integer) { ret = ((Integer) input).doubleValue(); } else if (input instanceof Double) { ret = (Double) input; } else if (input instanceof String) { try { ret = Double.parseDouble((String) input); } catch (NumberFormatException e) { } } else if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length > 0) { ret = (Double) getDouble(array[0]); } } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }### Answer: @Test public void getDoubleWithStringParam_returnDouble() throws Exception { Double value = valueWidget.getDouble("123"); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); } @Test public void getDoubleWithDoubleParam_returnDouble() throws Exception { Double value = valueWidget.getDouble(new Double(123d)); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); } @Test public void getDoubleWithIntegerParam_returnDouble() throws Exception { Double value = valueWidget.getDouble(new Double(123d)); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); } @Test public void getDoubleWithArrayParam_returnDouble() throws Exception { Double value = valueWidget.getDouble(new Double[]{123d, 234d}); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); }
### Question: ValueWidget extends DOMWidget { protected Integer[] getArrayOfInteger(Object input, Integer lowerDefault, Integer upperDefault) { Integer[] ret = new Integer[2]; ret[0] = lowerDefault; ret[1] = upperDefault; if (input != null) { if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length == 1) { ret[0] = (Integer) getInteger(array[0]); } else if (array.length > 1) { ret[0] = (Integer) getInteger(array[0]); ret[1] = (Integer) getInteger(array[1]); } } else if (input instanceof Collection<?>) { Collection<?> coll = (Collection<?>) input; if (coll.size() == 1) { ret[0] = (Integer) getInteger(coll.toArray()[0]); } else if (coll.size() > 1) { ret[0] = (Integer) getInteger(coll.toArray()[0]); ret[1] = (Integer) getInteger(coll.toArray()[1]); } } else { ret[0] = getInteger(input); } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }### Answer: @Test public void getArrayOfIntegerWithNullArrayParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(null, 5, 6); Assertions.assertThat(value[0]).isEqualTo(5); Assertions.assertThat(value[1]).isEqualTo(6); } @Test public void getArrayOfIntegerWithOneValueArrayParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(new String[]{"1"}, 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(6); } @Test public void getArrayOfIntegerWithTwoValueArrayParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(new String[]{"1", "2"}, 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(2); } @Test public void getArrayOfIntegerWithOneValueListParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(Arrays.asList("1"), 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(6); } @Test public void getArrayOfIntegerWithTwoValueListParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(Arrays.asList("1", "2"), 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(2); } @Test public void getArrayOfIntegerWithStringParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger("1", 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(6); }
### Question: JavaEvaluator implements Evaluator { @Override public void evaluate(SimpleEvaluationObject seo, String code) { jobQueue.add(new jobDescriptor(code,seo)); syncObject.release(); } JavaEvaluator(String id, String sId); @Override void startWorker(); String getShellId(); void killAllThreads(); void cancelExecution(); void resetEnvironment(); @Override void exit(); @Override void setShellOptions(final KernelParameters kernelParameters); @Override void evaluate(SimpleEvaluationObject seo, String code); @Override AutocompleteResult autocomplete(String code, int caretPosition); }### Answer: @Test public void evaluatePlot_shouldCreatePlotObject() throws Exception { String code = "import com.twosigma.beaker.chart.xychart.*;\n" + "Plot plot = new Plot(); plot.setTitle(\"test title\");\n" + "return plot;"; SimpleEvaluationObject seo = new SimpleEvaluationObject(code, new ExecuteCodeCallbackTest()); javaEvaluator.evaluate(seo, code); waitForResult(seo); Assertions.assertThat(seo.getStatus()).isEqualTo(FINISHED); Assertions.assertThat(seo.getPayload() instanceof Plot).isTrue(); Assertions.assertThat(((Plot)seo.getPayload()).getTitle()).isEqualTo("test title"); } @Test public void evaluateDivisionByZero_shouldReturnArithmeticException() throws Exception { String code = "return 16/0;"; SimpleEvaluationObject seo = new SimpleEvaluationObject(code, new ExecuteCodeCallbackTest()); javaEvaluator.evaluate(seo, code); waitForResult(seo); Assertions.assertThat(seo.getStatus()).isEqualTo(ERROR); Assertions.assertThat((String)seo.getPayload()).contains("java.lang.ArithmeticException"); }
### Question: ValueWidget extends DOMWidget { protected Double[] getArrayOfDouble(Object input, Double lowerDefault, Double upperDefault) { Double[] ret = new Double[2]; ret[0] = lowerDefault; ret[1] = upperDefault; if (input != null) { if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length == 1) { ret[0] = (Double) getDouble(array[0]); } else if (array.length > 1) { ret[0] = (Double) getDouble(array[0]); ret[1] = (Double) getDouble(array[1]); } } else if (input instanceof Collection<?>) { Collection<?> coll = (Collection<?>) input; if (coll.size() == 1) { ret[0] = (Double) getDouble(coll.toArray()[0]); } else if (coll.size() > 1) { ret[0] = (Double) getDouble(coll.toArray()[0]); ret[1] = (Double) getDouble(coll.toArray()[1]); } } else { ret[0] = getDouble(input); } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }### Answer: @Test public void getArrayOfDoubleWithNullArrayParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(null, 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(5d); Assertions.assertThat(value[1]).isEqualTo(6d); } @Test public void getArrayOfDoubleWithOneValueArrayParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(new String[]{"1"}, 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(6d); } @Test public void getArrayOfDoubleWithTwoValueArrayParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(new String[]{"1", "2"}, 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(2d); } @Test public void getArrayOfDoubleWithOneValueListParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(Arrays.asList("1"), 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(6d); } @Test public void getArrayOfDoubleWithTwoValueListParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(Arrays.asList("1", "2"), 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(2d); } @Test public void getArrayOfDoubleWithStringParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble("1", 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(6d); }
### Question: ValueWidget extends DOMWidget { public String getString(Object input) { String ret = ""; if (input != null) { if (input instanceof String) { ret = (String) input; } else if (input instanceof byte[]) { ret = new String((byte[]) input); } else { ret = input.toString(); } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }### Answer: @Test public void getStringWithStringParam_returnString() throws Exception { String value = valueWidget.getString("abc"); Assertions.assertThat(value).isEqualTo("abc"); } @Test public void getStringWithByteArrayParam_returnString() throws Exception { String value = valueWidget.getString("abc".getBytes()); Assertions.assertThat(value).isEqualTo("abc"); } @Test public void getStringWithDoubleParam_returnString() throws Exception { String value = valueWidget.getString(new Integer(123)); Assertions.assertThat(value).isEqualTo("123"); } @Test public void getStringWithNullParam_returnEmptyString() throws Exception { String value = valueWidget.getString(null); Assertions.assertThat(value).isEmpty(); }
### Question: ValueWidget extends DOMWidget { public String[] getStringArray(Object input) { List<String> ret = new ArrayList<>(); if (input != null) { if (input instanceof Object[]) { Object[] array = (Object[]) input; for (Object o : array) { ret.add(getString(o)); } }else if(input instanceof Collection<?>){ Collection<Object> array = (Collection<Object>) input; for (Object o : array) { ret.add(getString(o)); } } else { ret.add(getString(input)); } } return ((ArrayList<String>) ret).stream().toArray(String[]::new); } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }### Answer: @Test public void getStringArrayWithNullArrayParam_returnEmptyArray() throws Exception { String[] value = valueWidget.getStringArray(null); Assertions.assertThat(value).isEmpty(); } @Test public void getStringArrayWithArrayParam_returnArray() throws Exception { String[] value = valueWidget.getStringArray(new String[]{"ab", "cd"}); Assertions.assertThat(value[0]).isEqualTo("ab"); Assertions.assertThat(value[1]).isEqualTo("cd"); } @Test public void getStringArrayWithListParam_returnArray() throws Exception { String[] value = valueWidget.getStringArray(Arrays.asList("ab", "cd")); Assertions.assertThat(value[0]).isEqualTo("ab"); Assertions.assertThat(value[1]).isEqualTo("cd"); } @Test public void getStringArrayWithIntegerParam_returnArray() throws Exception { String[] value = valueWidget.getStringArray(new Integer(123)); Assertions.assertThat(value[0]).isEqualTo("123"); }
### Question: MorphiaUtils { public static List<String> getApplicationPackageName(final ApplicationContext applicationContext) { Set<String> candidateClasses = new HashSet<>(); candidateClasses.addAll(Arrays.asList(applicationContext.getBeanNamesForAnnotation(SpringBootApplication.class))); candidateClasses.addAll(Arrays.asList(applicationContext.getBeanNamesForAnnotation(EnableAutoConfiguration.class))); candidateClasses.addAll(Arrays.asList(applicationContext.getBeanNamesForAnnotation(ComponentScan.class))); if (candidateClasses.isEmpty()) { throw new RuntimeException("Is mandatory for the starter have @SpringBootApplication, @EnableAutoConfiguration or @ComponentScan annotation"); } else { return candidateClasses.parallelStream() .map(candidateClazz -> applicationContext.getBean(candidateClazz).getClass().getPackage().getName()) .distinct() .collect(Collectors.toList()); } } static List<String> getApplicationPackageName(final ApplicationContext applicationContext); static Set<Class<?>> getClasses(final String packageName); }### Answer: @Test(expected = Exception.class) public void testWhenNoApplicationAnnotation_ShouldReturnAException() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationAcceptNoSpringBootApplication.class); MorphiaUtils.getApplicationPackageName(context); } @Test public void testCallGetPackageName_ShouldReturnAPackageName() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationTest.class); List<String> applicationPackageName = MorphiaUtils.getApplicationPackageName(context); assertThat(applicationPackageName.size(), is(1)); assertThat(applicationPackageName.get(0), is("io.github.ganchix.morphia.utils.context.normal")); }
### Question: MorphiaUtils { public static Set<Class<?>> getClasses(final String packageName) { Reflections reflections = new Reflections(packageName); return reflections.getTypesAnnotatedWith(Entity.class); } static List<String> getApplicationPackageName(final ApplicationContext applicationContext); static Set<Class<?>> getClasses(final String packageName); }### Answer: @Test public void testCallGetClasses_ShouldReturnAClassesInPackage() { Set<Class<?>> classes = MorphiaUtils.getClasses("io.github.ganchix.morphia.utils.context.normal"); assertThat(classes.size(), is(1)); } @Test public void testCallGetClasses_ShouldReturnAClassesInPackage1() { Set<Class<?>> classes = MorphiaUtils.getClasses("io.github.ganchix.morphia.utils.context.normal.NotClass.class"); }
### Question: Fruit { public <T> T fromHtml(String html, Class<T> classOfT) { return fromHtml(html, (Type) classOfT); } Fruit(); T fromHtml(String html, Class<T> classOfT); T fromHtml(String html, Type typeOfT); T fromHtml(File file, String charsetName, String baseUri, Class<T> classOfT); @SuppressWarnings("unchecked") T fromHtml(Element element, Type typeOfT); PickAdapter<T> getAdapter(Class<T> type); @SuppressWarnings("unchecked") PickAdapter<T> getAdapter(TypeToken<T> type); }### Answer: @Test public void testDirctList() { FruitItems items = new Fruit().fromHtml(htmlStr, FruitItems.class); assert items.size() == 5; assert items.get(4).getId() == 5; System.out.println("fruitItems: " + fruitInfo); } @Test public void testNullInput() { assert null == new Fruit().fromHtml("", Object.class); }
### Question: NoticesXmlParser { public static Notices parse(final InputStream inputStream) throws Exception { try { final XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(inputStream, null); parser.nextTag(); return parse(parser); } finally { inputStream.close(); } } private NoticesXmlParser(); static Notices parse(final InputStream inputStream); }### Answer: @Test public void testParse() throws Exception { assertNotNull(NoticesXmlParser.parse(RuntimeEnvironment.application.getResources().openRawResource(R.raw.notices))); }
### Question: LicenseResolver { public static void registerLicense(final License license) { sLicenses.put(license.getName(), license); } private LicenseResolver(); static void registerLicense(final License license); static License read(final String license); }### Answer: @Test public void testRegisterLicense() throws Exception { LicenseResolver.registerLicense(new TestLicense()); final License license = LicenseResolver.read(TEST_LICENSE_NAME); assertNotNull(license); assertEquals(TEST_LICENSE_NAME, license.getName()); }
### Question: LicenseResolver { public static License read(final String license) { final String trimmedLicense = license.trim(); if (sLicenses.containsKey(trimmedLicense)) { return sLicenses.get(trimmedLicense); } else { throw new IllegalStateException(String.format("no such license available: %s, did you forget to register it?", trimmedLicense)); } } private LicenseResolver(); static void registerLicense(final License license); static License read(final String license); }### Answer: @Test(expected = IllegalStateException.class) public void testReadUnknownLicense() throws Exception { LicenseResolver.read(TEST_LICENSE_NAME); } @Test public void testReadKnownLicense() throws Exception { final License license = LicenseResolver.read("MIT License"); assertNotNull(license); assertEquals("MIT License", license.getName()); }
### Question: XPathRecordReader { public synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued) { addField0(xpath, name, multiValued, false, 0); return this; } XPathRecordReader(String forEachXpath); synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued); synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued, int flags); List<Map<String, Object>> getAllRecords(Reader r); void streamRecords(Reader r, Handler handler); static final int FLATTEN; }### Answer: @Test public void unsupported_Xpaths() { String xml = "<root><b><a x=\"a/b\" h=\"hello-A\"/> </b></root>"; XPathRecordReader rr=null; try { rr = new XPathRecordReader(" Assert.fail("A RuntimeException was expected: } catch (RuntimeException ex) { } try { rr.addField("bold" ,"b", false); Assert.fail("A RuntimeException was expected: 'b' xpaths must begin with '/'."); } catch (RuntimeException ex) { } }
### Question: EvaluatorBag { public static Evaluator getSqlEscapingEvaluator() { return new Evaluator() { public String evaluate(String expression, Context context) { List l = parseParams(expression, context.getVariableResolver()); if (l.size() != 1) { throw new DataImportHandlerException(SEVERE, "'escapeSql' must have at least one parameter "); } String s = l.get(0).toString(); return s.replaceAll("'", "''").replaceAll("\"", "\"\"").replaceAll("\\\\", "\\\\\\\\"); } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }### Answer: @Test public void testGetSqlEscapingEvaluator() { Evaluator sqlEscaper = EvaluatorBag.getSqlEscapingEvaluator(); runTests(sqlTests, sqlEscaper); }
### Question: EvaluatorBag { public static Evaluator getUrlEvaluator() { return new Evaluator() { public String evaluate(String expression, Context context) { List l = parseParams(expression, context.getVariableResolver()); if (l.size() != 1) { throw new DataImportHandlerException(SEVERE, "'encodeUrl' must have at least one parameter "); } String s = l.get(0).toString(); try { return URLEncoder.encode(s.toString(), "UTF-8"); } catch (Exception e) { wrapAndThrow(SEVERE, e, "Unable to encode expression: " + expression + " with value: " + s); return null; } } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }### Answer: @Test public void testGetUrlEvaluator() throws Exception { Evaluator urlEvaluator = EvaluatorBag.getUrlEvaluator(); runTests(urlTests, urlEvaluator); }
### Question: EvaluatorBag { public static List parseParams(String expression, VariableResolver vr) { List result = new ArrayList(); expression = expression.trim(); String[] ss = expression.split(","); for (int i = 0; i < ss.length; i++) { ss[i] = ss[i].trim(); if (ss[i].startsWith("'")) { StringBuilder sb = new StringBuilder(); while (true) { sb.append(ss[i]); if (ss[i].endsWith("'")) break; i++; if (i >= ss.length) throw new DataImportHandlerException(SEVERE, "invalid string at " + ss[i - 1] + " in function params: " + expression); sb.append(","); } String s = sb.substring(1, sb.length() - 1); s = s.replaceAll("\\\\'", "'"); result.add(s); } else { if (Character.isDigit(ss[i].charAt(0))) { try { Double doub = Double.parseDouble(ss[i]); result.add(doub); } catch (NumberFormatException e) { if (vr.resolve(ss[i]) == null) { wrapAndThrow( SEVERE, e, "Invalid number :" + ss[i] + "in parameters " + expression); } } } else { result.add(new VariableWrapper(ss[i], vr)); } } } return result; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }### Answer: @Test public void parseParams() { Map m = new HashMap(); m.put("b","B"); VariableResolverImpl vr = new VariableResolverImpl(); vr.addNamespace("a",m); List l = EvaluatorBag.parseParams(" 1 , a.b, 'hello!', 'ds,o,u\'za',",vr); Assert.assertEquals(new Double(1),l.get(0)); Assert.assertEquals("B",((EvaluatorBag.VariableWrapper)l.get(1)).resolve()); Assert.assertEquals("hello!",l.get(2)); Assert.assertEquals("ds,o,u'za",l.get(3)); }
### Question: EvaluatorBag { static Map<String, Object> getFunctionsNamespace(final List<Map<String, String>> fn, DocBuilder docBuilder) { final Map<String, Evaluator> evaluators = new HashMap<String, Evaluator>(); evaluators.put(DATE_FORMAT_EVALUATOR, getDateFormatEvaluator()); evaluators.put(SQL_ESCAPE_EVALUATOR, getSqlEscapingEvaluator()); evaluators.put(URL_ENCODE_EVALUATOR, getUrlEvaluator()); evaluators.put(ESCAPE_SOLR_QUERY_CHARS, getSolrQueryEscapingEvaluator()); SolrCore core = docBuilder == null ? null : docBuilder.dataImporter.getCore(); for (Map<String, String> map : fn) { try { evaluators.put(map.get(NAME), (Evaluator) loadClass(map.get(CLASS), core).newInstance()); } catch (Exception e) { wrapAndThrow(SEVERE, e, "Unable to instantiate evaluator: " + map.get(CLASS)); } } return new HashMap<String, Object>() { @Override public String get(Object key) { if (key == null) return null; Matcher m = FORMAT_METHOD.matcher((String) key); if (!m.find()) return null; String fname = m.group(1); Evaluator evaluator = evaluators.get(fname); if (evaluator == null) return null; VariableResolverImpl vri = VariableResolverImpl.CURRENT_VARIABLE_RESOLVER.get(); return evaluator.evaluate(m.group(2), Context.CURRENT_CONTEXT.get()); } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }### Answer: @Test public void testEscapeSolrQueryFunction() { final VariableResolverImpl resolver = new VariableResolverImpl(); ContextImpl context = new ContextImpl(null, resolver, null, Context.FULL_DUMP, Collections.EMPTY_MAP, null, null); Context.CURRENT_CONTEXT.set(context); try { Map m= new HashMap(); m.put("query","c:t"); resolver.addNamespace("dataimporter.functions", EvaluatorBag .getFunctionsNamespace(Collections.EMPTY_LIST, null)); resolver.addNamespace("e",m); String s = resolver .replaceTokens("${dataimporter.functions.escapeQueryChars(e.query)}"); org.junit.Assert.assertEquals("c\\:t", s); } finally { Context.CURRENT_CONTEXT.remove(); } }
### Question: DateFormatTransformer extends Transformer { @SuppressWarnings("unchecked") public Object transformRow(Map<String, Object> aRow, Context context) { for (Map<String, String> map : context.getAllEntityFields()) { Locale locale = Locale.getDefault(); String customLocale = map.get("locale"); if(customLocale != null){ locale = new Locale(customLocale); } String fmt = map.get(DATE_TIME_FMT); if (fmt == null) continue; String column = map.get(DataImporter.COLUMN); String srcCol = map.get(RegexTransformer.SRC_COL_NAME); if (srcCol == null) srcCol = column; try { Object o = aRow.get(srcCol); if (o instanceof List) { List inputs = (List) o; List<Date> results = new ArrayList<Date>(); for (Object input : inputs) { results.add(process(input, fmt, locale)); } aRow.put(column, results); } else { if (o != null) { aRow.put(column, process(o, fmt, locale)); } } } catch (ParseException e) { LOG.warn("Could not parse a Date field ", e); } } return aRow; } @SuppressWarnings("unchecked") Object transformRow(Map<String, Object> aRow, Context context); static final String DATE_TIME_FMT; }### Answer: @Test @SuppressWarnings("unchecked") public void testTransformRow_SingleRow() throws Exception { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "lastModified")); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "dateAdded", RegexTransformer.SRC_COL_NAME, "lastModified", DateFormatTransformer.DATE_TIME_FMT, "MM/dd/yyyy")); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); Date now = format.parse(format.format(new Date())); Map row = AbstractDataImportHandlerTestCase.createMap("lastModified", format .format(now)); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, null); new DateFormatTransformer().transformRow(row, context); Assert.assertEquals(now, row.get("dateAdded")); } @Test @SuppressWarnings("unchecked") public void testTransformRow_MultipleRows() throws Exception { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "lastModified")); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "dateAdded", RegexTransformer.SRC_COL_NAME, "lastModified", DateFormatTransformer.DATE_TIME_FMT, "MM/dd/yyyy hh:mm:ss.SSS")); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS"); Date now1 = format.parse(format.format(new Date())); Date now2 = format.parse(format.format(new Date())); Map row = new HashMap(); List list = new ArrayList(); list.add(format.format(now1)); list.add(format.format(now2)); row.put("lastModified", list); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, null); new DateFormatTransformer().transformRow(row, context); List output = new ArrayList(); output.add(now1); output.add(now2); Assert.assertEquals(output, row.get("dateAdded")); }
### Question: DocBuilder { @SuppressWarnings("unchecked") static Class loadClass(String name, SolrCore core) throws ClassNotFoundException { try { return core != null ? core.getResourceLoader().findClass(name) : Class.forName(name); } catch (Exception e) { try { String n = DocBuilder.class.getPackage().getName() + "." + name; return core != null ? core.getResourceLoader().findClass(n) : Class.forName(n); } catch (Exception e1) { throw new ClassNotFoundException("Unable to load " + name + " or " + DocBuilder.class.getPackage().getName() + "." + name, e); } } } DocBuilder(DataImporter dataImporter, SolrWriter writer, DataImporter.RequestParams reqParams); VariableResolverImpl getVariableResolver(); @SuppressWarnings("unchecked") void execute(); @SuppressWarnings("unchecked") void addStatusMessage(String msg); @SuppressWarnings("unchecked") Set<Map<String, Object>> collectDelta(DataConfig.Entity entity, VariableResolverImpl resolver, Set<Map<String, Object>> deletedRows); void abort(); public Statistics importStatistics; static final String TIME_ELAPSED; static final String LAST_INDEX_TIME; static final String INDEX_START_TIME; }### Answer: @Test public void loadClass() throws Exception { Class clz = DocBuilder.loadClass("RegexTransformer", null); Assert.assertNotNull(clz); }
### Question: VariableResolver { public abstract Object resolve(String name); abstract Object resolve(String name); abstract String replaceTokens(String template); }### Answer: @Test public void testSimpleNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace("hello", ns); Assert.assertEquals("WORLD", vri.resolve("hello.world")); } @Test public void testDefaults(){ System.setProperty(TestVariableResolver.class.getName(),"hello"); HashMap m = new HashMap(); m.put("hello","world"); VariableResolverImpl vri = new VariableResolverImpl(m); Object val = vri.resolve(TestVariableResolver.class.getName()); Assert.assertEquals("hello", val); Assert.assertEquals("world",vri.resolve("hello")); } @Test public void testNestedNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace("hello", ns); ns = new HashMap<String, Object>(); ns.put("world1", "WORLD1"); vri.addNamespace("hello.my", ns); Assert.assertEquals("WORLD1", vri.resolve("hello.my.world1")); } @Test public void test3LevelNestedNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace("hello", ns); ns = new HashMap<String, Object>(); ns.put("world1", "WORLD1"); vri.addNamespace("hello.my.new", ns); Assert.assertEquals("WORLD1", vri.resolve("hello.my.new.world1")); } @Test public void testDefaultNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace(null, ns); Assert.assertEquals("WORLD", vri.resolve("world")); } @Test public void testDefaultNamespace1() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace(null, ns); Assert.assertEquals("WORLD", vri.resolve("world")); }
### Question: EntityProcessorBase extends EntityProcessor { public void init(Context context) { rowIterator = null; this.context = context; if (isFirstInit) { firstInit(context); } query = null; } void init(Context context); Map<String, Object> nextModifiedRowKey(); Map<String, Object> nextDeletedRowKey(); Map<String, Object> nextModifiedParentRowKey(); Map<String, Object> nextRow(); void destroy(); static final String TRANSFORMER; static final String TRANSFORM_ROW; static final String ON_ERROR; static final String ABORT; static final String CONTINUE; static final String SKIP; static final String SKIP_DOC; static final String CACHE_KEY; static final String CACHE_LOOKUP; }### Answer: @Test public void multiTransformer() { List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); Map<String, String> entity = new HashMap<String, String>(); entity.put("transformer", T1.class.getName() + "," + T2.class.getName() + "," + T3.class.getName()); fields.add(TestRegexTransformer.getField("A", null, null, null, null)); fields.add(TestRegexTransformer.getField("B", null, null, null, null)); Context context = AbstractDataImportHandlerTestCase.getContext(null, null, new MockDataSource(), Context.FULL_DUMP, fields, entity); Map<String, Object> src = new HashMap<String, Object>(); src.put("A", "NA"); src.put("B", "NA"); EntityProcessorWrapper sep = new EntityProcessorWrapper(new SqlEntityProcessor(), null); sep.init(context); Map<String, Object> res = sep.applyTransformer(src); Assert.assertNotNull(res.get("T1")); Assert.assertNotNull(res.get("T2")); Assert.assertNotNull(res.get("T3")); }
### Question: DataConfig { public void readFromXml(Element e) { List<Element> n = getChildNodes(e, "document"); if (n.isEmpty()) { throw new DataImportHandlerException(SEVERE, "DataImportHandler " + "configuration file must have one <document> node."); } document = new Document(n.get(0)); n = getChildNodes(e, SCRIPT); if (!n.isEmpty()) { script = new Script(n.get(0)); } n = getChildNodes(e, FUNCTION); if (!n.isEmpty()) { for (Element element : n) { String func = getStringAttribute(element, NAME, null); String clz = getStringAttribute(element, CLASS, null); if (func == null || clz == null){ throw new DataImportHandlerException( SEVERE, "<function> must have a 'name' and 'class' attributes"); } else { functions.add(getAllAttributes(element)); } } } n = getChildNodes(e, DATA_SRC); if (!n.isEmpty()) { for (Element element : n) { Properties p = new Properties(); HashMap<String, String> attrs = getAllAttributes(element); for (Map.Entry<String, String> entry : attrs.entrySet()) { p.setProperty(entry.getKey(), entry.getValue()); } dataSources.put(p.getProperty("name"), p); } } if(dataSources.get(null) == null){ for (Properties properties : dataSources.values()) { dataSources.put(null,properties); break; } } } void readFromXml(Element e); static String getTxt(Node elem, StringBuilder buffer); static List<Element> getChildNodes(Element e, String byName); void clearCaches(); public Document document; public List<Map<String, String >> functions; public Script script; public Map<String, Properties> dataSources; public Map<String, SchemaField> lowerNameVsSchemaField; static final String SCRIPT; static final String NAME; static final String PROCESSOR; @Deprecated static final String IMPORTER_NS; static final String IMPORTER_NS_SHORT; static final String ROOT_ENTITY; static final String FUNCTION; static final String CLASS; static final String DATA_SRC; }### Answer: @Test public void basic() throws Exception { javax.xml.parsers.DocumentBuilder builder = DocumentBuilderFactory .newInstance().newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); DataConfig dc = new DataConfig(); dc.readFromXml(doc.getDocumentElement()); Assert.assertEquals("atrimlisting", dc.document.entities.get(0).name); }
### Question: TemplateTransformer extends Transformer { @SuppressWarnings("unchecked") public Object transformRow(Map<String, Object> row, Context context) { VariableResolverImpl resolver = (VariableResolverImpl) context .getVariableResolver(); for (Map<String, String> map : context.getAllEntityFields()) { String expr = map.get(TEMPLATE); if (expr == null) continue; String column = map.get(DataImporter.COLUMN); boolean resolvable = true; List<String> variables = getVars(expr); for (String v : variables) { if (resolver.resolve(v) == null) { LOG.warn("Unable to resolve variable: " + v + " while parsing expression: " + expr); resolvable = false; } } if (!resolvable) continue; if(variables.size() == 1 && expr.startsWith("${") && expr.endsWith("}")){ row.put(column, resolver.resolve(variables.get(0))); } else { row.put(column, resolver.replaceTokens(expr)); } } return row; } @SuppressWarnings("unchecked") Object transformRow(Map<String, Object> row, Context context); static final String TEMPLATE; }### Answer: @Test @SuppressWarnings("unchecked") public void testTransformRow() { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "firstName")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "lastName")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "middleName")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "name", TemplateTransformer.TEMPLATE, "${e.lastName}, ${e.firstName} ${e.middleName}")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "emails", TemplateTransformer.TEMPLATE, "${e.mail}")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "mrname", TemplateTransformer.TEMPLATE,"Mr ${e.name}")); List<String> mails = Arrays.asList(new String[]{"[email protected]", "[email protected]"}); Map row = AbstractDataImportHandlerTestCase.createMap( "firstName", "Shalin", "middleName", "Shekhar", "lastName", "Mangar", "mail", mails); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Map<String, String> entityAttrs = AbstractDataImportHandlerTestCase.createMap( "name", "e"); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, entityAttrs); new TemplateTransformer().transformRow(row, context); Assert.assertEquals("Mangar, Shalin Shekhar", row.get("name")); Assert.assertEquals("Mr Mangar, Shalin Shekhar", row.get("mrname")); Assert.assertEquals(mails,row.get("emails")); }
### Question: MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { private int compare(String a, String b) { if (a != null && b != null) { return a.compareTo(b); } if (a == null) { if (b == null) { return 0; } return -1; } return 1; } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testCompare() { MetaLocale meta1 = new MetaLocale(null, "Latn", null, null); MetaLocale meta2 = new MetaLocale(null, "Grek", null, null); assertEquals(meta1.compareTo(meta2), 5); assertEquals(meta2.compareTo(meta1), -5); meta2 = new MetaLocale("en", "Latn", null, null); assertEquals(meta1.compareTo(meta2), -1); assertEquals(meta2.compareTo(meta1), 1); }
### Question: MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { @Override public boolean equals(Object obj) { if (obj instanceof MetaLocale) { MetaLocale other = (MetaLocale) obj; return Arrays.equals(fields, other.fields); } return false; } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testEquals() { MetaLocale meta1 = new MetaLocale(null, "Latn", null, null); MetaLocale meta2 = new MetaLocale(null, "Latn", null, null); assertEquals(meta1, meta2); assertEquals(meta1.hashCode(), meta2.hashCode()); meta2 = new MetaLocale("und", "Latn", null, null); assertEquals(meta1, meta2); assertEquals(meta1.hashCode(), meta2.hashCode()); meta2 = new MetaLocale("en", "Latn", null, null); assertNotEquals(meta1, meta2); assertNotEquals(meta1.hashCode(), meta2.hashCode()); }
### Question: UnitFactorMap { public UnitCategory getUnitCategory() { return category; } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }### Answer: @Test public void testBasics() { assertEquals(UnitCategory.ANGLE, new UnitFactorMap(UnitCategory.ANGLE).getUnitCategory()); }
### Question: UnitFactorMap { public void sortUnits(Unit[] units) { Arrays.sort(units, (a, b) -> { Integer ia = unitOrder.get(a); Integer ib = unitOrder.get(b); if (ia == null) { return 1; } if (ib == null) { return -1; } return Integer.compare(ia, ib); }); } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }### Answer: @Test public void testSortUnits() { Unit[] units = new Unit[] { Unit.KILOMETER, Unit.NANOMETER, Unit.MILE, Unit.INCH, Unit.LIGHT_YEAR }; UnitFactors.LENGTH.sortUnits(units); Unit[] expected = new Unit[] { Unit.LIGHT_YEAR, Unit.MILE, Unit.KILOMETER, Unit.INCH, Unit.NANOMETER }; assertEquals(units, expected); units = new Unit[] { Unit.AMPERE, Unit.INCH, Unit.BUSHEL, Unit.MILE }; UnitFactors.LENGTH.sortUnits(units); expected = new Unit[] { Unit.MILE, Unit.INCH, Unit.AMPERE, Unit.BUSHEL }; assertEquals(units, expected); }
### Question: UnitFactorMap { public String dump(Unit unit) { StringBuilder buf = new StringBuilder(); buf.append(unit).append(":\n"); Map<Unit, UnitFactor> map = factors.get(unit); for (Unit base : map.keySet()) { UnitFactor factor = map.get(base); buf.append(" ").append(factor).append(" "); buf.append(factor.rational().compute(RoundingMode.HALF_EVEN).toPlainString()).append('\n'); } return buf.toString(); } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }### Answer: @Test public void testDumpMapping() { String factors = UnitFactors.LENGTH.dump(Unit.INCH); assertTrue(factors.contains("Factor(2.54, CENTIMETER)")); assertTrue(factors.contains("Factor(1 / 12, FOOT)")); }
### Question: UnitFactorSet { public List<UnitValue> factors() { return factors; } UnitFactorSet(Unit base, UnitFactorMap factorMap, Unit...units); UnitFactorSet(UnitFactorMap factorMap, Unit...units); private UnitFactorSet(Unit unitBase, boolean forceBase, UnitFactorMap factorMap, Unit...units); Unit base(); List<UnitValue> factors(); }### Answer: @Test public void testDurationFactors() { UnitFactorSet set = new UnitFactorSet(UnitFactors.DURATION, Unit.YEAR, Unit.DAY, Unit.MONTH); assertEquals(set.factors(), Arrays.asList( new UnitValue("365.2425", Unit.YEAR), new UnitValue("30.436875", Unit.MONTH), new UnitValue("1", Unit.DAY) )); }
### Question: DigitBuffer implements CharSequence { @Override public DigitBuffer subSequence(int start, int end) { start = clamp(start, 0, size - 1); end = clamp(end, start, size - 1); int sz = end - start; char[] newbuf = new char[16 + sz]; System.arraycopy(buf, start, newbuf, 0, sz); return new DigitBuffer(newbuf, sz); } DigitBuffer(); DigitBuffer(int capacity); private DigitBuffer(char[] buf, int size); void reset(); @Override int length(); @Override DigitBuffer subSequence(int start, int end); @Override char charAt(int i); int capacity(); char first(); char last(); DigitBuffer append(String s); void append(DigitBuffer other); DigitBuffer append(char ch); void appendTo(StringBuilder dest); void reverse(int start); @Override String toString(); }### Answer: @Test public void testSubsequence() { DigitBuffer buf = new DigitBuffer(); for (int i = 0; i < 10; i++) { char ch = (char)('a' + i); buf.append(ch); } assertEquals(buf.length(), 10); DigitBuffer sub = buf.subSequence(2, 7); assertEquals(sub.length(), 5); assertEquals(sub.toString(), "cdefg"); sub = buf.subSequence(2, 2); assertEquals(sub.length(), 0); assertEquals(sub.toString(), ""); sub = buf.subSequence(-1, 5); assertEquals(sub.length(), 5); assertEquals(sub.toString(), "abcde"); sub = buf.subSequence(2, 20); assertEquals(sub.length(), 7); assertEquals(sub.toString(), "cdefghi"); sub = buf.subSequence(7, 2); assertEquals(sub.length(), 0); assertEquals(sub.toString(), ""); }
### Question: NumberFormattingUtils { public static int integerDigits(BigDecimal n) { return n.precision() - n.scale(); } static int integerDigits(BigDecimal n); static BigDecimal setup( BigDecimal n, // number to be formatted NumberRoundMode roundMode, // rounding mode NumberFormatMode formatMode, // formatting mode (significant digits, etc) int minIntDigits, // maximum integer digits to emit int maxFracDigits, // maximum fractional digits to emit int minFracDigits, // minimum fractional digits to emit int maxSigDigits, // maximum significant digits to emit int minSigDigits); static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize); }### Answer: @Test public void testIntegerDigits() { for (int i = 1; i < 10; i++) { intDigits(num("12345", i), 5); intDigits(num("0.12345", i), 0); intDigits(num("12345.12345", i), 5); } }
### Question: NumberFormattingUtils { public static BigDecimal setup( BigDecimal n, NumberRoundMode roundMode, NumberFormatMode formatMode, int minIntDigits, int maxFracDigits, int minFracDigits, int maxSigDigits, int minSigDigits) { RoundingMode mode = roundMode.toRoundingMode(); boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC; if (useSignificant && minSigDigits > 0 && maxSigDigits > 0) { if (n.precision() > maxSigDigits) { int scale = maxSigDigits - n.precision() + n.scale(); n = n.setScale(scale, mode); } if (formatMode == NumberFormatMode.SIGNIFICANT_MAXFRAC && maxFracDigits < n.scale()) { n = n.setScale(maxFracDigits, mode); } n = n.stripTrailingZeros(); boolean zero = n.signum() == 0; int precision = n.precision(); if (zero && n.scale() == 1) { precision--; } if (precision < minSigDigits) { int scale = minSigDigits - precision + n.scale(); n = n.setScale(scale, mode); } } else { int scale = Math.max(minFracDigits, Math.min(n.scale(), maxFracDigits)); n = n.setScale(scale, mode); n = n.stripTrailingZeros(); if (n.scale() < minFracDigits) { n = n.setScale(minFracDigits, mode); } } return n; } static int integerDigits(BigDecimal n); static BigDecimal setup( BigDecimal n, // number to be formatted NumberRoundMode roundMode, // rounding mode NumberFormatMode formatMode, // formatting mode (significant digits, etc) int minIntDigits, // maximum integer digits to emit int maxFracDigits, // maximum fractional digits to emit int minFracDigits, // minimum fractional digits to emit int maxSigDigits, // maximum significant digits to emit int minSigDigits); static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize); }### Answer: @Test public void testSetup() { Builder fmt = format(SIGNIFICANT).minSigDigits(1).maxSigDigits(1); setup(fmt.get(), "0", "0"); setup(fmt.get(), "0.0", "0"); setup(fmt.get(), "1.0", "1"); setup(fmt.get(), "1.23004", "1"); setup(fmt.get(), "12345", "10000"); setup(fmt.get(), "0.12345", "0.1"); setup(fmt.get(), "3.14159", "3"); setup(fmt.get(), "0.1", "0.1"); setup(fmt.get(), "0.999999", "1"); fmt = format(NumberFormatMode.DEFAULT).minFracDigits(1).maxFracDigits(3); setup(fmt.get(), "0", "0.0"); setup(fmt.get(), "0.0", "0.0"); setup(fmt.get(), "1.0", "1.0"); setup(fmt.get(), "1.23004", "1.23"); setup(fmt.get(), "12345", "12345.0"); setup(fmt.get(), "0.12345", "0.123"); setup(fmt.get(), "3.14159", "3.142"); setup(fmt.get(), "0.1", "0.1"); setup(fmt.get(), "0.999999", "1.0"); }
### Question: MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { public String variant() { return getField(VARIANT, ""); } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testVariant() { MetaLocale meta = new MetaLocale("en", null, "US", "POSIX"); assertEquals(meta.compact(), "en-US-POSIX"); assertEquals(meta.expanded(), "en-Zzzz-US-POSIX"); }
### Question: NumberPattern { public Format format() { return format == null ? DEFAULT_FORMAT : format; } protected NumberPattern(String pattern, List<Node> parsed, Format format); String pattern(); List<Node> parsed(); Format format(); String render(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testDecimalStandard() { assertPattern("-#,##0.###", MINUS, format(3, 0, 1, 3, 0)); assertPattern("#,##,##0.###", format(3, 2, 1, 3, 0)); assertPattern("-#0.######", MINUS, format(0, 0, 1, 6, 0)); } @Test public void testDecimalPercent() { assertPattern("#,##0%", format(3, 0, 1, 0, 0), PERCENT); assertPattern("#,##0\u00a0%", format(3, 0, 1, 0, 0), text(NBSP), PERCENT); assertPattern("#,##,##0%", format(3, 2, 1, 0, 0), PERCENT); assertPattern("-%#,##0", MINUS, PERCENT, format(3, 0, 1, 0, 0)); assertPattern("%\u00a0#,##0", PERCENT, text(NBSP), format(3, 0, 1, 0, 0)); } @Test public void testDecimalLong() { assertPattern("0 billion", format(0, 0, 1, 0, 0), text(" billion")); assertPattern("000 thousand", format(0, 0, 3, 0, 0), text(" thousand")); }
### Question: DateTimePatternParser { public List<Node> parse(String raw) { StringBuilder buf = new StringBuilder(); char field = '\0'; int width = 0; boolean inquote = false; int length = raw.length(); int i = 0; List<Node> nodes = new ArrayList<>(); while (i < length) { char ch = raw.charAt(i); if (inquote) { if (ch == '\'') { inquote = false; field = '\0'; } else { buf.append(ch); } i++; continue; } switch (ch) { case 'G': case 'y': case 'Y': case 'u': case 'U': case 'r': case 'Q': case 'q': case 'M': case 'L': case 'l': case 'w': case 'W': case 'd': case 'D': case 'F': case 'g': case 'E': case 'e': case 'c': case 'a': case 'b': case 'B': case 'h': case 'H': case 'K': case 'k': case 'j': case 'J': case 'C': case 'm': case 's': case 'S': case 'A': case 'z': case 'Z': case 'O': case 'v': case 'V': case 'X': case 'x': if (buf.length() > 0) { nodes.add(new Text(buf.toString())); buf.setLength(0); } if (ch != field) { if (field != '\0') { nodes.add(new Field(field, width)); } field = ch; width = 1; } else { width++; } break; default: if (field != '\0') { nodes.add(new Field(field, width)); } field = '\0'; if (ch == '\'') { inquote = true; } else { buf.append(ch); } break; } i++; } if (width > 0 && field != '\0') { nodes.add(new Field(field, width)); } else if (buf.length() > 0) { nodes.add(new Text(buf.toString())); } return nodes; } Pair<List<Node>, List<Node>> splitIntervalPattern(String raw); static String render(List<Node> nodes); List<Node> parse(String raw); }### Answer: @Test public void testParse() { assertPattern("y/M/d 'at' h:m", field('y', 1), text("/"), field('M', 1), text("/"), field('d', 1), text(" at "), field('h', 1), text(":"), field('m', 1)); }
### Question: LanguageResolver { protected MetaLocale addLikelySubtags(MetaLocale src) { MetaLocale dst = src.copy(); if (src.hasAll()) { return dst; } MetaLocale temp = src.copy(); temp.setVariant(null); for (int flags : MATCH_ORDER) { set(src, temp, flags); MetaLocale match = likelySubtagsMap.get(temp); if (match != null) { if (!dst.hasLanguage()) { dst.setLanguage(match._language()); } if (!dst.hasScript()) { dst.setScript(match._script()); } if (!dst.hasTerritory()) { dst.setTerritory(match._territory()); } break; } } return dst; } LanguageResolver(Map<MetaLocale, MetaLocale> likelySubtagsMap); CLDR.Locale matchLanguageTag(String tag); CLDR.Locale matchLocale(java.util.Locale locale); }### Answer: @Test public void testAddLikelySubtags() { assertMatch("en", "en-Latn-US"); assertMatch("und-US", "en-Latn-US"); assertMatch("en-US", "en-Latn-US"); assertMatch("en_US", "en-Latn-US"); assertMatch("en-Zzzz-US", "en-Latn-US"); assertMatch("en-US-u-cu-USD", "en-Latn-US"); assertMatch("en-GB", "en-Latn-GB"); assertMatch("es", "es-Latn-ES"); assertMatch("es_ES", "es-Latn-ES"); assertMatch("es_419", "es-Latn-419"); assertMatch("es-Latn-419", "es-Latn-419"); assertMatch("sr", "sr-Cyrl-RS"); assertMatch("sr-Cyrl", "sr-Cyrl-RS"); assertMatch("sr-RS", "sr-Cyrl-RS"); assertMatch("sr-Cyrl-BA", "sr-Cyrl-BA"); assertMatch("sr-Latn", "sr-Latn-RS"); assertMatch("sr_Latn_BA", "sr-Latn-BA"); assertMatch("sr-Latn-RS", "sr-Latn-RS"); assertMatch("sr-Cyrl-XY", "sr-Cyrl-XY"); assertMatch("be", "be-Cyrl-BY"); assertMatch("be-BY", "be-Cyrl-BY"); assertMatch("be-Cyrl-BY", "be-Cyrl-BY"); assertMatch("und-BY", "be-Cyrl-BY"); assertMatch("zh-TW", "zh-Hant-TW"); assertMatch("zh-CN", "zh-Hans-CN"); assertMatch("zh", "zh-Hans-CN"); }
### Question: LanguageMatcher { public Match match(String desiredRaw) { return matchImpl(parse(desiredRaw), DEFAULT_THRESHOLD); } LanguageMatcher(String supportedLocales); LanguageMatcher(List<String> supportedLocales); Match match(String desiredRaw); Match match(String desiredRaw, int threshold); Match match(List<String> desired); Match match(List<String> desired, int threshold); List<Match> matches(String desiredRaw); List<Match> matches(String desiredRaw, int threshold); List<Match> matches(List<String> desired); List<Match> matches(List<String> desired, int threshold); }### Answer: @Test public void testCases() throws IOException { for (Case c : load()) { match(c.supported, c.desired, c.result); } } @Test public void testBasic() { match("en-US fr-FR de-DE es-ES", "zh ar de", "de-DE"); } @Test public void testList() { match(asList("en", "ar", "zh", "es"), asList("no", "he", "zh", "es"), "zh"); match(asList("en_US", "fr_FR", "und-DE"), asList("zh", "de"), "und-DE"); match(asList("en ar", "de es fr"), asList("no he", "es"), "es"); }
### Question: LanguageMatcher { public List<Match> matches(String desiredRaw) { return matchesImpl(parse(desiredRaw), DEFAULT_THRESHOLD); } LanguageMatcher(String supportedLocales); LanguageMatcher(List<String> supportedLocales); Match match(String desiredRaw); Match match(String desiredRaw, int threshold); Match match(List<String> desired); Match match(List<String> desired, int threshold); List<Match> matches(String desiredRaw); List<Match> matches(String desiredRaw, int threshold); List<Match> matches(List<String> desired); List<Match> matches(List<String> desired, int threshold); }### Answer: @Test public void testMatches() { matchlist("es-419, es-ES", "es-AR", "es-419:4 es-ES:5"); matchlist("es-ES, es-419", "es-AR", "es-419:4 es-ES:5"); matchlist("es-419, es", "es-AR", "es-419:4 es:5"); matchlist("es, es-419", "es-AR", "es-419:4 es:5"); matchlist("es-MX, es", "es-AR", "es-MX:4 es:5"); matchlist("es, es-MX", "es-AR", "es-MX:4 es:5"); matchlist("es-ES, es-419, es-PT", "es-MX", "es-419:4 es-ES:5 es-PT:5"); matchlist("es-MX, es-419, es-ES", "es-AR", "es-419:4 es-MX:4 es-ES:5"); matchlist("zh-HK, zh-TW, zh", "zh-MO", "zh-HK:4 zh-TW:5 zh:23"); matchlist("en-US", "en-GB", "en-US:3"); matchlist("en-IN", "en-GB", "en-IN:4"); matchlist("en-GB", "en-US", "en-GB:5"); matchlist("en-IN, en-US", "en-GB", "en-US:3 en-IN:4"); matchlist("en-GB, en-US", "en-IN", "en-GB:3 en-US:5"); matchlist("en-GB, en-US", "en-VI", "en-US:4 en-GB:5"); matchlist("en-US, en-GB, en-VI", "en-IN", "en-GB:3 en-US:5 en-VI:5"); matchlist("en-US, en-IN, en-VI", "en-GB", "en-US:3 en-IN:4 en-VI:5"); matchlist("en-IN, en-GB, en-US", "en-VI", "en-US:4 en-GB:5 en-IN:5"); }
### Question: FileInfosPresenter implements FileInfosContract.Presenter { @Override public void loadFileInfos() { mFileInfosRepository .listFileInfos(mDirectory) .observeOn(mSchedulerProvider.ui()) .subscribe(new Action1<List<FileInfo>>() { @Override public void call(List<FileInfo> fileInfos) { if (fileInfos.isEmpty()) { mView.showNoFileInfos(); } else { mView.showFileInfos(fileInfos); } } }); } FileInfosPresenter(@NonNull FileInfo directory, @NonNull BaseSchedulerProvider schedulerProvider, @NonNull FileInfosContract.View view, @NonNull FileInfosRepository fileInfosRepository); @Override void subscribe(); @Override void unsubscribe(); @Override void loadFileInfos(); }### Answer: @Test public void loadFileInfos_success() throws Exception { setAvailableFileInfos(mMockFileInfosRepository); mFileInfosPresenter.loadFileInfos(); Mockito.verify(mMockView, Mockito.times(1)).showFileInfos(Mockito.anyListOf(FileInfo.class)); }
### Question: UserServiceImpl implements UserService { @Override public void create(User user) { User existing = userRepository.findByUsername(user.getUsername()); Assert.isNull(existing, "user already exist: " + user.getUsername()); String hash = encoder.encode(user.getPassword()); user.setPassword(hash); user.setEnabled(true); user = userRepository.save(user); UserRole userRole = new UserRole(user.getId(), UserUtility.ROLE_USER); userRoleRepository.save(userRole); logger.info("new user has been created {}", user.getUsername()); } @Override void create(User user); }### Answer: @Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(userRepository).findByUsername(anyString()); try { final User user = new User("imrenagi", "imrenagi", "imre"); userService.create(user); fail(); } catch (Exception e) { } } @Test public void shouldSaveNewUserWithUserRole() { final User user = new User("imrenagi", "imrenagi", "imre", "nagi"); user.setId(1L); doReturn(null).when(userRepository).findByUsername(user.getUsername()); doReturn(user).when(userRepository).save(any(User.class)); userService.create(user); verify(userRepository, times(1)).save(any(User.class)); verify(userRoleRepository, times(1)).save(any(UserRole.class)); }
### Question: MysqlUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userRepository.findByUsername(s); log.info("user is found! -> " + user.getUsername()); if (user == null) { log.info("user is not found!"); throw new UsernameNotFoundException(s); } return user; } @Override UserDetails loadUserByUsername(String s); }### Answer: @Test public void shouldReturnUserDetailWhenAUserIsFound() throws Exception { final User user = new User("imrenagi", "1234", "imre", "nagi"); doReturn(user).when(repository).findByUsername(user.getUsername()); UserDetails found = userDetailsService.loadUserByUsername(user.getUsername()); assertEquals(user.getUsername(), found.getUsername()); assertEquals(user.getPassword(), found.getPassword()); verify(repository, times(1)).findByUsername(user.getUsername()); } @Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(repository).findByUsername(anyString()); try { userDetailsService.loadUserByUsername(anyString()); fail(); } catch (Exception e) { } }
### Question: AccountServiceImpl implements AccountService { @Override public Account findByUserName(String username) { Assert.hasLength(username); return repository.findByUsername(username); } @Override Account findByUserName(String username); @Override Account findByEmail(String email); @Override Account create(User user); @Override List<Account> findAll(); }### Answer: @Test public void shouldFindByUserName() { final Account account = new Account(); account.setUsername("test"); doReturn(account).when(repository).findByUsername(account.getUsername()); Account found = accountService.findByUserName(account.getUsername()); assertEquals(account, found); verify(repository, times(1)).findByUsername(account.getUsername()); } @Test(expected = IllegalArgumentException.class) public void shouldFailFindByUserNameForEmptyUsername() { accountService.findByUserName(""); }
### Question: AccountServiceImpl implements AccountService { @Override public Account findByEmail(String email) { Assert.hasLength(email); return repository.findByEmail(email); } @Override Account findByUserName(String username); @Override Account findByEmail(String email); @Override Account create(User user); @Override List<Account> findAll(); }### Answer: @Test public void shouldFindByEmail() { final Account account = new Account(); account.setUsername("imrenagi"); account.setEmail("[email protected]"); doReturn(account).when(repository).findByEmail(account.getEmail()); Account found = accountService.findByEmail(account.getEmail()); assertEquals(account, found); verify(repository, times(1)).findByEmail(account.getEmail()); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenFindByEmptyEmail() { accountService.findByEmail(""); }
### Question: BigFontGenerator { public String convert(String text, int position) { HashMap<Character, String> hashMap = fonts.get(position); ArrayList<String> chars = new ArrayList<>(); for (int i = 0; i < text.length(); i++) { String s = hashMap.get(Character.toUpperCase(text.charAt(i))); if (s == null) { throw new UnsupportedOperationException("Invalid character " + text.charAt(i)); } chars.add(s); } StringBuilder result = new StringBuilder(); String[][] maps = new String[chars.size()][chars.get(0).split("\\n").length]; for (int i = 0; i < chars.size(); i++) { String str = chars.get(i); maps[i] = str.split("\\r?\\n"); } for (int j = 0; j < maps[0].length; j++) { for (int i = 0; i < chars.size(); i++) { result.append(maps[i][j]); } if (j != maps[0].length - 1) { result.append("\n"); } } return result.toString(); } BigFontGenerator(); boolean isLoaded(); void load(InputStream[] inputStream); int getSize(); String convert(String text, int position); }### Answer: @Test public void convert() throws Exception { String path = "C:\\github\\ascii_generate\\app\\src\\test\\java\\com\\duy\\ascii\\art\\bigtext\\out.txt"; PrintStream stream = new PrintStream(new FileOutputStream(path)); for (int i = 0; i < mBigFontGenerator.getSize(); i++) { String convert = mBigFontGenerator.convert("hello", i); stream.println(convert); System.out.println(convert); } stream.flush(); stream.close(); }
### Question: JavacTaskImpl extends JavacTask { public Boolean call() { if (!used.getAndSet(true)) { initContext(); notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>(); compilerMain.setAPIMode(true); result = compilerMain.compile(args, context, fileObjects, processors); cleanup(); return result == 0; } else { throw new IllegalStateException("multiple calls to method 'call'"); } } JavacTaskImpl(Main compilerMain, String[] args, Context context, List<JavaFileObject> fileObjects); JavacTaskImpl(Main compilerMain, Iterable<String> flags, Context context, Iterable<String> classes, Iterable<? extends JavaFileObject> fileObjects); Boolean call(); void setProcessors(Iterable<? extends Processor> processors); void setLocale(Locale locale); JavaFileObject asJavaFileObject(File file); void setTaskListener(TaskListener taskListener); Iterable<? extends CompilationUnitTree> parse(); Iterable<? extends TypeElement> enter(); Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees); @Override Iterable<? extends Element> analyze(); Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes); @Override Iterable<? extends JavaFileObject> generate(); Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes); TypeMirror getTypeMirror(Iterable<? extends Tree> path); JavacElements getElements(); JavacTypes getTypes(); Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node); Context getContext(); void updateContext(Context newContext); Type parseType(String expr, TypeElement scope); }### Answer: @Test public void testDynamicArgs() { javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler(); List<String> args = Arrays.asList("-help"); try { javax.tools.JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, null, null, args, null, null); compilationTask.call(); } catch (IllegalArgumentException e) { System.out.println("必然会抛IllegalArgumentException异常"); } }
### Question: Main { public static void main(String[] args) throws Exception { if (args.length > 0 && args[0].equals("-Xjdb")) { String[] newargs = new String[args.length + 2]; Class<?> c = Class.forName("com.sun.tools.example.debug.tty.TTY"); Method method = c.getDeclaredMethod("main", new Class<?>[] { args.getClass() }); method.setAccessible(true); System.arraycopy(args, 1, newargs, 3, args.length - 1); newargs[0] = "-connect"; newargs[1] = "com.sun.jdi.CommandLineLaunch:options=-esa -ea:com.sun.tools..."; newargs[2] = "com.sun.tools.javac.Main"; method.invoke(null, new Object[] { newargs }); } else { System.exit(compile(args)); } } static void main(String[] args); static int compile(String[] args); static int compile(String[] args, PrintWriter out); }### Answer: @Test public void testMain_fullversion() throws Exception { String[] args = {"-fullversion"}; Main.main(args); } @Test public void testMain_SimpleCompile() { String [] args = { JavacTestTool.JAVAFILES_PATH + "Simple.java", "-d", JavacTestTool.CLASSFILES_PATH, "-verbose" }; try { Main.main(args); } catch (Exception e) { e.printStackTrace(); } } @Test public void testMain_Xprint() throws Exception { String[] args = { "-Xprint", "java.lang.String"}; Main.main(args); } @Test public void testMain_X() throws Exception { String[] args = {"-X"}; Main.main(args); } @Test public void testMain_help() throws Exception { String[] args = {"-help"}; Main.main(args); } @Test public void testMain_version() throws Exception { String[] args = {"-version"}; Main.main(args); }
### Question: Launcher { public static void main(String... args) { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); JFileChooser fileChooser; Preferences prefs = Preferences.userNodeForPackage(Launcher.class); if (args.length > 0) fileChooser = new JFileChooser(args[0]); else { String fileName = prefs.get("recent.file", null); fileChooser = new JFileChooser(); if (fileName != null) { fileChooser = new JFileChooser(); fileChooser.setSelectedFile(new File(fileName)); } } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { String fileName = fileChooser.getSelectedFile().getPath(); prefs.put("recent.file", fileName); javac.run( System.in, null, null, "-d", "D:/Workspace/JSE/workspace/Compiler_javac/test-files/class-files", fileName); } } static void main(String... args); }### Answer: @Test public void testLauncher_fileChooser() { String[] args = {"D:/Workspace/JSE/workspace/Compiler_javac"}; Launcher.main(args); } @Test public void testLauncher_noArgs() { String[] args = {}; Launcher.main(args); } @Test public void testLauncher_Xprint() throws Exception { String[] args = { "-Xprint", "java.lang.String"}; Launcher.main(args); }
### Question: Main { public static int compile(String[] args) { com.sun.tools.javac.main.Main compiler = new com.sun.tools.javac.main.Main("javac"); return compiler.compile(args); } static void main(String[] args); static int compile(String[] args); static int compile(String[] args, PrintWriter out); }### Answer: @Test public void testMain_nullArgs() throws Exception { String[] args = {}; int status = Main.compile(args); assertTrue(status == 2); System.exit(status); }
### Question: Parser { public MavenRepositoryURL getRepositoryURL() { return m_repositoryURL; } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void behaviorSnapshotEnbled() throws MalformedURLException { Parser parser; parser = new Parser( "http: assertTrue(parser.getRepositoryURL().isSnapshotsEnabled()); assertTrue(parser.getRepositoryURL().isReleasesEnabled()); }
### Question: Parser { public String getResourceName() { return m_resourceName; } Parser( final String path ); String getResourceName(); }### Answer: @Test public void getResourceNameWithContainingSlash() throws MalformedURLException { assertEquals( "Resource name", "somewhere/resource", new Parser( "somewhere/resource" ).getResourceName() ); } @Test public void getResourceNameWithoutLeadingSlash() throws MalformedURLException { assertEquals( "Resource name", "resource", new Parser( "resource" ).getResourceName() ); } @Test public void getResourceNameWithLeadingSlash() throws MalformedURLException { assertEquals( "Resource name", "resource", new Parser( "/resource" ).getResourceName() ); }
### Question: AbstractConnection extends URLConnection { protected static boolean checkJarIsLegal(String name) { boolean isMatched = false; for (Pattern pattern : blacklist) { isMatched = pattern.matcher(name).find(); if (isMatched) { break; } } return !isMatched; } protected AbstractConnection( final URL url, final Configuration configuration ); @Override InputStream getInputStream(); @Override void connect(); }### Answer: @Test public void testCheckJarIsLegal() { String[] servletJarNamesToTest = { "servlet.jar", "servlet-2.5.jar", "servlet-api.jar", "servlet-api-2.5.jar" }; for (String servletName : servletJarNamesToTest) { assertFalse(AbstractConnection.checkJarIsLegal(servletName)); } String[] jasperJarNamesToTest = { "jasper.jar", "jasper-2.5.jar", }; for (String servletName : jasperJarNamesToTest) { assertFalse(AbstractConnection.checkJarIsLegal(servletName)); } }
### Question: Parser { public URL getWrappedJarURL() { return m_wrappedJarURL; } Parser( final String path, final boolean certificateCheck ); URL getWrappedJarURL(); Properties getWrappingProperties(); OverwriteMode getOverwriteMode(); }### Answer: @Test public void validWrappedJarURL() throws MalformedURLException { Parser parser = new Parser( "file:toWrap.jar", true ); assertEquals( "Wrapped Jar URL", new URL( "file:toWrap.jar" ), parser.getWrappedJarURL() ); assertNotNull( "Properties was not expected to be null", parser.getWrappedJarURL() ); }
### Question: ConfigurationImpl extends PropertyStore implements Configuration { public Boolean getCertificateCheck() { if( !contains( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ) ) { return set( ServiceConstants.PROPERTY_CERTIFICATE_CHECK, Boolean.valueOf( m_propertyResolver.get( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ) ) ); } return get( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ); } ConfigurationImpl( final PropertyResolver propertyResolver ); Boolean getCertificateCheck(); }### Answer: @Test public void getCertificateCheck() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.url.wrap.certificateCheck" ) ).andReturn( "true" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Certificate check", true, config.getCertificateCheck() ); verify( propertyResolver ); } @Test public void getDefaultCertificateCheck() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.url.wrap.certificateCheck" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Certificate check", false, config.getCertificateCheck() ); verify( propertyResolver ); }
### Question: Connection extends URLConnection { @Override public InputStream getInputStream() throws IOException { return new BundleBuilder( m_parser.getOptions(), new ResourceWriter( new FileTailImpl( m_parser.getDirectory(), m_parser.getTailExpr() ) .getParentOfTail() ) ).build(); } Connection( URL url, Configuration config ); @Override InputStream getInputStream(); void connect(); }### Answer: @Test public void simple() throws IOException { String clazz = this.getClass().getName().replaceAll( "\\.", "/" ) + ".class"; URL url = new URL( "http:.$tail=" + clazz + "&Foo=bar" ); Configuration config = createMock( Configuration.class ); Connection con = new Connection( url, config ); InputStream inp = con.getInputStream(); FunctionalTest.dumpToConsole( inp, 16 ); }
### Question: Parser { public File getDirectory() { return m_directory; } Parser( String url ); File getDirectory(); Properties getOptions(); String getTailExpr(); }### Answer: @Test public void parseValidURL() throws IOException { File f = new File( System.getProperty( "java.io.tmpdir" ) ); assertEquals( f.getCanonicalPath(), new Parser( "http:" + f.getCanonicalPath() ).getDirectory().getAbsolutePath() ); }
### Question: Parser { public Properties getOptions() { return m_options; } Parser( String url ); File getDirectory(); Properties getOptions(); String getTailExpr(); }### Answer: @Test public void parseWithMoreParams() throws IOException, URISyntaxException { Parser parser = new Parser( "http:." + "$a=1&b=2" ); assertEquals( "1", parser.getOptions().get( "a" ) ); assertEquals( "2", parser.getOptions().get( "b" ) ); assertEquals( 2, parser.getOptions().size() ); }
### Question: Parser { public String getSnapshotPath( final String version, final String timestamp, final String buildnumber ) { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( version ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( VERSION_SEPARATOR ) .append( getSnapshotVersion( version, timestamp, buildnumber ) ) .append( m_fullClassifier ) .append( TYPE_SEPARATOR ) .append( m_type ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void snapshotPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version-SNAPSHOT" ); assertEquals( "Artifact snapshot path", "group/artifact/version-SNAPSHOT/artifact-version-timestamp-build.jar", parser.getSnapshotPath( "version-SNAPSHOT", "timestamp", "build" ) ); }
### Question: Parser { public String getArtifactPath() { return getArtifactPath( m_version ); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void artifactPathWithVersion() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact path", "group/artifact/version2/artifact-version2.jar", parser.getArtifactPath( "version2" ) ); }
### Question: Parser { public String getVersionMetadataPath( final String version ) { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( version ) .append( FILE_SEPARATOR ) .append( METADATA_FILE ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void versionMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Version metadata path", "group/artifact/version2/maven-metadata.xml", parser.getVersionMetadataPath( "version2" ) ); }
### Question: Parser { public String getArtifactMetdataPath() { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( METADATA_FILE ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void artifactMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact metadata path", "group/artifact/maven-metadata.xml", parser.getArtifactMetdataPath() ); }
### Question: Parser { public String getArtifactLocalMetdataPath() { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( METADATA_FILE_LOCAL ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }### Answer: @Test public void artifactLocalMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact local metadata path", "group/artifact/maven-metadata-local.xml", parser.getArtifactLocalMetdataPath() ); }
### Question: Connection extends URLConnection { public InputStream getInputStream() throws IOException { connect(); InputStream is; if( url.getAuthority() != null ) { is = getFromSpecificBundle(); } else { is = getFromClasspath(); if( is == null ) { is = getFromInstalledBundles(); } } if( is == null ) { throw new IOException( "URL [" + m_parser.getResourceName() + "] could not be resolved from classpath" ); } return is; } Connection( final URL url, final BundleContext bundleContext ); @Override void connect(); InputStream getInputStream(); static final String PROTOCOL; }### Answer: @Test public void searchFirstTheThreadClasspath() throws IOException { BundleContext context = createMock( BundleContext.class ); replay( context ); InputStream is = new Connection( new URL( "http:connection/resource" ), context ).getInputStream(); assertNotNull( "Returned input stream is null", is ); verify( context ); }
### Question: MatrixUtils { public static double[] slicedSimilarity(double[][] matrix, double[] vector, int sliceSize) { int size = matrix.length; double[] result = new double[size]; for (int i = 0; i < size; i = i + sliceSize) { int end = i + sliceSize; if (end > size) { end = size; } double[][] m = Arrays.copyOfRange(matrix, i, end); double[] sim = mult(m, vector); System.arraycopy(sim, 0, result, i, sim.length); } return result; } static double[] vectorSimilarity(SparseDataset matrix, SparseArray vector); static SparseVector asSparseVector(int ncol, SparseArray vector); static double[] vectorSimilarity(double[][] matrix, double[] vector); static double[] slicedSimilarity(double[][] matrix, double[] vector, int sliceSize); static double[][] matrixSimilarity(SparseDataset d1, SparseDataset d2); static double[][] to2d(DenseMatrix dense); static CompRowMatrix asRowMatrix(SparseDataset dataset); static double[][] l2RowNormalize(double[][] data); static double[] rowWiseDot(double[][] m1, double[][] m2); static double[] rowWiseSparseDot(SparseDataset m1, SparseDataset m2); }### Answer: @Test public void slicedSimilarityEven() { double[][] matrix = { {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6} }; double[] vector = {0, 1}; int sliceSize = 2; double[] similarity = MatrixUtils.slicedSimilarity(matrix, vector, sliceSize); double[] expected = {1, 2, 3, 4, 5, 6}; assertTrue(Arrays.equals(expected, similarity)); } @Test public void slicedSimilarityUneven() { double[][] matrix = { {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, }; double[] vector = {0, 1}; int sliceSize = 3; double[] similarity = MatrixUtils.slicedSimilarity(matrix, vector, sliceSize); double[] expected = {1, 2, 3, 4, 5, 6, 7}; assertTrue(Arrays.equals(expected, similarity)); }
### Question: RelevanceModel { public static Dataset concat(Dataset d1, Dataset d2) { double[][] X = concat(d1.getX(), d2.getX()); double[] y = concat(d1.getY(), d2.getY()); return new Dataset(X, y); } static void main(String[] args); static Dataset concat(Dataset d1, Dataset d2); static double[] concat(double[] y1, double[] y2); static double[][] concat(double[][] X1, double[][] X2); static double auc(SoftClassifier<double[]> model, Dataset dataset); static double[] predict(SoftClassifier<double[]> model, Dataset dataset); }### Answer: @Test public void concat1d() { double[] y1 = { 1.0, 2.0, 3.0 }; double[] y2 = { 4.0, 5.0 }; double[] y = RelevanceModel.concat(y1, y2); double[] expected = { 1.0, 2.0, 3.0, 4.0, 5.0 }; assertTrue(Arrays.equals(y, expected)); } @Test public void concat2d() { double[][] X1 = { { 0.0, 1.0 }, { 0.0, 2.0 }, { 0.0, 3.0 } }; double[][] X2 = { { 0.0, 4.0 }, { 0.0, 5.0 } }; double[][] X = RelevanceModel.concat(X1, X2); double[][] expected = { { 0.0, 1.0 }, { 0.0, 2.0 }, { 0.0, 3.0 }, { 0.0, 4.0 }, { 0.0, 5.0 } }; assertTrue(Arrays.deepEquals(X, expected)); }
### Question: NerGroup { public static List<String> groupNer(List<Word> tokens) { if (tokens.isEmpty()) { return Collections.emptyList(); } String prevNer = "O"; List<List<Word>> groups = new ArrayList<>(); List<Word> group = new ArrayList<>(); for (Word w : tokens) { String ner = w.getNer(); if (prevNer.equals(ner) && !"O".equals(ner)) { group.add(w); continue; } groups.add(group); group = new ArrayList<>(); group.add(w); prevNer = ner; } groups.add(group); return groups.stream() .filter(l -> !l.isEmpty()) .map(list -> joinLemmas(list)) .collect(Collectors.toList()); } static List<String> groupNer(List<Word> tokens); }### Answer: @Test public void test() { List<Word> tokens = Arrays.asList( new Word("My", "My", "_", "O"), new Word("name", "name", "_", "O"), new Word("is", "is", "_", "O"), new Word("Justin", "Justin", "_", "PERSON"), new Word("Bieber", "Bieber", "_", "PERSON"), new Word("I", "I", "_", "O"), new Word("live", "live", "_", "O"), new Word("in", "in", "_", "O"), new Word("Brooklyn", "Brooklyn", "_", "LOCATION"), new Word(",", ",", "_", "O"), new Word("New", "New", "_", "LOCATION"), new Word("York", "York", "_", "LOCATION"), new Word(".", ".", "_", "O") ); List<String> results = NerGroup.groupNer(tokens); List<String> expected = Arrays.asList("My", "name", "is", "Justin Bieber", "I", "live", "in", "Brooklyn", ",", "New York", "."); assertEquals(expected, results); }
### Question: DefaultJavaRunner implements StoppableJavaRunner { static String getJavaExecutable( final String javaHome ) throws PlatformException { if( javaHome == null ) { throw new PlatformException( "JAVA_HOME is not set." ); } return javaHome + "/bin/java"; } DefaultJavaRunner(); DefaultJavaRunner( boolean wait ); synchronized void exec( final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory ); synchronized void exec( final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory, final String[] envOptions ); void shutdown(); void waitForExit(); }### Answer: @Test public void getJavaExecutable() throws Exception { assertEquals( "Java executable", "javaHome/bin/java", DefaultJavaRunner.getJavaExecutable( "javaHome" ) ); } @Test( expected = PlatformException.class ) public void getJavaExecutableWithInvalidJavaHome() throws Exception { DefaultJavaRunner.getJavaExecutable( null ); }
### Question: ConciergePlatformBuilder implements PlatformBuilder { public String[] getArguments( final PlatformContext context ) { return null; } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getArguments() throws MalformedURLException { replay( m_bundleContext ); assertArrayEquals( "Arguments", null, new ConciergePlatformBuilder( m_bundleContext, "version" ).getArguments( m_platformContext ) ); verify( m_bundleContext ); }
### Question: ConciergePlatformBuilder implements PlatformBuilder { public String[] getVMOptions( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); final Collection<String> vmOptions = new ArrayList<String>(); final File workingDirectory = context.getWorkingDirectory(); vmOptions.add( "-Dosgi.maxLevel=100" ); vmOptions.add( "-Dxargs=" + context.getFilePathStrategy().normalizeAsPath( new File( new File( workingDirectory, CONFIG_DIRECTORY ), CONFIG_INI ) ) ); final String bootDelegation = context.getConfiguration().getBootDelegation(); if( bootDelegation != null ) { vmOptions.add( "-D" + Constants.FRAMEWORK_BOOTDELEGATION + "=" + bootDelegation ); } return vmOptions.toArray( new String[vmOptions.size()] ); } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getVMOptions() { expect( m_configuration.getBootDelegation() ).andReturn( "javax.*" ); replay( m_configuration, m_bundleContext ); assertArrayEquals( "System options", new String[]{ "-Dosgi.maxLevel=100", "-Dxargs=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "concierge/config.ini" ) ), "-D" + Constants.FRAMEWORK_BOOTDELEGATION + "=javax.*" }, new ConciergePlatformBuilder( m_bundleContext, "version" ).getVMOptions( m_platformContext ) ); verify( m_configuration, m_bundleContext ); } @Test public void getVMOptionsWithoutBootDelegation() { expect( m_configuration.getBootDelegation() ).andReturn( null ); replay( m_configuration, m_bundleContext ); assertArrayEquals( "System options", new String[]{ "-Dosgi.maxLevel=100", "-Dxargs=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "concierge/config.ini" ) ) }, new ConciergePlatformBuilder( m_bundleContext, "version" ).getVMOptions( m_platformContext ) ); verify( m_configuration, m_bundleContext ); } @Test( expected = IllegalArgumentException.class ) public void getSystemPropertiesWithNullPlatformContext() { replay( m_bundleContext ); new ConciergePlatformBuilder( m_bundleContext, "version" ).getVMOptions( null ); verify( m_bundleContext ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String getMainClassName() { return MAIN_CLASS_NAME; } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void mainClassName() { replay( m_bundleContext ); assertEquals( "Main class name", "org.knopflerfish.framework.Main", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getMainClassName() ); verify( m_bundleContext ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String getRequiredProfile( final PlatformContext context ) { final Boolean console = context.getConfiguration().startConsole(); if( console == null || !console ) { return null; } else { return CONSOLE_PROFILE; } } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getRequiredProfilesWithoutConsole() { expect( m_configuration.startConsole() ).andReturn( null ); replay( m_bundleContext, m_configuration ); assertNull( "Required profiles is not null", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); } @Test public void getRequiredProfilesWithConsole() { expect( m_configuration.startConsole() ).andReturn( true ); replay( m_bundleContext, m_configuration ); assertEquals( "Required profiles", "tui", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String[] getArguments( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); return new String[]{ "-xargs", context.getFilePathStrategy().normalizeAsUrl( new File( new File( context.getWorkingDirectory(), CONFIG_DIRECTORY ), CONFIG_INI ) ) }; } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getArguments() throws MalformedURLException { replay( m_bundleContext ); assertArrayEquals( "Arguments", new String[]{ "-xargs", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "knopflerfish/config.ini" ) ), }, new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getArguments( m_platformContext ) ); verify( m_bundleContext ); }
### Question: KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String[] getVMOptions( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); final Collection<String> vmOptions = new ArrayList<String>(); final File workingDirectory = context.getWorkingDirectory(); vmOptions.add( "-Dorg.osgi.framework.dir=" + context.getFilePathStrategy().normalizeAsPath( new File( new File( workingDirectory, CONFIG_DIRECTORY ), CACHE_DIRECTORY ) ) ); return vmOptions.toArray( new String[vmOptions.size()] ); } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }### Answer: @Test public void getVMOptions() { replay( m_bundleContext ); assertArrayEquals( "System properties", new String[]{ "-Dorg.osgi.framework.dir=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "knopflerfish/fwdir" ) ) }, new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getVMOptions( m_platformContext ) ); verify( m_bundleContext ); } @Test( expected = IllegalArgumentException.class ) public void getSystemPropertiesWithNullPlatformContext() { replay( m_bundleContext ); new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getVMOptions( null ); verify( m_bundleContext ); }
### Question: CommandLineImpl implements CommandLine { public String getOption( final String key ) { final List<String> values = m_options.get( key ); return values == null || values.size() == 0 ? null : values.get( 0 ); } CommandLineImpl( final String... args ); String getOption( final String key ); String[] getMultipleOption( final String key ); List<String> getArguments(); String getArgumentsFileURL(); @Override String toString(); static final Pattern OPTION_PATTERN; }### Answer: @Test public void simpleOption() { CommandLine commandLine = new CommandLineImpl( "--simpleOption=simpleValue" ); assertEquals( "Option value", "simpleValue", commandLine.getOption( "simpleOption" ) ); } @Test public void optionWithAValueThatContainsEqual01() { CommandLine commandLine = new CommandLineImpl( "--simpleOption=-Dhttp.port=80" ); assertEquals( "Option value", "-Dhttp.port=80", commandLine.getOption( "simpleOption" ) ); } @Test public void optionWithAValueThatContainsEqual02() { CommandLine commandLine = new CommandLineImpl( "--simpleOption=-Dhttp.port=80 -Dhttp.port.secure=443" ); assertEquals( "Option value", "-Dhttp.port=80 -Dhttp.port.secure=443", commandLine.getOption( "simpleOption" ) ); } @Test public void implicitFalseValue() { CommandLine commandLine = new CommandLineImpl( "--noSimpleOption" ); assertEquals( "Option value", "false", commandLine.getOption( "simpleOption" ) ); } @Test public void implicitTrueValue() { CommandLine commandLine = new CommandLineImpl( "--simpleOption" ); assertEquals( "Option value", "true", commandLine.getOption( "simpleOption" ) ); } @Test public void readArgsFile() { CommandLine commandLine = new CommandLineImpl( "--args=file:src/test/resources/runner.args" ); assertEquals( "option1 value", "value1", commandLine.getOption( "option1" ) ); assertEquals( "option2 value", "-Dhttp.port=80", commandLine.getOption( "option2" ) ); assertEquals( "option3 value", "false", commandLine.getOption( "option3" ) ); assertEquals( "option4 value", "true", commandLine.getOption( "option4" ) ); assertEquals( "vmo value", "-Doscar.embedded.execution=false " + "-Djava.library.path=native " + "-Djava.util.logging.config.file=../conf/logging.properties", commandLine.getOption( "vmo" ) ); assertEquals( "option5 value", "value5", commandLine.getOption( "option5" ) ); assertEquals( "option6 value", "", commandLine.getOption( "option6" ) ); assertEquals( "sp value", "org.osgi.framework; javax.swing; " + "javax.swing.event; javax.swing.table; javax.swing.text; " + "javax.swing.text.html;", commandLine.getOption( "sp" ) ); assertEquals( "option7 value", "value7continued", commandLine.getOption( "option7" ) ); assertEquals( "option8 value", "value8", commandLine.getOption( "option8" ) ); } @Test public void profilesAsArgs() { CommandLine commandLine = new CommandLineImpl( "--noArgs", "log", "web/[1.0,2.0)" ); assertEquals( "Profiles option", "log:web/[1.0,2.0)", commandLine.getOption( "profiles" ) ); }
### Question: CommandLineImpl implements CommandLine { public String[] getMultipleOption( final String key ) { final List<String> values = m_options.get( key ); return values == null || values.size() == 0 ? new String[0] : values.toArray( new String[values.size()] ); } CommandLineImpl( final String... args ); String getOption( final String key ); String[] getMultipleOption( final String key ); List<String> getArguments(); String getArgumentsFileURL(); @Override String toString(); static final Pattern OPTION_PATTERN; }### Answer: @Test public void arrayValueNotDefined() { CommandLine commandLine = new CommandLineImpl( "--some" ); assertArrayEquals( "Option value", new String[0], commandLine.getMultipleOption( "array" ) ); }