src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
SearchHistoryEntity implements SearchHistory { @Override public CarmenFeature getCarmenFeature() { return carmenFeature; } SearchHistoryEntity(@NonNull String placeId, CarmenFeature carmenFeature); @Override @NonNull String getPlaceId(); @Override CarmenFeature getCarmenFeature(); }
@Test public void getCarmenFeature_doesReturnTheSetCarmenFeature() throws Exception { CarmenFeature feature = CarmenFeature.builder() .id("myCarmenFeature") .properties(new JsonObject()) .build(); SearchHistoryEntity entity = new SearchHistoryEntity("placeId", feature); assertNotNull(entity.getCarmenFeature()); assertThat(entity.getCarmenFeature().id(), equalTo("myCarmenFeature")); }
DraggableAnnotationController { boolean startDragging(@NonNull Annotation annotation, @NonNull AnnotationManager annotationManager) { if (annotation.isDraggable()) { for (OnAnnotationDragListener d : (List<OnAnnotationDragListener>) annotationManager.getDragListeners()) { d.onAnnotationDragStarted(annotation); } draggedAnnotation = annotation; draggedAnnotationManager = annotationManager; return true; } return false; } @SuppressLint("ClickableViewAccessibility") DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap); @VisibleForTesting DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap, final AndroidGesturesManager androidGesturesManager, int touchAreaShiftX, int touchAreaShiftY, int touchAreaMaxX, int touchAreaMaxY); static DraggableAnnotationController getInstance(MapView mapView, MapboxMap mapboxMap); }
@Test public void annotationNotDraggableTest() { when(annotation.isDraggable()).thenReturn(false); draggableAnnotationController.startDragging(annotation, annotationManager); verify(dragListener, times(0)).onAnnotationDragStarted(annotation); } @Test public void annotationDragStartTest() { when(annotation.isDraggable()).thenReturn(true); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); draggableAnnotationController.startDragging(annotation, annotationManager); verify(dragListener, times(1)).onAnnotationDragStarted(annotation); }
DraggableAnnotationController { void stopDragging(@Nullable Annotation annotation, @Nullable AnnotationManager annotationManager) { if (annotation != null && annotationManager != null) { for (OnAnnotationDragListener d : (List<OnAnnotationDragListener>) annotationManager.getDragListeners()) { d.onAnnotationDragFinished(annotation); } } draggedAnnotation = null; draggedAnnotationManager = null; } @SuppressLint("ClickableViewAccessibility") DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap); @VisibleForTesting DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap, final AndroidGesturesManager androidGesturesManager, int touchAreaShiftX, int touchAreaShiftY, int touchAreaMaxX, int touchAreaMaxY); static DraggableAnnotationController getInstance(MapView mapView, MapboxMap mapboxMap); }
@Test public void annotationDragStopNoneTest() { draggableAnnotationController.stopDragging(null, null); verify(dragListener, times(0)).onAnnotationDragFinished(annotation); } @Test public void annotationDragStopTest() { when(annotation.isDraggable()).thenReturn(true); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); draggableAnnotationController.stopDragging(annotation, annotationManager); verify(dragListener, times(1)).onAnnotationDragFinished(annotation); }
CarmenFeatureConverter { @TypeConverter public static CarmenFeature toCarmenFeature(String serializedCarmenFeature) { return serializedCarmenFeature == null ? null : CarmenFeature.fromJson(serializedCarmenFeature); } private CarmenFeatureConverter(); @TypeConverter static CarmenFeature toCarmenFeature(String serializedCarmenFeature); @TypeConverter static String fromCarmenFeature(@NonNull CarmenFeature carmenFeature); }
@Test public void toCarmenFeature_equalsNull() throws Exception { CarmenFeature carmenFeature = CarmenFeatureConverter.toCarmenFeature(null); assertNull(carmenFeature); } @Test public void toCarmenFeature_successfullyConvertsToFeature() throws Exception { String json = "{\"id\":\"place.9962989141465270\",\"type\":\"Feature\"," + "\"place_type\":[\"place\"],\"relevance\":0.99,\"properties\":{\"wikidata\":\"Q65\"}," + "\"text\":\"Los Angeles\",\"place_name\":\"Los Angeles, California, United States\"," + "\"bbox\":[-118.529221009603,33.901599990108,-118.121099990025,34.1612200099034]," + "\"center\":[-118.2439,34.0544],\"geometry\":{\"type\":\"Point\"," + "\"coordinates\":[-118.2439,34.0544]},\"context\":[{\"id\":\"region.3591\"," + "\"short_code\":\"US-CA\",\"wikidata\":\"Q99\",\"text\":\"California\"}," + "{\"id\":\"country.3145\",\"short_code\":\"us\",\"wikidata\":\"Q30\"," + "\"text\":\"United States\"}]}"; CarmenFeature carmenFeature = CarmenFeatureConverter.toCarmenFeature(json); assertNotNull(carmenFeature); assertThat(carmenFeature.id(), equalTo("place.9962989141465270")); assertThat(carmenFeature.type(), equalTo("Feature")); assertThat(carmenFeature.relevance(), equalTo(0.99)); assertThat(carmenFeature.text(), equalTo("Los Angeles")); assertThat(carmenFeature.placeName(), equalTo("Los Angeles, California, United States")); }
DraggableAnnotationController { boolean onMoveBegin(MoveGestureDetector detector) { for (AnnotationManager annotationManager : annotationManagers) { if (detector.getPointersCount() == 1) { Annotation annotation = annotationManager.queryMapForFeatures(detector.getFocalPoint()); if (annotation != null && startDragging(annotation, annotationManager)) { return true; } } } return false; } @SuppressLint("ClickableViewAccessibility") DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap); @VisibleForTesting DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap, final AndroidGesturesManager androidGesturesManager, int touchAreaShiftX, int touchAreaShiftY, int touchAreaMaxX, int touchAreaMaxY); static DraggableAnnotationController getInstance(MapView mapView, MapboxMap mapboxMap); }
@Test public void gestureOnMoveBeginWrongPointersTest() { when(annotation.isDraggable()).thenReturn(true); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); PointF pointF = new PointF(); when(annotationManager.queryMapForFeatures(pointF)).thenReturn(annotation); when(moveGestureDetector.getFocalPoint()).thenReturn(pointF); when(moveGestureDetector.getPointersCount()).thenReturn(0); boolean moveBegan1 = draggableAnnotationController.onMoveBegin(moveGestureDetector); assertFalse(moveBegan1); when(moveGestureDetector.getPointersCount()).thenReturn(2); boolean moveBegan2 = draggableAnnotationController.onMoveBegin(moveGestureDetector); assertFalse(moveBegan2); verify(dragListener, times(0)).onAnnotationDragStarted(annotation); } @Test public void gestureOnMoveBeginTest() { when(annotation.isDraggable()).thenReturn(true); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); PointF pointF = new PointF(); when(annotationManager.queryMapForFeatures(pointF)).thenReturn(annotation); when(moveGestureDetector.getFocalPoint()).thenReturn(pointF); when(moveGestureDetector.getPointersCount()).thenReturn(1); boolean moveBegan = draggableAnnotationController.onMoveBegin(moveGestureDetector); assertTrue(moveBegan); verify(dragListener, times(1)).onAnnotationDragStarted(annotation); } @Test public void gestureOnMoveBeginNonDraggableAnnotationTest() { when(annotation.isDraggable()).thenReturn(false); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); PointF pointF = new PointF(); when(annotationManager.queryMapForFeatures(pointF)).thenReturn(annotation); when(moveGestureDetector.getFocalPoint()).thenReturn(pointF); when(moveGestureDetector.getPointersCount()).thenReturn(1); boolean moveBegan = draggableAnnotationController.onMoveBegin(moveGestureDetector); assertFalse(moveBegan); verify(dragListener, times(0)).onAnnotationDragStarted(annotation); }
SymbolManager extends AnnotationManager<SymbolLayer, Symbol, SymbolOptions, OnSymbolDragListener, OnSymbolClickListener, OnSymbolLongClickListener> { @Override public void setFilter(@NonNull Expression expression) { layerFilter = expression; layer.setFilter(layerFilter); } @UiThread SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<SymbolLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Symbol> create(@NonNull String json); @UiThread List<Symbol> create(@NonNull FeatureCollection featureCollection); String getSymbolPlacement(); void setSymbolPlacement(@Property.SYMBOL_PLACEMENT String value); Float getSymbolSpacing(); void setSymbolSpacing( Float value); Boolean getSymbolAvoidEdges(); void setSymbolAvoidEdges( Boolean value); Boolean getIconAllowOverlap(); void setIconAllowOverlap( Boolean value); Boolean getIconIgnorePlacement(); void setIconIgnorePlacement( Boolean value); Boolean getIconOptional(); void setIconOptional( Boolean value); String getIconRotationAlignment(); void setIconRotationAlignment(@Property.ICON_ROTATION_ALIGNMENT String value); String getIconTextFit(); void setIconTextFit(@Property.ICON_TEXT_FIT String value); Float[] getIconTextFitPadding(); void setIconTextFitPadding( Float[] value); Float getIconPadding(); void setIconPadding( Float value); Boolean getIconKeepUpright(); void setIconKeepUpright( Boolean value); String getIconPitchAlignment(); void setIconPitchAlignment(@Property.ICON_PITCH_ALIGNMENT String value); String getTextPitchAlignment(); void setTextPitchAlignment(@Property.TEXT_PITCH_ALIGNMENT String value); String getTextRotationAlignment(); void setTextRotationAlignment(@Property.TEXT_ROTATION_ALIGNMENT String value); Float getTextLineHeight(); void setTextLineHeight( Float value); String[] getTextVariableAnchor(); void setTextVariableAnchor( String[] value); Float getTextMaxAngle(); void setTextMaxAngle( Float value); Float getTextPadding(); void setTextPadding( Float value); Boolean getTextKeepUpright(); void setTextKeepUpright( Boolean value); Boolean getTextAllowOverlap(); void setTextAllowOverlap( Boolean value); Boolean getTextIgnorePlacement(); void setTextIgnorePlacement( Boolean value); Boolean getTextOptional(); void setTextOptional( Boolean value); Float[] getIconTranslate(); void setIconTranslate( Float[] value); String getIconTranslateAnchor(); void setIconTranslateAnchor(@Property.ICON_TRANSLATE_ANCHOR String value); Float[] getTextTranslate(); void setTextTranslate( Float[] value); String getTextTranslateAnchor(); void setTextTranslateAnchor(@Property.TEXT_TRANSLATE_ANCHOR String value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testInitialization() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(symbolLayer); assertTrue(symbolManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : symbolManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(symbolLayer).setProperties(symbolManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(symbolLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testInitializationOnStyleReload() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(symbolLayer); assertTrue(symbolManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : symbolManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(symbolLayer).setProperties(symbolManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); Expression filter = Expression.literal(false); symbolManager.setFilter(filter); ArgumentCaptor<MapView.OnDidFinishLoadingStyleListener> loadingArgumentCaptor = ArgumentCaptor.forClass(MapView.OnDidFinishLoadingStyleListener.class); verify(mapView).addOnDidFinishLoadingStyleListener(loadingArgumentCaptor.capture()); loadingArgumentCaptor.getValue().onDidFinishLoadingStyle(); ArgumentCaptor<Style.OnStyleLoaded> styleLoadedArgumentCaptor = ArgumentCaptor.forClass(Style.OnStyleLoaded.class); verify(mapboxMap).getStyle(styleLoadedArgumentCaptor.capture()); Style newStyle = mock(Style.class); when(newStyle.isFullyLoaded()).thenReturn(true); GeoJsonSource newSource = mock(GeoJsonSource.class); when(coreElementProvider.getSource(null)).thenReturn(newSource); SymbolLayer newLayer = mock(SymbolLayer.class); when(coreElementProvider.getLayer()).thenReturn(newLayer); styleLoadedArgumentCaptor.getValue().onStyleLoaded(newStyle); verify(newStyle).addSource(newSource); verify(newStyle).addLayer(newLayer); assertTrue(symbolManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : symbolManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(newLayer).setProperties(symbolManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(symbolLayer).setFilter(filter); verify(draggableAnnotationController, times(2)).onSourceUpdated(); verify(newSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testGeoJsonOptionsInitialization() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, geoJsonOptions, draggableAnnotationController); verify(style).addSource(optionedGeoJsonSource); verify(style).addLayer(symbolLayer); assertTrue(symbolManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : symbolManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(symbolLayer).setProperties(symbolManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(symbolLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(optionedGeoJsonSource).setGeoJson(any(FeatureCollection.class)); }
SymbolManager extends AnnotationManager<SymbolLayer, Symbol, SymbolOptions, OnSymbolDragListener, OnSymbolClickListener, OnSymbolLongClickListener> { @UiThread public List<Symbol> create(@NonNull String json) { return create(FeatureCollection.fromJson(json)); } @UiThread SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting SymbolManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<SymbolLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Symbol> create(@NonNull String json); @UiThread List<Symbol> create(@NonNull FeatureCollection featureCollection); String getSymbolPlacement(); void setSymbolPlacement(@Property.SYMBOL_PLACEMENT String value); Float getSymbolSpacing(); void setSymbolSpacing( Float value); Boolean getSymbolAvoidEdges(); void setSymbolAvoidEdges( Boolean value); Boolean getIconAllowOverlap(); void setIconAllowOverlap( Boolean value); Boolean getIconIgnorePlacement(); void setIconIgnorePlacement( Boolean value); Boolean getIconOptional(); void setIconOptional( Boolean value); String getIconRotationAlignment(); void setIconRotationAlignment(@Property.ICON_ROTATION_ALIGNMENT String value); String getIconTextFit(); void setIconTextFit(@Property.ICON_TEXT_FIT String value); Float[] getIconTextFitPadding(); void setIconTextFitPadding( Float[] value); Float getIconPadding(); void setIconPadding( Float value); Boolean getIconKeepUpright(); void setIconKeepUpright( Boolean value); String getIconPitchAlignment(); void setIconPitchAlignment(@Property.ICON_PITCH_ALIGNMENT String value); String getTextPitchAlignment(); void setTextPitchAlignment(@Property.TEXT_PITCH_ALIGNMENT String value); String getTextRotationAlignment(); void setTextRotationAlignment(@Property.TEXT_ROTATION_ALIGNMENT String value); Float getTextLineHeight(); void setTextLineHeight( Float value); String[] getTextVariableAnchor(); void setTextVariableAnchor( String[] value); Float getTextMaxAngle(); void setTextMaxAngle( Float value); Float getTextPadding(); void setTextPadding( Float value); Boolean getTextKeepUpright(); void setTextKeepUpright( Boolean value); Boolean getTextAllowOverlap(); void setTextAllowOverlap( Boolean value); Boolean getTextIgnorePlacement(); void setTextIgnorePlacement( Boolean value); Boolean getTextOptional(); void setTextOptional( Boolean value); Float[] getIconTranslate(); void setIconTranslate( Float[] value); String getIconTranslateAnchor(); void setIconTranslateAnchor(@Property.ICON_TRANSLATE_ANCHOR String value); Float[] getTextTranslate(); void setTextTranslate( Float[] value); String getTextTranslateAnchor(); void setTextTranslateAnchor(@Property.TEXT_TRANSLATE_ANCHOR String value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testAddSymbol() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Symbol symbol = symbolManager.create(new SymbolOptions().withLatLng(new LatLng())); assertEquals(symbolManager.getAnnotations().get(0), symbol); } @Test public void addSymbolFromFeatureCollection() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Geometry geometry = Point.fromLngLat(10, 10); Feature feature = Feature.fromGeometry(geometry); feature.addNumberProperty("symbol-sort-key", 2.0f); feature.addNumberProperty("icon-size", 2.0f); feature.addStringProperty("icon-image", "undefined"); feature.addNumberProperty("icon-rotate", 2.0f); feature.addProperty("icon-offset", convertArray(new Float[] {0f, 0f})); feature.addStringProperty("icon-anchor", ICON_ANCHOR_CENTER); feature.addStringProperty("text-field", ""); feature.addProperty("text-font", convertArray(new String[]{"Open Sans Regular", "Arial Unicode MS Regular"})); feature.addNumberProperty("text-size", 2.0f); feature.addNumberProperty("text-max-width", 2.0f); feature.addNumberProperty("text-letter-spacing", 2.0f); feature.addStringProperty("text-justify", TEXT_JUSTIFY_AUTO); feature.addNumberProperty("text-radial-offset", 2.0f); feature.addStringProperty("text-anchor", TEXT_ANCHOR_CENTER); feature.addNumberProperty("text-rotate", 2.0f); feature.addStringProperty("text-transform", TEXT_TRANSFORM_NONE); feature.addProperty("text-offset", convertArray(new Float[] {0f, 0f})); feature.addNumberProperty("icon-opacity", 2.0f); feature.addStringProperty("icon-color", "rgba(0, 0, 0, 1)"); feature.addStringProperty("icon-halo-color", "rgba(0, 0, 0, 1)"); feature.addNumberProperty("icon-halo-width", 2.0f); feature.addNumberProperty("icon-halo-blur", 2.0f); feature.addNumberProperty("text-opacity", 2.0f); feature.addStringProperty("text-color", "rgba(0, 0, 0, 1)"); feature.addStringProperty("text-halo-color", "rgba(0, 0, 0, 1)"); feature.addNumberProperty("text-halo-width", 2.0f); feature.addNumberProperty("text-halo-blur", 2.0f); feature.addBooleanProperty("is-draggable", true); List<Symbol> symbols = symbolManager.create(FeatureCollection.fromFeature(feature)); Symbol symbol = symbols.get(0); assertEquals(symbol.geometry, geometry); assertEquals(symbol.getSymbolSortKey(), 2.0f); assertEquals(symbol.getIconSize(), 2.0f); assertEquals(symbol.getIconImage(), "undefined"); assertEquals(symbol.getIconRotate(), 2.0f); PointF iconOffsetExpected = new PointF(new Float[] {0f, 0f}[0], new Float[] {0f, 0f}[1]); assertEquals(iconOffsetExpected.x, symbol.getIconOffset().x); assertEquals(iconOffsetExpected.y, symbol.getIconOffset().y); assertEquals(symbol.getIconAnchor(), ICON_ANCHOR_CENTER); assertEquals(symbol.getTextField(), ""); assertTrue(Arrays.equals(symbol.getTextFont(), new String[]{"Open Sans Regular", "Arial Unicode MS Regular"})); assertEquals(symbol.getTextSize(), 2.0f); assertEquals(symbol.getTextMaxWidth(), 2.0f); assertEquals(symbol.getTextLetterSpacing(), 2.0f); assertEquals(symbol.getTextJustify(), TEXT_JUSTIFY_AUTO); assertEquals(symbol.getTextRadialOffset(), 2.0f); assertEquals(symbol.getTextAnchor(), TEXT_ANCHOR_CENTER); assertEquals(symbol.getTextRotate(), 2.0f); assertEquals(symbol.getTextTransform(), TEXT_TRANSFORM_NONE); PointF textOffsetExpected = new PointF(new Float[] {0f, 0f}[0], new Float[] {0f, 0f}[1]); assertEquals(textOffsetExpected.x, symbol.getTextOffset().x); assertEquals(textOffsetExpected.y, symbol.getTextOffset().y); assertEquals(symbol.getIconOpacity(), 2.0f); assertEquals(symbol.getIconColor(), "rgba(0, 0, 0, 1)"); assertEquals(symbol.getIconHaloColor(), "rgba(0, 0, 0, 1)"); assertEquals(symbol.getIconHaloWidth(), 2.0f); assertEquals(symbol.getIconHaloBlur(), 2.0f); assertEquals(symbol.getTextOpacity(), 2.0f); assertEquals(symbol.getTextColor(), "rgba(0, 0, 0, 1)"); assertEquals(symbol.getTextHaloColor(), "rgba(0, 0, 0, 1)"); assertEquals(symbol.getTextHaloWidth(), 2.0f); assertEquals(symbol.getTextHaloBlur(), 2.0f); assertTrue(symbol.isDraggable()); } @Test public void addSymbols() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng> latLngList = new ArrayList<>(); latLngList.add(new LatLng()); latLngList.add(new LatLng(1, 1)); List< SymbolOptions> options = new ArrayList<>(); for (LatLng latLng : latLngList) { options.add(new SymbolOptions().withLatLng(latLng)); } List<Symbol> symbols = symbolManager.create(options); assertTrue("Returned value size should match", symbols.size() == 2); assertTrue("Annotations size should match", symbolManager.getAnnotations().size() == 2); } @Test public void testDeleteSymbol() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Symbol symbol = symbolManager.create(new SymbolOptions().withLatLng(new LatLng())); symbolManager.delete(symbol); assertTrue(symbolManager.getAnnotations().size() == 0); } @Test public void testGeometrySymbol() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); LatLng latLng = new LatLng(12, 34); SymbolOptions options = new SymbolOptions().withLatLng(latLng); Symbol symbol = symbolManager.create(options); assertEquals(options.getLatLng(), latLng); assertEquals(symbol.getLatLng(), latLng); assertEquals(options.getGeometry(), Point.fromLngLat(34, 12)); assertEquals(symbol.getGeometry(), Point.fromLngLat(34, 12)); } @Test public void testFeatureIdSymbol() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Symbol symbolZero = symbolManager.create(new SymbolOptions().withLatLng(new LatLng())); Symbol symbolOne = symbolManager.create(new SymbolOptions().withLatLng(new LatLng())); assertEquals(symbolZero.getFeature().get(Symbol.ID_KEY).getAsLong(), 0); assertEquals(symbolOne.getFeature().get(Symbol.ID_KEY).getAsLong(), 1); } @Test public void testSymbolDraggableFlag() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Symbol symbolZero = symbolManager.create(new SymbolOptions().withLatLng(new LatLng())); assertFalse(symbolZero.isDraggable()); symbolZero.setDraggable(true); assertTrue(symbolZero.isDraggable()); symbolZero.setDraggable(false); assertFalse(symbolZero.isDraggable()); } @Test public void testSymbolSortKeyLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(symbolSortKey(get("symbol-sort-key"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withSymbolSortKey(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(symbolSortKey(get("symbol-sort-key"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(symbolSortKey(get("symbol-sort-key"))))); } @Test public void testIconSizeLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconSize(get("icon-size"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconSize(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconSize(get("icon-size"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconSize(get("icon-size"))))); } @Test public void testIconImageLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconImage(get("icon-image"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconImage("undefined"); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconImage(get("icon-image"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconImage(get("icon-image"))))); } @Test public void testIconRotateLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconRotate(get("icon-rotate"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconRotate(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconRotate(get("icon-rotate"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconRotate(get("icon-rotate"))))); } @Test public void testIconOffsetLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconOffset(get("icon-offset"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconOffset(new Float[] {0f, 0f}); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconOffset(get("icon-offset"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconOffset(get("icon-offset"))))); } @Test public void testIconAnchorLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconAnchor(get("icon-anchor"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconAnchor(ICON_ANCHOR_CENTER); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconAnchor(get("icon-anchor"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconAnchor(get("icon-anchor"))))); } @Test public void testTextFieldLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textField(get("text-field"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextField(""); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textField(get("text-field"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textField(get("text-field"))))); } @Test public void testTextFontLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textFont(get("text-font"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextFont(new String[]{"Open Sans Regular", "Arial Unicode MS Regular"}); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textFont(get("text-font"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textFont(get("text-font"))))); } @Test public void testTextSizeLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textSize(get("text-size"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextSize(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textSize(get("text-size"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textSize(get("text-size"))))); } @Test public void testTextMaxWidthLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textMaxWidth(get("text-max-width"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextMaxWidth(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textMaxWidth(get("text-max-width"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textMaxWidth(get("text-max-width"))))); } @Test public void testTextLetterSpacingLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textLetterSpacing(get("text-letter-spacing"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextLetterSpacing(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textLetterSpacing(get("text-letter-spacing"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textLetterSpacing(get("text-letter-spacing"))))); } @Test public void testTextJustifyLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textJustify(get("text-justify"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextJustify(TEXT_JUSTIFY_AUTO); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textJustify(get("text-justify"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textJustify(get("text-justify"))))); } @Test public void testTextRadialOffsetLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textRadialOffset(get("text-radial-offset"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextRadialOffset(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textRadialOffset(get("text-radial-offset"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textRadialOffset(get("text-radial-offset"))))); } @Test public void testTextAnchorLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textAnchor(get("text-anchor"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextAnchor(TEXT_ANCHOR_CENTER); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textAnchor(get("text-anchor"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textAnchor(get("text-anchor"))))); } @Test public void testTextRotateLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textRotate(get("text-rotate"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextRotate(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textRotate(get("text-rotate"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textRotate(get("text-rotate"))))); } @Test public void testTextTransformLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textTransform(get("text-transform"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextTransform(TEXT_TRANSFORM_NONE); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textTransform(get("text-transform"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textTransform(get("text-transform"))))); } @Test public void testTextOffsetLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textOffset(get("text-offset"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextOffset(new Float[] {0f, 0f}); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textOffset(get("text-offset"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textOffset(get("text-offset"))))); } @Test public void testIconOpacityLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconOpacity(get("icon-opacity"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconOpacity(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconOpacity(get("icon-opacity"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconOpacity(get("icon-opacity"))))); } @Test public void testIconColorLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconColor(get("icon-color"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconColor("rgba(0, 0, 0, 1)"); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconColor(get("icon-color"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconColor(get("icon-color"))))); } @Test public void testIconHaloColorLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconHaloColor(get("icon-halo-color"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconHaloColor("rgba(0, 0, 0, 1)"); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconHaloColor(get("icon-halo-color"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconHaloColor(get("icon-halo-color"))))); } @Test public void testIconHaloWidthLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconHaloWidth(get("icon-halo-width"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconHaloWidth(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconHaloWidth(get("icon-halo-width"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconHaloWidth(get("icon-halo-width"))))); } @Test public void testIconHaloBlurLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(iconHaloBlur(get("icon-halo-blur"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withIconHaloBlur(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconHaloBlur(get("icon-halo-blur"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(iconHaloBlur(get("icon-halo-blur"))))); } @Test public void testTextOpacityLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textOpacity(get("text-opacity"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextOpacity(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textOpacity(get("text-opacity"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textOpacity(get("text-opacity"))))); } @Test public void testTextColorLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textColor(get("text-color"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextColor("rgba(0, 0, 0, 1)"); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textColor(get("text-color"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textColor(get("text-color"))))); } @Test public void testTextHaloColorLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textHaloColor(get("text-halo-color"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextHaloColor("rgba(0, 0, 0, 1)"); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textHaloColor(get("text-halo-color"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textHaloColor(get("text-halo-color"))))); } @Test public void testTextHaloWidthLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textHaloWidth(get("text-halo-width"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextHaloWidth(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textHaloWidth(get("text-halo-width"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textHaloWidth(get("text-halo-width"))))); } @Test public void testTextHaloBlurLayerProperty() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(symbolLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(textHaloBlur(get("text-halo-blur"))))); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()).withTextHaloBlur(2.0f); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textHaloBlur(get("text-halo-blur"))))); symbolManager.create(options); verify(symbolLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(textHaloBlur(get("text-halo-blur"))))); } @Test public void testCustomData() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()); options.withData(new JsonPrimitive("hello")); Symbol symbol = symbolManager.create(options); assertEquals(new JsonPrimitive("hello"), symbol.getData()); } @Test public void testClearAll() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()); symbolManager.create(options); assertEquals(1, symbolManager.getAnnotations().size()); symbolManager.deleteAll(); assertEquals(0, symbolManager.getAnnotations().size()); } @Test public void testIgnoreClearedAnnotations() { symbolManager = new SymbolManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); SymbolOptions options = new SymbolOptions().withLatLng(new LatLng()); Symbol symbol = symbolManager.create(options); assertEquals(1, symbolManager.annotations.size()); symbolManager.getAnnotations().clear(); symbolManager.updateSource(); assertTrue(symbolManager.getAnnotations().isEmpty()); symbolManager.update(symbol); assertTrue(symbolManager.getAnnotations().isEmpty()); }
CarmenFeatureConverter { @TypeConverter public static String fromCarmenFeature(@NonNull CarmenFeature carmenFeature) { return carmenFeature.toJson(); } private CarmenFeatureConverter(); @TypeConverter static CarmenFeature toCarmenFeature(String serializedCarmenFeature); @TypeConverter static String fromCarmenFeature(@NonNull CarmenFeature carmenFeature); }
@Test public void fromCarmenFeature_doesSerializeCorrectly() { String json = "{\"type\":\"Feature\",\"id\":\"id\",\"geometry\":{\"type\":\"Point\"," + "\"coordinates\":[1.0,2.0]},\"properties\":{\"hello\":\"world\"},\"address\":\"address\"," + "\"matching_place_name\":\"matchingPlaceName\",\"language\":\"language\"}"; JsonObject obj = new JsonObject(); obj.addProperty("hello", "world"); CarmenFeature carmenFeature = CarmenFeature.builder() .geometry(Point.fromLngLat(1.0, 2.0)) .address("address") .bbox(null) .id("id") .language("language") .matchingPlaceName("matchingPlaceName") .properties(obj) .build(); String serializedFeature = CarmenFeatureConverter.fromCarmenFeature(carmenFeature); assertThat(serializedFeature, equalTo(json)); }
PlacePickerOptions implements BasePlaceOptions, Parcelable { public static Builder builder() { return new AutoValue_PlacePickerOptions.Builder() .includeReverseGeocode(true) .includeDeviceLocationButton(false); } @Override @Nullable abstract String language(); @Override @Nullable abstract String geocodingTypes(); @Nullable abstract LatLngBounds startingBounds(); @Nullable @Override abstract Integer toolbarColor(); @Nullable abstract CameraPosition statingCameraPosition(); abstract boolean includeReverseGeocode(); abstract boolean includeDeviceLocationButton(); static Builder builder(); }
@Test public void builder() throws Exception { PlaceOptions.Builder builder = PlaceOptions.builder(); assertNotNull(builder); }
PlacePicker { @Nullable public static CarmenFeature getPlace(Intent data) { String json = data.getStringExtra(PlaceConstants.RETURNING_CARMEN_FEATURE); if (json == null) { return null; } return CarmenFeature.fromJson(json); } private PlacePicker(); @Nullable static CarmenFeature getPlace(Intent data); static CameraPosition getLastCameraPosition(Intent data); }
@Test public void getPlace_returnsNullWhenJsonNotFound() throws Exception { Intent data = new Intent(); CarmenFeature carmenFeature = PlacePicker.getPlace(data); assertNull(carmenFeature); } @Test public void getPlace_returnsDeserializedCarmenFeature() throws Exception { String json = "{\"type\":\"Feature\",\"id\":\"id\",\"geometry\":{\"type\":\"Point\"," + "\"coordinates\":[1.0, 2.0]},\"properties\":{},\"address\":\"address\"," + "\"matching_place_name\":\"matchingPlaceName\",\"language\":\"language\"}"; Intent data = mock(Intent.class); data.putExtra(PlaceConstants.RETURNING_CARMEN_FEATURE, json); when(data.getStringExtra(PlaceConstants.RETURNING_CARMEN_FEATURE)).thenReturn(json); CarmenFeature carmenFeature = PlacePicker.getPlace(data); assertNotNull(carmenFeature); assertThat(carmenFeature.type(), equalTo("Feature")); assertThat(carmenFeature.id(), equalTo("id")); assertThat(carmenFeature.address(), equalTo("address")); assertThat(carmenFeature.matchingPlaceName(), equalTo("matchingPlaceName")); assertThat(carmenFeature.language(), equalTo("language")); }
CircleManager extends AnnotationManager<CircleLayer, Circle, CircleOptions, OnCircleDragListener, OnCircleClickListener, OnCircleLongClickListener> { @Override public void setFilter(@NonNull Expression expression) { layerFilter = expression; layer.setFilter(layerFilter); } @UiThread CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<CircleLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Circle> create(@NonNull String json); @UiThread List<Circle> create(@NonNull FeatureCollection featureCollection); Float[] getCircleTranslate(); void setCircleTranslate( Float[] value); String getCircleTranslateAnchor(); void setCircleTranslateAnchor(@Property.CIRCLE_TRANSLATE_ANCHOR String value); String getCirclePitchScale(); void setCirclePitchScale(@Property.CIRCLE_PITCH_SCALE String value); String getCirclePitchAlignment(); void setCirclePitchAlignment(@Property.CIRCLE_PITCH_ALIGNMENT String value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testInitialization() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(circleLayer); assertTrue(circleManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : circleManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(circleLayer).setProperties(circleManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(circleLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testInitializationOnStyleReload() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(circleLayer); assertTrue(circleManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : circleManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(circleLayer).setProperties(circleManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); Expression filter = Expression.literal(false); circleManager.setFilter(filter); ArgumentCaptor<MapView.OnDidFinishLoadingStyleListener> loadingArgumentCaptor = ArgumentCaptor.forClass(MapView.OnDidFinishLoadingStyleListener.class); verify(mapView).addOnDidFinishLoadingStyleListener(loadingArgumentCaptor.capture()); loadingArgumentCaptor.getValue().onDidFinishLoadingStyle(); ArgumentCaptor<Style.OnStyleLoaded> styleLoadedArgumentCaptor = ArgumentCaptor.forClass(Style.OnStyleLoaded.class); verify(mapboxMap).getStyle(styleLoadedArgumentCaptor.capture()); Style newStyle = mock(Style.class); when(newStyle.isFullyLoaded()).thenReturn(true); GeoJsonSource newSource = mock(GeoJsonSource.class); when(coreElementProvider.getSource(null)).thenReturn(newSource); CircleLayer newLayer = mock(CircleLayer.class); when(coreElementProvider.getLayer()).thenReturn(newLayer); styleLoadedArgumentCaptor.getValue().onStyleLoaded(newStyle); verify(newStyle).addSource(newSource); verify(newStyle).addLayer(newLayer); assertTrue(circleManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : circleManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(newLayer).setProperties(circleManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(circleLayer).setFilter(filter); verify(draggableAnnotationController, times(2)).onSourceUpdated(); verify(newSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testGeoJsonOptionsInitialization() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, geoJsonOptions, draggableAnnotationController); verify(style).addSource(optionedGeoJsonSource); verify(style).addLayer(circleLayer); assertTrue(circleManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : circleManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(circleLayer).setProperties(circleManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(circleLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(optionedGeoJsonSource).setGeoJson(any(FeatureCollection.class)); }
CircleManager extends AnnotationManager<CircleLayer, Circle, CircleOptions, OnCircleDragListener, OnCircleClickListener, OnCircleLongClickListener> { @UiThread public List<Circle> create(@NonNull String json) { return create(FeatureCollection.fromJson(json)); } @UiThread CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting CircleManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<CircleLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Circle> create(@NonNull String json); @UiThread List<Circle> create(@NonNull FeatureCollection featureCollection); Float[] getCircleTranslate(); void setCircleTranslate( Float[] value); String getCircleTranslateAnchor(); void setCircleTranslateAnchor(@Property.CIRCLE_TRANSLATE_ANCHOR String value); String getCirclePitchScale(); void setCirclePitchScale(@Property.CIRCLE_PITCH_SCALE String value); String getCirclePitchAlignment(); void setCirclePitchAlignment(@Property.CIRCLE_PITCH_ALIGNMENT String value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testAddCircle() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Circle circle = circleManager.create(new CircleOptions().withLatLng(new LatLng())); assertEquals(circleManager.getAnnotations().get(0), circle); } @Test public void addCircleFromFeatureCollection() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Geometry geometry = Point.fromLngLat(10, 10); Feature feature = Feature.fromGeometry(geometry); feature.addNumberProperty("circle-radius", 2.0f); feature.addStringProperty("circle-color", "rgba(0, 0, 0, 1)"); feature.addNumberProperty("circle-blur", 2.0f); feature.addNumberProperty("circle-opacity", 2.0f); feature.addNumberProperty("circle-stroke-width", 2.0f); feature.addStringProperty("circle-stroke-color", "rgba(0, 0, 0, 1)"); feature.addNumberProperty("circle-stroke-opacity", 2.0f); feature.addBooleanProperty("is-draggable", true); List<Circle> circles = circleManager.create(FeatureCollection.fromFeature(feature)); Circle circle = circles.get(0); assertEquals(circle.geometry, geometry); assertEquals(circle.getCircleRadius(), 2.0f); assertEquals(circle.getCircleColor(), "rgba(0, 0, 0, 1)"); assertEquals(circle.getCircleBlur(), 2.0f); assertEquals(circle.getCircleOpacity(), 2.0f); assertEquals(circle.getCircleStrokeWidth(), 2.0f); assertEquals(circle.getCircleStrokeColor(), "rgba(0, 0, 0, 1)"); assertEquals(circle.getCircleStrokeOpacity(), 2.0f); assertTrue(circle.isDraggable()); } @Test public void addCircles() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); List<LatLng> latLngList = new ArrayList<>(); latLngList.add(new LatLng()); latLngList.add(new LatLng(1, 1)); List< CircleOptions> options = new ArrayList<>(); for (LatLng latLng : latLngList) { options.add(new CircleOptions().withLatLng(latLng)); } List<Circle> circles = circleManager.create(options); assertTrue("Returned value size should match", circles.size() == 2); assertTrue("Annotations size should match", circleManager.getAnnotations().size() == 2); } @Test public void testDeleteCircle() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Circle circle = circleManager.create(new CircleOptions().withLatLng(new LatLng())); circleManager.delete(circle); assertTrue(circleManager.getAnnotations().size() == 0); } @Test public void testGeometryCircle() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); LatLng latLng = new LatLng(12, 34); CircleOptions options = new CircleOptions().withLatLng(latLng); Circle circle = circleManager.create(options); assertEquals(options.getLatLng(), latLng); assertEquals(circle.getLatLng(), latLng); assertEquals(options.getGeometry(), Point.fromLngLat(34, 12)); assertEquals(circle.getGeometry(), Point.fromLngLat(34, 12)); } @Test public void testFeatureIdCircle() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Circle circleZero = circleManager.create(new CircleOptions().withLatLng(new LatLng())); Circle circleOne = circleManager.create(new CircleOptions().withLatLng(new LatLng())); assertEquals(circleZero.getFeature().get(Circle.ID_KEY).getAsLong(), 0); assertEquals(circleOne.getFeature().get(Circle.ID_KEY).getAsLong(), 1); } @Test public void testCircleDraggableFlag() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); Circle circleZero = circleManager.create(new CircleOptions().withLatLng(new LatLng())); assertFalse(circleZero.isDraggable()); circleZero.setDraggable(true); assertTrue(circleZero.isDraggable()); circleZero.setDraggable(false); assertFalse(circleZero.isDraggable()); } @Test public void testCircleRadiusLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleRadius(get("circle-radius"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleRadius(2.0f); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleRadius(get("circle-radius"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleRadius(get("circle-radius"))))); } @Test public void testCircleColorLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleColor(get("circle-color"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleColor("rgba(0, 0, 0, 1)"); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleColor(get("circle-color"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleColor(get("circle-color"))))); } @Test public void testCircleBlurLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleBlur(get("circle-blur"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleBlur(2.0f); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleBlur(get("circle-blur"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleBlur(get("circle-blur"))))); } @Test public void testCircleOpacityLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleOpacity(get("circle-opacity"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleOpacity(2.0f); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleOpacity(get("circle-opacity"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleOpacity(get("circle-opacity"))))); } @Test public void testCircleStrokeWidthLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleStrokeWidth(get("circle-stroke-width"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleStrokeWidth(2.0f); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleStrokeWidth(get("circle-stroke-width"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleStrokeWidth(get("circle-stroke-width"))))); } @Test public void testCircleStrokeColorLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleStrokeColor(get("circle-stroke-color"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleStrokeColor("rgba(0, 0, 0, 1)"); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleStrokeColor(get("circle-stroke-color"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleStrokeColor(get("circle-stroke-color"))))); } @Test public void testCircleStrokeOpacityLayerProperty() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(circleLayer, times(0)).setProperties(argThat(new PropertyValueMatcher(circleStrokeOpacity(get("circle-stroke-opacity"))))); CircleOptions options = new CircleOptions().withLatLng(new LatLng()).withCircleStrokeOpacity(2.0f); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleStrokeOpacity(get("circle-stroke-opacity"))))); circleManager.create(options); verify(circleLayer, times(1)).setProperties(argThat(new PropertyValueMatcher(circleStrokeOpacity(get("circle-stroke-opacity"))))); } @Test public void testCustomData() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); CircleOptions options = new CircleOptions().withLatLng(new LatLng()); options.withData(new JsonPrimitive("hello")); Circle circle = circleManager.create(options); assertEquals(new JsonPrimitive("hello"), circle.getData()); } @Test public void testClearAll() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); CircleOptions options = new CircleOptions().withLatLng(new LatLng()); circleManager.create(options); assertEquals(1, circleManager.getAnnotations().size()); circleManager.deleteAll(); assertEquals(0, circleManager.getAnnotations().size()); } @Test public void testIgnoreClearedAnnotations() { circleManager = new CircleManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); CircleOptions options = new CircleOptions().withLatLng(new LatLng()); Circle circle = circleManager.create(options); assertEquals(1, circleManager.annotations.size()); circleManager.getAnnotations().clear(); circleManager.updateSource(); assertTrue(circleManager.getAnnotations().isEmpty()); circleManager.update(circle); assertTrue(circleManager.getAnnotations().isEmpty()); }
PlacePicker { public static CameraPosition getLastCameraPosition(Intent data) { return data.getParcelableExtra(PlaceConstants.MAP_CAMERA_POSITION); } private PlacePicker(); @Nullable static CarmenFeature getPlace(Intent data); static CameraPosition getLastCameraPosition(Intent data); }
@Test @Ignore public void getLastCameraPosition() throws Exception { CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(2.0, 3.0)) .bearing(30) .zoom(20) .build(); Parcel parcel = mock(Parcel.class); cameraPosition.writeToParcel(parcel, 0); parcel.setDataPosition(0); Intent data = mock(Intent.class); data.putExtra(PlaceConstants.MAP_CAMERA_POSITION, cameraPosition); CameraPosition position = PlacePicker.getLastCameraPosition(data); assertNotNull(position); }
LineManager extends AnnotationManager<LineLayer, Line, LineOptions, OnLineDragListener, OnLineClickListener, OnLineLongClickListener> { @Override public void setFilter(@NonNull Expression expression) { layerFilter = expression; layer.setFilter(layerFilter); } @UiThread LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style); @UiThread LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId); @UiThread LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions); @VisibleForTesting LineManager(@NonNull MapView mapView, @NonNull MapboxMap mapboxMap, @NonNull Style style, @NonNull CoreElementProvider<LineLayer> coreElementProvider, @Nullable String belowLayerId, @Nullable GeoJsonOptions geoJsonOptions, DraggableAnnotationController draggableAnnotationController); @UiThread List<Line> create(@NonNull String json); @UiThread List<Line> create(@NonNull FeatureCollection featureCollection); String getLineCap(); void setLineCap(@Property.LINE_CAP String value); Float getLineMiterLimit(); void setLineMiterLimit( Float value); Float getLineRoundLimit(); void setLineRoundLimit( Float value); Float[] getLineTranslate(); void setLineTranslate( Float[] value); String getLineTranslateAnchor(); void setLineTranslateAnchor(@Property.LINE_TRANSLATE_ANCHOR String value); Float[] getLineDasharray(); void setLineDasharray( Float[] value); @Override void setFilter(@NonNull Expression expression); @Nullable Expression getFilter(); }
@Test public void testInitialization() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(lineLayer); assertTrue(lineManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : lineManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(lineLayer).setProperties(lineManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(lineLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testInitializationOnStyleReload() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, null, draggableAnnotationController); verify(style).addSource(geoJsonSource); verify(style).addLayer(lineLayer); assertTrue(lineManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : lineManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(lineLayer).setProperties(lineManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(draggableAnnotationController).onSourceUpdated(); verify(geoJsonSource).setGeoJson(any(FeatureCollection.class)); Expression filter = Expression.literal(false); lineManager.setFilter(filter); ArgumentCaptor<MapView.OnDidFinishLoadingStyleListener> loadingArgumentCaptor = ArgumentCaptor.forClass(MapView.OnDidFinishLoadingStyleListener.class); verify(mapView).addOnDidFinishLoadingStyleListener(loadingArgumentCaptor.capture()); loadingArgumentCaptor.getValue().onDidFinishLoadingStyle(); ArgumentCaptor<Style.OnStyleLoaded> styleLoadedArgumentCaptor = ArgumentCaptor.forClass(Style.OnStyleLoaded.class); verify(mapboxMap).getStyle(styleLoadedArgumentCaptor.capture()); Style newStyle = mock(Style.class); when(newStyle.isFullyLoaded()).thenReturn(true); GeoJsonSource newSource = mock(GeoJsonSource.class); when(coreElementProvider.getSource(null)).thenReturn(newSource); LineLayer newLayer = mock(LineLayer.class); when(coreElementProvider.getLayer()).thenReturn(newLayer); styleLoadedArgumentCaptor.getValue().onStyleLoaded(newStyle); verify(newStyle).addSource(newSource); verify(newStyle).addLayer(newLayer); assertTrue(lineManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : lineManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(newLayer).setProperties(lineManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(lineLayer).setFilter(filter); verify(draggableAnnotationController, times(2)).onSourceUpdated(); verify(newSource).setGeoJson(any(FeatureCollection.class)); } @Test public void testGeoJsonOptionsInitialization() { lineManager = new LineManager(mapView, mapboxMap, style, coreElementProvider, null, geoJsonOptions, draggableAnnotationController); verify(style).addSource(optionedGeoJsonSource); verify(style).addLayer(lineLayer); assertTrue(lineManager.dataDrivenPropertyUsageMap.size() > 0); for (Boolean value : lineManager.dataDrivenPropertyUsageMap.values()) { assertFalse(value); } verify(lineLayer).setProperties(lineManager.constantPropertyUsageMap.values().toArray(new PropertyValue[0])); verify(lineLayer, times(0)).setFilter(any(Expression.class)); verify(draggableAnnotationController).onSourceUpdated(); verify(optionedGeoJsonSource).setGeoJson(any(FeatureCollection.class)); }
TightCouplingProcessor { public List<View> generateView() { Assert.notNull(project, "Project must not be null"); Assert.notNull(projectEvent, "Event must not be null"); Assert.notNull(commit, "Commit must not be null"); Assert.notNull(commit, "Commit must contain files"); if (commit.getFiles().size() == 0) return null; List<File> fileList = commit.getFiles(); List<List<String>> fileGroups = subsets(fileList.stream() .map(f -> f.getFileName().toLowerCase()) .sorted() .collect(Collectors.toList())); return fileGroups.stream() .map(f -> { String key = generateKey(f); View view = new View("tcq"); view.setId(key); view.setProjectId(projectEvent.getProjectId()); view.setMatches(1); view.setFileIds(f); view.setCreatedAt(commit.getCreatedAt()); view.setLastModified(commit.getCommitDate()); return view; }).collect(Collectors.toList()); } TightCouplingProcessor(); TightCouplingProcessor(ProjectEvent projectEvent, Project project, Commit commit); List<View> generateView(); }
@Test public void generateView() throws Exception { MessageDigest md5 = java.security.MessageDigest.getInstance("MD5"); Commit commit = new Commit(Arrays.asList(new File("file1.txt"), new File("file2.txt"))); Project project = new Project("test"); project.setIdentity(1L); project.setOwner("test"); project.setStatus(ProjectStatus.PROJECT_CREATED); ProjectEvent projectEvent = new ProjectEvent(); Map<String, Commit> map = new HashMap<>(); map.put("commit", commit); projectEvent.setPayload(map); projectEvent.setProjectId(project.getIdentity()); projectEvent.setType(ProjectEventType.COMMIT_EVENT); TightCouplingProcessor tightCouplingProcessor = new TightCouplingProcessor(projectEvent, project, commit); View expectedView = new View("tcq"); expectedView.setFileIds(commit.getFiles().stream() .map(f -> f.getFileName().toLowerCase()) .sorted() .collect(Collectors.toList())); expectedView.setMatches(1); expectedView.setProjectId(project.getIdentity()); expectedView.setId("tcq_1_" + tightCouplingProcessor.getMd5Hash(expectedView.getFileIds().stream() .map(tightCouplingProcessor::getMd5Hash) .collect(Collectors.joining("_")))); List<View> expectedViewList = Collections.singletonList(expectedView); List<View> actualViewList = tightCouplingProcessor.generateView(); System.out.println(expectedViewList.toString()); System.out.println(actualViewList.toString()); Assert.assertArrayEquals(expectedViewList.toArray(), actualViewList.toArray()); }
TightCouplingProcessor { List<List<String>> subsets(List<String> set) { List<List<String>> subsets = new ArrayList<>(); int n = set.size(); for (int i = 0; i < (1 << n); i++) { List<String> combination = new ArrayList<>(); for (int j = 0; j < n; j++) if ((i & (1 << j)) > 0) combination.add(set.get(j)); if (combination.size() == 2) subsets.add(combination); } return subsets; } TightCouplingProcessor(); TightCouplingProcessor(ProjectEvent projectEvent, Project project, Commit commit); List<View> generateView(); }
@Test public void subsetReturnsCorrectCombinations() { TightCouplingProcessor tightCouplingProcessor = new TightCouplingProcessor(); List<String> input = Arrays.asList("a", "b", "c"); List<List<String>> expected = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("a", "c"), Arrays.asList("b", "c")); List<List<String>> actual = tightCouplingProcessor.subsets(input); Assert.assertArrayEquals(expected.stream().flatMap(Collection::stream).toArray(), actual.stream().flatMap(Collection::stream).toArray()); }
InvocationStatistics { public void addInvocation(Invocation invocation) { numberOfInvocations++; if (this.methodName != null) { this.methodName = invocation.getMethodName(); } this.recentDuration = invocation.getRecentDuration(); this.lastInvocationTimestamp = invocation.getCreationTime(); String currentException = invocation.getException(); if (currentException != null) { this.exception = currentException; numberOfExceptions++; } this.recalculate(); } InvocationStatistics(String methodName); InvocationStatistics(); void addInvocation(Invocation invocation); String getMethodName(); long getRecentDuration(); long getMinDuration(); long getMaxDuration(); long getAverageDuration(); long getNumberOfExceptions(); boolean isExceptional(); String getException(); long getLastInvocationTimestamp(); long getTotalDuration(); static Comparator<InvocationStatistics> recent(); static Comparator<InvocationStatistics> unstable(); static Comparator<InvocationStatistics> slowest(); }
@Test public void addInvocation() { Invocation first = new Invocation(null, 15, null, 1); Invocation second = new Invocation(null, 15, null, 2); Invocation another = new Invocation(null, 30, null, 2); this.cut.addInvocation(first); this.cut.addInvocation(second); this.cut.addInvocation(another); long averageDuration = this.cut.getAverageDuration(); assertThat(averageDuration, is(20l)); long maxDuration = this.cut.getMaxDuration(); assertThat(maxDuration, is(30l)); long minDuration = this.cut.getMinDuration(); assertThat(minDuration, is(15l)); long lastInvocation = this.cut.getLastInvocationTimestamp(); assertThat(lastInvocation, is(2l)); long totalDuration = this.cut.getTotalDuration(); assertThat(totalDuration, is(60l)); long recentDuration = this.cut.getRecentDuration(); assertThat(recentDuration, is(30l)); }
InvocationMonitoring { public void reset() { this.statistics.clear(); } @PostConstruct void init(); void onNewCall(@Observes Invocation invocation); List<InvocationStatistics> getExceptional(); List<InvocationStatistics> getUnstable(); List<InvocationStatistics> getSlowest(); List<InvocationStatistics> getRecent(); void reset(); }
@Test public void reset() { Invocation ex1 = new Invocation("unstable", 1, "lazy - don't call me", 1); Invocation ex2 = new Invocation("does not matter", 2, null, 2); this.cut.onNewCall(ex1); this.cut.onNewCall(ex2); List<InvocationStatistics> recent = this.cut.getRecent(); assertThat(recent.size(), is(2)); this.cut.reset(); recent = this.cut.getExceptional(); assertTrue(recent.isEmpty()); }
BluetoothController implements Closeable { public boolean isBluetoothEnabled() { return bluetooth.isEnabled(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTryCheckThatBluetoothIsEnabledShouldCheckThatMethodReturnCorrectData() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); when(adapter.isEnabled()).thenReturn(true); BluetoothController controller = new BluetoothController(activity, adapter, listener); assertThat(controller.isBluetoothEnabled(), is(true)); }
BluetoothController implements Closeable { public void turnOnBluetooth() { Log.d(TAG, "Enabling Bluetooth."); broadcastReceiverDelegator.onBluetoothTurningOn(); bluetooth.enable(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTryEnableBluetoothShouldCheckThatBluetoothAdapterCallEnableMethod() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.turnOnBluetooth(); verify(adapter).enable(); }
BluetoothController implements Closeable { public boolean isDiscovering() { return bluetooth.isDiscovering(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTryCallDiscoveringMethodOnBluetoothShouldCheckThatIsCalled() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.isDiscovering(); verify(adapter).isDiscovering(); }
BluetoothController implements Closeable { public int getPairingDeviceStatus() { if (this.boundingDevice == null) { throw new IllegalStateException("No device currently bounding"); } int bondState = this.boundingDevice.getBondState(); if (bondState != BluetoothDevice.BOND_BONDING) { this.boundingDevice = null; } return bondState; } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test(expected = IllegalStateException.class) public void whenTryBoundingDeviceButDeviceIsNullShouldCheckThatThrowException() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.getPairingDeviceStatus(); }
BluetoothController implements Closeable { public static String getDeviceName(BluetoothDevice device) { String deviceName = device.getName(); if (deviceName == null) { deviceName = device.getAddress(); } return deviceName; } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTryGetDeviceNameShouldCheckThatAllIsOK() throws Exception { BluetoothDevice device = mock(BluetoothDevice.class); when(device.getName()).thenReturn("android"); assertThat(BluetoothController.getDeviceName(device), is("android")); } @Test public void whenTryGetDeviceNameButItIsNullShouldCheckThatControllerReturnAddress() throws Exception { BluetoothDevice device = mock(BluetoothDevice.class); when(device.getName()).thenReturn(null); when(device.getName()).thenReturn("08-ED-B9-49-B2-E5"); assertThat(BluetoothController.getDeviceName(device), is("08-ED-B9-49-B2-E5")); }
BluetoothController implements Closeable { public boolean isAlreadyPaired(BluetoothDevice device) { return bluetooth.getBondedDevices().contains(device); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTryCheckThatDevicesAlreadyPairedShouldCheckThatMethodWorksCorrect() throws Exception { Activity activity = mock(Activity.class); Set<BluetoothDevice> devices = new HashSet<>(); BluetoothDevice device = mock(BluetoothDevice.class); devices.add(device); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); when(adapter.getBondedDevices()).thenReturn(devices); BluetoothController controller = new BluetoothController(activity, adapter, listener); assertThat(controller.isAlreadyPaired(device), is(true)); }
BluetoothController implements Closeable { public static String deviceToString(BluetoothDevice device) { return "[Address: " + device.getAddress() + ", Name: " + device.getName() + "]"; } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTryCastDeviceToStringShouldCheckThatAllIsOk() throws Exception { BluetoothDevice device = mock(BluetoothDevice.class); when(device.getName()).thenReturn("device"); when(device.getAddress()).thenReturn("08-ED-B9-49-B2-E5"); String actual = "[Address: 08-ED-B9-49-B2-E5, Name: device]"; assertEquals(actual, BluetoothController.deviceToString(device)); }
BluetoothController implements Closeable { public void turnOnBluetoothAndScheduleDiscovery() { this.bluetoothDiscoveryScheduled = true; turnOnBluetooth(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }
@Test public void whenTurnOnBluetoothAndScheduleDiscoveryShouldCheckThatBTenabled() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.turnOnBluetoothAndScheduleDiscovery(); verify(adapter).enable(); }
ReflectionUtil { public static Set<Class> getSubTypes(final Class<?> clazz) { Set<Class> subClasses = subclassesCache.get(clazz); if (null == subClasses) { updateReflectionPackages(); final Set<Class> newSubClasses = new HashSet<>(); if (clazz.isInterface()) { getScanner().matchClassesImplementing(clazz, c -> { if (isPublicConcrete(c)) { newSubClasses.add(c); } }).scan(); } else { getScanner().matchSubclassesOf(clazz, c -> { if (isPublicConcrete(c)) { newSubClasses.add(c); } }).scan(); } subClasses = Collections.unmodifiableSet(newSubClasses); subclassesCache.put(clazz, subClasses); } return subClasses; } private ReflectionUtil(); static Class<?> getClassFromName(final String className); static Map<String, Set<Class>> getSimpleClassNames(final Class<?> clazz); static Set<Class> getSubTypes(final Class<?> clazz); static Set<Class> getAnnotatedTypes(final Class<? extends Annotation> annoClass); static boolean isPublicConcrete(final Class clazz); static void keepPublicConcreteClasses(final Collection<Class> classes); static void resetReflectionPackages(); static void resetReflectionCache(); static void updateReflectionPackages(); static void addReflectionPackages(final String... newPackages); static void addReflectionPackages(final Iterable<String> newPackages); static Set<String> getReflectionPackages(); static final String PACKAGES_KEY; static final Set<String> DEFAULT_PACKAGES; }
@Test public void shouldReturnUnmodifiableClasses() { final Set<Class> subclasses = ReflectionUtil.getSubTypes(Number.class); assertThrows(UnsupportedOperationException.class, () -> subclasses.add(String.class)); } @Test public void shouldCacheSubclasses() { final Set<Class> subclasses = ReflectionUtil.getSubTypes(Number.class); final Set<Class> subclasses2 = ReflectionUtil.getSubTypes(Number.class); assertSame(subclasses, subclasses2); } @Test public void shouldReturnSubclasses() { final Set<Class> subclasses = ReflectionUtil.getSubTypes(Number.class); final HashSet<Class<? extends Number>> expected = Sets.newHashSet( TestCustomNumber.class, uk.gov.gchq.koryphe.serialisation.json.obj.second.TestCustomNumber.class ); assertEquals(expected, subclasses); assertFalse(subclasses.contains(UnsignedLong.class)); }
Regex extends KoryphePredicate<String> { @Override public boolean test(final String input) { return !(null == input || input.getClass() != String.class) && controlValue.matcher(input).matches(); } Regex(); Regex(final String controlValue); Regex(final Pattern controlValue); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern getControlValue(); void setControlValue(final Pattern controlValue); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAccepValidValue() { final Regex filter = new Regex("te[a-d]{3}st"); boolean accepted = filter.test("teaadst"); assertTrue(accepted); } @Test public void shouldRejectInvalidValue() { final Regex filter = new Regex("fa[a-d]{3}il"); boolean accepted = filter.test("favcdil"); assertFalse(accepted); }
Regex extends KoryphePredicate<String> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Pattern getControlValue() { return controlValue; } Regex(); Regex(final String controlValue); Regex(final Pattern controlValue); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern getControlValue(); void setControlValue(final Pattern controlValue); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final Regex filter = new Regex("test"); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.Regex\",%n" + " \"value\" : {%n" + " \"java.util.regex.Pattern\" : \"test\"%n" + " }%n" + "}"), json); final Regex deserialisedFilter = JsonSerialiser.deserialise(json, Regex.class); assertEquals(filter.getControlValue().pattern(), deserialisedFilter.getControlValue().pattern()); assertNotNull(deserialisedFilter); }
AreIn extends KoryphePredicate<Collection<?>> { @Override public boolean test(final Collection<?> input) { return null == allowedValues || allowedValues.isEmpty() || (null != input && allowedValues.containsAll(input)); } AreIn(); AreIn(final Collection<?> allowedValues); AreIn(final Object... allowedValues); @JsonIgnore Collection<?> getValues(); void setValues(final Collection<?> allowedValues); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenValuesAndInputAreNullOrEmpty() { final AreIn filter = new AreIn(); boolean accepted = filter.test((Collection) null); assertTrue(accepted); } @Test public void shouldAcceptWhenValuesIsEmpty() { final AreIn filter = new AreIn(); boolean accepted = filter.test(list); assertTrue(accepted); } @Test public void shouldAcceptWhenAllValuesInList() { final AreIn filter = new AreIn(VALUE1, VALUE2); boolean accepted = filter.test(list); assertTrue(accepted); } @Test public void shouldAcceptWhenAllValuesInSet() { final AreIn filter = new AreIn(VALUE1, VALUE2); boolean accepted = filter.test(set); assertTrue(accepted); } @Test public void shouldRejectWhenNotAllValuesPresentInList() { final AreIn filter = new AreIn(VALUE1); boolean accepted = filter.test(list); assertFalse(accepted); } @Test public void shouldRejectWhenNotAllValuesPresentInSet() { final AreIn filter = new AreIn(VALUE1); boolean accepted = filter.test(set); assertFalse(accepted); } @Test public void shouldAcceptEmptyLists() { final AreIn filter = new AreIn(VALUE1); boolean accepted = filter.test(new ArrayList<>()); assertTrue(accepted); } @Test public void shouldAcceptEmptySets() { final AreIn filter = new AreIn(VALUE1); boolean accepted = filter.test(new HashSet<>()); assertTrue(accepted); }
IterableUtil { public static <T> CloseableIterable<T> concat(final Iterable<? extends Iterable<? extends T>> iterables) { return new ChainedIterable<>(iterables); } private IterableUtil(); static CloseableIterable<T> filter(final Iterable<T> iterable, final Predicate predicate); static CloseableIterable<T> filter(final Iterable<T> iterable, final List<Predicate> predicates); static CloseableIterable<O_ITEM> map(final Iterable<I_ITEM> iterable, final Function function); static CloseableIterable<O_ITEM> map(final Iterable<I_ITEM> iterable, final List<Function> functions); static CloseableIterable<T> concat(final Iterable<? extends Iterable<? extends T>> iterables); static CloseableIterable<T> limit(final Iterable<T> iterable, final int start, final Integer end, final boolean truncate); }
@Test public void shouldWrapAllIterables() { final List<Integer> itr1 = Collections.singletonList(0); final List<Integer> itr2 = new ArrayList<>(0); final List<Integer> itr3 = Lists.newArrayList(1, 2, 3, 4); final List<Integer> itr4 = Lists.newArrayList(5, 6); final Iterable<Integer> itrConcat = IterableUtil.concat(Arrays.asList(itr1, itr2, itr3, itr4)); assertEquals(Lists.newArrayList(0, 1, 2, 3, 4, 5, 6), Lists.newArrayList(itrConcat)); } @Test public void shouldRemoveElementFromFirstIterable() { final List<Integer> itr1 = Lists.newArrayList(0); final List<Integer> itr2 = new ArrayList<>(0); final List<Integer> itr3 = Lists.newArrayList(1, 2, 3, 4); final List<Integer> itr4 = Lists.newArrayList(5, 6); final int itr1Size = itr1.size(); final int itr2Size = itr2.size(); final int itr3Size = itr3.size(); final int itr4Size = itr4.size(); final Iterable<Integer> itrConcat = IterableUtil.concat(Arrays.asList(itr1, itr2, itr3, itr4)); final Iterator<Integer> itr = itrConcat.iterator(); assertEquals(0, (int) itr.next()); itr.remove(); assertEquals(itr1Size - 1, itr1.size()); assertEquals(itr2Size, itr2.size()); assertEquals(itr3Size, itr3.size()); assertEquals(itr4Size, itr4.size()); } @Test public void shouldRemoveElementFromThirdIterable() { final List<Integer> itr1 = Lists.newArrayList(0); final List<Integer> itr2 = new ArrayList<>(0); final List<Integer> itr3 = Lists.newArrayList(1, 2, 3, 4); final List<Integer> itr4 = Lists.newArrayList(5, 6); final int itr1Size = itr1.size(); final int itr2Size = itr2.size(); final int itr3Size = itr3.size(); final int itr4Size = itr4.size(); final Iterable<Integer> itrConcat = IterableUtil.concat(Arrays.asList(itr1, itr2, itr3, itr4)); final Iterator<Integer> itr = itrConcat.iterator(); assertEquals(0, (int) itr.next()); assertEquals(1, (int) itr.next()); itr.remove(); assertEquals(itr1Size, itr1.size()); assertEquals(itr2Size, itr2.size()); assertEquals(itr3Size - 1, itr3.size()); assertEquals(itr4Size, itr4.size()); }
AreIn extends KoryphePredicate<Collection<?>> { @JsonIgnore public Collection<?> getValues() { return allowedValues; } AreIn(); AreIn(final Collection<?> allowedValues); AreIn(final Object... allowedValues); @JsonIgnore Collection<?> getValues(); void setValues(final Collection<?> allowedValues); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final AreIn filter = new AreIn(VALUE1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.AreIn\",%n" + " \"values\" : [{\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}]%n" + "}"), json); final AreIn deserialisedFilter = JsonSerialiser.deserialise(json, AreIn.class); assertNotNull(deserialisedFilter); assertArrayEquals(Collections.singleton(VALUE1).toArray(), deserialisedFilter.getValues().toArray()); }
IsMoreThan extends KoryphePredicate<Comparable> implements InputValidator { @Override public boolean test(final Comparable input) { if (null == input || !controlValue.getClass().isAssignableFrom(input.getClass())) { return false; } final int compareVal = controlValue.compareTo(input); if (orEqualTo) { return compareVal <= 0; } return compareVal < 0; } IsMoreThan(); IsMoreThan(final Comparable<?> controlValue); IsMoreThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldAcceptTheValueWhenMoreThan() { final IsMoreThan filter = new IsMoreThan(5); boolean accepted = filter.test(6); assertTrue(accepted); } @Test public void shouldAcceptTheValueWhenMoreThanAndOrEqualToIsTrue() { final IsMoreThan filter = new IsMoreThan(5, true); boolean accepted = filter.test(6); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenLessThanAndOrEqualToIsTrue() { final IsMoreThan filter = new IsMoreThan(5, true); boolean accepted = filter.test(4); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenLessThan() { final IsMoreThan filter = new IsMoreThan(5); boolean accepted = filter.test(4); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqual() { final IsMoreThan filter = new IsMoreThan(5); boolean accepted = filter.test(5); assertFalse(accepted); } @Test public void shouldAcceptTheValueWhenEqualAndOrEqualToIsTrue() { final IsMoreThan filter = new IsMoreThan(5, true); boolean accepted = filter.test(5); assertTrue(accepted); }
IsMoreThan extends KoryphePredicate<Comparable> implements InputValidator { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Comparable getControlValue() { return controlValue; } IsMoreThan(); IsMoreThan(final Comparable<?> controlValue); IsMoreThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CustomObj controlValue = new CustomObj(); final IsMoreThan filter = new IsMoreThan(controlValue); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsMoreThan\",%n" + " \"orEqualTo\" : false,%n" + " \"value\" : {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}%n" + "}"), json); final IsMoreThan deserialisedFilter = JsonSerialiser.deserialise(json, IsMoreThan.class); assertNotNull(deserialisedFilter); assertEquals(controlValue, deserialisedFilter.getControlValue()); }
IsMoreThan extends KoryphePredicate<Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == controlValue) { result.addError("Control value has not been set"); return result; } if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 1 argument is required."); return result; } if (!controlValue.getClass().isAssignableFrom(arguments[0])) { result.addError("Control value class " + controlValue.getClass().getName() + " is not compatible with the input type: " + arguments[0]); } return result; } IsMoreThan(); IsMoreThan(final Comparable<?> controlValue); IsMoreThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldCheckInputClass() { final IsMoreThan predicate = new IsMoreThan(1); assertTrue(predicate.isInputValid(Integer.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Integer.class).isValid()); }
IsXMoreThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public boolean test(final Comparable input1, final Comparable input2) { return null != input1 && null != input2 && input1.getClass() == input2.getClass() && (input1.compareTo(input2) > 0); } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldAcceptWhenMoreThan() { final IsXMoreThanY filter = new IsXMoreThanY(); boolean accepted = filter.test(2, 1); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenMoreThan() { final IsXMoreThanY filter = new IsXMoreThanY(); boolean accepted = filter.test(5, 6); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqualTo() { final IsXMoreThanY filter = new IsXMoreThanY(); boolean accepted = filter.test(5, 5); assertFalse(accepted); }
IsXMoreThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 2 != arguments.length || null == arguments[0] || null == arguments[1]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 2 arguments are required."); return result; } if (!arguments[0].equals(arguments[1]) || !Comparable.class.isAssignableFrom(arguments[0])) { result.addError("Inputs must be the same class type and comparable: " + arguments[0] + "," + arguments[1]); } return result; } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldCheckInputClass() { final IsXLessThanY predicate = new IsXLessThanY(); assertTrue(predicate.isInputValid(Integer.class, Integer.class).isValid()); assertTrue(predicate.isInputValid(String.class, String.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Double.class).isValid()); }
And extends PredicateComposite<I, Predicate<I>> { @Override public boolean test(final I input) { if (components == null || components.isEmpty()) { return true; } else { return super.test(input); } } And(); And(final Predicate<?>... predicates); And(final List<Predicate> predicates); @Override boolean test(final I input); @Override String toString(); }
@Test public void shouldAcceptWhenAllFunctionsAccept() { final Predicate<String> func1 = mock(Predicate.class); final Predicate<String> func2 = mock(Predicate.class); final Predicate<String> func3 = mock(Predicate.class); final And<String> and = new And<>(func1, func2, func3); given(func1.test("value")).willReturn(true); given(func2.test("value")).willReturn(true); given(func3.test("value")).willReturn(true); boolean accepted = and.test("value"); assertTrue(accepted); } @Test public void shouldAcceptWhenNoFunctions() { final And and = new And(); boolean accepted = and.test(new String[] {"test"}); assertTrue(accepted); } @Test public void shouldAcceptWhenNoFunctionsAndNullInput() { final And and = new And(); boolean accepted = and.test(null); assertTrue(accepted); } @Test public void shouldRejectWhenOneFunctionRejects() { final Predicate<String> func1 = mock(Predicate.class); final Predicate<String> func2 = mock(Predicate.class); final Predicate<String> func3 = mock(Predicate.class); final And<String> and = new And<>(func1, func2, func3); given(func1.test("value")).willReturn(true); given(func2.test("value")).willReturn(false); given(func3.test("value")).willReturn(true); boolean accepted = and.test("value"); assertFalse(accepted); verify(func1).test("value"); verify(func2).test("value"); verify(func3, never()).test("value"); } @Test public void shouldHandlePredicateWhenConstructedWithASingleSelection() { final And and = new And<>( new Exists(), new IsA(String.class), new IsEqual("test") ); final boolean result = and.test("test"); assertTrue(result); } @Test public void shouldHandlePredicateWhenBuiltAndWithASingleSelection() { final And and = new And.Builder<String>() .select(0) .execute(new Exists()) .select(0) .execute(new IsA(String.class)) .select(0) .execute(new IsEqual("test")) .build(); final boolean result = and.test("test"); final boolean tupleResult = and.test(new ArrayTuple("test")); assertTrue(result); assertTrue(tupleResult); }
AreEqual extends KoryphePredicate2<Object, Object> { @Override public boolean test(final Object input1, final Object input2) { if (null == input1) { return null == input2; } return input1.equals(input2); } @Override boolean test(final Object input1, final Object input2); }
@Test public void shouldAcceptTheWhenEqualValues() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test("test", "test"); assertTrue(accepted); } @Test public void shouldAcceptWhenAllNull() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test(null, null); assertTrue(accepted); } @Test public void shouldRejectWhenOneIsNull() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test(null, "test"); assertFalse(accepted); } @Test public void shouldRejectWhenNotEqual() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test("test", "test2"); assertFalse(accepted); }
IsFalse extends KoryphePredicate<Boolean> { @Override public boolean test(final Boolean input) { return Boolean.FALSE.equals(input); } @Override boolean test(final Boolean input); }
@Test public void shouldAcceptTheValueWhenFalse() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(false); assertTrue(accepted); } @Test public void shouldAcceptTheValueWhenObjectFalse() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(Boolean.FALSE); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenNull() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(null); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenTrue() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(true); assertFalse(accepted); }
IsA extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { return null == input || null == type || type.isAssignableFrom(input.getClass()); } IsA(); IsA(final Class<?> type); IsA(final String type); void setType(final String type); String getType(); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptTheValueWhenSameClass() { final IsA predicate = new IsA(String.class); boolean valid = predicate.test("Test"); assertTrue(valid); } @Test public void shouldRejectTheValueWhenDifferentClasses() { final IsA predicate = new IsA(String.class); boolean valid = predicate.test(5); assertFalse(valid); } @Test public void shouldAcceptTheValueWhenSuperClass() { final IsA predicate = new IsA(Number.class); boolean valid = predicate.test(5); assertTrue(valid); } @Test public void shouldAcceptTheValueWhenNullValue() { final IsA predicate = new IsA(String.class); boolean valid = predicate.test(null); assertTrue(valid); }
IterableUtil { public static <T> CloseableIterable<T> limit(final Iterable<T> iterable, final int start, final Integer end, final boolean truncate) { return new LimitedIterable<>(iterable, start, end, truncate); } private IterableUtil(); static CloseableIterable<T> filter(final Iterable<T> iterable, final Predicate predicate); static CloseableIterable<T> filter(final Iterable<T> iterable, final List<Predicate> predicates); static CloseableIterable<O_ITEM> map(final Iterable<I_ITEM> iterable, final Function function); static CloseableIterable<O_ITEM> map(final Iterable<I_ITEM> iterable, final List<Function> functions); static CloseableIterable<T> concat(final Iterable<? extends Iterable<? extends T>> iterables); static CloseableIterable<T> limit(final Iterable<T> iterable, final int start, final Integer end, final boolean truncate); }
@Test public void shouldLimitResultsToFirstItem() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 0; final int end = 1; final CloseableIterable<Integer> limitedValues = IterableUtil.limit(values, start, end, true); assertEquals(values.subList(start, end), Lists.newArrayList(limitedValues)); } @Test public void shouldLimitResultsToLastItem() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 2; final int end = Integer.MAX_VALUE; final CloseableIterable<Integer> limitedValues = IterableUtil.limit(values, start, end, true); assertEquals(values.subList(start, values.size()), Lists.newArrayList(limitedValues)); } @Test public void shouldNotLimitResults() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 0; final int end = Integer.MAX_VALUE; final CloseableIterable<Integer> limitedValues = IterableUtil.limit(values, start, end, true); assertEquals(values, Lists.newArrayList(limitedValues)); } @Test public void shouldReturnNoValuesIfStartIsBiggerThanSize() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 5; final int end = Integer.MAX_VALUE; final CloseableIterable<Integer> limitedValues = IterableUtil.limit(values, start, end, true); assertTrue(Lists.newArrayList(limitedValues).isEmpty()); } @Test public void shouldThrowExceptionIfStartIsBiggerThanEnd() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 3; final int end = 1; final Exception exception = assertThrows(IllegalArgumentException.class, () -> IterableUtil.limit(values, start, end, false)); assertEquals("The start pointer must be less than the end pointer.", exception.getMessage()); } @Test public void shouldThrowExceptionIfDataIsTruncated() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 0; final int end = 2; final boolean truncate = false; final CloseableIterable<Integer> limitedValues = IterableUtil.limit(values, start, end, truncate); final Exception exception = assertThrows(NoSuchElementException.class, () -> { for (final Integer i : limitedValues) { } }); assertEquals("Limit of " + end + " exceeded.", exception.getMessage()); } @Test public void shouldHandleNullIterable() { final CloseableIterable<Integer> nullIterable = IterableUtil.limit(null, 0, 1, true); assertTrue(Lists.newArrayList(nullIterable).isEmpty()); } @Test public void shouldHandleLimitEqualToIterableLength() { final List<Integer> values = Arrays.asList(0, 1, 2, 3); final int start = 0; final int end = 4; final boolean truncate = false; final CloseableIterable<Integer> equalValues = IterableUtil.limit(values, start, end, truncate); assertEquals(values, Lists.newArrayList(equalValues)); }
IsA extends KoryphePredicate<Object> { public String getType() { return null != type ? type.getName() : null; } IsA(); IsA(final Class<?> type); IsA(final String type); void setType(final String type); String getType(); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldCreateIsAFromClassName() { final String type = "java.lang.String"; final IsA predicate = new IsA(type); assertNotNull(predicate); assertEquals(predicate.getType(), type); } @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final Class<Integer> type = Integer.class; final IsA filter = new IsA(type); final String json = JsonSerialiser.serialise(filter); assertEquals("{\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsA\",\"type\":\"java.lang.Integer\"}", json); final IsA deserialisedFilter = JsonSerialiser.deserialise(json, IsA.class); assertNotNull(deserialisedFilter); assertEquals(type.getName(), deserialisedFilter.getType()); }
AbstractInTimeRange extends KoryphePredicate<T> { @Override public String toString() { return new ToStringBuilder(this) .appendSuper(predicate.toString()) .toString(); } protected AbstractInTimeRange(final AbstractInTimeRangeDual<T> predicate); @Override boolean test(final T value); String getStart(); Long getStartOffset(); Boolean isStartInclusive(); String getEnd(); Long getEndOffset(); Boolean isEndInclusive(); TimeUnit getOffsetUnit(); @JsonInclude(Include.NON_DEFAULT) TimeUnit getTimeUnit(); TimeZone getTimeZone(); @JsonGetter("timeZone") String getTimeZoneId(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptValuesInRangeDayOffsetFromStart() { final long start = System.currentTimeMillis() - 100 * DAYS_TO_MILLISECONDS; final long end = System.currentTimeMillis() - 60 * DAYS_TO_MILLISECONDS; final AbstractInTimeRange<T> filter = createBuilder() .start(Long.toString(start)) .startOffset(-7L) .end(Long.toString(end)) .endOffset(-2L) .build(); final List<Long> validValues = Arrays.asList( start - 7 * DAYS_TO_MILLISECONDS, end - 3 * DAYS_TO_MILLISECONDS, end - 2 * DAYS_TO_MILLISECONDS ); final List<Long> invalidValues = Arrays.asList( start - 7 * DAYS_TO_MILLISECONDS - 1, end - 2 * DAYS_TO_MILLISECONDS + 1, end ); testValues(true, validValues, filter); testValues(false, invalidValues, filter); }
AbstractInTimeRangeDual extends KoryphePredicate2<Comparable<T>, Comparable<T>> { @JsonGetter("timeZone") public String getTimeZoneId() { return null != timeZone ? timeZone.getID() : null; } protected AbstractInTimeRangeDual(); protected AbstractInTimeRangeDual(final Function<Long, T> toT); void initialise(); @Override boolean test(final Comparable<T> startValue, final Comparable<T> endValue); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); Long getStartOffset(); String getStart(); Boolean isStartInclusive(); Boolean isStartFullyContained(); String getEnd(); Long getEndOffset(); Boolean isEndInclusive(); Boolean isEndFullyContained(); TimeUnit getOffsetUnit(); @JsonInclude(Include.NON_DEFAULT) TimeUnit getTimeUnit(); TimeZone getTimeZone(); @JsonGetter("timeZone") String getTimeZoneId(); }
@Test public void shouldSetSystemPropertyTimeZone() { final String timeZone = "Etc/GMT+6"; System.setProperty(DateUtil.TIME_ZONE, timeZone); final AbstractInTimeRangeDual predicate = createBuilder() .start("1") .end("10") .startFullyContained(true) .endFullyContained(true) .build(); assertEquals(timeZone, predicate.getTimeZoneId()); } @Test public void shouldNotOverrideUserTimeZone() { final String timeZone = "Etc/GMT+6"; final String userTimeZone = "Etc/GMT+4"; System.setProperty(DateUtil.TIME_ZONE, timeZone); final AbstractInTimeRangeDual predicate = createBuilder() .start("1") .end("10") .startFullyContained(true) .endFullyContained(true) .timeZone(userTimeZone) .build(); assertEquals(userTimeZone, predicate.getTimeZoneId()); }
Not extends KoryphePredicate<I> implements InputValidator { @Override public boolean test(final I input) { return null != predicate && !predicate.test(input); } Not(); Not(final Predicate<I> predicate); void setPredicate(final Predicate<I> predicate); Predicate<I> getPredicate(); @Override boolean test(final I input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldAcceptTheValueWhenTheWrappedFunctionReturnsFalse() { final Predicate<String> function = mock(Predicate.class); final Not<String> filter = new Not<>(function); given(function.test("some value")).willReturn(false); boolean accepted = filter.test("some value"); assertTrue(accepted); verify(function).test("some value"); } @Test public void shouldRejectTheValueWhenTheWrappedFunctionReturnsTrue() { final Predicate<String> function = mock(Predicate.class); final Not<String> filter = new Not<>(function); given(function.test("some value")).willReturn(true); boolean accepted = filter.test("some value"); assertFalse(accepted); verify(function).test("some value"); } @Test public void shouldRejectTheValueWhenNullFunction() { final Not<String> filter = new Not<>(); boolean accepted = filter.test("some value"); assertFalse(accepted); }
Not extends KoryphePredicate<I> implements InputValidator { public Predicate<I> getPredicate() { return predicate; } Not(); Not(final Predicate<I> predicate); void setPredicate(final Predicate<I> predicate); Predicate<I> getPredicate(); @Override boolean test(final I input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final IsA isA = new IsA(String.class); final Not<Object> filter = new Not<>(isA); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.Not\",%n" + " \"predicate\" : {%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsA\",%n" + " \"type\" : \"java.lang.String\"%n" + " }%n" + "}"), json); final Not deserialisedFilter = JsonSerialiser.deserialise(json, Not.class); assertNotNull(deserialisedFilter); assertEquals(String.class.getName(), ((IsA) deserialisedFilter.getPredicate()).getType()); }
IsTrue extends KoryphePredicate<Boolean> { @Override public boolean test(final Boolean input) { return Boolean.TRUE.equals(input); } @Override boolean test(final Boolean input); }
@Test public void shouldAcceptTheValueWhenTrue() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(true); assertTrue(accepted); } @Test public void shouldAcceptTheValueWhenObjectTrue() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(Boolean.TRUE); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenNull() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(null); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenFalse() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(false); assertFalse(accepted); }
IsEqual extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { if (null == controlValue) { return null == input; } return controlValue.equals(input); } IsEqual(); IsEqual(final Object controlValue); @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Object getControlValue(); void setControlValue(final Object controlValue); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptTheTestValue() { final IsEqual filter = new IsEqual("test"); boolean accepted = filter.test("test"); assertTrue(accepted); } @Test public void shouldAcceptWhenControlValueAndTestValueAreNull() { final IsEqual filter = new IsEqual(); boolean accepted = filter.test(null); assertTrue(accepted); } @Test public void shouldRejectWhenNotEqual() { final IsEqual filter = new IsEqual("test"); boolean accepted = filter.test("a different value"); assertFalse(accepted); }
IsEqual extends KoryphePredicate<Object> { @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) public Object getControlValue() { return controlValue; } IsEqual(); IsEqual(final Object controlValue); @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Object getControlValue(); void setControlValue(final Object controlValue); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CustomObj controlValue = new CustomObj(); final IsEqual filter = new IsEqual(controlValue); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsEqual\",%n" + " \"value\" : {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}%n" + "}"), json); final IsEqual deserialisedFilter = JsonSerialiser.deserialise(json, IsEqual.class); assertNotNull(deserialisedFilter); assertEquals(controlValue, deserialisedFilter.getControlValue()); }
CollectionContains extends KoryphePredicate<Collection<?>> { @Override public boolean test(final Collection<?> input) { return input.contains(value); } CollectionContains(); CollectionContains(final Object value); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Object getValue(); void setValue(final Object value); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenValueInList() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(list); assertTrue(accepted); } @Test public void shouldAcceptWhenValueInSet() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(set); assertTrue(accepted); } @Test public void shouldRejectWhenValueNotPresentInList() { final CollectionContains filter = new CollectionContains(VALUE2); boolean accepted = filter.test(list); assertFalse(accepted); } @Test public void shouldRejectWhenValueNotPresentInSet() { final CollectionContains filter = new CollectionContains(VALUE2); boolean accepted = filter.test(set); assertFalse(accepted); } @Test public void shouldRejectEmptyLists() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(new ArrayList<>()); assertFalse(accepted); } @Test public void shouldRejectEmptySets() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(new HashSet<>()); assertFalse(accepted); }
CollectionContains extends KoryphePredicate<Collection<?>> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Object getValue() { return value; } CollectionContains(); CollectionContains(final Object value); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Object getValue(); void setValue(final Object value); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CollectionContains filter = new CollectionContains(VALUE1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.CollectionContains\",%n" + " \"value\" : {\"class\":\"uk.gov.gchq.koryphe.util.CustomObj\", \"value\":\"1\"}%n" + "}"), json); final CollectionContains deserialisedFilter = JsonSerialiser.deserialise(json, CollectionContains.class); assertNotNull(deserialisedFilter); assertEquals(VALUE1, deserialisedFilter.getValue()); }
MapContainsPredicate extends KoryphePredicate<Map> { @Override public boolean test(final Map input) { if (null != input && null != keyPredicate) { for (final Object key : input.keySet()) { if (keyPredicate.test(key)) { return true; } } } return false; } MapContainsPredicate(); MapContainsPredicate(final Predicate keyPredicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate getKeyPredicate(); void setKeyPredicate(final Predicate keyPredicate); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenKeyEqualsInMap() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_1); boolean accepted = filter.test(map1); assertTrue(accepted); } @Test public void shouldAcceptWhenKeyRegexInMap() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_2); boolean accepted = filter.test(map1); assertTrue(accepted); } @Test public void shouldRejectWhenKeyNotPresent() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_NOT_IN_MAP); boolean accepted = filter.test(map1); assertFalse(accepted); } @Test public void shouldRejectEmptyMaps() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_1); boolean accepted = filter.test(new HashMap()); assertFalse(accepted); }
MapContainsPredicate extends KoryphePredicate<Map> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Predicate getKeyPredicate() { return keyPredicate; } MapContainsPredicate(); MapContainsPredicate(final Predicate keyPredicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate getKeyPredicate(); void setKeyPredicate(final Predicate keyPredicate); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals("{" + "\"class\":\"uk.gov.gchq.koryphe.impl.predicate.MapContainsPredicate\"," + "\"keyPredicate\":{" + "\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsEqual\"," + "\"value\":\"key1\"" + "}" + "}", json); final MapContainsPredicate deserialisedFilter = JsonSerialiser.deserialise(json, MapContainsPredicate.class); assertNotNull(deserialisedFilter); assertEquals(KEY_PREDICATE_1, deserialisedFilter.getKeyPredicate()); }
AgeOffFromDays extends KoryphePredicate2<Long, Integer> { @Override public boolean test(final Long timestamp, final Integer days) { return null != timestamp && null != days && (System.currentTimeMillis() - (days * DAYS_TO_MILLISECONDS) < timestamp); } @Override boolean test(final Long timestamp, final Integer days); static final long DAYS_TO_MILLISECONDS; }
@Test public void shouldAcceptWhenWithinAgeOffLimit() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(System.currentTimeMillis() - AGE_OFF_MILLISECONDS + MINUTE_IN_MILLISECONDS, AGE_OFF_DAYS); assertTrue(accepted); } @Test public void shouldAcceptWhenOutsideAgeOffLimit() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(System.currentTimeMillis() - AGE_OFF_MILLISECONDS - DAY_IN_MILLISECONDS, AGE_OFF_DAYS); assertFalse(accepted); } @Test public void shouldNotAcceptWhenTimestampIsNull() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(null, 0); assertFalse(accepted); } @Test public void shouldNotAcceptWhenDaysIsNull() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(0L, null); assertFalse(accepted); }
IsLessThan extends KoryphePredicate<Comparable> implements InputValidator { @Override public boolean test(final Comparable input) { if (null == input || !controlValue.getClass().isAssignableFrom(input.getClass())) { return false; } final int compareVal = controlValue.compareTo(input); if (orEqualTo) { return compareVal >= 0; } return compareVal > 0; } IsLessThan(); IsLessThan(final Comparable<?> controlValue); IsLessThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenLessThan() { final IsLessThan filter = new IsLessThan(5); boolean accepted = filter.test(4); assertTrue(accepted); } @Test public void shouldAcceptWhenLessThanAndOrEqualToIsTrue() { final IsLessThan filter = new IsLessThan(5, true); boolean accepted = filter.test(4); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenMoreThan() { final IsLessThan filter = new IsLessThan(5); boolean accepted = filter.test(6); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenMoreThanAndOrEqualToIsTrue() { final IsLessThan filter = new IsLessThan(5, true); boolean accepted = filter.test(6); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqualTo() { final IsLessThan filter = new IsLessThan(5); boolean accepted = filter.test(5); assertFalse(accepted); } @Test public void shouldAcceptTheValueWhenEqualToAndOrEqualToIsTrue() { final IsLessThan filter = new IsLessThan(5, true); boolean accepted = filter.test(5); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenEqual() { final IsLessThan filter = new IsLessThan(5); boolean accepted = filter.test(5); assertFalse(accepted); }
IsLessThan extends KoryphePredicate<Comparable> implements InputValidator { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Comparable getControlValue() { return controlValue; } IsLessThan(); IsLessThan(final Comparable<?> controlValue); IsLessThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CustomObj controlValue = new CustomObj(); final IsLessThan filter = new IsLessThan(controlValue); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsLessThan\",%n" + " \"orEqualTo\" : false,%n" + " \"value\" : {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}%n" + "}"), json); final IsLessThan deserialisedFilter = JsonSerialiser.deserialise(json, IsLessThan.class); assertNotNull(deserialisedFilter); assertEquals(controlValue, deserialisedFilter.getControlValue()); } @Test public void shouldJsonSerialiseAndDeserialiseWithSimpleLongClassName() throws IOException { final IsLessThan filter = new IsLessThan(1L); final String json; try { SimpleClassNameCache.setUseFullNameForSerialisation(false); json = JsonSerialiser.serialise(filter); } finally { SimpleClassNameCache.setUseFullNameForSerialisation(SimpleClassNameCache.DEFAULT_USE_FULL_NAME_FOR_SERIALISATION); } JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"IsLessThan\",%n" + " \"orEqualTo\" : false,%n" + " \"value\" : {\"Long\":1}%n" + "}"), json); final IsLessThan deserialisedFilter = JsonSerialiser.deserialise(json, IsLessThan.class); assertNotNull(deserialisedFilter); assertEquals(1L, deserialisedFilter.getControlValue()); }
IsLessThan extends KoryphePredicate<Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == controlValue) { result.addError("Control value has not been set"); return result; } if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 1 argument is required."); return result; } if (!controlValue.getClass().isAssignableFrom(arguments[0])) { result.addError("Control value class " + controlValue.getClass().getName() + " is not compatible with the input type: " + arguments[0]); } return result; } IsLessThan(); IsLessThan(final Comparable<?> controlValue); IsLessThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldCheckInputClass() { final IsLessThan predicate = new IsLessThan(1); assertTrue(predicate.isInputValid(Integer.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Integer.class).isValid()); }
IsLongerThan extends KoryphePredicate<Object> implements InputValidator { @Override public boolean test(final Object input) { if (null == input) { return true; } if (orEqualTo) { return getLength(input) >= minLength; } else { return getLength(input) > minLength; } } IsLongerThan(); IsLongerThan(final int minLength); IsLongerThan(final int minLength, final boolean orEqualTo); int getMinLength(); void setMinLength(final int minLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptTheValueWhenMoreThan() { final IsLongerThan filter = new IsLongerThan(5); final boolean accepted = filter.test("123456"); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenLessThan() { final IsLongerThan filter = new IsLongerThan(5); final boolean accepted = filter.test("1234"); assertFalse(accepted); } @Test public void shouldAcceptTheIterableValueWhenEqualTo() { final IsLongerThan filter = new IsLongerThan(5, true); final boolean accepted = filter.test(Collections.nCopies(5, "item")); assertTrue(accepted); } @Test public void shouldRejectTheIterableValueWhenNotEqualTo() { final IsLongerThan filter = new IsLongerThan(5, false); final boolean accepted = filter.test(Collections.nCopies(5, "item")); assertFalse(accepted); } @Test public void shouldAcceptTheIterableValueWhenMoreThan() { final IsLongerThan filter = new IsLongerThan(5, true); final boolean accepted = filter.test(Collections.nCopies(6, "item")); assertTrue(accepted); } @Test public void shouldRejectTheIterableValueWhenLessThan() { final IsLongerThan filter = new IsLongerThan(5); final boolean accepted = filter.test(Collections.nCopies(4, "item")); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqual() { final IsLongerThan filter = new IsLongerThan(5); final boolean accepted = filter.test("12345"); assertFalse(accepted); } @Test public void shouldThrowExceptionWhenTheValueWhenUnknownType() { final IsLongerThan filter = new IsLongerThan(5); assertThrows(IllegalArgumentException.class, () -> filter.test(4)); }
IsLongerThan extends KoryphePredicate<Object> implements InputValidator { public int getMinLength() { return minLength; } IsLongerThan(); IsLongerThan(final int minLength); IsLongerThan(final int minLength, final boolean orEqualTo); int getMinLength(); void setMinLength(final int minLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final int min = 5; final IsLongerThan filter = new IsLongerThan(min); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsLongerThan\",%n" + " \"orEqualTo\" : false,%n" + " \"minLength\" : 5%n" + "}"), json); final IsLongerThan deserialisedFilter = JsonSerialiser.deserialise(json, IsLongerThan.class); assertNotNull(deserialisedFilter); assertEquals(min, deserialisedFilter.getMinLength()); }
IsLongerThan extends KoryphePredicate<Object> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 1 argument is required."); return result; } if (!String.class.isAssignableFrom(arguments[0]) && !Object[].class.isAssignableFrom(arguments[0]) && !Iterable.class.isAssignableFrom(arguments[0]) && !Map.class.isAssignableFrom(arguments[0])) { result.addError("Input class " + arguments[0].getName() + " must be one of the following: " + String.class.getName() + ", " + Object[].class.getName() + ", " + Iterable.class.getName() + ", " + Map.class.getName()); } return result; } IsLongerThan(); IsLongerThan(final int minLength); IsLongerThan(final int minLength, final boolean orEqualTo); int getMinLength(); void setMinLength(final int minLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldCheckInputClass() { final IsLongerThan predicate = new IsLongerThan(10); assertTrue(predicate.isInputValid(String.class).isValid()); assertTrue(predicate.isInputValid(Object[].class).isValid()); assertTrue(predicate.isInputValid(Integer[].class).isValid()); assertTrue(predicate.isInputValid(Collection.class).isValid()); assertTrue(predicate.isInputValid(List.class).isValid()); assertTrue(predicate.isInputValid(Map.class).isValid()); assertTrue(predicate.isInputValid(HashMap.class).isValid()); assertFalse(predicate.isInputValid(String.class, HashMap.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Integer.class).isValid()); }
MapContains extends KoryphePredicate<Map> { @Override public boolean test(final Map input) { return input.containsKey(key); } MapContains(); MapContains(final String key); String getKey(); void setKey(final String key); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenKeyInMap() { final MapContains filter = new MapContains(KEY1); boolean accepted = filter.test(map1); assertTrue(accepted); } @Test public void shouldRejectWhenKeyNotPresent() { final MapContains filter = new MapContains(KEY2); boolean accepted = filter.test(map1); assertFalse(accepted); } @Test public void shouldRejectEmptyMaps() { final MapContains filter = new MapContains(KEY1); boolean accepted = filter.test(new HashMap<>()); assertFalse(accepted); }
MapContains extends KoryphePredicate<Map> { public String getKey() { return key; } MapContains(); MapContains(final String key); String getKey(); void setKey(final String key); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final MapContains filter = new MapContains(KEY1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.MapContains\",%n" + " \"key\" : \"key1\"%n" + "}"), json); final MapContains deserialisedFilter = JsonSerialiser.deserialise(json, MapContains.class); assertNotNull(deserialisedFilter); assertEquals(KEY1, deserialisedFilter.getKey()); }
IsXLessThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public boolean test(final Comparable input1, final Comparable input2) { return null != input1 && null != input2 && input1.getClass() == input2.getClass() && (input1.compareTo(input2) < 0); } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldAcceptWhenLessThan() { final IsXLessThanY filter = new IsXLessThanY(); boolean accepted = filter.test(1, 2); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenMoreThan() { final IsXLessThanY filter = new IsXLessThanY(); boolean accepted = filter.test(6, 5); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqualTo() { final IsXLessThanY filter = new IsXLessThanY(); boolean accepted = filter.test(5, 5); assertFalse(accepted); }
ReflectionUtil { public static Map<String, Set<Class>> getSimpleClassNames(final Class<?> clazz) { Map<String, Set<Class>> simpleClassNames = simpleClassNamesCache.get(clazz); if (null == simpleClassNames) { final Set<Class> subTypes = getSubTypes(clazz); simpleClassNames = new HashMap<>(subTypes.size()); for (final Class subType : subTypes) { final Set<Class> simpleClasses = simpleClassNames.computeIfAbsent(subType.getSimpleName(), k -> new HashSet<>()); simpleClasses.add(subType); } simpleClassNames = Collections.unmodifiableMap(simpleClassNames); simpleClassNamesCache.put(clazz, simpleClassNames); } return simpleClassNames; } private ReflectionUtil(); static Class<?> getClassFromName(final String className); static Map<String, Set<Class>> getSimpleClassNames(final Class<?> clazz); static Set<Class> getSubTypes(final Class<?> clazz); static Set<Class> getAnnotatedTypes(final Class<? extends Annotation> annoClass); static boolean isPublicConcrete(final Class clazz); static void keepPublicConcreteClasses(final Collection<Class> classes); static void resetReflectionPackages(); static void resetReflectionCache(); static void updateReflectionPackages(); static void addReflectionPackages(final String... newPackages); static void addReflectionPackages(final Iterable<String> newPackages); static Set<String> getReflectionPackages(); static final String PACKAGES_KEY; static final Set<String> DEFAULT_PACKAGES; }
@Test public void shouldReturnUnmodifiableSimpleClassNames() { final Map<String, Set<Class>> simpleClassNames = ReflectionUtil.getSimpleClassNames(Number.class); assertThrows(UnsupportedOperationException.class, () -> simpleClassNames.put("test", new HashSet<>())); } @Test public void shouldCacheSimpleNames() { final Map<String, Set<Class>> simpleClassNames = ReflectionUtil.getSimpleClassNames(Number.class); final Map<String, Set<Class>> simpleClassNames2 = ReflectionUtil.getSimpleClassNames(Number.class); assertSame(simpleClassNames, simpleClassNames2); } @Test public void shouldReturnSimpleClassNames() { final Map<String, Set<Class>> simpleClassNames = ReflectionUtil.getSimpleClassNames(Number.class); final HashSet<Class<? extends Number>> expected = Sets.newHashSet( TestCustomNumber.class, uk.gov.gchq.koryphe.serialisation.json.obj.second.TestCustomNumber.class ); assertEquals(expected, simpleClassNames.get(TestCustomNumber.class.getSimpleName())); assertFalse(simpleClassNames.containsKey(UnsignedLong.class.getSimpleName())); }
IsXLessThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 2 != arguments.length || null == arguments[0] || null == arguments[1]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 2 arguments are required."); return result; } if (!arguments[0].equals(arguments[1]) || !Comparable.class.isAssignableFrom(arguments[0])) { result.addError("Inputs must be the same class type and comparable: " + arguments[0] + "," + arguments[1]); } return result; } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldCheckInputClass() { final IsXLessThanY predicate = new IsXLessThanY(); assertTrue(predicate.isInputValid(Integer.class, Integer.class).isValid()); assertTrue(predicate.isInputValid(String.class, String.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Double.class).isValid()); }
Or extends PredicateComposite<I, Predicate<I>> { @Override public boolean test(final I input) { for (final Predicate<I> predicate : components) { try { if (predicate.test(input)) { return true; } } catch (final ClassCastException e) { if (predicate instanceof TupleAdaptedPredicate && !(input instanceof Tuple)) { if (((TupleAdaptedPredicate) predicate).getPredicate().test(input)) { return true; } } else { throw e; } } } return false; } Or(); Or(final Predicate<?>... predicates); Or(final List<Predicate> predicates); @Override boolean test(final I input); @Override String toString(); }
@Test public void shouldAcceptWhenOneFunctionsAccepts() { final Predicate<String> func1 = mock(Predicate.class); final Predicate<String> func2 = mock(Predicate.class); final Predicate<String> func3 = mock(Predicate.class); final Or<String> or = new Or<>(func1, func2, func3); given(func1.test("value")).willReturn(false); given(func2.test("value")).willReturn(true); given(func3.test("value")).willReturn(true); boolean accepted = or.test("value"); assertTrue(accepted); verify(func1).test("value"); verify(func2).test("value"); verify(func3, never()).test("value"); } @Test public void shouldRejectWhenNoFunctions() { final Or or = new Or(); boolean accepted = or.test(new String[]{"test"}); assertFalse(accepted); } @Test public void shouldRejectWhenNoFunctionsOrNullInput() { final Or<String> or = new Or<>(); boolean accepted = or.test(null); assertFalse(accepted); } @Test public void shouldRejectWhenAllFunctionsReject() { final Predicate<String> func1 = mock(Predicate.class); final Predicate<String> func2 = mock(Predicate.class); final Predicate<String> func3 = mock(Predicate.class); final Or<String> or = new Or<>(func1, func2, func3); given(func1.test("value")).willReturn(false); given(func2.test("value")).willReturn(false); given(func3.test("value")).willReturn(false); boolean accepted = or.test("value"); assertFalse(accepted); verify(func1).test("value"); verify(func2).test("value"); verify(func3).test("value"); } @Test public void shouldHandlePredicateWhenConstructedWithASingleSelection() { final Or or = new Or<>( new Exists(), new IsA(String.class), new IsEqual("test") ); final boolean result = or.test("test"); assertTrue(result); } @Test public void shouldHandlePredicateWhenBuiltAndWithASingleSelection() { final Or or = new Or.Builder<String>() .select(0) .execute(new Exists()) .select(0) .execute(new IsA(String.class)) .select(0) .execute(new IsEqual("test")) .build(); final boolean result = or.test("test"); final boolean tupleResult = or.test(new ArrayTuple("test")); assertTrue(result); assertTrue(tupleResult); }
AgeOff extends KoryphePredicate<Long> { public long getAgeOffTime() { return ageOffTime; } AgeOff(); AgeOff(final long ageOffTime); @Override boolean test(final Long input); long getAgeOffTime(); void setAgeOffTime(final long ageOffTime); void setAgeOffDays(final int ageOfDays); void setAgeOffHours(final long ageOfHours); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final long HOURS_TO_MILLISECONDS; static final long DAYS_TO_MILLISECONDS; static final long AGE_OFF_TIME_DEFAULT; }
@Test public void shouldUseDefaultAgeOffTime() { final AgeOff filter = new AgeOff(); final long ageOfTime = filter.getAgeOffTime(); assertEquals(AgeOff.AGE_OFF_TIME_DEFAULT, ageOfTime); } @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final AgeOff filter = new AgeOff(CUSTOM_AGE_OFF); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.AgeOff\",%n" + " \"ageOffTime\" : 100000%n" + "}"), json); final AgeOff deserialisedFilter = JsonSerialiser.deserialise(json, AgeOff.class); assertNotNull(deserialisedFilter); assertEquals(CUSTOM_AGE_OFF, deserialisedFilter.getAgeOffTime()); }
AgeOff extends KoryphePredicate<Long> { @Override public boolean test(final Long input) { return null != input && (System.currentTimeMillis() - input) < ageOffTime; } AgeOff(); AgeOff(final long ageOffTime); @Override boolean test(final Long input); long getAgeOffTime(); void setAgeOffTime(final long ageOffTime); void setAgeOffDays(final int ageOfDays); void setAgeOffHours(final long ageOfHours); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final long HOURS_TO_MILLISECONDS; static final long DAYS_TO_MILLISECONDS; static final long AGE_OFF_TIME_DEFAULT; }
@Test public void shouldAcceptWhenWithinAgeOffLimit() { final AgeOff filter = new AgeOff(CUSTOM_AGE_OFF); final boolean accepted = filter.test(System.currentTimeMillis() - CUSTOM_AGE_OFF + MINUTE_IN_MILLISECONDS); assertTrue(accepted); } @Test public void shouldAcceptWhenOutsideAgeOffLimit() { final AgeOff filter = new AgeOff(CUSTOM_AGE_OFF); final boolean accepted = filter.test(System.currentTimeMillis() - CUSTOM_AGE_OFF - MINUTE_IN_MILLISECONDS); assertFalse(accepted); }
If extends KoryphePredicate<I> { @Override public boolean test(final I input) { boolean conditionTmp; if (null == condition) { conditionTmp = null != predicate && predicate.test(input); } else { conditionTmp = condition; } if (conditionTmp) { return null != then && then.test(input); } return null != otherwise && otherwise.test(input); } If(); If(final boolean condition, final Predicate<? super I> then); If(final boolean condition, final Predicate<? super I> then, final Predicate<? super I> otherwise); If(final Predicate<? super I> predicate, final Predicate<? super I> then); If(final Predicate<? super I> predicate, final Predicate<? super I> then, final Predicate<? super I> otherwise); @Override boolean test(final I input); Boolean getCondition(); void setCondition(final boolean condition); Predicate<? super I> getThen(); void setThen(final Predicate<? super I> then); Predicate<? super I> getOtherwise(); void setOtherwise(final Predicate<? super I> otherwise); Predicate<? super I> getPredicate(); void setPredicate(final Predicate<? super I> predicate); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldReturnTrueWithSuccessfulThen() { final Object input = "testValue"; final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Object> filter = new If<>(true, then, otherwise); given(then.test(input)).willReturn(true); final boolean accepted = filter.test(input); assertTrue(accepted); verify(otherwise, never()).test(input); } @Test public void shouldReturnFalseFromFailedOtherwise() { final Object input = 6; final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Object> filter = new If<>(false, then, otherwise); given(otherwise.test(input)).willReturn(false); final boolean denied = filter.test(input); assertFalse(denied); verify(then, never()).test(input); } @Test public void shouldRejectValueWithNullFunctions() { final Object input = "testValue"; final If<Object> filter = new If<>(); final boolean denied = filter.test(input); assertFalse(denied); } @Test public void shouldApplyPredicateAndPassBothConditions() { final Object input = mock(Object.class); final Predicate predicate = mock(Predicate.class); final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Object> filter = new If<>(predicate, then, otherwise); given(predicate.test(input)).willReturn(true); given(then.test(input)).willReturn(true); final boolean result = filter.test(input); assertTrue(result); verify(predicate).test(input); verify(then).test(input); verify(otherwise, never()).test(input); } @Test public void shouldApplyPredicateAndPassSecondCondition() { final Object input = mock(Object.class); final Predicate predicate = mock(Predicate.class); final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Object> filter = new If<>(predicate, then, otherwise); given(predicate.test(input)).willReturn(false); given(otherwise.test(input)).willReturn(true); final boolean result = filter.test(input); assertTrue(result); verify(predicate).test(input); verify(then, never()).test(input); verify(otherwise).test(input); } @Test public void shouldApplyPredicateAndPassFirstButNotSecondCondition() { final Object input = mock(Object.class); final Predicate predicate = mock(Predicate.class); final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Object> filter = new If<>(predicate, then, otherwise); given(predicate.test(input)).willReturn(true); given(then.test(input)).willReturn(false); final boolean result = filter.test(input); assertFalse(result); verify(predicate).test(input); verify(then).test(input); verify(otherwise, never()).test(input); } @Test public void shouldApplyPredicateButFailBothConditions() { final Object input = mock(Object.class); final Predicate predicate = mock(Predicate.class); final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Object> filter = new If<>(predicate, then, otherwise); given(predicate.test(input)).willReturn(false); given(otherwise.test(input)).willReturn(false); final boolean result = filter.test(input); assertFalse(result); verify(predicate).test(input); verify(then, never()).test(input); verify(otherwise).test(input); } @Test public void shouldDelegateNullInputToPredicates() { final Comparable input = null; final Predicate predicate = mock(Predicate.class); final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Comparable> filter = new If<>(predicate, then, otherwise); final boolean result = filter.test(input); assertFalse(result); verify(predicate).test(input); verify(then, never()).test(input); verify(otherwise).test(input); } @Test public void shouldReturnFalseForNullConditionalPredicate() { final Object input = "testValue"; final Predicate predicate = null; final Predicate then = mock(Predicate.class); final If<Object> filter = new If<>(predicate, then); final boolean result = filter.test(input); assertFalse(result); verify(then, never()).test(input); } @Test public void shouldReturnFalseForNullThenOrOtherwise() { final Object input = "testValue"; final Predicate predicate = mock(Predicate.class); final Predicate then = null; final Predicate otherwise = null; final If<Object> filter = new If<>(predicate, then, otherwise); given(predicate.test(input)).willReturn(true); final boolean result = filter.test(input); assertFalse(result); verify(predicate).test(input); } @Test public void shouldApplyPredicatesToSelectionWithIfBuilder() { final Integer firstVal = 6; final Integer secondVal = 2; final Integer thirdVal = 4; final ArrayTuple input = new ArrayTuple(firstVal, secondVal, thirdVal); final Predicate predicate = mock(Predicate.class); final Predicate then = mock(Predicate.class); final Predicate otherwise = mock(Predicate.class); final If<Tuple<Integer>> filter = new If.SelectedBuilder() .predicate(predicate, 0) .then(then, 1) .otherwise(otherwise, 2) .build(); given(predicate.test(firstVal)).willReturn(true); given(then.test(secondVal)).willReturn(true); final boolean result = filter.test(input); assertTrue(result); verify(predicate).test(firstVal); verify(then).test(secondVal); } @Test public void shouldApplyPredicatesToMultipleSelectionsWithIfBuilder() { final Integer firstInput = 2; final Integer secondInput = 7; final Integer thirdInput = 1; final ArrayTuple input = new ArrayTuple(firstInput, secondInput, thirdInput); final ReferenceArrayTuple<Integer> refTuple = new ReferenceArrayTuple<>(input, new Integer[]{1, 2}); final Predicate predicate = mock(Predicate.class); final KoryphePredicate2 then = mock(KoryphePredicate2.class); final KoryphePredicate2 otherwise = mock(KoryphePredicate2.class); final If<Tuple<Integer>> filter = new If.SelectedBuilder() .predicate(predicate, 0) .then(then, 1, 2) .otherwise(otherwise, 1, 2) .build(); given(predicate.test(firstInput)).willReturn(true); given(then.test(refTuple)).willReturn(true); final boolean result = filter.test(input); assertTrue(result); verify(predicate).test(firstInput); verify(then).test(refTuple); verify(otherwise, never()).test(refTuple); } @Test public void shouldUseCorrectInputOnEachUse() { If filter = new If<>(new IsLessThan(2), new IsLessThan(0), new IsLessThan(4)); assertFalse(filter.test(1)); assertTrue(filter.test(-1)); assertTrue(filter.test(3)); }
IsIn extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { return null != allowedValues && allowedValues.contains(input); } IsIn(); IsIn(final Collection<Object> controlData); IsIn(final Object... controlData); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @JsonIgnore Set<Object> getAllowedValues(); void setAllowedValues(final Set<Object> allowedValues); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenValueInList() { final IsIn filter = new IsIn(Arrays.asList("A", "B", "C")); boolean accepted = filter.test("B"); assertTrue(accepted); } @Test public void shouldRejectWhenValueNotInList() { final IsIn filter = new IsIn(Arrays.asList("A", "B", "C")); boolean accepted = filter.test("D"); assertFalse(accepted); }
IsIn extends KoryphePredicate<Object> { @JsonIgnore public Set<Object> getAllowedValues() { return allowedValues; } IsIn(); IsIn(final Collection<Object> controlData); IsIn(final Object... controlData); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @JsonIgnore Set<Object> getAllowedValues(); void setAllowedValues(final Set<Object> allowedValues); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final Object[] controlData = {1, new CustomObj(), 3}; final IsIn filter = new IsIn(Arrays.asList(controlData)); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsIn\",%n" + " \"values\" : [ 1, {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}, 3 ]%n" + "}"), json); final IsIn deserialisedFilter = JsonSerialiser.deserialise(json, IsIn.class); assertNotNull(deserialisedFilter); assertEquals(Sets.newHashSet(controlData), deserialisedFilter.getAllowedValues()); }
Exists extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { return null != input; } @Override boolean test(final Object input); }
@Test public void shouldAcceptTheValueWhenNotNull() { final Exists filter = new Exists(); boolean accepted = filter.test("Not null value"); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenNull() { final Exists filter = new Exists(); boolean accepted = filter.test(null); assertFalse(accepted); }
MultiRegex extends KoryphePredicate<String> { @Override public boolean test(final String input) { if (null == input || input.getClass() != String.class) { return false; } for (final Pattern pattern : patterns) { if (pattern.matcher(input).matches()) { return true; } } return false; } MultiRegex(); MultiRegex(final Pattern... patterns); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern[] getPatterns(); void setPatterns(final Pattern[] patterns); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptValidValue() { Pattern[] patterns = new Pattern[2]; patterns[0] = Pattern.compile("fail"); patterns[1] = Pattern.compile("pass"); final MultiRegex filter = new MultiRegex(patterns); boolean accepted = filter.test("pass"); assertTrue(accepted); } @Test public void shouldRejectInvalidValue() { Pattern[] patterns = new Pattern[2]; patterns[0] = Pattern.compile("fail"); patterns[1] = Pattern.compile("reallyFail"); final MultiRegex filter = new MultiRegex(patterns); boolean accepted = filter.test("pass"); assertFalse(accepted); }
MultiRegex extends KoryphePredicate<String> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Pattern[] getPatterns() { return Arrays.copyOf(patterns, patterns.length); } MultiRegex(); MultiRegex(final Pattern... patterns); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern[] getPatterns(); void setPatterns(final Pattern[] patterns); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { Pattern[] patterns = new Pattern[2]; patterns[0] = Pattern.compile("test"); patterns[1] = Pattern.compile("test2"); final MultiRegex filter = new MultiRegex(patterns); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.MultiRegex\",%n" + " \"value\" : [ {%n" + " \"java.util.regex.Pattern\" : \"test\"%n" + " }, {%n" + " \"java.util.regex.Pattern\" : \"test2\"%n" + " } ]%n" + "}"), json); final MultiRegex deserialisedFilter = JsonSerialiser.deserialise(json, MultiRegex.class); assertNotNull(deserialisedFilter); assertEquals(patterns[0].pattern(), deserialisedFilter.getPatterns()[0].pattern()); assertEquals(patterns[1].pattern(), deserialisedFilter.getPatterns()[1].pattern()); }
IsShorterThan extends KoryphePredicate<Object> implements InputValidator { @Override public boolean test(final Object input) { if (null == input) { return true; } if (orEqualTo) { return getLength(input) <= maxLength; } else { return getLength(input) < maxLength; } } IsShorterThan(); IsShorterThan(final int maxLength); IsShorterThan(final int maxLength, final boolean orEqualTo); int getMaxLength(); void setMaxLength(final int maxLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptTheValueWhenLessThan() { final IsShorterThan filter = new IsShorterThan(5); final boolean accepted = filter.test("1234"); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenMoreThan() { final IsShorterThan filter = new IsShorterThan(5); final boolean accepted = filter.test("123456"); assertFalse(accepted); } @Test public void shouldAcceptTheIterableValueWhenEqualTo() { final IsShorterThan filter = new IsShorterThan(5, true); final boolean accepted = filter.test(Collections.nCopies(5, "item")); assertTrue(accepted); } @Test public void shouldRejectTheIterableValueWhenNotEqualTo() { final IsShorterThan filter = new IsShorterThan(5, false); final boolean accepted = filter.test(Collections.nCopies(5, "item")); assertFalse(accepted); } @Test public void shouldAcceptTheIterableValueWhenLessThan() { final IsShorterThan filter = new IsShorterThan(5, true); final boolean accepted = filter.test(Collections.nCopies(4, "item")); assertTrue(accepted); } @Test public void shouldRejectTheIterableValueWhenMoreThan() { final IsShorterThan filter = new IsShorterThan(5); final boolean accepted = filter.test(Collections.nCopies(6, "item")); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqual() { final IsShorterThan filter = new IsShorterThan(5); final boolean accepted = filter.test("12345"); assertFalse(accepted); } @Test public void shouldThrowExceptionWhenTheValueWhenUnknownType() { final IsShorterThan filter = new IsShorterThan(5); assertThrows(IllegalArgumentException.class, () -> filter.test(4)); }
IsShorterThan extends KoryphePredicate<Object> implements InputValidator { public int getMaxLength() { return maxLength; } IsShorterThan(); IsShorterThan(final int maxLength); IsShorterThan(final int maxLength, final boolean orEqualTo); int getMaxLength(); void setMaxLength(final int maxLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final int max = 5; final IsShorterThan filter = new IsShorterThan(max); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsShorterThan\",%n" + " \"orEqualTo\" : false,%n" + " \"maxLength\" : 5%n" + "}"), json); final IsShorterThan deserialisedFilter = JsonSerialiser.deserialise(json, IsShorterThan.class); assertNotNull(deserialisedFilter); assertEquals(max, deserialisedFilter.getMaxLength()); }
IsShorterThan extends KoryphePredicate<Object> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 1 argument is required."); return result; } if (!String.class.isAssignableFrom(arguments[0]) && !Object[].class.isAssignableFrom(arguments[0]) && !Iterable.class.isAssignableFrom(arguments[0]) && !Map.class.isAssignableFrom(arguments[0])) { result.addError("Input class " + arguments[0].getName() + " must be one of the following: " + String.class.getName() + ", " + Object[].class.getName() + ", " + Iterable.class.getName() + ", " + Map.class.getName()); } return result; } IsShorterThan(); IsShorterThan(final int maxLength); IsShorterThan(final int maxLength, final boolean orEqualTo); int getMaxLength(); void setMaxLength(final int maxLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldCheckInputClass() { final IsShorterThan predicate = new IsShorterThan(10); assertTrue(predicate.isInputValid(String.class).isValid()); assertTrue(predicate.isInputValid(Object[].class).isValid()); assertTrue(predicate.isInputValid(Integer[].class).isValid()); assertTrue(predicate.isInputValid(Collection.class).isValid()); assertTrue(predicate.isInputValid(List.class).isValid()); assertTrue(predicate.isInputValid(Map.class).isValid()); assertTrue(predicate.isInputValid(HashMap.class).isValid()); assertFalse(predicate.isInputValid(String.class, HashMap.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Integer.class).isValid()); }
StringConcat extends KorypheBinaryOperator<String> { public void setSeparator(final String separator) { this.separator = separator; } StringConcat(); StringConcat(final String separator); @Override String _apply(final String a, final String b); String getSeparator(); void setSeparator(final String separator); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldConcatStringsTogether() { final StringConcat function = new StringConcat(); function.setSeparator(";"); state = function.apply(state, "1"); state = function.apply(state, "2"); state = function.apply(state, null); assertEquals("1;2", state); }
StringDeduplicateConcat extends KorypheBinaryOperator<String> { @Override protected String _apply(final String a, final String b) { final Set<String> set = new LinkedHashSet<>(); Collections.addAll(set, p.split(StringUtils.removeStart(a, separator))); Collections.addAll(set, p.split(StringUtils.removeStart(b, separator))); return StringUtils.join(set, separator); } String getSeparator(); void setSeparator(final String separator); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldRemoveDuplicate() { final StringDeduplicateConcat sdc = new StringDeduplicateConcat(); String output = sdc._apply("test,string", "test,success"); assertEquals("test,string,success", output); } @Test public void shouldHandleTrailingDelimiter() { final StringDeduplicateConcat sdc = new StringDeduplicateConcat(); String output = sdc._apply("test,for,", "trailing,delimiters,"); assertEquals("test,for,trailing,delimiters", output); } @Test public void shouldHandleLeadingDelimiter() { final StringDeduplicateConcat sdc = new StringDeduplicateConcat(); String output = sdc._apply(",test,for", ",leading,delimiters"); assertEquals("test,for,leading,delimiters", output); }
ExtractKeys extends KorypheFunction<Map<K, V>, Iterable<K>> { @Override public Iterable<K> apply(final Map<K, V> map) { return null == map ? null : map.keySet(); } @Override Iterable<K> apply(final Map<K, V> map); }
@Test public void shouldExtractKeysFromGivenMap() { final ExtractKeys<String, Integer> function = new ExtractKeys<>(); final Map<String, Integer> input = new HashMap<>(); input.put("first", 1); input.put("second", 2); input.put("third", 3); final Iterable<String> results = function.apply(input); assertEquals(Sets.newHashSet("first", "second", "third"), results); } @Test public void shouldReturnEmptySetForEmptyMap() { final ExtractKeys<String, String> function = new ExtractKeys<>(); final Iterable<String> results = function.apply(new HashMap<>()); assertTrue(Iterables.isEmpty(results)); } @Test public void shouldReturnNullForNullInput() { final ExtractKeys<String, String> function = new ExtractKeys<>(); final Map<String, String> input = null; final Iterable result = function.apply(input); assertNull(result); }
DivideBy extends KorypheFunction<Integer, Tuple2<Integer, Integer>> { @Override public Tuple2<Integer, Integer> apply(final Integer input) { if (input == null) { return null; } else { return new Tuple2<>(input / by, input % by); } } DivideBy(); DivideBy(final int by); int getBy(); void setBy(final int by); @Override Tuple2<Integer, Integer> apply(final Integer input); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldDivideBy2() { final DivideBy function = new DivideBy(2); Tuple2<Integer, Integer> output = function.apply(4); assertEquals(new Tuple2<>(2, 0), output); } @Test public void shouldDivideBy2WithRemainder() { final DivideBy function = new DivideBy(2); Tuple2<Integer, Integer> output = function.apply(5); assertEquals(new Tuple2<>(2, 1), output); } @Test public void shouldDivideBy1IfByIsNull() { final DivideBy function = new DivideBy(); Tuple2<Integer, Integer> output = function.apply(9); assertEquals(new Tuple2<>(9, 0), output); }
DivideBy extends KorypheFunction<Integer, Tuple2<Integer, Integer>> { public int getBy() { return by; } DivideBy(); DivideBy(final int by); int getBy(); void setBy(final int by); @Override Tuple2<Integer, Integer> apply(final Integer input); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final DivideBy function = new DivideBy(4); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.DivideBy\",%n" + " \"by\" : 4%n" + "}"), json); final DivideBy deserialisedDivideBy = JsonSerialiser.deserialise(json, DivideBy.class); assertNotNull(deserialisedDivideBy); assertEquals(4, deserialisedDivideBy.getBy()); }
StringJoin extends KorypheFunction<Iterable<I_ITEM>, String> { @Override public String apply(final Iterable<I_ITEM> items) { return StringUtils.join(IterableUtil.map(items, new ToString()), delimiter); } StringJoin(); StringJoin(final String delimiter); @Override String apply(final Iterable<I_ITEM> items); String getDelimiter(); void setDelimiter(final String delimiter); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringJoin function = new StringJoin(); final String result = function.apply(null); assertNull(result); } @Test public void shouldHandleNullDelimiter() { final StringJoin<String> function = new StringJoin<>(null); final Set<String> input = Sets.newHashSet("a", "b", "c"); final String result = function.apply(input); assertEquals("abc", result); } @Test public void shouldJoinIterableOfStrings() { final StringJoin<String> function = new StringJoin<>(); final Set<String> input = Sets.newHashSet("a", "b", "c"); final String result = function.apply(input); assertEquals("abc", result); } @Test public void shouldJoinIterableOfIntegers() { final StringJoin<Integer> function = new StringJoin<>(); final List<Integer> input = Lists.newArrayList(1, 2, 3, 4, 5); final String result = function.apply(input); assertEquals("12345", result); } @Test public void shouldJoinIterableOfStringsWithDelimiter() { final StringJoin<String> function = new StringJoin<>(","); final Set<String> input = Sets.newHashSet("a", "b", "c"); final String result = function.apply(input); assertEquals("a,b,c", result); } @Test public void shouldJoinIterableOfIntegersWithDelimiter() { final StringJoin<Integer> function = new StringJoin<>(" "); final List<Integer> input = Lists.newArrayList(1, 2, 3, 4, 5); final String result = function.apply(input); assertEquals("1 2 3 4 5", result); }
PredicateComposite extends Composite<C> implements Predicate<I>, InputValidator { @Override public boolean test(final I input) { for (final C predicate : components) { try { if (!predicate.test(input)) { return false; } } catch (final ClassCastException e) { if (predicate instanceof TupleAdaptedPredicate && !(input instanceof Tuple)) { if (!((TupleAdaptedPredicate) predicate).getPredicate().test(input)) { return false; } } else { throw e; } } } return true; } PredicateComposite(); PredicateComposite(final List<C> predicates); @JsonProperty("predicates") List<C> getComponents(); @Override boolean test(final I input); @Override ValidationResult isInputValid(final Class<?>... arguments); }
@Test public void shouldPassInputToTupleAdaptedPredicateIfAutomaticallyUnpacked() { Integer unpackedInput = 5; Tuple1<Integer> input = new Tuple1<>(unpackedInput); PredicateComposite predicateComposite = new PredicateComposite<>( Arrays.asList(new TupleAdaptedPredicate<>(new IsLessThan(10), new Integer[]{0})) ); boolean unpackedTest = predicateComposite.test(unpackedInput); boolean test = predicateComposite.test(input); assertTrue(unpackedTest); assertTrue(test); } @Test public void shouldThrowExceptionIfInputClassesDontMatchInputAndPredicateIsNotTupleAdapted() { String input = "test"; PredicateComposite predicateComposite = new PredicateComposite(Arrays.asList(new IsA(String.class), new IsFalse())); try { predicateComposite.test(input); fail("Expected an exception"); } catch (final ClassCastException e) { assertNotNull(e.getMessage()); } } @Test public void shouldFailIfOneOfThePredicatesDontPass() { Long notAnInteger = 3L; PredicateComposite predicateComposite = new PredicateComposite(Arrays.asList( new Exists(), new IsA(Integer.class), new IsLessThan(10))); boolean result = predicateComposite.test(notAnInteger); assertFalse(result); } @Test public void shouldPassIfAllThePredicatesPass() { Integer input = 3; PredicateComposite predicateComposite = new PredicateComposite(Arrays.asList( new Exists(), new IsA(Integer.class), new IsLessThan(10))); boolean result = predicateComposite.test(input); assertTrue(result); }
StringRegexSplit extends KorypheFunction<String, List<String>> { @Override public List<String> apply(final String input) { if (null == input) { return null; } final Pattern pattern = Pattern.compile(regex); return Arrays.asList(pattern.split(input)); } StringRegexSplit(); StringRegexSplit(final String regex); @Override List<String> apply(final String input); String getRegex(); void setRegex(final String regex); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringRegexSplit function = new StringRegexSplit(); final List<String> result = function.apply(null); assertNull(result); } @Test public void shouldSplitString() { final StringRegexSplit function = new StringRegexSplit(","); final String input = "first,second,third"; final List<String> result = function.apply(input); assertThat(result, hasItems("first", "second", "third")); }
FirstValid extends KorypheFunction<Iterable<I_ITEM>, I_ITEM> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Predicate getPredicate() { return predicate; } FirstValid(); FirstValid(final Predicate predicate); @Override I_ITEM apply(final Iterable<I_ITEM> iterable); FirstValid<I_ITEM> predicate(final Predicate predicate); FirstValid<I_ITEM> setPredicate(final Predicate predicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate getPredicate(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final FirstValid predicate = getInstance(); final String json = JsonSerialiser.serialise(predicate); JsonSerialiser.assertEquals("{" + "\"class\":\"uk.gov.gchq.koryphe.impl.function.FirstValid\"," + "\"predicate\":{\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsMoreThan\",\"orEqualTo\":false,\"value\":1}" + "}", json); final FirstValid deserialised = JsonSerialiser.deserialise(json, FirstValid.class); assertNotNull(deserialised); assertEquals(1, ((IsMoreThan) deserialised.getPredicate()).getControlValue()); }
ToLong extends KorypheFunction<Object, Long> { @Override public Long apply(final Object value) { if (null == value) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof String) { return Long.valueOf(((String) value)); } throw new IllegalArgumentException("Could not convert value to Long: " + value); } @Override Long apply(final Object value); }
@Test public void shouldConvertToLong() { final ToLong function = new ToLong(); Object output = function.apply(5); assertEquals(5L, output); assertEquals(Long.class, output.getClass()); } @Test public void shouldReturnNullWhenValueIsNull() { final ToLong function = new ToLong(); final Object output = function.apply(null); assertNull(output); }
ToTuple extends KorypheFunction<Object, Tuple<?>> { @Override public Tuple<?> apply(final Object value) { if (isNull(value)) { return null; } if (value instanceof Tuple) { return (Tuple<?>) value; } if (value instanceof Map) { return new MapTuple<>(((Map<?, Object>) value)); } if (value instanceof Object[]) { return new ArrayTuple(((Object[]) value)); } if (value.getClass().isArray()) { if (value instanceof int[]) { return new ArrayTuple(ArrayUtils.toObject((int[]) value)); } if (value instanceof double[]) { return new ArrayTuple(ArrayUtils.toObject((double[]) value)); } if (value instanceof long[]) { return new ArrayTuple(ArrayUtils.toObject((long[]) value)); } if (value instanceof float[]) { return new ArrayTuple(ArrayUtils.toObject((float[]) value)); } if (value instanceof short[]) { return new ArrayTuple(ArrayUtils.toObject((short[]) value)); } if (value instanceof boolean[]) { return new ArrayTuple(ArrayUtils.toObject((boolean[]) value)); } if (value instanceof byte[]) { return new ArrayTuple(ArrayUtils.toObject((byte[]) value)); } if (value instanceof char[]) { return new ArrayTuple(ArrayUtils.toObject((char[]) value)); } } if (value instanceof Iterable) { return new ArrayTuple((Iterable) value); } return new ReflectiveTuple(value); } @Override Tuple<?> apply(final Object value); }
@Test public void shouldConvertListIntoArrayTuple() { final ToTuple function = new ToTuple(); Tuple output = function.apply(Lists.newArrayList(1, 2, 3, 4)); assertEquals(new ArrayTuple(1, 2, 3, 4), output); } @Test public void shouldConvertPrimitiveArrayIntoArrayTuple() { final ToTuple function = new ToTuple(); Tuple output = function.apply(new int[]{1, 2, 3, 4}); assertEquals(new ArrayTuple(1, 2, 3, 4), output); } @Test public void shouldConvertArrayIntoArrayTuple() { final ToTuple function = new ToTuple(); Tuple output = function.apply(new Integer[]{1, 2, 3, 4}); assertEquals(new ArrayTuple(1, 2, 3, 4), output); } @Test public void shouldConvertMapIntoMapTuple() { final ToTuple function = new ToTuple(); Map<String, Object> input = new HashMap<>(); input.put("A", 1); input.put("B", 2); input.put("C", 3); Tuple output = function.apply(input); assertEquals(new MapTuple<>(input), output); } @Test public void shouldConvertObjectIntoReflectiveTuple() { final ToTuple function = new ToTuple(); Object input = new SimpleObj("value1"); Tuple output = function.apply(input); assertEquals(new ReflectiveTuple(input), output); }
NthItem extends KorypheFunction<Iterable<T>, T> { public int getSelection() { return selection; } NthItem(); NthItem(final int selection); @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") T apply(final Iterable<T> input); void setSelection(final int selection); int getSelection(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final NthItem function = new NthItem(2); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.NthItem\",%n" + " \"selection\" : 2%n" + "}"), json); final NthItem deserialised = JsonSerialiser.deserialise(json, NthItem.class); assertNotNull(deserialised); assertEquals(2, deserialised.getSelection()); }
NthItem extends KorypheFunction<Iterable<T>, T> { @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") public T apply(final Iterable<T> input) { if (null == input) { throw new IllegalArgumentException("Input cannot be null"); } try { return Iterables.get(input, selection); } finally { CloseableUtil.close(input); } } NthItem(); NthItem(final int selection); @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") T apply(final Iterable<T> input); void setSelection(final int selection); int getSelection(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnCorrectValueWithInteger() { final NthItem<Integer> function = new NthItem<>(2); final Integer result = function.apply(Arrays.asList(1, 2, 3, 4, 5)); assertNotNull(result); assertEquals(3, result); } @Test public void shouldReturnCorrectValueWithString() { final NthItem<String> function = new NthItem<>(1); final String result = function.apply(Arrays.asList("these", "are", "test", "strings")); assertNotNull(result); assertEquals("are", result); } @Test public void shouldReturnNullForNullElement() { final NthItem<Integer> function = new NthItem<>(1); final Integer result = function.apply(Arrays.asList(1, null, 3)); assertNull(result); } @Test public void shouldThrowExceptionForNullInput() { final NthItem<Integer> function = new NthItem<>(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(null)); assertEquals("Input cannot be null", exception.getMessage()); }
LastItem extends KorypheFunction<Iterable<T>, T> { @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") public T apply(final Iterable<T> input) { if (null == input) { throw new IllegalArgumentException("Input cannot be null"); } try { return Iterables.getLast(input, null); } finally { CloseableUtil.close(input); } } @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") T apply(final Iterable<T> input); }
@Test public void shouldReturnCorrectValueWithInteger() { final LastItem<Integer> function = new LastItem<>(); final Integer result = function.apply(Arrays.asList(2, 3, 5, 7, 11)); assertNotNull(result); assertEquals(new Integer(11), result); } @Test public void shouldReturnCorrectValueWithString() { final LastItem<String> function = new LastItem<>(); final String result = function.apply(Arrays.asList("these", "are", "test", "strings")); assertNotNull(result); assertEquals("strings", result); } @Test public void shouldReturnNullForNullElement() { final LastItem<Integer> function = new LastItem<>(); final Integer result = function.apply(Arrays.asList(1, 2, null)); assertNull(result); } @Test public void shouldThrowExceptionForNullInput() { final LastItem<Integer> function = new LastItem<>(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(null)); assertEquals("Input cannot be null", exception.getMessage()); }
Divide extends KorypheFunction2<Integer, Integer, Tuple2<Integer, Integer>> { @Override public Tuple2<Integer, Integer> apply(final Integer input1, final Integer input2) { int in2 = input2 == null ? 1 : input2; if (input1 == null) { return null; } else { return new Tuple2<>(input1 / in2, input1 % in2); } } @Override Tuple2<Integer, Integer> apply(final Integer input1, final Integer input2); }
@Test public void shouldDivide2() { final Divide function = new Divide(); Tuple2<Integer, Integer> output = function.apply(4, 2); assertEquals(new Tuple2<>(2, 0), output); } @Test public void shouldDivideBy2WithRemainder() { final Divide function = new Divide(); Tuple2<Integer, Integer> output = function.apply(5, 2); assertEquals(new Tuple2<>(2, 1), output); } @Test public void shouldDivide1IfNull() { final Divide function = new Divide(); Tuple2<Integer, Integer> output = function.apply(9, null); assertEquals(new Tuple2<>(9, 0), output); }
DictionaryLookup extends KorypheFunction<K, V> { @Override public V apply(final K key) { if (dictionary == null) { throw new IllegalArgumentException("The " + DictionaryLookup.class.getName() + " KorypheFunction has not been provided with a dictionary"); } return dictionary.get(key); } DictionaryLookup(); DictionaryLookup(final Map<K, V> dictionary); @Override V apply(final K key); Map<K, V> getDictionary(); void setDictionary(final Map<K, V> dictionary); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnExistingValueInDictionary() { assertEquals(1, (int) dictionaryLookUp.apply("one")); assertEquals(2, (int) dictionaryLookUp.apply("two")); } @Test public void shouldReturnNullIfNullKeyIsSupplied() { assertNull(dictionaryLookUp.apply(null)); } @Test public void shouldReturnNullIfItemDoesntExistInDictionary() { assertNull(dictionaryLookUp.apply("three")); } @Test public void shouldThrowExceptionIfDictionaryIsSetToNull() { final Exception exception = assertThrows(IllegalArgumentException.class, () -> new DictionaryLookup<>().apply("four")); final String expected = "The uk.gov.gchq.koryphe.impl.function.DictionaryLookup KorypheFunction has not been provided with a dictionary"; assertEquals(expected, exception.getMessage()); }
CsvLinesToMaps extends KorypheFunction<Iterable<String>, Iterable<Map<String, Object>>> implements Serializable { @Override public Iterable<Map<String, Object>> apply(final Iterable<String> csvStrings) { if (isNull(csvStrings)) { return null; } final CloseableIterable<String> csvRecords = IterableUtil.limit(csvStrings, firstRow, null, false); return IterableUtil.map(csvRecords, (item) -> createMap((String) item)); } @Override Iterable<Map<String, Object>> apply(final Iterable<String> csvStrings); List<String> getHeader(); void setHeader(final List<String> header); int getFirstRow(); void setFirstRow(final int firstRow); CsvLinesToMaps firstRow(final int firstRow); CsvLinesToMaps header(final String... header); CsvLinesToMaps header(final Collection<String> header); char getDelimiter(); void setDelimiter(final char delimiter); CsvLinesToMaps delimiter(final char delimiter); boolean isQuoted(); void setQuoted(final boolean quoted); CsvLinesToMaps quoted(); CsvLinesToMaps quoted(final boolean quoted); char getQuoteChar(); void setQuoteChar(final char quoteChar); CsvLinesToMaps quoteChar(final char quoteChar); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnNullForNullInput() { final CsvLinesToMaps function = new CsvLinesToMaps(); final List<String> input = null; final Object result = function.apply(input); assertNull(result); }
Gunzip extends KorypheFunction<byte[], byte[]> { @SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS", justification = "Returning null means the input was null") @Override public byte[] apply(final byte[] compressed) { if (isNull(compressed)) { return null; } if (compressed.length == 0) { return new byte[0]; } try (final GZIPInputStream gzipStream = new GZIPInputStream(new ByteArrayInputStream(compressed))) { return IOUtils.toByteArray(gzipStream); } catch (final IOException e) { throw new RuntimeException("Failed to decompress provided gzipped string", e); } } @SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS", justification = "Returning null means the input was null") @Override byte[] apply(final byte[] compressed); }
@Test public void shouldUncompressString() throws IOException { final Gunzip function = new Gunzip(); final byte[] input = "test string".getBytes(); final byte[] gzip; try (final ByteArrayOutputStream out = new ByteArrayOutputStream(); final GZIPOutputStream gzipOut = new GZIPOutputStream(out)) { gzipOut.write(input); gzipOut.flush(); gzipOut.close(); gzip = out.toByteArray(); } final byte[] result = function.apply(gzip); assertArrayEquals(input, result); } @Test public void shouldReturnNullForNullInput() { final Gunzip function = new Gunzip(); final byte[] result = function.apply(null); assertNull(result); }
Length extends KorypheFunction<Object, Integer> implements InputValidator { @Override public Integer apply(final Object value) { final int length; if (null == value) { length = 0; } else if (value instanceof String) { length = ((String) value).length(); } else if (value instanceof Object[]) { length = ((Object[]) value).length; } else if (value instanceof Iterable) { if (null != maxLength) { length = Iterables.size(IterableUtil.limit((Iterable) value, 0, maxLength, true)); } else { length = Iterables.size((Iterable) value); } } else if (value instanceof Map) { length = ((Map) value).size(); } else { throw new IllegalArgumentException("Could not determine the size of the provided value"); } if (null == maxLength) { return length; } return Math.min(length, maxLength); } Length(); Length(final Integer maxLength); @Override Integer apply(final Object value); @Override ValidationResult isInputValid(final Class<?>... arguments); Integer getMaxLength(); void setMaxLength(final Integer maxLength); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnZeroForNullInputValue() { final Length function = new Length(); final Integer result = function.apply(null); assertEquals(new Integer(0), result); } @Test public void shouldReturnLengthForStringInput() { final Length function = new Length(); final String input = "testString"; final Integer result = function.apply(input); assertEquals(new Integer(10), result); } @Test public void shouldReturnLengthForObjectArrayInput() { final Length function = new Length(); final Object[] input = new Object[5]; final Integer result = function.apply(input); assertEquals(new Integer(5), result); } @Test public void shouldReturnLengthForListInput() { final Length function = new Length(); final List<Object> input = new ArrayList<>(); input.add(3); input.add(7.2); input.add("test"); input.add("string"); final Integer result = function.apply(input); assertEquals(new Integer(4), result); } @Test public void shouldReturnLengthForSetInput() { final Length function = new Length(); final Set<Object> input = new HashSet<>(); input.add(2.718); input.add(3.142); input.add("constants"); final Integer result = function.apply(input); assertEquals(new Integer(3), result); } @Test public void shouldReturnLengthForMapInput() { final Length function = new Length(); final Map<String, String> input = new HashMap<>(); input.put("one", "two"); input.put("three", "four"); input.put("five", "six"); input.put("seven", "eight"); final Integer result = function.apply(input); assertEquals(new Integer(4), result); } @Test public void shouldThrowExceptionForIncompatibleInputType() { final Length function = new Length(); final Concat input = new Concat(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(input)); assertEquals("Could not determine the size of the provided value", exception.getMessage()); }
Length extends KorypheFunction<Object, Integer> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". One (1) argument is required."); return result; } if (!String.class.isAssignableFrom(arguments[0]) && !Object[].class.isAssignableFrom(arguments[0]) && !Iterable.class.isAssignableFrom(arguments[0]) && !Map.class.isAssignableFrom(arguments[0])) { result.addError("Input class " + arguments[0].getName() + " must be one of the following: " + String.class.getName() + ", " + Object[].class.getName() + ", " + Iterable.class.getName() + ", " + Map.class.getName()); } return result; } Length(); Length(final Integer maxLength); @Override Integer apply(final Object value); @Override ValidationResult isInputValid(final Class<?>... arguments); Integer getMaxLength(); void setMaxLength(final Integer maxLength); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldCheckInputClass() { final Length function = new Length(); assertTrue(function.isInputValid(String.class).isValid()); assertTrue(function.isInputValid(Object[].class).isValid()); assertTrue(function.isInputValid(Integer[].class).isValid()); assertTrue(function.isInputValid(Collection.class).isValid()); assertTrue(function.isInputValid(List.class).isValid()); assertTrue(function.isInputValid(Map.class).isValid()); assertTrue(function.isInputValid(HashMap.class).isValid()); assertFalse(function.isInputValid(String.class, HashMap.class).isValid()); assertFalse(function.isInputValid(Double.class).isValid()); assertFalse(function.isInputValid(Integer.class, Integer.class).isValid()); }
DeserialiseJson extends KorypheFunction<String, T> implements Serializable { public DeserialiseJson<T> outputClass(final Class<T> outputClass) { setOutputClass(outputClass); return this; } DeserialiseJson(); DeserialiseJson(final Class<T> outputClass); @Override T apply(final String json); Class<T> getOutputClass(); DeserialiseJson<T> outputClass(final Class<T> outputClass); void setOutputClass(final Class<T> outputClass); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final DeserialiseJson function = new DeserialiseJson().outputClass(Map.class); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.DeserialiseJson\",%n" + " \"outputClass\" : \"java.util.Map\"" + "}"), json); }
DeserialiseJson extends KorypheFunction<String, T> implements Serializable { @Override public T apply(final String json) { if (isNull(json)) { return null; } try { return MAPPER.readValue(json, outputClass); } catch (final IOException e) { throw new RuntimeException("Failed to deserialise JSON", e); } } DeserialiseJson(); DeserialiseJson(final Class<T> outputClass); @Override T apply(final String json); Class<T> getOutputClass(); DeserialiseJson<T> outputClass(final Class<T> outputClass); void setOutputClass(final Class<T> outputClass); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldParseJson() { final DeserialiseJson function = new DeserialiseJson(); final String input = "{\"elements\": [{\"value\": \"value1\"}, {\"value\": \"value2\"}]}"; Object result = function.apply(input); Map<String, Object> element2aMap = new HashMap<>(); element2aMap.put("value", "value1"); Map<String, Object> element2bMap = new HashMap<>(); element2bMap.put("value", "value2"); HashMap<Object, Object> expectedRootMap = new HashMap<>(); expectedRootMap.put("elements", Arrays.asList(element2aMap, element2bMap)); assertEquals(expectedRootMap, result); } @Test public void shouldReturnNullForNullInput() { final DeserialiseJson function = new DeserialiseJson(); Object result = function.apply(null); assertNull(result); }