src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
WaynameFeatureFilter { @Nullable Point findPointFromCurrentPoint(@Nullable Point currentPoint, @NonNull LineString lineString) { List<Point> lineStringCoordinates = lineString.coordinates(); int coordinateSize = lineStringCoordinates.size(); if (coordinateSize < TWO_POINTS) { return null; } Point lastLinePoint = lineStringCoordinates.get(coordinateSize - 1); if (currentPoint == null || currentPoint.equals(lastLinePoint)) { return null; } LineString sliceFromCurrentPoint = lineSlice(currentPoint, lastLinePoint, lineString); LineString meterSlice = lineSliceAlong(sliceFromCurrentPoint, ZERO_METERS, (double) 10, UNIT_METRES); List<Point> slicePoints = meterSlice.coordinates(); if (slicePoints.isEmpty()) { return null; } return slicePoints.get(FIRST); } WaynameFeatureFilter( @NonNull List<Feature> queriedFeatures, @NonNull Location currentLocation, @NonNull List<Point> currentStepPoints); }
@Test public void findPointFromCurrentPoint() { Feature featureOne = Feature.fromJson(loadJsonFixture("feature_one.json")); Point currentPoint = Point.fromLngLat(1.234, 4.567); WaynameFeatureFilter waynameFeatureFilter = buildFilter(); Point featureAheadOfUser = waynameFeatureFilter.findPointFromCurrentPoint(currentPoint, (LineString) featureOne.geometry()); }
LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { @Override public void onCameraIdle() { if (!isEnabled) { return; } updateMaxFps(); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }
@Test public void onCameraIdle_newFpsIsSetZoom16() { double zoom = 16d; MapboxMap mapboxMap = mock(MapboxMap.class); when(mapboxMap.getCameraPosition()).thenReturn(buildCameraPosition(zoom)); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onCameraIdle(); verify(locationComponent).setMaxAnimationFps(eq(25)); } @Test public void onCameraIdle_newFpsIsSetZoom14() { double zoom = 14d; MapboxMap mapboxMap = mock(MapboxMap.class); when(mapboxMap.getCameraPosition()).thenReturn(buildCameraPosition(zoom)); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onCameraIdle(); verify(locationComponent).setMaxAnimationFps(eq(15)); } @Test public void onCameraIdle_newFpsIsSetZoom10() { double zoom = 10d; MapboxMap mapboxMap = mock(MapboxMap.class); when(mapboxMap.getCameraPosition()).thenReturn(buildCameraPosition(zoom)); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onCameraIdle(); verify(locationComponent).setMaxAnimationFps(eq(10)); } @Test public void onCameraIdle_newFpsIsSet5() { double zoom = 5d; MapboxMap mapboxMap = mock(MapboxMap.class); when(mapboxMap.getCameraPosition()).thenReturn(buildCameraPosition(zoom)); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onCameraIdle(); verify(locationComponent).setMaxAnimationFps(eq(5)); }
LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { void onStart() { mapboxMap.addOnCameraIdleListener(this); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }
@Test public void onStart_idleListenerAdded() { MapboxMap mapboxMap = mock(MapboxMap.class); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onStart(); verify(mapboxMap, times(2)).addOnCameraIdleListener(eq(locationFpsDelegate)); }
LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { void onStop() { mapboxMap.removeOnCameraIdleListener(this); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }
@Test public void onStop_idleListenerRemoved() { MapboxMap mapboxMap = mock(MapboxMap.class); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onStop(); verify(mapboxMap).removeOnCameraIdleListener(eq(locationFpsDelegate)); }
LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { void updateEnabled(boolean isEnabled) { this.isEnabled = isEnabled; resetMaxFps(); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }
@Test public void updateEnabled_falseResetsToMax() { MapboxMap mapboxMap = mock(MapboxMap.class); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.updateEnabled(false); verify(locationComponent).setMaxAnimationFps(eq(Integer.MAX_VALUE)); }
MapWayName { void updateWayNameWithPoint(PointF point) { if (!isAutoQueryEnabled) { return; } List<Feature> roadLabelFeatures = findRoadLabelFeatures(point); boolean invalidLabelFeatures = roadLabelFeatures.isEmpty(); if (invalidLabelFeatures) { return; } executeFeatureFilterTask(roadLabelFeatures); } MapWayName(WaynameFeatureFinder featureInteractor, @NonNull MapPaddingAdjustor paddingAdjustor); }
@Test public void onFeatureWithoutNamePropertyReturned_updateIsIgnored() { PointF point = mock(PointF.class); SymbolLayer waynameLayer = mock(SymbolLayer.class); List<Feature> roads = new ArrayList<>(); Feature road = mock(Feature.class); roads.add(road); MapWayName mapWayName = buildMapWayname(point, roads); mapWayName.updateWayNameWithPoint(point); verify(waynameLayer, times(0)).setProperties(any(PropertyValue.class)); }
NavigationViewSubscriber implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void unsubscribe() { navigationViewModel.retrieveRoute().removeObservers(lifecycleOwner); navigationViewModel.retrieveDestination().removeObservers(lifecycleOwner); navigationViewModel.retrieveNavigationLocation().removeObservers(lifecycleOwner); navigationViewModel.retrieveShouldRecordScreenshot().removeObservers(lifecycleOwner); navigationViewModel.retrieveIsFeedbackSentSuccess().removeObservers(lifecycleOwner); } NavigationViewSubscriber(final LifecycleOwner owner, final NavigationViewModel navigationViewModel, final NavigationPresenter navigationPresenter); }
@Test public void checkObserversAreRemovedWhenUnsubscribe() { when(navigationViewModel.retrieveRoute()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveNavigationLocation()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveDestination()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveShouldRecordScreenshot()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveIsFeedbackSentSuccess()).thenReturn(mock(MutableLiveData.class)); theNavigationViewSubscriber.unsubscribe(); verify(navigationViewModel.retrieveRoute()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveNavigationLocation()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveDestination()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveShouldRecordScreenshot()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveIsFeedbackSentSuccess()).removeObservers(eq(lifecycleOwner)); }
NavigationViewSubscriber implements LifecycleObserver { void subscribe() { navigationViewModel.retrieveRoute().observe(lifecycleOwner, directionsRoute -> { if (directionsRoute != null) { navigationPresenter.onRouteUpdate(directionsRoute); } }); navigationViewModel.retrieveDestination().observe(lifecycleOwner, point -> { if (point != null) { navigationPresenter.onDestinationUpdate(point); } }); navigationViewModel.retrieveNavigationLocation().observe(lifecycleOwner, location -> { if (location != null) { navigationPresenter.onNavigationLocationUpdate(location); } }); navigationViewModel.retrieveShouldRecordScreenshot().observe(lifecycleOwner, shouldRecordScreenshot -> { if (shouldRecordScreenshot != null && shouldRecordScreenshot) { navigationPresenter.onShouldRecordScreenshot(); } }); navigationViewModel.retrieveIsFeedbackSentSuccess().observe(lifecycleOwner, isFeedbackSentSuccess -> { if (isFeedbackSentSuccess != null && isFeedbackSentSuccess) { navigationPresenter.onFeedbackSent(); } }); } NavigationViewSubscriber(final LifecycleOwner owner, final NavigationViewModel navigationViewModel, final NavigationPresenter navigationPresenter); }
@Test public void checkObserversAreAddedWhenSubscribe() { when(navigationViewModel.retrieveRoute()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveNavigationLocation()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveDestination()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveShouldRecordScreenshot()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveIsFeedbackSentSuccess()).thenReturn(mock(MutableLiveData.class)); theNavigationViewSubscriber.subscribe(); verify(navigationViewModel.retrieveRoute()).observe(eq(lifecycleOwner), any(Observer.class)); verify(navigationViewModel.retrieveNavigationLocation()).observe(eq(lifecycleOwner), any(Observer.class)); verify(navigationViewModel.retrieveDestination()).observe(eq(lifecycleOwner), any(Observer.class)); verify(navigationViewModel.retrieveShouldRecordScreenshot()).observe(eq(lifecycleOwner), any(Observer.class)); verify(navigationViewModel.retrieveIsFeedbackSentSuccess()).observe(eq(lifecycleOwner), any(Observer.class)); }
NavigationOnCameraTrackingChangedListener implements OnCameraTrackingChangedListener { @Override public void onCameraTrackingDismissed() { if (summaryBehavior.getState() != BottomSheetBehavior.STATE_HIDDEN) { navigationPresenter.onCameraTrackingDismissed(); } } NavigationOnCameraTrackingChangedListener(NavigationPresenter navigationPresenter, BottomSheetBehavior summaryBehavior); @Override void onCameraTrackingDismissed(); @Override void onCameraTrackingChanged(int currentMode); }
@Test public void onCameraTrackingDismissed_presenterNotifiedWithVisibleBottomsheet() { NavigationPresenter presenter = mock(NavigationPresenter.class); BottomSheetBehavior behavior = mock(BottomSheetBehavior.class); when(behavior.getState()).thenReturn(BottomSheetBehavior.STATE_EXPANDED); NavigationOnCameraTrackingChangedListener listener = new NavigationOnCameraTrackingChangedListener( presenter, behavior ); listener.onCameraTrackingDismissed(); verify(presenter).onCameraTrackingDismissed(); } @Test public void onCameraTrackingDismissed_ignoredWithHiddenBottomsheet() { NavigationPresenter presenter = mock(NavigationPresenter.class); BottomSheetBehavior behavior = mock(BottomSheetBehavior.class); when(behavior.getState()).thenReturn(BottomSheetBehavior.STATE_HIDDEN); NavigationOnCameraTrackingChangedListener listener = new NavigationOnCameraTrackingChangedListener( presenter, behavior ); listener.onCameraTrackingDismissed(); verify(presenter, times(0)).onCameraTrackingDismissed(); }
AbbreviationCreator extends NodeCreator<AbbreviationCreator.AbbreviationNode, AbbreviationVerifier> { @Override void preProcess(@NonNull TextView textView, @NonNull List<BannerComponentNode> bannerComponentNodes) { String text = abbreviateBannerText(textView, bannerComponentNodes); textView.setText(text); } AbbreviationCreator(AbbreviationVerifier abbreviationVerifier, HashMap abbreviations, TextViewUtils textViewUtils); AbbreviationCreator(AbbreviationVerifier abbreviationVerifier); AbbreviationCreator(); }
@Test public void preProcess_abbreviate() { String abbreviation = "smtxt"; BannerComponents bannerComponents = BannerComponentsFaker.bannerComponentsBuilder() .abbreviation(abbreviation) .abbreviationPriority(0) .build(); TextView textView = mock(TextView.class); AbbreviationVerifier abbreviationVerifier = mock(AbbreviationVerifier.class); when(abbreviationVerifier.isNodeType(bannerComponents)).thenReturn(true); TextViewUtils textViewUtils = mock(TextViewUtils.class); when(textViewUtils.textFits(textView, abbreviation)).thenReturn(true); when(textViewUtils.textFits(textView, bannerComponents.text())).thenReturn(false); BannerComponentNode node = mock(AbbreviationCreator.AbbreviationNode.class); when(((AbbreviationCreator.AbbreviationNode) node).getAbbreviate()).thenReturn(true); when(node.toString()).thenReturn(abbreviation); AbbreviationCreator abbreviationCreator = new AbbreviationCreator(abbreviationVerifier); abbreviationCreator.preProcess(textView, Collections.singletonList(node)); verify(textView).setText(abbreviation); }
AbbreviationCreator extends NodeCreator<AbbreviationCreator.AbbreviationNode, AbbreviationVerifier> { @NonNull @Override AbbreviationNode setupNode(@NonNull BannerComponents components, int index, int startIndex, String modifier) { addPriorityInfo(components, index); return new AbbreviationNode(components, startIndex); } AbbreviationCreator(AbbreviationVerifier abbreviationVerifier, HashMap abbreviations, TextViewUtils textViewUtils); AbbreviationCreator(AbbreviationVerifier abbreviationVerifier); AbbreviationCreator(); }
@Test public void setupNode() { String abbreviation = "smtxt"; int abbreviationPriority = 0; BannerComponents bannerComponents = BannerComponentsFaker.bannerComponentsBuilder() .abbreviation(abbreviation) .abbreviationPriority(abbreviationPriority) .build(); AbbreviationVerifier abbreviationVerifier = mock(AbbreviationVerifier.class); when(abbreviationVerifier.isNodeType(bannerComponents)).thenReturn(true); HashMap<Integer, List<Integer>> abbreviations = new HashMap(); AbbreviationCreator abbreviationCreator = new AbbreviationCreator(abbreviationVerifier, abbreviations, mock(TextViewUtils.class)); List<BannerComponentNode> bannerComponentNodes = new ArrayList<>(); bannerComponentNodes.add(new AbbreviationCreator.AbbreviationNode(bannerComponents, 0)); abbreviationCreator.setupNode(bannerComponents, 0, 0, ""); assertEquals(abbreviations.size(), 1); assertEquals(abbreviations.get(abbreviationPriority).get(0), Integer.valueOf(0)); }
NavigationPresenter { void onRouteOverviewClick() { view.setWayNameActive(false); view.setWayNameVisibility(false); view.updateCameraRouteOverview(); view.showRecenterBtn(); } NavigationPresenter(NavigationContract.View view); }
@Test public void onRouteOverviewButtonClick_cameraIsAdjustedToRoute() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteOverviewClick(); verify(view).updateCameraRouteOverview(); } @Test public void onRouteOverviewButtonClick_recenterBtnIsShown() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteOverviewClick(); verify(view).showRecenterBtn(); } @Test public void onRouteOverviewButtonClick_mapWaynameIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteOverviewClick(); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); }
BannerComponentTree { void loadInstruction(TextView textView) { for (NodeCreator nodeCreator : nodeCreators) { nodeCreator.preProcess(textView, bannerComponentNodes); } for (NodeCreator nodeCreator : nodeCreators) { nodeCreator.postProcess(textView, bannerComponentNodes); } } BannerComponentTree(@NonNull BannerText bannerText, NodeCreator... nodeCreators); }
@Test public void loadInstruction() { BannerComponents bannerComponents = BannerComponentsFaker.bannerComponents(); List<BannerComponents> bannerComponentsList = Collections.singletonList(bannerComponents); TestNode testNode = mock(TestNode.class); TestCreator testCreator = mock(TestCreator.class); when(testCreator.isNodeType(bannerComponents)).thenReturn(true); when(testCreator.setupNode(bannerComponents, 0, 0, null)).thenReturn(testNode); TextView textView = mock(TextView.class); BannerText bannerText = mock(BannerText.class); when(bannerText.components()).thenReturn(bannerComponentsList); BannerComponentTree bannerComponentTree = new BannerComponentTree(bannerText, testCreator); bannerComponentTree.loadInstruction(textView); InOrder inOrder = inOrder(testCreator, testCreator); inOrder.verify(testCreator).preProcess(any(TextView.class), any(List.class)); inOrder.verify(testCreator).postProcess(any(TextView.class), any(List.class)); }
NavigationPresenter { void onRecenterClick() { view.setSummaryBehaviorHideable(false); view.setSummaryBehaviorState(BottomSheetBehavior.STATE_EXPANDED); view.setWayNameActive(true); if (!TextUtils.isEmpty(view.retrieveWayNameText())) { view.setWayNameVisibility(true); } view.resetCameraPosition(); view.hideRecenterBtn(); } NavigationPresenter(NavigationContract.View view); }
@Test public void onRecenterBtnClick_recenterBtnIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRecenterClick(); verify(view).hideRecenterBtn(); } @Test public void onRecenterBtnClick_cameraIsResetToTracking() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRecenterClick(); verify(view).resetCameraPosition(); } @Test public void onRecenterBtnClick_mapWayNameIsShown() { NavigationContract.View view = mock(NavigationContract.View.class); when(view.retrieveWayNameText()).thenReturn("Some way name"); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRecenterClick(); verify(view).setWayNameActive(true); verify(view).setWayNameVisibility(true); }
NavigationPresenter { void onWayNameChanged(@NonNull String wayName) { if (TextUtils.isEmpty(wayName) || view.isSummaryBottomSheetHidden()) { view.setWayNameActive(false); view.setWayNameVisibility(false); return; } view.updateWayNameView(wayName); view.setWayNameActive(true); view.setWayNameVisibility(true); } NavigationPresenter(NavigationContract.View view); }
@Test public void onWayNameChanged_mapWayNameIsShown() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged("Some way name"); verify(view).setWayNameActive(true); verify(view).setWayNameVisibility(true); } @Test public void onWayNameChanged_mapWayNameIsUpdated() { String someWayName = "Some way name"; NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged(someWayName); verify(view).updateWayNameView(someWayName); } @Test public void onWayNameChanged_mapWayNameIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged(""); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); } @Test public void onWayNameChanged_mapWayNameIsHiddenWithCollapsedBottomsheet() { NavigationContract.View view = mock(NavigationContract.View.class); when(view.isSummaryBottomSheetHidden()).thenReturn(true); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged("some valid way name"); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); }
NavigationPresenter { void onNavigationStopped() { view.setWayNameActive(false); view.setWayNameVisibility(false); } NavigationPresenter(NavigationContract.View view); }
@Test public void onNavigationStopped_mapWayNameIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onNavigationStopped(); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); }
NavigationPresenter { void onRouteUpdate(DirectionsRoute directionsRoute) { view.drawRoute(directionsRoute); if (resumeState && view.isRecenterButtonVisible()) { view.updateCameraRouteOverview(); } else { view.startCamera(directionsRoute); } } NavigationPresenter(NavigationContract.View view); }
@Test public void onRouteUpdate_routeIsDrawn() { DirectionsRoute directionsRoute = mock(DirectionsRoute.class); NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteUpdate(directionsRoute); verify(view).drawRoute(directionsRoute); } @Test public void onRouteUpdate_cameraIsStartedOnFirstRoute() { DirectionsRoute directionsRoute = mock(DirectionsRoute.class); NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteUpdate(directionsRoute); verify(view).startCamera(directionsRoute); }
MapRouteClickListener implements MapboxMap.OnMapClickListener { @Override public boolean onMapClick(@NonNull LatLng point) { if (!isRouteVisible()) { return false; } Map<LineString, DirectionsRoute> routeLineStrings = routeLine.retrieveRouteLineStrings(); if (invalidMapClick(routeLineStrings)) { return false; } List<DirectionsRoute> directionsRoutes = routeLine.retrieveDirectionsRoutes(); findClickedRoute(point, routeLineStrings, directionsRoutes); return false; } MapRouteClickListener(MapRouteLine routeLine); @Override boolean onMapClick(@NonNull LatLng point); }
@Test public void checksOnRouteSelectionChangeListenerIsCalledWhenClickedRouteIsFound() { DirectionsRoute anyRoute = buildMockDirectionsRoute(); List<DirectionsRoute> anyDirectionsRoutes = buildDirectionsRoutes(anyRoute); LineString anyRouteGeometry = LineString.fromPolyline(anyRoute.geometry(), Constants.PRECISION_6); HashMap<LineString, DirectionsRoute> anyLineStringDirectionsRouteMap = buildLineStringDirectionsRouteHashMap(anyRoute, anyRouteGeometry); MapRouteLine mockedMapRouteLine = buildMockMapRouteLine(true, anyLineStringDirectionsRouteMap); when(mockedMapRouteLine.retrieveDirectionsRoutes()).thenReturn(anyDirectionsRoutes); MapRouteClickListener theMapRouteClickListener = new MapRouteClickListener(mockedMapRouteLine); OnRouteSelectionChangeListener mockedOnRouteSelectionChangeListener = buildMockOnRouteSelectionChangeListener(theMapRouteClickListener); LatLng mockedPoint = mock(LatLng.class); theMapRouteClickListener.onMapClick(mockedPoint); verify(mockedOnRouteSelectionChangeListener).onNewPrimaryRouteSelected(any(DirectionsRoute.class)); } @Test public void updatesPrimaryRouteIndexWhenClickedRouteIsFound() { DirectionsRoute anyRoute = buildMockDirectionsRoute(); List<DirectionsRoute> anyDirectionsRoutes = buildDirectionsRoutes(anyRoute); LineString anyRouteGeometry = LineString.fromPolyline(anyRoute.geometry(), Constants.PRECISION_6); HashMap<LineString, DirectionsRoute> anyLineStringDirectionsRouteMap = buildLineStringDirectionsRouteHashMap(anyRoute, anyRouteGeometry); MapRouteLine mockedMapRouteLine = buildMockMapRouteLine(true, anyLineStringDirectionsRouteMap); when(mockedMapRouteLine.retrieveDirectionsRoutes()).thenReturn(anyDirectionsRoutes); MapRouteClickListener theMapRouteClickListener = new MapRouteClickListener(mockedMapRouteLine); buildMockOnRouteSelectionChangeListener(theMapRouteClickListener); LatLng mockedPoint = mock(LatLng.class); theMapRouteClickListener.onMapClick(mockedPoint); verify(mockedMapRouteLine).updatePrimaryRouteIndex(anyRoute); } @Test public void checksOnRouteSelectionChangeListenerIsNotCalledWhenRouteIsNotVisible() { HashMap<LineString, DirectionsRoute> mockedLineStringDirectionsRouteMap = mock(HashMap.class); MapRouteLine mockedMapRouteLine = buildMockMapRouteLine(false, mockedLineStringDirectionsRouteMap); MapRouteClickListener theMapRouteClickListener = new MapRouteClickListener(mockedMapRouteLine); OnRouteSelectionChangeListener mockedOnRouteSelectionChangeListener = buildMockOnRouteSelectionChangeListener(theMapRouteClickListener); LatLng mockedPoint = mock(LatLng.class); theMapRouteClickListener.onMapClick(mockedPoint); verify(mockedOnRouteSelectionChangeListener, never()).onNewPrimaryRouteSelected(any(DirectionsRoute.class)); }
AlertViewAnimatorListener implements Animator.AnimatorListener { @Override public void onAnimationEnd(Animator animation) { hideAlertView(); } AlertViewAnimatorListener(AlertView alertView); @Override void onAnimationStart(Animator animation); @Override void onAnimationEnd(Animator animation); @Override void onAnimationCancel(Animator animation); @Override void onAnimationRepeat(Animator animation); }
@Test public void onAnimationEnd_alertViewIsHidden() { AlertView alertView = mock(AlertView.class); AlertViewAnimatorListener listener = new AlertViewAnimatorListener(alertView); listener.onAnimationEnd(mock(Animator.class)); verify(alertView).hide(); }
DynamicCamera extends SimpleCamera { @Override public double zoom(@NonNull RouteInformation routeInformation) { if (isShutdown) { return DEFAULT_ZOOM; } if (validLocationAndProgress(routeInformation) && shouldUpdateZoom(routeInformation)) { return createZoom(routeInformation); } else if (routeInformation.getRoute() != null) { return super.zoom(routeInformation); } return mapboxMap.getCameraPosition().zoom; } DynamicCamera(@NonNull MapboxMap mapboxMap); @Override double tilt(@NonNull RouteInformation routeInformation); @Override double zoom(@NonNull RouteInformation routeInformation); void forceResetZoomLevel(); void clearMap(); }
@Test public void onInformationFromRoute_engineCreatesCorrectZoom() throws Exception { DynamicCamera cameraEngine = buildDynamicCamera(); RouteInformation routeInformation = new RouteInformation(buildDirectionsRoute(), null, null); double zoom = cameraEngine.zoom(routeInformation); assertEquals(15d, zoom, 0.1); } @Test public void onCameraPositionNull_engineReturnsDefaultZoom() throws Exception { DynamicCamera theCameraEngine = buildDynamicCamera(); RouteInformation anyRouteInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(1000d)); double defaultZoom = theCameraEngine.zoom(anyRouteInformation); assertEquals(15d, defaultZoom, 0.1); } @Test public void onCameraPositionZoomGreaterThanMax_engineReturnsMaxCameraZoom() throws Exception { MapboxMap mapboxMap = mock(MapboxMap.class); CameraPosition cameraPositionWithZoomGreaterThanMax = new CameraPosition.Builder() .zoom(20d) .build(); when(mapboxMap.getCameraForLatLngBounds(any(LatLngBounds.class), any(int[].class))).thenReturn(cameraPositionWithZoomGreaterThanMax); DynamicCamera theCameraEngine = new DynamicCamera(mapboxMap); RouteInformation anyRouteInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(1000d)); double maxCameraZoom = theCameraEngine.zoom(anyRouteInformation); assertEquals(16d, maxCameraZoom, 0.1); } @Test public void onCameraPositionZoomLessThanMin_engineReturnsMinCameraZoom() throws Exception { MapboxMap mapboxMap = mock(MapboxMap.class); CameraPosition cameraPositionWithZoomLessThanMin = new CameraPosition.Builder() .zoom(10d) .build(); when(mapboxMap.getCameraForLatLngBounds(any(LatLngBounds.class), any(int[].class))).thenReturn(cameraPositionWithZoomLessThanMin); DynamicCamera theCameraEngine = new DynamicCamera(mapboxMap); RouteInformation anyRouteInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(1000d)); double maxCameraZoom = theCameraEngine.zoom(anyRouteInformation); assertEquals(12d, maxCameraZoom, 0.1); } @Test public void onCameraPositionZoomGreaterThanMinAndLessThanMax_engineReturnsCameraPositionZoom() throws Exception { MapboxMap mapboxMap = mock(MapboxMap.class); CameraPosition cameraPositionWithZoomGreaterThanMinAndLessThanMax = new CameraPosition.Builder() .zoom(14d) .build(); when(mapboxMap.getCameraForLatLngBounds(any(LatLngBounds.class), any(int[].class))).thenReturn(cameraPositionWithZoomGreaterThanMinAndLessThanMax); DynamicCamera theCameraEngine = new DynamicCamera(mapboxMap); RouteInformation anyRouteInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(1000d)); double maxCameraZoom = theCameraEngine.zoom(anyRouteInformation); assertEquals(14d, maxCameraZoom, 0.1); }
DynamicCamera extends SimpleCamera { @Override public double tilt(@NonNull RouteInformation routeInformation) { if (isShutdown) { return DEFAULT_TILT; } RouteProgress progress = routeInformation.getRouteProgress(); if (progress != null) { double distanceRemaining = progress.getCurrentLegProgress().getCurrentStepProgress().getDistanceRemaining(); return createTilt(distanceRemaining); } return super.tilt(routeInformation); } DynamicCamera(@NonNull MapboxMap mapboxMap); @Override double tilt(@NonNull RouteInformation routeInformation); @Override double zoom(@NonNull RouteInformation routeInformation); void forceResetZoomLevel(); void clearMap(); }
@Test public void onInformationFromRoute_engineCreatesCorrectTilt() throws Exception { DynamicCamera cameraEngine = buildDynamicCamera(); RouteInformation routeInformation = new RouteInformation(buildDirectionsRoute(), null, null); double tilt = cameraEngine.tilt(routeInformation); assertEquals(50d, tilt, 0.1); } @Test public void onHighDistanceRemaining_engineCreatesCorrectTilt() throws Exception { DynamicCamera cameraEngine = buildDynamicCamera(); RouteInformation routeInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(1000d)); double tilt = cameraEngine.tilt(routeInformation); assertEquals(60d, tilt, 0.1); } @Test public void onMediumDistanceRemaining_engineCreatesCorrectTilt() throws Exception { DynamicCamera cameraEngine = buildDynamicCamera(); RouteInformation routeInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(200d)); double tilt = cameraEngine.tilt(routeInformation); assertEquals(45d, tilt, 0.1); } @Test public void onLowDistanceRemaining_engineCreatesCorrectTilt() throws Exception { DynamicCamera cameraEngine = buildDynamicCamera(); RouteInformation routeInformation = new RouteInformation(null, buildDefaultLocationUpdate(-77.0339782574523, 38.89993519985637), buildDefaultRouteProgress(null)); double tilt = cameraEngine.tilt(routeInformation); assertEquals(45d, tilt, 0.1); }
NavigationCameraTrackingChangedListener implements OnCameraTrackingChangedListener { @Override public void onCameraTrackingDismissed() { camera.updateCameraTrackingMode(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE); } NavigationCameraTrackingChangedListener(NavigationCamera camera); @Override void onCameraTrackingDismissed(); @Override void onCameraTrackingChanged(int currentMode); }
@Test public void onCameraTrackingDismissed_cameraSetToTrackingNone() { NavigationCamera camera = mock(NavigationCamera.class); NavigationCameraTrackingChangedListener listener = new NavigationCameraTrackingChangedListener(camera); listener.onCameraTrackingDismissed(); verify(camera).updateCameraTrackingMode(eq(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE)); }
NavigationCameraTrackingChangedListener implements OnCameraTrackingChangedListener { @Override public void onCameraTrackingChanged(int currentMode) { Integer trackingMode = camera.findTrackingModeFor(currentMode); if (trackingMode != null) { camera.updateCameraTrackingMode(trackingMode); } } NavigationCameraTrackingChangedListener(NavigationCamera camera); @Override void onCameraTrackingDismissed(); @Override void onCameraTrackingChanged(int currentMode); }
@Test public void onCameraTrackingChanged_navigationCameraTrackingUpdated() { NavigationCamera camera = mock(NavigationCamera.class); when(camera.findTrackingModeFor(CameraMode.TRACKING_GPS)).thenReturn(NavigationCamera.NAVIGATION_TRACKING_MODE_GPS); NavigationCameraTrackingChangedListener listener = new NavigationCameraTrackingChangedListener(camera); listener.onCameraTrackingChanged(CameraMode.TRACKING_GPS); verify(camera).updateCameraTrackingMode(eq(NavigationCamera.NAVIGATION_TRACKING_MODE_GPS)); }
NavigationCameraTransitionListener implements OnLocationCameraTransitionListener { @Override public void onLocationCameraTransitionFinished(int cameraMode) { camera.updateTransitionListenersFinished(cameraMode); } NavigationCameraTransitionListener(NavigationCamera camera); @Override void onLocationCameraTransitionFinished(int cameraMode); @Override void onLocationCameraTransitionCanceled(int cameraMode); }
@Test public void onLocationCameraTransitionFinished() { NavigationCamera camera = mock(NavigationCamera.class); NavigationCameraTransitionListener listener = new NavigationCameraTransitionListener(camera); int trackingGps = CameraMode.TRACKING_GPS; listener.onLocationCameraTransitionFinished(trackingGps); verify(camera).updateTransitionListenersFinished(trackingGps); }
NavigationCameraTransitionListener implements OnLocationCameraTransitionListener { @Override public void onLocationCameraTransitionCanceled(int cameraMode) { camera.updateTransitionListenersCancelled(cameraMode); camera.updateIsResetting(false); } NavigationCameraTransitionListener(NavigationCamera camera); @Override void onLocationCameraTransitionFinished(int cameraMode); @Override void onLocationCameraTransitionCanceled(int cameraMode); }
@Test public void onLocationCameraTransitionCanceled() { NavigationCamera camera = mock(NavigationCamera.class); NavigationCameraTransitionListener listener = new NavigationCameraTransitionListener(camera); int trackingGpsNorth = CameraMode.TRACKING_GPS_NORTH; listener.onLocationCameraTransitionCanceled(trackingGpsNorth); verify(camera).updateTransitionListenersCancelled(trackingGpsNorth); } @Test public void onLocationCameraTransitionCanceled_cameraStopsResetting() { NavigationCamera camera = mock(NavigationCamera.class); NavigationCameraTransitionListener listener = new NavigationCameraTransitionListener(camera); int trackingGpsNorth = CameraMode.TRACKING_GPS_NORTH; listener.onLocationCameraTransitionCanceled(trackingGpsNorth); verify(camera).updateIsResetting(eq(false)); }
ResetCancelableCallback implements MapboxMap.CancelableCallback { @Override public void onFinish() { camera.updateIsResetting(false); } ResetCancelableCallback(NavigationCamera camera); @Override void onCancel(); @Override void onFinish(); }
@Test public void onFinish_dynamicCameraIsReset() { NavigationCamera camera = mock(NavigationCamera.class); ResetCancelableCallback callback = new ResetCancelableCallback(camera); callback.onFinish(); verify(camera).updateIsResetting(eq(false)); }
ResetCancelableCallback implements MapboxMap.CancelableCallback { @Override public void onCancel() { camera.updateIsResetting(false); } ResetCancelableCallback(NavigationCamera camera); @Override void onCancel(); @Override void onFinish(); }
@Test public void onCancel_dynamicCameraIsReset() { NavigationCamera camera = mock(NavigationCamera.class); ResetCancelableCallback callback = new ResetCancelableCallback(camera); callback.onCancel(); verify(camera).updateIsResetting(eq(false)); }
InstructionListPresenter { void update(@NonNull RouteProgress routeProgress, @NonNull InstructionListAdapter adapter) { drivingSide = getDrivingSide(routeProgress); final List<BannerInstructions> routeInstructions = getBannerInstructionsFromRouteProgress(routeProgress); final List<BannerInstructions> filteredRouteInstructions = filterListAfterStep(routeProgress, routeInstructions); final List<BannerInstructions> oldItems = new ArrayList<>(instructions); final DiffUtil.DiffResult result = DiffUtil.calculateDiff(getDiffCallback(oldItems, filteredRouteInstructions)); instructions.clear(); instructions.addAll(filteredRouteInstructions); result.dispatchUpdatesTo(adapter); } InstructionListPresenter(DistanceFormatter distanceFormatter); }
@Test public void update_notifyItemRangeInserted() throws Exception { RouteProgress routeProgress = buildRouteProgress(); InstructionListAdapter adapter = mock(InstructionListAdapter.class); DistanceFormatter distanceFormatter = mock(DistanceFormatter.class); InstructionListPresenter presenter = new InstructionListPresenter(distanceFormatter); presenter.update(routeProgress, adapter); verify(adapter).notifyItemRangeInserted(0, 12); } @Test public void update_notifyItemRangeRemoved() throws Exception { RouteProgress initialRouteProgress = buildRouteProgress(); RouteProgress updatedRouteProgress = buildRouteProgressWithProgress(); InstructionListAdapter adapter = mock(InstructionListAdapter.class); DistanceFormatter distanceFormatter = mock(DistanceFormatter.class); InstructionListPresenter presenter = new InstructionListPresenter(distanceFormatter); presenter.update(initialRouteProgress, adapter); presenter.update(updatedRouteProgress, adapter); verify(adapter).notifyItemRangeRemoved(0, 3); }
InstructionListPresenter { @Nullable BannerInstructions findCurrentBannerInstructions(@Nullable LegStep currentStep, double stepDistanceRemaining) { if (currentStep == null) { return null; } List<BannerInstructions> instructions = currentStep.bannerInstructions(); if (instructions != null && !instructions.isEmpty()) { List<BannerInstructions> sortedInstructions = sortBannerInstructions(instructions); for (BannerInstructions bannerInstructions : sortedInstructions) { int distanceAlongGeometry = (int) bannerInstructions.distanceAlongGeometry(); if (distanceAlongGeometry >= (int) stepDistanceRemaining) { return bannerInstructions; } } return instructions.get(FIRST_INSTRUCTION_INDEX); } else { return null; } } InstructionListPresenter(DistanceFormatter distanceFormatter); }
@Test public void findCurrentBannerInstructions_returnsNullWithNullCurrentStep() throws Exception { LegStep currentStep = null; double stepDistanceRemaining = 0; SpannableString spannableString = mock(SpannableString.class); InstructionListPresenter presenter = buildPresenter(spannableString); BannerInstructions currentBannerInstructions = presenter.findCurrentBannerInstructions( currentStep, stepDistanceRemaining ); assertNull(currentBannerInstructions); } @Test public void findCurrentBannerInstructions_returnsNullWithCurrentStepEmptyInstructions() throws Exception { SpannableString spannableString = mock(SpannableString.class); RouteProgress routeProgress = buildRouteProgress(); InstructionListPresenter presenter = buildPresenter(spannableString); LegStep currentStep = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getStep(); double stepDistanceRemaining = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getDistanceRemaining(); List<BannerInstructions> currentInstructions = currentStep.bannerInstructions(); currentInstructions.clear(); BannerInstructions currentBannerInstructions = presenter.findCurrentBannerInstructions( currentStep, stepDistanceRemaining ); assertNull(currentBannerInstructions); } @Test public void findCurrentBannerInstructions_returnsCorrectCurrentInstruction() throws Exception { SpannableString spannableString = mock(SpannableString.class); RouteProgress routeProgress = buildRouteProgress(); InstructionListPresenter presenter = buildPresenter(spannableString); LegStep currentStep = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getStep(); double stepDistanceRemaining = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getDistanceRemaining(); BannerInstructions currentBannerInstructions = presenter.findCurrentBannerInstructions( currentStep, stepDistanceRemaining ); assertEquals(currentStep.bannerInstructions().get(0), currentBannerInstructions); } @Test public void findCurrentBannerInstructions_adjustedDistanceRemainingReturnsCorrectInstruction() throws Exception { SpannableString spannableString = mock(SpannableString.class); RouteProgress routeProgress = buildRouteProgress(); InstructionListPresenter presenter = buildPresenter(spannableString); LegStep currentStep = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getStep(); double stepDistanceRemaining = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getDistanceRemaining(); BannerInstructions currentBannerInstructions = presenter.findCurrentBannerInstructions( currentStep, stepDistanceRemaining ); assertEquals(currentStep.bannerInstructions().get(0), currentBannerInstructions); } @Test public void findCurrentBannerInstructions_adjustedDistanceRemainingRemovesCorrectInstructions() throws Exception { SpannableString spannableString = mock(SpannableString.class); RouteProgress routeProgress = buildRouteProgress(); InstructionListPresenter presenter = buildPresenter(spannableString); LegStep currentStep = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getStep(); double stepDistanceRemaining = routeProgress.getCurrentLegProgress().getCurrentStepProgress().getDistanceRemaining(); BannerInstructions currentBannerInstructions = presenter.findCurrentBannerInstructions( currentStep, stepDistanceRemaining ); assertEquals(currentStep.bannerInstructions().get(0), currentBannerInstructions); }
NavigationViewModelProgressObserver implements RouteProgressObserver, LocationObserver { @Override public void onRouteProgressChanged(@NotNull RouteProgress routeProgress) { viewModel.updateRouteProgress(routeProgress); } NavigationViewModelProgressObserver(NavigationViewModel viewModel); @Override void onRawLocationChanged(@NotNull Location rawLocation); @Override void onEnhancedLocationChanged( @NotNull Location enhancedLocation, @NotNull List<? extends Location> keyPoints ); @Override void onRouteProgressChanged(@NotNull RouteProgress routeProgress); }
@Test public void checksNavigationViewModelRouteProgressIsUpdatedWhenOnProgressChange() { NavigationViewModel mockedNavigationViewModel = mock(NavigationViewModel.class); NavigationViewModelProgressObserver theNavigationViewModelProgressObserver = new NavigationViewModelProgressObserver(mockedNavigationViewModel); RouteProgress theRouteProgress = mock(RouteProgress.class); theNavigationViewModelProgressObserver.onRouteProgressChanged(theRouteProgress); verify(mockedNavigationViewModel).updateRouteProgress(eq(theRouteProgress)); }
NavigationViewModelProgressObserver implements RouteProgressObserver, LocationObserver { @Override public void onEnhancedLocationChanged( @NotNull Location enhancedLocation, @NotNull List<? extends Location> keyPoints ) { viewModel.updateLocation(enhancedLocation); } NavigationViewModelProgressObserver(NavigationViewModel viewModel); @Override void onRawLocationChanged(@NotNull Location rawLocation); @Override void onEnhancedLocationChanged( @NotNull Location enhancedLocation, @NotNull List<? extends Location> keyPoints ); @Override void onRouteProgressChanged(@NotNull RouteProgress routeProgress); }
@Test @SuppressWarnings("unchecked assignment") public void checksNavigationViewModelLocationIsUpdatedWhenOnProgressChange() { NavigationViewModel mockedNavigationViewModel = mock(NavigationViewModel.class); NavigationViewModelProgressObserver theNavigationViewModelProgressChangeListener = new NavigationViewModelProgressObserver(mockedNavigationViewModel); Location theLocation = mock(Location.class); List<? extends Location> keyPoints = mock(List.class); theNavigationViewModelProgressChangeListener.onEnhancedLocationChanged(theLocation, keyPoints); verify(mockedNavigationViewModel).updateLocation(eq(theLocation)); }
NavigationViewEventDispatcher { void initializeListeners( @NonNull NavigationViewOptions navigationViewOptions, @NonNull NavigationViewModel navigationViewModel ) { assignFeedbackListener(navigationViewOptions.feedbackListener()); assignNavigationListener(navigationViewOptions.navigationListener(), navigationViewModel); assignBottomSheetCallback(navigationViewOptions.bottomSheetCallback()); assignInstructionListListener(navigationViewOptions.instructionListListener()); assignSpeechAnnouncementListener(navigationViewOptions.speechAnnouncementListener()); assignBannerInstructionsListener(navigationViewOptions.bannerInstructionsListener()); navigation = navigationViewModel.retrieveNavigation(); if (navigation != null) { assignRouteProgressChangeObserver(navigationViewOptions, navigation); assignLocationObserver(navigationViewOptions, navigation); assignArrivalObserver(navigationViewOptions, navigation); } } }
@Test public void onRouteProgressObserverAddedInOptions_isAddedToNavigation() { NavigationViewEventDispatcher eventDispatcher = new NavigationViewEventDispatcher(); NavigationViewOptions options = mock(NavigationViewOptions.class); RouteProgressObserver routeProgressObserver = setupRouteProgressObserver(options); NavigationViewModel navigationViewModel = mock(NavigationViewModel.class); MapboxNavigation navigation = mock(MapboxNavigation.class); when(navigationViewModel.retrieveNavigation()).thenReturn(navigation); eventDispatcher.initializeListeners(options, navigationViewModel); verify(navigation, times(1)).registerRouteProgressObserver(routeProgressObserver); }
NavigationViewEventDispatcher { VoiceInstructions onAnnouncement(VoiceInstructions announcement) { if (speechAnnouncementListener != null) { return speechAnnouncementListener.willVoice(announcement); } return announcement; } }
@Test public void onNewVoiceAnnouncement_instructionListenerIsCalled() { VoiceInstructions originalAnnouncement = mock(VoiceInstructions.class); SpeechAnnouncementListener speechAnnouncementListener = mock(SpeechAnnouncementListener.class); VoiceInstructions newAnnouncement = VoiceInstructions.builder() .announcement("New announcement").build(); when(speechAnnouncementListener.willVoice(originalAnnouncement)).thenReturn(newAnnouncement); NavigationViewEventDispatcher eventDispatcher = buildDispatcher(speechAnnouncementListener); eventDispatcher.onAnnouncement(originalAnnouncement); verify(speechAnnouncementListener).willVoice(originalAnnouncement); } @Test public void onNewVoiceAnnouncement_announcementToBeVoicedIsReturned() { VoiceInstructions originalAnnouncement = VoiceInstructions.builder().announcement("announcement").build(); SpeechAnnouncementListener speechAnnouncementListener = mock(SpeechAnnouncementListener.class); VoiceInstructions newAnnouncement = VoiceInstructions.builder() .announcement("New announcement").build(); when(speechAnnouncementListener.willVoice(originalAnnouncement)).thenReturn(newAnnouncement); NavigationViewEventDispatcher eventDispatcher = buildDispatcher(speechAnnouncementListener); VoiceInstructions modifiedAnnouncement = eventDispatcher.onAnnouncement(originalAnnouncement); assertEquals("New announcement", modifiedAnnouncement.announcement()); } @Test public void onNewVoiceAnnouncement_ssmlAnnouncementToBeVoicedIsReturned() { VoiceInstructions originalAnnouncement = VoiceInstructions.builder().announcement("announcement").build(); SpeechAnnouncementListener speechAnnouncementListener = mock(SpeechAnnouncementListener.class); VoiceInstructions newAnnouncement = VoiceInstructions.builder() .announcement("New announcement") .ssmlAnnouncement("New SSML announcement").build(); when(speechAnnouncementListener.willVoice(originalAnnouncement)).thenReturn(newAnnouncement); NavigationViewEventDispatcher eventDispatcher = buildDispatcher(speechAnnouncementListener); VoiceInstructions modifiedAnnouncement = eventDispatcher.onAnnouncement(originalAnnouncement); assertEquals("New SSML announcement", modifiedAnnouncement.ssmlAnnouncement()); }
InstructionCacheCallback implements Callback<ResponseBody> { @Override public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) { if (closeResponseBody(response)) { String url = call.request().url().toString(); loader.addCachedUrl(url); } } InstructionCacheCallback(VoiceInstructionLoader loader); @Override void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response); @Override void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable); }
@Test public void onResponse_cachedUrlIsAdded() { VoiceInstructionLoader loader = mock(VoiceInstructionLoader.class); Response<ResponseBody> response = mock(Response.class); ResponseBody body = mock(ResponseBody.class); when(response.body()).thenReturn(body); String url = "http: Call call = buildMockCall(url); InstructionCacheCallback callback = new InstructionCacheCallback(loader); callback.onResponse(call, response); verify(loader).addCachedUrl(eq(url)); } @Test public void onResponse_bodyIsClosed() { VoiceInstructionLoader loader = mock(VoiceInstructionLoader.class); Response<ResponseBody> response = mock(Response.class); ResponseBody body = mock(ResponseBody.class); when(response.body()).thenReturn(body); String url = "http: Call call = buildMockCall(url); InstructionCacheCallback callback = new InstructionCacheCallback(loader); callback.onResponse(call, response); verify(body).close(); } @Test public void onResponse_nullBodyIsIgnored() { VoiceInstructionLoader loader = mock(VoiceInstructionLoader.class); Response<ResponseBody> response = mock(Response.class); String url = "http: Call call = buildMockCall(url); InstructionCacheCallback callback = new InstructionCacheCallback(loader); callback.onResponse(call, response); verifyZeroInteractions(loader); }
NavigationSpeechPlayer implements SpeechPlayer { @Override public void play(VoiceInstructions voiceInstructions) { voiceInstructionsQueue.offer(voiceInstructions); SpeechPlayer player = speechPlayerProvider.retrieveSpeechPlayer(); if (player != null) { player.play(voiceInstructionsQueue.poll()); } } NavigationSpeechPlayer(SpeechPlayerProvider speechPlayerProvider); @Override void play(VoiceInstructions voiceInstructions); @Override boolean isMuted(); @Override void setMuted(boolean isMuted); @Override void onOffRoute(); @Override void onDestroy(); }
@Test public void onPlayAnnouncement_mapboxSpeechPlayerIsGivenAnnouncement() { MapboxSpeechPlayer speechPlayer = mock(MapboxSpeechPlayer.class); NavigationSpeechPlayer navigationSpeechPlayer = buildNavigationSpeechPlayer(speechPlayer); VoiceInstructions announcement = mock(VoiceInstructions.class); navigationSpeechPlayer.play(announcement); verify(speechPlayer).play(announcement); } @Test public void onPlayAnnouncement_androidSpeechPlayerIsGivenAnnouncement() { AndroidSpeechPlayer speechPlayer = mock(AndroidSpeechPlayer.class); NavigationSpeechPlayer navigationSpeechPlayer = buildNavigationSpeechPlayer(speechPlayer); VoiceInstructions announcement = mock(VoiceInstructions.class); navigationSpeechPlayer.play(announcement); verify(speechPlayer).play(announcement); }
NavigationSpeechPlayer implements SpeechPlayer { @Override public void setMuted(boolean isMuted) { this.isMuted = isMuted; voiceInstructionsQueue.clear(); speechPlayerProvider.setMuted(isMuted); } NavigationSpeechPlayer(SpeechPlayerProvider speechPlayerProvider); @Override void play(VoiceInstructions voiceInstructions); @Override boolean isMuted(); @Override void setMuted(boolean isMuted); @Override void onOffRoute(); @Override void onDestroy(); }
@Test public void onSetMuted_providerIsSetMuted() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); NavigationSpeechPlayer navigationSpeechPlayer = new NavigationSpeechPlayer(provider); navigationSpeechPlayer.setMuted(true); verify(provider).setMuted(true); }
NavigationSpeechPlayer implements SpeechPlayer { @Override public void onOffRoute() { voiceInstructionsQueue.clear(); speechPlayerProvider.onOffRoute(); } NavigationSpeechPlayer(SpeechPlayerProvider speechPlayerProvider); @Override void play(VoiceInstructions voiceInstructions); @Override boolean isMuted(); @Override void setMuted(boolean isMuted); @Override void onOffRoute(); @Override void onDestroy(); }
@Test public void onOffRoute_providerOnOffRouteIsCalled() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); NavigationSpeechPlayer navigationSpeechPlayer = new NavigationSpeechPlayer(provider); navigationSpeechPlayer.onOffRoute(); verify(provider).onOffRoute(); } @Test public void onDestroy_providerOnDestroyIsCalled() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); NavigationSpeechPlayer navigationSpeechPlayer = new NavigationSpeechPlayer(provider); navigationSpeechPlayer.onOffRoute(); verify(provider).onOffRoute(); }
NavigationVoiceListener implements VoiceListener { @Override public void onStart(@NonNull SpeechPlayerState state) { speechPlayerProvider.onSpeechPlayerStateChanged(state); audioFocusManager.requestAudioFocus(); } NavigationVoiceListener(SpeechPlayerProvider speechPlayerProvider, SpeechAudioFocusManager audioFocusManager); @Override void onStart(@NonNull SpeechPlayerState state); @Override void onDone(@NonNull SpeechPlayerState state); @Override void onError(String errorText, VoiceInstructions voiceInstructions); }
@Test public void onStart_audioFocusIsRequested() { SpeechAudioFocusManager audioFocusManager = mock(SpeechAudioFocusManager.class); NavigationVoiceListener navigationSpeechListener = buildSpeechListener(audioFocusManager); navigationSpeechListener.onStart(SpeechPlayerState.ONLINE_PLAYING); verify(audioFocusManager).requestAudioFocus(); } @Test public void onStart_speechPlayerStateChanged() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); NavigationVoiceListener navigationSpeechListener = buildSpeechListener(provider); SpeechPlayerState speechPlayerState = mock(SpeechPlayerState.class); navigationSpeechListener.onStart(speechPlayerState); verify(provider).onSpeechPlayerStateChanged(speechPlayerState); }
NavigationVoiceListener implements VoiceListener { @Override public void onDone(@NonNull SpeechPlayerState state) { speechPlayerProvider.onSpeechPlayerStateChanged(state); if (state == SpeechPlayerState.IDLE) { audioFocusManager.abandonAudioFocus(); } } NavigationVoiceListener(SpeechPlayerProvider speechPlayerProvider, SpeechAudioFocusManager audioFocusManager); @Override void onStart(@NonNull SpeechPlayerState state); @Override void onDone(@NonNull SpeechPlayerState state); @Override void onError(String errorText, VoiceInstructions voiceInstructions); }
@Test public void onDone_audioFocusIsAbandoned() { SpeechAudioFocusManager audioFocusManager = mock(SpeechAudioFocusManager.class); NavigationVoiceListener navigationSpeechListener = buildSpeechListener(audioFocusManager); navigationSpeechListener.onDone(SpeechPlayerState.IDLE); verify(audioFocusManager).abandonAudioFocus(); } @Test public void onDone_speechPlayerStateChangedToIdle() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); NavigationVoiceListener navigationSpeechListener = buildSpeechListener(provider); navigationSpeechListener.onDone(SpeechPlayerState.IDLE); verify(provider).onSpeechPlayerStateChanged(SpeechPlayerState.IDLE); navigationSpeechListener.onDone(SpeechPlayerState.OFFLINE_PLAYER_INITIALIZED); verify(provider).onSpeechPlayerStateChanged(SpeechPlayerState.IDLE); }
NavigationVoiceListener implements VoiceListener { @Override public void onError(String errorText, VoiceInstructions voiceInstructions) { Timber.e(errorText); speechPlayerProvider.onSpeechPlayerStateChanged(SpeechPlayerState.IDLE); speechPlayerProvider.retrieveAndroidSpeechPlayer().play(voiceInstructions); } NavigationVoiceListener(SpeechPlayerProvider speechPlayerProvider, SpeechAudioFocusManager audioFocusManager); @Override void onStart(@NonNull SpeechPlayerState state); @Override void onDone(@NonNull SpeechPlayerState state); @Override void onError(String errorText, VoiceInstructions voiceInstructions); }
@Test public void onError_fallbackGoesToAndroidSpeechPlayer() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); AndroidSpeechPlayer androidSpeechPlayer = mock(AndroidSpeechPlayer.class); when(provider.retrieveAndroidSpeechPlayer()).thenReturn(androidSpeechPlayer); NavigationVoiceListener navigationSpeechListener = buildSpeechListener(provider); VoiceInstructions announcement = buildAnnouncement(); navigationSpeechListener.onError("Error text", announcement); verify(androidSpeechPlayer).play(announcement); } @Test public void onError_speechPlayerStateChangedToIdle() { SpeechPlayerProvider provider = mock(SpeechPlayerProvider.class); AndroidSpeechPlayer androidSpeechPlayer = mock(AndroidSpeechPlayer.class); when(provider.retrieveAndroidSpeechPlayer()).thenReturn(androidSpeechPlayer); NavigationVoiceListener navigationSpeechListener = buildSpeechListener(provider); VoiceInstructions announcement = buildAnnouncement(); navigationSpeechListener.onError(anyString(), announcement); verify(provider).onSpeechPlayerStateChanged(SpeechPlayerState.IDLE); }
SpeechPlayerProvider { @Nullable SpeechPlayer retrieveSpeechPlayer() { if (speechPlayerState == SpeechPlayerState.OFFLINE_PLAYING) { return null; } if (voiceInstructionLoader.hasCache() || connectivityStatus.isConnectedFast() || (connectivityStatus.isConnected() && !isFallbackAlwaysEnabled)) { speechPlayerState = SpeechPlayerState.ONLINE_PLAYING; return speechPlayers.get(FIRST_PLAYER); } else if (speechPlayerState == SpeechPlayerState.IDLE) { speechPlayerState = SpeechPlayerState.OFFLINE_PLAYING; return androidSpeechPlayer; } else { return null; } } SpeechPlayerProvider(@NonNull Context context, String language, boolean voiceLanguageSupported, @NonNull VoiceInstructionLoader voiceInstructionLoader); SpeechPlayerProvider(@NonNull Context context, String language, boolean voiceLanguageSupported, @NonNull VoiceInstructionLoader voiceInstructionLoader, ConnectivityStatusProvider connectivityStatus); void setIsFallbackAlwaysEnabled(boolean isFallbackAlwaysEnabled); }
@Test public void voiceLanguageSupported_returnsMapboxSpeechPlayer() { boolean voiceLanguageSupported = true; SpeechPlayerProvider provider = buildSpeechPlayerProvider(voiceLanguageSupported); SpeechPlayer speechPlayer = provider.retrieveSpeechPlayer(); assertTrue(speechPlayer instanceof MapboxSpeechPlayer); } @Test public void voiceLanguageNotSupported_returnsAndroidSpeechPlayer() { boolean voiceLanguageNotSupported = false; SpeechPlayerProvider provider = buildSpeechPlayerProvider(voiceLanguageNotSupported); SpeechPlayer speechPlayer = provider.retrieveSpeechPlayer(); assertTrue(speechPlayer instanceof AndroidSpeechPlayer); } @Test public void hasCache_alwaysReturnsMapboxSpeechPlayer() { Context context = mock(Context.class); String language = Locale.US.getLanguage(); VoiceInstructionLoader voiceInstructionLoader = mock(VoiceInstructionLoader.class); when(voiceInstructionLoader.hasCache()).thenReturn(true); ConnectivityStatusProvider connectivityStatus = mock(ConnectivityStatusProvider.class); SpeechPlayerProvider provider = new SpeechPlayerProvider(context, language, true, voiceInstructionLoader, connectivityStatus); SpeechPlayer speechPlayer = provider.retrieveSpeechPlayer(); assertTrue(speechPlayer instanceof MapboxSpeechPlayer); } @Test public void offlinePlayerInitializingNoCacheNoConnectivity_returnNullSpeechPlayer() { Context context = mock(Context.class); String language = Locale.US.getLanguage(); VoiceInstructionLoader voiceInstructionLoader = mock(VoiceInstructionLoader.class); ConnectivityStatusProvider connectivityStatus = mock(ConnectivityStatusProvider.class); when(connectivityStatus.isConnectedFast()).thenReturn(false); SpeechPlayerProvider provider = new SpeechPlayerProvider(context, language, true, voiceInstructionLoader, connectivityStatus); SpeechPlayer speechPlayer = provider.retrieveSpeechPlayer(); assertNull(speechPlayer); }
SpeechPlayerProvider { AndroidSpeechPlayer retrieveAndroidSpeechPlayer() { return androidSpeechPlayer; } SpeechPlayerProvider(@NonNull Context context, String language, boolean voiceLanguageSupported, @NonNull VoiceInstructionLoader voiceInstructionLoader); SpeechPlayerProvider(@NonNull Context context, String language, boolean voiceLanguageSupported, @NonNull VoiceInstructionLoader voiceInstructionLoader, ConnectivityStatusProvider connectivityStatus); void setIsFallbackAlwaysEnabled(boolean isFallbackAlwaysEnabled); }
@Test public void retrieveAndroidSpeechPlayer_alwaysReturnsAndroidSpeechPlayer() { SpeechPlayerProvider provider = buildSpeechPlayerProvider(true); AndroidSpeechPlayer speechPlayer = provider.retrieveAndroidSpeechPlayer(); assertNotNull(speechPlayer); }
VoiceInstructionLoader { void requestInstruction(@NonNull String instruction, String textType, Callback<ResponseBody> callback) { if (context != null && !cache.isClosed() && mapboxSpeechBuilder != null) { MapboxSpeech mapboxSpeech = mapboxSpeechBuilder .instruction(instruction) .textType(textType) .build(); mapboxSpeech.enqueueCall(callback); } } VoiceInstructionLoader(@NonNull Context context, String accessToken, Cache cache); VoiceInstructionLoader(Context context, String accessToken, Cache cache, MapboxSpeech.Builder mapboxSpeechBuilder, ConnectivityStatusProvider connectivityStatus); @NonNull List<String> evictVoiceInstructions(); void cacheInstructions(@NonNull List<String> instructions); }
@Test public void checksRequestEnqueuedIfCacheIsNotClosedAndMapboxSpeechBuilderIsNotNull() { Cache anyCache = mock(Cache.class); when(anyCache.isClosed()).thenReturn(false); MapboxSpeech.Builder aSpeechBuilder = mock(MapboxSpeech.Builder.class); when(aSpeechBuilder.instruction(anyString())).thenReturn(aSpeechBuilder); when(aSpeechBuilder.textType(anyString())).thenReturn(aSpeechBuilder); MapboxSpeech aSpeech = mock(MapboxSpeech.class); when(aSpeechBuilder.build()).thenReturn(aSpeech); ConnectivityStatusProvider connectivityStatus = mock(ConnectivityStatusProvider.class); Context context = mock(Context.class); VoiceInstructionLoader theVoiceInstructionLoader = new VoiceInstructionLoader(context, "any_access_token", anyCache, aSpeechBuilder, connectivityStatus); Callback aCallback = mock(Callback.class); theVoiceInstructionLoader.requestInstruction("anyInstruction", "anyType", aCallback); verify(aSpeech, times(1)).enqueueCall(eq(aCallback)); } @Test public void checksRequestNotEnqueuedIfCacheIsClosed() { Cache anyCache = mock(Cache.class); when(anyCache.isClosed()).thenReturn(true); MapboxSpeech.Builder anySpeechBuilder = mock(MapboxSpeech.Builder.class); MapboxSpeech aSpeech = mock(MapboxSpeech.class); ConnectivityStatusProvider connectivityStatus = mock(ConnectivityStatusProvider.class); Context context = mock(Context.class); VoiceInstructionLoader theVoiceInstructionLoader = new VoiceInstructionLoader(context, "any_access_token", anyCache, anySpeechBuilder, connectivityStatus); Callback aCallback = mock(Callback.class); theVoiceInstructionLoader.requestInstruction("anyInstruction", "anyType", aCallback); verify(aSpeech, times(0)).enqueueCall(eq(aCallback)); } @Test public void checksRequestNotEnqueuedIfMapboxSpeechBuilderIsNull() { Cache anyCache = mock(Cache.class); when(anyCache.isClosed()).thenReturn(false); MapboxSpeech.Builder nullSpeechBuilder = null; MapboxSpeech aSpeech = mock(MapboxSpeech.class); ConnectivityStatusProvider connectivityStatus = mock(ConnectivityStatusProvider.class); Context context = mock(Context.class); VoiceInstructionLoader theVoiceInstructionLoader = new VoiceInstructionLoader(context, "any_access_token", anyCache, nullSpeechBuilder, connectivityStatus); Callback aCallback = mock(Callback.class); theVoiceInstructionLoader.requestInstruction("anyInstruction", "anyType", aCallback); verify(aSpeech, times(0)).enqueueCall(eq(aCallback)); }
RouteCallStatus { boolean isRouting(@NonNull Date currentDate) { if (responseReceived) { return false; } return diffInMilliseconds(callDate, currentDate) < FIVE_SECONDS_IN_MILLISECONDS; } RouteCallStatus(Date callDate); }
@Test public void isRouting_returnsTrueUnderTwoSeconds() { Date callDate = mock(Date.class); when(callDate.getTime()).thenReturn(0L); Date currentDate = mock(Date.class); when((currentDate.getTime())).thenReturn(1000L); RouteCallStatus callStatus = new RouteCallStatus(callDate); boolean isRouting = callStatus.isRouting(currentDate); assertTrue(isRouting); } @Test public void isRouting_returnsFalseOverFiveSeconds() { Date callDate = mock(Date.class); when(callDate.getTime()).thenReturn(0L); Date currentDate = mock(Date.class); when((currentDate.getTime())).thenReturn(5100L); RouteCallStatus callStatus = new RouteCallStatus(callDate); boolean isRouting = callStatus.isRouting(currentDate); assertFalse(isRouting); }
NavigationViewWayNameListener implements OnWayNameChangedListener { @Override public void onWayNameChanged(@NonNull String wayName) { presenter.onWayNameChanged(wayName); } NavigationViewWayNameListener(NavigationPresenter presenter); @Override void onWayNameChanged(@NonNull String wayName); }
@Test public void onWayNameChanged_presenterReceivesNewWayName() { NavigationPresenter presenter = mock(NavigationPresenter.class); String newWayName = "New way name"; OnWayNameChangedListener listener = new NavigationViewWayNameListener(presenter); listener.onWayNameChanged(newWayName); verify(presenter).onWayNameChanged(newWayName); }
SymbolOnStyleLoadedListener implements MapView.OnDidFinishLoadingStyleListener { @Override public void onDidFinishLoadingStyle() { mapboxMap.getStyle().addImage(MAPBOX_NAVIGATION_MARKER_NAME, markerBitmap); } SymbolOnStyleLoadedListener(MapboxMap mapboxMap, Bitmap markerBitmap); @Override void onDidFinishLoadingStyle(); }
@Test public void onDidFinishLoadingStyle_markerIsAdded() { MapboxMap mapboxMap = mock(MapboxMap.class); Style style = mock(Style.class); when(mapboxMap.getStyle()).thenReturn(style); Bitmap markerBitmap = mock(Bitmap.class); SymbolOnStyleLoadedListener listener = new SymbolOnStyleLoadedListener(mapboxMap, markerBitmap); listener.onDidFinishLoadingStyle(); verify(style).addImage(eq(MAPBOX_NAVIGATION_MARKER_NAME), eq(markerBitmap)); }
MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { void addProgressChangeListener(@NonNull MapboxNavigation navigation) { this.navigation = navigation; navigation.registerRouteProgressObserver(fpsProgressListener); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }
@Test public void addProgressChangeListener_navigationReceivesListener() { MapboxNavigation navigation = mock(MapboxNavigation.class); MapFpsDelegate delegate = new MapFpsDelegate(mock(MapView.class), mock(MapBatteryMonitor.class)); delegate.addProgressChangeListener(navigation); verify(navigation).registerRouteProgressObserver(any(FpsDelegateProgressChangeListener.class)); }
Maybe { public abstract <B> Maybe<B> map(Function<A, B> func); private Maybe(); abstract Maybe<B> map(Function<A, B> func); abstract Maybe<B> bind(Function<A, Maybe<B>> func); abstract Maybe<A> filter(Predicate<A> predicate); abstract A getOrElse(A def); abstract boolean isDefined(); abstract Maybe<C> lift2(BiFunction<A, B, C> func, Maybe<B> maybe); static Just<A> just(A value); static Nothing<A> nothing(); static Maybe<A> fromNullable(A value); static Maybe<List<A>> sequence(List<Maybe<A>> list); }
@Test public void testMap() { Map<String, String> param = new HashMap<>(); param.put("a", "5"); param.put("b", "true"); param.put("c", "-3"); assertEquals(5, readPositiveIntParam(param, "a")); assertEquals(0, readPositiveIntParam(param, "b")); assertEquals(0, readPositiveIntParam(param, "c")); assertEquals(0, readPositiveIntParam(param, "d")); }
CashMachine { public static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted) { return lookup(currencySupply, value) .bind(numUnits -> (unitsWanted < 0 || numUnits - unitsWanted < 0) ? Maybe.<Integer>nothing() : just(numUnits - unitsWanted)); } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testUnitsLeftAfterTakeThreeTwenties() { Maybe<Integer> result = CashMachine.unitsLeft(currencySupply, 20, 3); assert (result.equals(just(2))); } @Test public void testUnitsLeftAfterTakeOneHundred() { Maybe<Integer> result = CashMachine.unitsLeft(currencySupply, 100, 1); assert (result.equals(nothing())); }
CashMachine { public static <A> List<String> listNotes(List<A> amounts, List<String> currencies) { return amounts.bind(amount -> (List<String>) currencies.bind(currency -> List.itemList(currency + amount.toString()))); } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testListMachineNotes() { List<String> currencies = itemList("$AU", "$NZ"); List<String> result = CashMachine.listNotes(itemList(20, 50, 100), currencies); assert (result.equals(itemList("$AU20", "$NZ20", "$AU50", "$NZ50", "$AU100", "$NZ100"))); }
CashMachine { public static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination) { return sequence(combination.foldRight((tuple, acc) -> List.cons(unitsLeft(currencySupply, tuple.first(), tuple.second()), acc), (List<Maybe<Integer>>) List.<Maybe<Integer>>emptyList())); } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testSeventyComboServiceable() { List<Tuple<Integer, Integer>> combination = itemList(tuple(20, 1), tuple(50, 1)); Maybe<List<Integer>> result = CashMachine.checkAmountServiceable(currencySupply, combination); assert (result.equals(just(List.itemList(4, 9)))); } @Test public void testOneHundredAndSeventyComboNotServiceable() { List<Tuple<Integer, Integer>> combination = itemList(tuple(20, 6), tuple(50, 1)); Maybe<List<Integer>> result = CashMachine.checkAmountServiceable(currencySupply, combination); assert (result.equals(nothing())); }
CashMachine { public static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue) { List<Tuple<Integer, Integer>> result = List.emptyList(); for (int i = amount/currencyValue; i >= 0; i--) { result = List.cons(Tuple.tuple(currencyValue, i), result); } return result; } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testCreateValueUnitTuples() { List<Tuple<Integer, Integer>> result = CashMachine.createValueUnitTuplesForValue(100, 50); assert (result.equals(List.itemList(tuple(50, 0), tuple(50, 1), tuple(50, 2)))); }
CashMachine { public static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies) { return List.sequence(machineCurrencies.foldRight((value, acc) -> List.cons(createValueUnitTuplesForValue(amount, value), acc), (List<List<Tuple<Integer, Integer>>>) List.<List<Tuple<Integer, Integer>>>emptyList())); } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testFindAllPossibleCombosForAmount() { List<List<Tuple<Integer, Integer>>> result = CashMachine.findCombinationSearchSpaceForAmount(50, itemList(20, 50)); assert (result.equals(itemList(itemList(tuple(20, 0), tuple(50, 0)), itemList(tuple(20, 0), tuple(50, 1)), itemList(tuple(20, 1), tuple(50, 0)), itemList(tuple(20, 1), tuple(50, 1)), itemList(tuple(20, 2), tuple(50, 0)), itemList(tuple(20, 2), tuple(50, 1))))); }
CashMachine { public static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies) { return findCombinationSearchSpaceForAmount(amount, machineCurrencies).filter(list -> (list.foldRight((tuple, acc) -> acc + (tuple.first() * tuple.second()), 0)).equals(amount)); } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testFindCombosForAmount() { List<List<Tuple<Integer, Integer>>> result = CashMachine.findCombinationsForAmount(100, itemList(20, 50, 100)); assert (result.equals(itemList(itemList(tuple(20, 0), tuple(50, 0), tuple(100, 1)), itemList(tuple(20, 0), tuple(50, 2), tuple(100, 0)), itemList(tuple(20, 5), tuple(50, 0), tuple(100, 0))))); }
CashMachine { public static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply) { List<Integer> machineCurrencies = machineSupply.foldRight((tuple, acc) -> List.cons(tuple.first(), acc), (List<Integer>) List.<Integer>emptyList()); return findCombinationsForAmount(amount, machineCurrencies).filter(combo -> checkAmountServiceable(machineSupply, combo).isDefined()); } static Maybe<V> lookup(List<Tuple<K, V>> tupleList, K key); static Maybe<Integer> unitsLeft(List<Tuple<Integer, Integer>> currencySupply, Integer value, Integer unitsWanted); static List<String> listNotes(List<A> amounts, List<String> currencies); static Maybe<List<Integer>> checkAmountServiceable(List<Tuple<Integer, Integer>> currencySupply, List<Tuple<Integer, Integer>> combination); static List<Tuple<Integer, Integer>> createValueUnitTuplesForValue(Integer amount, Integer currencyValue); static List<List<Tuple<Integer, Integer>>> findCombinationSearchSpaceForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findCombinationsForAmount(Integer amount, List<Integer> machineCurrencies); static List<List<Tuple<Integer, Integer>>> findServiceableCombinations(Integer amount, List<Tuple<Integer, Integer>> machineSupply); }
@Test public void testFindServiceableCombos() { List<List<Tuple<Integer, Integer>>> result = CashMachine.findServiceableCombinations(100, currencySupply); assert (result.equals(itemList(itemList(tuple(20, 0), tuple(50, 2), tuple(100, 0)), itemList(tuple(20, 5), tuple(50, 0), tuple(100, 0))))); }
Maybe { public abstract <B, C> Maybe<C> lift2(BiFunction<A, B, C> func, Maybe<B> maybe); private Maybe(); abstract Maybe<B> map(Function<A, B> func); abstract Maybe<B> bind(Function<A, Maybe<B>> func); abstract Maybe<A> filter(Predicate<A> predicate); abstract A getOrElse(A def); abstract boolean isDefined(); abstract Maybe<C> lift2(BiFunction<A, B, C> func, Maybe<B> maybe); static Just<A> just(A value); static Nothing<A> nothing(); static Maybe<A> fromNullable(A value); static Maybe<List<A>> sequence(List<Maybe<A>> list); }
@Test public void testLift2() { BiFunction<Integer, Integer, Integer> function = (a, b) -> a + b; Maybe<Integer> maybe = just(1); Maybe<Integer> maybe2 = just(2); Maybe<Integer> result = maybe.lift2(function, maybe2); assert (result.equals(just(3))); }
Maybe { public static <A> Maybe<List<A>> sequence(List<Maybe<A>> list) { return list.foldRight((o, a) -> o.lift2(List::cons, a), (Maybe<List<A>>) Maybe.<List<A>>just(List.<A>emptyList())); } private Maybe(); abstract Maybe<B> map(Function<A, B> func); abstract Maybe<B> bind(Function<A, Maybe<B>> func); abstract Maybe<A> filter(Predicate<A> predicate); abstract A getOrElse(A def); abstract boolean isDefined(); abstract Maybe<C> lift2(BiFunction<A, B, C> func, Maybe<B> maybe); static Just<A> just(A value); static Nothing<A> nothing(); static Maybe<A> fromNullable(A value); static Maybe<List<A>> sequence(List<Maybe<A>> list); }
@Test public void testSequence() { List<Maybe<Integer>> list = itemList(fromNullable(1), fromNullable(2), fromNullable(3)); Maybe<List<Integer>> result = Maybe.sequence(list); assert (result.equals(just(itemList(1, 2, 3)))); }
List { public abstract List<A> append(List<A> list); private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testAppend() { List<Integer> list = itemList(1, 2, 3); List<Integer> list2 = itemList(4, 5); List<Integer> result = list.append(list2); assert(result.equals(itemList(1, 2, 3, 4, 5))); }
List { public abstract <B> B foldRight(BiFunction<A, B, B> function, B accumulator); private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testFoldRight() { List<Integer> list = itemList(1, 2, 3); List<Integer> acc = List.emptyList(); List<Integer> result = list.foldRight((integer, accumulator) -> cons(integer + 1, accumulator), acc); assert(result.equals(itemList(2, 3, 4))); }
List { public abstract List<A> filter(Predicate<A> predicate); private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testFilter() { List<Integer> list = itemList(1, 2, 3); List<Integer> result = list.filter(i -> i % 2 == 0); assert(result.equals(itemList(2))); }
List { public abstract <B> List<B> map(Function<A, B> func); private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testMap() { List<Integer> list = itemList(1, 2, 3); List<Integer> result = list.map(i -> i + 1); assert(result.equals(itemList(2, 3, 4))); }
List { public abstract <B> List<B> bind(Function<A, List<B>> func); private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testBind() { List<Integer> list = itemList(1, 2, 3); List<Integer> result = list.bind(integer -> itemList(integer * 2)); assert(result.equals(itemList(2, 4, 6))); }
List { public abstract <B, C> List<C> lift2(BiFunction<A, B, C> function, List<B> list); private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testLift2() { BiFunction<Integer, Integer, Integer> function = (a, b) -> a + b; List<Integer> list = itemList(1, 2, 3); List<Integer> list2 = itemList(4, 5, 6); List<Integer> result = list.lift2(function, list2); assert(result.equals(itemList(5, 6, 7, 6, 7, 8, 7, 8, 9))); }
List { public static <A> List<List<A>> sequence(List<List<A>> list) { return list.foldRight((l, a) -> l.lift2(List::cons, a), itemList((List<A>) List.<A>emptyList())); } private List(); abstract List<B> map(Function<A, B> func); abstract List<B> bind(Function<A, List<B>> func); abstract List<A> filter(Predicate<A> predicate); abstract boolean isEmpty(); abstract B foldRight(BiFunction<A, B, B> function, B accumulator); abstract List<A> append(List<A> list); abstract List<C> lift2(BiFunction<A, B, C> function, List<B> list); static EmptyList<A> emptyList(); @SafeVarargs static List<A> itemList(A... values); static List<A> cons(A value, List<A> list); static List<List<A>> sequence(List<List<A>> list); }
@Test public void testSequence() { List<List<Integer>> list = itemList(itemList(1, 2), itemList(3, 4)); List<List<Integer>> result = List.sequence(list); assert(result.equals(itemList(itemList(1, 3), itemList(1, 4), itemList(2, 3), itemList(2, 4)))); }
JbpmRestClient { public void newProcessInstance(String processId) throws URISyntaxException, IOException { URI startProcessUrl = new URL(jbpmUrl + "/rs/process/definition/" + processId + "/new_instance").toURI(); HttpPost newInstance = new HttpPost(startProcessUrl); httpclient.execute(newInstance); } JbpmRestClient(HttpClient httpclient, String jbpmUrl); void logon(String username, String password); void newProcessInstanceAndCompleteFirstTask(String processId, Map<String,Object> params); void newProcessInstance(String processId); }
@Test @Ignore public void testNewProcessInstance() throws Exception { HttpClient httpclient = new DefaultHttpClient(); JbpmRestClient jbpmClient = new JbpmRestClient(httpclient, "http: try { jbpmClient.logon("admin", "admin"); Map<String,Object> parameters = new HashMap<String,Object>(); parameters.put("DevDeploymentUrl", "http: parameters.put("DevDeploymentUrlMethod", "POST"); parameters.put("ArtifactUuid", "e67e1b09-1de7-4945-a47f-45646752437a"); jbpmClient.newProcessInstanceAndCompleteFirstTask("overlord.demo.SimpleReleaseProcess",parameters); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } }
WorkflowFactory { public static BpmManager newInstance() { BpmManager bpmManager = ServiceRegistryUtil.getSingleService(BpmManager.class); if (bpmManager == null) throw new RuntimeException(Messages.i18n.format("WorkflowFactory.MissingBPMProvider")); return bpmManager; } static BpmManager newInstance(); }
@Test public void testPersistenceFactory() throws Exception { BpmManager bpmManager = WorkflowFactory.newInstance(); Assert.assertEquals(EmbeddedJbpmManager.class, bpmManager.getClass()); } @Test @Ignore public void testNewProcessInstance() throws Exception { BpmManager bpmManager = WorkflowFactory.newInstance(); String processId = "com.sample.evaluation"; Map<String,Object> parameters = new HashMap<String,Object>(); parameters.put("employee", "krisv"); parameters.put("reason", "just bc"); parameters.put("uuid", "some-uuid-" + new Date()); bpmManager.newProcessInstance(null, processId, parameters); }
QueryExecutor { public static synchronized void execute() throws SrampClientException, MalformedURLException, ConfigException { BpmManager bpmManager = WorkflowFactory.newInstance(); SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient(); QueryAccessor accesor = new QueryAccessor(); WorkflowAccesor workflowAccesor = new WorkflowAccesor(); Iterator<Query> queryIterator = accesor.getQueries().iterator(); while (queryIterator.hasNext()) { Query query = queryIterator.next(); try { String srampQuery = query.getSrampQuery(); QueryResultSet queryResultSet = client.query(srampQuery); if (queryResultSet.size() > 0) { Iterator<ArtifactSummary> queryResultIterator = queryResultSet.iterator(); while (queryResultIterator.hasNext()) { ArtifactSummary artifactSummary = queryResultIterator.next(); boolean workflowAlreadyCreated = false; if (workflowAccesor.existRunningWorkflow(artifactSummary.getUuid(), artifactSummary.getName(), query.getWorkflowId(), null, query.getParameters())) { workflowAlreadyCreated = true; } if (workflowAlreadyCreated) { if (logger.isDebugEnabled()) logger.debug(Messages.i18n.format( "QueryExecutor.ExistingWorkflowError", artifactSummary.getUuid(), query.getWorkflowId(), query.getParameters())); } else { String hashGuid = createWorkflowArtifactGuid(artifactSummary.getUuid(), query.getWorkflowId()); BaseArtifactType workflowArtifact = workflowAccesor.save(hashGuid, artifactSummary.getUuid(), artifactSummary.getName(), query.getWorkflowId(), query.getParameters()); BaseArtifactType artifact = client.getArtifactMetaData(artifactSummary.getType(), artifactSummary.getUuid()); logger.info(Messages.i18n.format("QueryExecutor.StartingWorkflow", query.getWorkflowId(), artifact.getUuid())); Map<String,Object> parameters = query.getParsedParameters(); parameters.put("ArtifactUuid", artifact.getUuid()); parameters.put("ArtifactName", artifact.getName()); if (artifact.getVersion() != null) { parameters.put("ArtifactVersion", artifact.getVersion()); } parameters.put("ArtifactCreatedBy", artifact.getCreatedBy()); parameters.put("ArtifactCreatedTimestamp", artifact.getCreatedTimestamp().toGregorianCalendar()); parameters.put("ArtifactLastModifiedBy", artifact.getLastModifiedBy()); parameters.put("ArtifactLastModifiedTimestamp", artifact.getLastModifiedTimestamp().toGregorianCalendar()); parameters.put("ArtifactType", artifactSummary.getType().getType()); String deploymentId=buildDeploymentId(client,query.getWorkflowId()); if(StringUtils.isNotBlank(deploymentId)){ long processInstanceId = bpmManager.newProcessInstance(deploymentId, query.getWorkflowId(), parameters); workflowAccesor.update(workflowArtifact, processInstanceId); } else{ throw new RuntimeException(Messages.i18n.format("QueryExecutor.DeploymentId.Empty")); } } } } } catch (Exception e) { logger.error(Messages.i18n.format("QueryExecutor.ExceptionFor", query.getSrampQuery(), e.getMessage()), e); } } try { QueryResultSet queryResultSet = client.query(SIGNAL_QUERY); if (queryResultSet.size() > 0) { Iterator<ArtifactSummary> queryResultIterator = queryResultSet.iterator(); while (queryResultIterator.hasNext()) { ArtifactSummary artifactSummary = queryResultIterator.next(); BaseArtifactType pomArtifact = client.getArtifactMetaData(artifactSummary.getType(), artifactSummary.getUuid()); for (Relationship relationship: pomArtifact.getRelationship()) { if (GROUPED_BY.equals(relationship.getRelationshipType())) { for (org.oasis_open.docs.s_ramp.ns.s_ramp_v1.Target target: relationship.getRelationshipTarget()) { List<Long> processesIds = workflowAccesor.getProcessIds(target.getValue()); for (Long processId : processesIds) { for (Property signalProperty : pomArtifact.getProperty()) { if (signalProperty.getPropertyName().equals(MAVEN_PROPERTY_SIGNAL)) { String signalType = signalProperty.getPropertyValue(); bpmManager.signalProcess(processId, signalType, pomArtifact.getUuid()); signalProperty.setPropertyName(MAVEN_PROPERTY_SIGNAL + ".sent"); client.updateArtifactMetaData(pomArtifact); break; } } } } } } } } } catch (Exception e) { logger.error(Messages.i18n.format("QueryExecutor.ExceptionFor", SIGNAL_QUERY, e.getMessage()), e); } } static synchronized void execute(); }
@Test @Ignore public void testMonitor() throws ConfigException, SrampClientException, SrampAtomException, URISyntaxException, IOException { QueryExecutor.execute(); }
UiConfigurationServlet extends HttpServlet { protected static String generateJSONConfig(HttpServletRequest request, DtgovUIConfig config, IDtgovClient client) throws Exception { StringWriter json = new StringWriter(); JsonFactory f = new JsonFactory(); JsonGenerator g = f.createJsonGenerator(json); g.useDefaultPrettyPrinter(); g.writeStartObject(); g.writeObjectFieldStart("srampui"); g.writeStringField("urlBase", config.getConfiguration().getString(DtgovUIConfig.SRAMP_UI_URL_BASE, autoGenerateSrampUiUrlBase(request))); g.writeEndObject(); g.writeObjectFieldStart("auth"); g.writeStringField("currentUser", request.getRemoteUser()); g.writeBooleanField("isAdmin", AuthUtils.isOverlordAdmin(request)); g.writeEndObject(); g.writeObjectFieldStart("deployments"); @SuppressWarnings("unchecked") Iterator<String> typeKeys = config.getConfiguration().getKeys(DtgovUIConfig.DEPLOYMENT_TYPE_PREFIX); int count = 0; g.writeObjectFieldStart("types"); while (typeKeys.hasNext()) { String typeKey = typeKeys.next(); String value = config.getConfiguration().getString(typeKey); if (value.contains(":")) { int idx = value.indexOf(':'); String label = value.substring(0, idx); String type = value.substring(idx+1); g.writeStringField(label, type); count++; } } if (count == 0) { g.writeStringField(Messages.i18n.format("UiConfigurationServlet.TypeSwitchYard"), "ext/SwitchYardApplication"); g.writeStringField(Messages.i18n.format("UiConfigurationServlet.TypeWebApp"), "ext/JavaWebApplication"); g.writeStringField(Messages.i18n.format("UiConfigurationServlet.TypeJ2EEApp"), "ext/JavaEnterpriseApplication"); } g.writeEndObject(); List<DeploymentStage> stages = config.getStages(); g.writeObjectFieldStart("stages"); if (stages.isEmpty()) { g.writeStringField(Messages.i18n.format("UiConfigurationServlet.StageDevelopment"), "http: g.writeStringField(Messages.i18n.format("UiConfigurationServlet.StageQA"), "http: g.writeStringField(Messages.i18n.format("UiConfigurationServlet.StageProd"), "http: } else { for (DeploymentStage deploymentStage : stages) { g.writeStringField(deploymentStage.getLabel(), deploymentStage.getClassifier()); } } g.writeEndObject(); g.writeEndObject(); g.writeObjectFieldStart("workflow"); @SuppressWarnings("unchecked") Iterator<String> workflowPropertyTypes = config.getConfiguration().getKeys(DtgovUIConfig.WORKFLOW_PROPERTY_PREFIX); count = 0; g.writeObjectFieldStart("propertyTypes"); if(workflowPropertyTypes!=null){ while (workflowPropertyTypes.hasNext()) { String workflowPropertyTypeKey = workflowPropertyTypes.next(); String value = config.getConfiguration().getString(workflowPropertyTypeKey); if (value.contains(":")) { int idx = value.indexOf(':'); String label = value.substring(0, idx); String type = value.substring(idx+1); g.writeStringField(label, type); count++; } } } if (count == 0) { g.writeStringField(Messages.i18n.format("UiConfigurationServlet.workflow.property.deploymentUrl"), "{governance.url}/rest/deploy/{target}/{uuid}"); g.writeStringField(Messages.i18n.format("UiConfigurationServlet.workflow.property.notificationUrl"), "{governance.url}/rest/notify/email/{group}/deployed/{target}/{uuid}"); g.writeStringField(Messages.i18n.format("UiConfigurationServlet.workflow.property.updateMetadataUrl"), "{governance.url}/rest/update/{name}/{value}/{uuid}"); } g.writeEndObject(); g.writeEndObject(); g.writeObjectFieldStart("target"); TargetType[] targetTypes = TargetType.values(); count = 0; g.writeObjectFieldStart("types"); if (targetTypes != null) { for (int i = 0; i < targetTypes.length; i++) { TargetType targetType = targetTypes[i]; String label = Messages.i18n.format("target.type." + targetType.getValue()); g.writeStringField(label, targetType.getValue()); } } g.writeEndObject(); g.writeEndObject(); List<Deployer> customDeployers = null; if (client != null) { customDeployers = client.getCustomDeployerNames(); } g.writeObjectFieldStart("customDeployers"); if (customDeployers != null && customDeployers.size() > 0) { for (Deployer customDeployer : customDeployers) { g.writeStringField(customDeployer.getName(), customDeployer.getName()); } } g.writeEndObject(); g.flush(); g.close(); return json.toString(); } UiConfigurationServlet(); }
@Test public void testGenerateJSONConfig_Configured() throws Exception { final PropertiesConfiguration config = new PropertiesConfiguration(); config.addProperty(DtgovUIConfig.DEPLOYMENT_TYPE_PREFIX + ".switchyard", "SwitchYard Application:ext/SwitchYardApplication"); config.addProperty(DtgovUIConfig.DEPLOYMENT_TYPE_PREFIX + ".war", "Web Application:ext/JavaWebApplication"); config.addProperty(DtgovUIConfig.DEPLOYMENT_CLASSIFIER_STAGE_PREFIX + ".dev", "Development:http: config.addProperty(DtgovUIConfig.DEPLOYMENT_CLASSIFIER_STAGE_PREFIX + ".prod", "Production:http: HttpServletRequest request = new MockHttpServletRequest(); String rval = UiConfigurationServlet.generateJSONConfig(request, new DtgovUIConfig() { @Override public Configuration getConfiguration() { return config; } }, null); Assert.assertNotNull(rval); Assert.assertTrue(rval.contains("http: } @Test public void testGenerateJSONConfig_Default() throws Exception { final PropertiesConfiguration config = new PropertiesConfiguration(); HttpServletRequest request = new MockHttpServletRequest(); String rval = UiConfigurationServlet.generateJSONConfig(request, new DtgovUIConfig() { @Override public Configuration getConfiguration() { return config; } }, null); Assert.assertNotNull(rval); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public void destroy() throws ImplementationException { killWorkflowSubprocess(); removeFromShutdownHooks(); deleteWorkingDirectory(); deleteSecurityManagerDirectory(); core.deleteLocalResources(); } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testDestroy1() throws Exception { lw.destroy(); assertEquals(l(), events); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { File validateFilename(String filename) throws RemoteException { if (filename == null) throw new IllegalArgumentException("filename must be non-null"); try { return getValidatedFile(base, filename.split("/")); } catch (IOException e) { throw new IllegalArgumentException("failed to validate filename", e); } } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testValidateFilename() throws Exception { lw.validateFilename("foobar"); lw.validateFilename("foo/bar"); lw.validateFilename("foo.bar"); lw.validateFilename("foo..bar"); } @Test(expected = IllegalArgumentException.class) public void testValidateFilenameBad0() throws Exception { lw.validateFilename("./."); } @Test(expected = IllegalArgumentException.class) public void testValidateFilenameBad1() throws Exception { lw.validateFilename("/"); } @Test(expected = IllegalArgumentException.class) public void testValidateFilenameBad2() throws Exception { lw.validateFilename(""); } @Test(expected = IllegalArgumentException.class) public void testValidateFilenameBad3() throws Exception { lw.validateFilename(null); } @Test(expected = IllegalArgumentException.class) public void testValidateFilenameBad4() throws Exception { lw.validateFilename(".."); } @Test(expected = IllegalArgumentException.class) public void testValidateFilenameBad5() throws Exception { lw.validateFilename("foo/../bar"); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public RemoteInput makeInput(String name) throws RemoteException { return new InputDelegate(name); } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testMakeInput() throws Exception { assertEquals(0, lw.getInputs().size()); RemoteInput ri = lw.makeInput("TEST"); assertNotNull(ri); assertEquals(1, lw.getInputs().size()); assertNotSame(ri, lw.getInputs().get(0)); assertEquals("TEST", ri.getName()); assertNull(ri.getFile()); assertNull(ri.getValue()); lw.setInputBaclavaFile("bad"); ri.setFile("good"); assertEquals("good", ri.getFile()); assertNull(lw.getInputBaclavaFile()); ri.setValue("very good"); assertEquals("very good", ri.getValue()); assertNull(ri.getFile()); assertNull(lw.getInputBaclavaFile()); lw.makeInput("TEST2"); assertEquals(2, lw.getInputs().size()); } @Test(expected = IllegalArgumentException.class) public void testMakeInputFileSanity() throws Exception { lw.makeInput("foo").setFile("/../bar"); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public RemoteListener makeListener(String type, String configuration) throws RemoteException { throw new RemoteException("listener manufacturing unsupported"); } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testMakeListener() { Throwable t = null; try { lw.makeListener("?", "?"); } catch (Throwable caught) { t = caught; } assertNotNull(t); assertSame(RemoteException.class, t.getClass()); assertNotNull(t.getMessage()); assertEquals("listener manufacturing unsupported", t.getMessage()); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public void addListener(RemoteListener listener) throws RemoteException, ImplementationException { throw new ImplementationException("not implemented"); } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testAddListener() { Throwable t = null; try { lw.addListener(null); } catch (Throwable caught) { t = caught; } assertNotNull(t); assertSame(ImplementationException.class, t.getClass()); assertNotNull(t.getMessage()); assertEquals("not implemented", t.getMessage()); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public void setOutputBaclavaFile(String filename) throws RemoteException { if (status != Initialized) throw new IllegalStateException("not initializing"); if (filename != null) outputBaclavaFile = validateFilename(filename); else outputBaclavaFile = null; outputBaclava = filename; } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test(expected = IllegalArgumentException.class) public void testSetOutputBaclavaFile2() throws Exception { lw.setOutputBaclavaFile("/foobar"); } @Test(expected = IllegalArgumentException.class) public void testSetOutputBaclavaFile3() throws Exception { lw.setOutputBaclavaFile("foo/../bar"); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public void setStatus(RemoteStatus newStatus) throws IllegalStateTransitionException, RemoteException, ImplementationException, StillWorkingOnItException { if (status == newStatus) return; switch (newStatus) { case Initialized: throw new IllegalStateTransitionException( "may not move back to start"); case Operating: switch (status) { case Initialized: boolean started; try { started = createWorker(); } catch (Exception e) { throw new ImplementationException( "problem creating executing workflow", e); } if (!started) throw new StillWorkingOnItException( "workflow start in process"); break; case Stopped: try { core.startWorker(); } catch (Exception e) { throw new ImplementationException( "problem continuing workflow run", e); } break; case Finished: throw new IllegalStateTransitionException("already finished"); default: break; } status = Operating; break; case Stopped: switch (status) { case Initialized: throw new IllegalStateTransitionException( "may only stop from Operating"); case Operating: try { core.stopWorker(); } catch (Exception e) { throw new ImplementationException( "problem stopping workflow run", e); } break; case Finished: throw new IllegalStateTransitionException("already finished"); default: break; } status = Stopped; break; case Finished: switch (status) { case Operating: case Stopped: try { core.killWorker(); if (finish == null) finish = new Date(); } catch (Exception e) { throw new ImplementationException( "problem killing workflow run", e); } default: break; } status = Finished; break; } } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testSetStatus0() throws Exception { lw.setStatus(RemoteStatus.Initialized); lw.setStatus(RemoteStatus.Initialized); lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Stopped); lw.setStatus(RemoteStatus.Stopped); lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Finished); lw.setStatus(RemoteStatus.Finished); assertEquals( l("init[", "XWC", "WF", "36", "<null>", "{}", "{}", "<null>", "]", "stop", "start", "kill"), events); } @Test public void testSetStatus1() throws Exception { lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Stopped); lw.setStatus(RemoteStatus.Finished); assertEquals( l("init[", "XWC", "WF", "36", "<null>", "{}", "{}", "<null>", "]", "stop", "kill"), events); } @Test public void testSetStatus2() throws Exception { lw.setStatus(RemoteStatus.Initialized); lw.setStatus(RemoteStatus.Finished); assertEquals(l(), events); } @Test(expected = IllegalStateTransitionException.class) public void testSetStatus3() throws Exception { lw.setStatus(RemoteStatus.Initialized); lw.setStatus(RemoteStatus.Finished); lw.setStatus(RemoteStatus.Initialized); } @Test(expected = IllegalStateTransitionException.class) public void testSetStatus4() throws Exception { lw.setStatus(RemoteStatus.Initialized); lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Initialized); } @Test(expected = IllegalStateTransitionException.class) public void testSetStatus5() throws Exception { lw.setStatus(RemoteStatus.Initialized); lw.setStatus(RemoteStatus.Stopped); } @Test(expected = IllegalStateTransitionException.class) public void testSetStatus6() throws Exception { lw.setStatus(RemoteStatus.Finished); lw.setStatus(RemoteStatus.Stopped); } @Test(expected = IllegalStateTransitionException.class) public void testSetStatus7() throws Exception { lw.setStatus(RemoteStatus.Operating); lw.setStatus(RemoteStatus.Stopped); lw.setStatus(RemoteStatus.Initialized); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public String getInputBaclavaFile() { return inputBaclava; } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetInputBaclavaFile() throws Exception { assertNull(lw.getInputBaclavaFile()); lw.setInputBaclavaFile("IBaclava"); assertNotNull(lw.getInputBaclavaFile()); assertEquals("IBaclava", lw.getInputBaclavaFile()); lw.makeInput("FOO").setValue("BAR"); assertNull(lw.getInputBaclavaFile()); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public List<String> getListenerTypes() { return emptyList(); } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetListenerTypes() { assertEquals("[]", lw.getListenerTypes().toString()); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public List<RemoteListener> getListeners() { return singletonList(core.getDefaultListener()); } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetListeners() throws Exception { assertEquals(1, lw.getListeners().size()); RemoteListener rl = lw.getListeners().get(0); assertEquals("RLNAME", rl.getName()); assertEquals("RLCONFIG", rl.getConfiguration()); assertEquals("RLTYPE", rl.getType()); assertEquals("[RLP1, RLP2]", Arrays.asList(rl.listProperties()) .toString()); assertEquals("RLPROP[RLP1]", rl.getProperty("RLP1")); assertEquals("RLPROP[RLP2]", rl.getProperty("RLP2")); rl.setProperty("FOOBAR", "BARFOO"); assertEquals(l("setProperty[", "FOOBAR", "BARFOO", "]"), events); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public String getOutputBaclavaFile() { return outputBaclava; } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetOutputBaclavaFile() throws Exception { assertNull(lw.getOutputBaclavaFile()); lw.setOutputBaclavaFile("notnull"); assertEquals("notnull", lw.getOutputBaclavaFile()); lw.setOutputBaclavaFile(null); assertNull(lw.getOutputBaclavaFile()); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public RemoteSecurityContext getSecurityContext() throws RemoteException, ImplementationException { try { return new SecurityDelegate(masterToken); } catch (RemoteException e) { if (e.getCause() != null) throw new ImplementationException( "problem initializing security context", e.getCause()); throw e; } catch (IOException e) { throw new ImplementationException( "problem initializing security context", e); } } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetSecurityContext() throws Exception { boolean md = DO_MKDIR; LocalWorker.DO_MKDIR = false; try { assertNotNull(lw.getSecurityContext()); } finally { LocalWorker.DO_MKDIR = md; } }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public RemoteStatus getStatus() { if (status == Operating) { status = core.getWorkerStatus(); if (status == Finished && finish == null) finish = new Date(); } return status; } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetStatusInitial() { assertEquals(RemoteStatus.Initialized, lw.getStatus()); } @Test public void testGetStatus() throws Exception { assertEquals(RemoteStatus.Initialized, lw.getStatus()); returnThisStatus = RemoteStatus.Operating; assertEquals(RemoteStatus.Initialized, lw.getStatus()); lw.setStatus(RemoteStatus.Operating); assertEquals(RemoteStatus.Operating, lw.getStatus()); assertEquals(RemoteStatus.Operating, lw.getStatus()); returnThisStatus = RemoteStatus.Finished; assertEquals(RemoteStatus.Finished, lw.getStatus()); returnThisStatus = RemoteStatus.Stopped; assertEquals(RemoteStatus.Finished, lw.getStatus()); assertEquals( l("init[", "XWC", "WF", "36", "<null>", "{}", "{}", "<null>", "]", "status=Operating", "status=Operating", "status=Finished"), events); }
LocalWorker extends UnicastRemoteObject implements RemoteSingleRun { @Override public RemoteDirectory getWorkingDirectory() { return baseDir; } protected LocalWorker(String executeWorkflowCommand, String workflow, UsageRecordReceiver urReceiver, UUID id, Map<String, String> seedEnvironment, List<String> javaParams, WorkerFactory workerFactory); @Override void destroy(); @Override void addListener(RemoteListener listener); @Override String getInputBaclavaFile(); @Override List<RemoteInput> getInputs(); @Override List<String> getListenerTypes(); @Override List<RemoteListener> getListeners(); @Override String getOutputBaclavaFile(); @Override RemoteSecurityContext getSecurityContext(); @Override RemoteStatus getStatus(); @Override RemoteDirectory getWorkingDirectory(); @Override RemoteInput makeInput(String name); @Override RemoteListener makeListener(String type, String configuration); @Override void setInputBaclavaFile(String filename); @Override void setOutputBaclavaFile(String filename); @Override void setGenerateProvenance(boolean prov); @Override void setStatus(RemoteStatus newStatus); @Override Date getFinishTimestamp(); @Override Date getStartTimestamp(); @Override void setInteractionServiceDetails(URL feed, URL webdav, URL publish); @Override void ping(); }
@Test public void testGetWorkingDirectory() throws Exception { RemoteDirectory rd = lw.getWorkingDirectory(); assertNotNull(rd); assertNotNull(rd.getContents()); assertNull(rd.getContainingDirectory()); assertNotNull(rd.getName()); assertEquals(-1, rd.getName().indexOf('/')); assertFalse("..".equals(rd.getName())); assertEquals("", rd.getName()); }
Generate { public static void main(final String[] args) { final File baseDirectory = new File(args.length == 0 ? "." : args[0]); if (!baseDirectory.isDirectory()) { LOGGER.log(Level.SEVERE, baseDirectory.getAbsolutePath() + " is not a directory."); } else { new Generate().handleDirectory(baseDirectory); } } static void main(final String[] args); }
@Test public void test() throws IOException { createFile("base/withinfo/ClassA.java", "package base.withinfo;\n\npublic ClassA {\n}\n"); createFile("base/withinfo/package-info.java", "base withinfo.second;\n"); createFile("base/noinfo/ClassA.java", "package base.noinfo;\n\npublic ClassA {\n}\n"); Generate.main(new String[] { baseDirectory.getAbsolutePath() }); String contents = readFile("base/noinfo/package-info.java"); Assert.assertEquals("package base.noinfo;\n", contents); } @Test public void testNotADirectory() throws IOException { File file = createFile("base/withinfo/ClassA.java", "package base.withinfo;\n\npublic ClassA {\n}\n"); Generate.main(new String[] { file.getAbsolutePath() }); }
EfferentCouplingRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM)); for (final Package<Location> packageToCheck : model.getPackages()) { final int efferentCoupling = packageToCheck.getPackageUsages().size(); LOGGER.debug("Package {}: efferent={}", packageToCheck.getName(), efferentCoupling); if (efferentCoupling > maximum) { final Set<Class<Location>> classes = selectClassesWithEfferentUsage(packageToCheck.getClasses()); registerIssue(context, settings, rule, packageToCheck, classes, "Reduce number of packages used by this package (allowed: " + maximum + ", actual: " + efferentCoupling + ")"); } } } EfferentCouplingRule(final Settings settings); @Override void define(final NewRepository repository); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); final String message = issue.primaryLocation().message(); System.out.println("Message: " + message); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageC/package-info.java", issue.primaryLocation().inputComponent().key()); Assert.assertEquals("Reduce number of packages used by this package (allowed: 1, actual: 2)", message); } @Test public void testOnClasses() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); settings.setProperty(PackageAnalyzerProperties.CLASS_MODE_KEY, PackageAnalyzerProperties.CLASS_MODE_ALL); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(2, sensorContext.allIssues().size()); final Map<String,Issue> issues = sensorContext.allIssues().stream().collect(Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageC/ClassA.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageC/ClassB.java"); }
MissingPackageInfoRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { for (final Package<Location> packageToCheck : model.getPackages()) { LOGGER.debug("Package {}: extenal={}", packageToCheck.getExternal()); if (packageToCheck.getExternal() == null) { for (final Class<Location> classToReport : packageToCheck.getClasses()) { registerIssue(context, rule, classToReport, "Add a package-info.java to the package."); } } } } MissingPackageInfoRule(); @Override void define(final NewRepository repository); @Override boolean supportsLanguage(final String language); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = new Model<>(); model.addPackage("packageA", location("packageA/package-info.java")); model.addClass(Name.of("packageA.ClassA"), true, location("packageA/ClassA.java")); model.addClass(Name.of("packageA.ClassB"), true, location("packageA/ClassB.java")); model.addPackage("packageB", null); model.addClass(Name.of("packageB.ClassA"), true, location("packageB/ClassA.java")); model.addClass(Name.of("packageB.ClassB"), true, null); model.addClass(Name.of("packageB.ClassC"), true, location("packageB/ClassC.java")); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(2, sensorContext.allIssues().size()); final List<String> keys = sensorContext.allIssues().stream() .map(issue -> issue.primaryLocation().inputComponent().key()).collect(Collectors.toList()); Assert.assertTrue(keys.contains(BaseRuleTest.PROJECT_KEY + ":packageB/ClassA.java")); Assert.assertTrue(keys.contains(BaseRuleTest.PROJECT_KEY + ":packageB/ClassC.java")); }
AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public final void scanModel(final SensorContext context, final String language, final Model<Location> model) { final ActiveRule rule = context.activeRules().find(RuleKey.of(BaseRules.getRepositoryKey(language), ruleKey)); if (rule == null) { LOGGER.debug("Rule {}:{} is not active", BaseRules.getRepositoryKey(language), ruleKey); return; } scanModel(context, rule, model); } protected AbstractPackageAnalyzerRule(final String ruleKey); @Override final void scanModel(final SensorContext context, final String language, final Model<Location> model); }
@Test public void active() { final ActiveRules activeRules = Mockito.mock(ActiveRules.class); sensorContext.setActiveRules(activeRules); Mockito.when(activeRules.find(RuleKey.of("package-analyzer-test-no", "test"))).thenReturn(null); Mockito.when(activeRules.find(RuleKey.of("package-analyzer-test-yes", "test"))).thenReturn(activeRule); final Model<Location> model = new Model<>(); model.addPackage("packageA", location("packageA/package-info.java")); subject.scanModel(sensorContext, "test-no", model); Assert.assertEquals(0, sensorContext.allIssues().size()); subject.scanModel(sensorContext, "test-yes", model); Assert.assertEquals(1, sensorContext.allIssues().size()); } @Test public void noLocation() { final Model<Location> model = new Model<>(); model.addPackage("packageA", null); model.addPackage("packageB", location("packageB/package-info.java")); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); }
AbstractnessRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM)); for (final Package<Location> packageToCheck : model.getPackages()) { final Set<Class<Location>> classes = packageToCheck.getClasses().stream().filter(Class::isAbstract) .collect(Collectors.toSet()); final int abstractClasses = classes.size(); final int totalClasses = packageToCheck.getClasses().size(); final int abstractness = totalClasses == 0 ? 0 : (abstractClasses * 100 / totalClasses); LOGGER.debug("Package {}: abstract={}, total={}, abstractness={}", packageToCheck.getName(), abstractClasses, totalClasses, abstractness); if (abstractness > maximum) { registerIssue(context, settings, rule, packageToCheck, classes, "Reduce number of abstract classes in this package (allowed: " + maximum + "%, actual: " + abstractness + "%)"); } } } AbstractnessRule(final Settings settings); @Override void define(final NewRepository repository); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(3, sensorContext.allIssues().size()); Map<String, Issue> issues = sensorContext.allIssues().stream().collect( Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageD/ClassB.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageD/ClassC.java"); } @Test public void testPackage() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_PACKAGE); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); final String message = issue.primaryLocation().message(); System.out.println("Message: " + message); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java", issue.primaryLocation().inputComponent().key()); Assert.assertEquals("Reduce number of abstract classes in this package (allowed: 60%, actual: 100%)", message); } @Test public void testClasses() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(2, sensorContext.allIssues().size()); Map<String, Issue> issues = sensorContext.allIssues().stream().collect( Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageD/ClassB.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageD/ClassC.java"); } @Test public void testClassesFirstOnly() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); settings.setProperty(PackageAnalyzerProperties.CLASS_MODE_KEY, PackageAnalyzerProperties.CLASS_MODE_FIRST); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); Map<String, Issue> issues = sensorContext.allIssues().stream().collect( Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageD/ClassB.java"); }
NumberOfClassesAndInterfacesRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM)); for (final Package<Location> packageToCheck : model.getPackages()) { final int classcount = packageToCheck.getClasses().size(); LOGGER.debug("Package {}: total={}", packageToCheck.getName(), classcount); if (classcount > maximum) { registerIssue(context, settings, rule, packageToCheck, packageToCheck.getClasses(), "Reduce number of classes in package (allowed: " + maximum + ", actual: " + classcount + ")"); } } } NumberOfClassesAndInterfacesRule(final Settings settings); @Override void define(final NewRepository repository); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); final String message = issue.primaryLocation().message(); System.out.println("Message: " + message); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java", issue.primaryLocation().inputComponent().key()); Assert.assertEquals("Reduce number of classes in package (allowed: 2, actual: 3)", message); } @Test public void testOnClasses() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(2, sensorContext.allIssues().size()); Map<String,Issue> issues = sensorContext.allIssues().stream().collect(Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/ClassA.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/ClassC.java"); }
AfferentCouplingRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM)); for (final Package<Location> packageToCheck : model.getPackages()) { final int afferentCoupling = packageToCheck.getUsedByPackages().size(); LOGGER.debug("Package {}: afferent={}", packageToCheck.getName(), afferentCoupling); if (afferentCoupling > maximum) { final Set<Class<Location>> classes = selectClassesWithAfferentUsage(packageToCheck.getClasses()); registerIssue(context, settings, rule, packageToCheck, classes, "Reduce number of packages that use this package (allowed: " + maximum + ", actual: " + afferentCoupling + ")"); } } } AfferentCouplingRule(final Settings settings); @Override void define(final NewRepository repository); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); final String message = issue.primaryLocation().message(); System.out.println("Message: " + message); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java", issue.primaryLocation().inputComponent().key()); Assert.assertEquals("Reduce number of packages that use this package (allowed: 1, actual: 2)", message); } @Test public void testClasses() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); settings.setProperty(PackageAnalyzerProperties.CLASS_MODE_KEY, PackageAnalyzerProperties.CLASS_MODE_ALL); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageA/ClassA.java", issue.primaryLocation().inputComponent().key()); }
PackageDependencyCyclesRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { final Analyzer<Location> analyzer = new Analyzer<>(); final List<PackageCycle<Location>> packageCycles = analyzer.findPackageCycles(model); LOGGER.debug("Package cycles: {}", packageCycles.size()); int packageCycleIdentifier = 0; final Map<Package<Location>, StringBuilder> identifierMeasures = new HashMap<>(); for (final PackageCycle<Location> packageCycle : packageCycles) { packageCycleIdentifier++; final List<Package<Location>> packagesInCycle = packageCycle.getPackagesInCycle(); for (int packageInCycleIndex = 0; packageInCycleIndex < packagesInCycle.size(); packageInCycleIndex++) { final Package<Location> packageInCycle = packagesInCycle.get(packageInCycleIndex); final int nextPackageInCycleIndex = packageInCycleIndex + 1; final Package<Location> nextPackageInCycle = packagesInCycle .get(nextPackageInCycleIndex == packagesInCycle.size() ? 0 : nextPackageInCycleIndex); if (identifierMeasures.containsKey(packageInCycle)) { identifierMeasures.get(packageInCycle).append(",").append(Integer.toString(packageCycleIdentifier)); } else { identifierMeasures.put(packageInCycle, new StringBuilder(Integer.toString(packageCycleIdentifier))); } final String message = formatMessage(packageCycle, packageInCycle); final Set<Class<Location>> classes = selectClasses(packageInCycle.getClasses(), nextPackageInCycle); registerIssue(context, settings, rule, packageInCycle, classes, message); } } for (final Map.Entry<Package<Location>, StringBuilder> measure : identifierMeasures.entrySet()) { registerMeasure(context, PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER, measure.getKey(), measure.getValue().toString()); } } PackageDependencyCyclesRule(final Settings settings); @Override void define(final NewRepository repository); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); String message = issue.primaryLocation().message(); System.out.println("Message: " + message); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java", issue.primaryLocation().inputComponent().key()); Assert.assertEquals("Break the package cycle containing the following cycle of packages: packageA (ClassA references classC, classD, classE, classX, ClassB references classB, ClassC references classB, ClassD references classC), packageB (ClassA references classA)", message); } @Test public void testOnClasses() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(2, sensorContext.allIssues().size()); Map<String,Issue> issues = sensorContext.allIssues().stream().collect(Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/ClassB.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/ClassC.java"); } @Test public void testMultiple() { final Model<Location> model = new Model<>(); model.addPackage("packageA", location("packageA/package-info.java")); model.addClass(Name.of("packageA.ClassA"), false, null).addUsage(Name.of("packageB.classA")); model.addClass(Name.of("packageA.ClassA"), false, null).addUsage(Name.of("packageC.classA")); model.addPackage("packageB", location("packageB/package-info.java")); model.addClass(Name.of("packageB.ClassA"), false, null).addUsage(Name.of("packageA.classA")); model.addClass(Name.of("packageB.ClassA"), false, null).addUsage(Name.of("packageC.classA")); model.addPackage("packageC", location("packageC/package-info.java")); model.addClass(Name.of("packageC.ClassA"), false, null).addUsage(Name.of("packageA.classA")); model.addClass(Name.of("packageC.ClassA"), false, null).addUsage(Name.of("packageB.classA")); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(12, sensorContext.allIssues().size()); Assert.assertEquals("1,2,3,5", sensorContext.measure(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java", PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER).value()); Assert.assertEquals("1,2,3,4", sensorContext.measure(BaseRuleTest.PROJECT_KEY + ":packageB/package-info.java", PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER).value()); Assert.assertEquals("2,3,4,5", sensorContext.measure(BaseRuleTest.PROJECT_KEY + ":packageC/package-info.java", PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER).value()); }
InstabilityRule extends AbstractPackageAnalyzerRule implements PackageAnalyzerRule { @Override public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) { final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM)); for (final Package<Location> packageToCheck : model.getPackages()) { final int afferentCoupling = packageToCheck.getUsedByPackages().size(); final int efferentCoupling = packageToCheck.getPackageUsages().size(); final int totalCoupling = efferentCoupling + afferentCoupling; final int instability = totalCoupling == 0 ? 0 : (efferentCoupling * 100) / totalCoupling; LOGGER.debug("Package {}: efferent={}, total={}, instability={}", packageToCheck.getName(), efferentCoupling, totalCoupling, instability); if (instability > maximum) { final Set<Class<Location>> classes = EfferentCouplingRule .selectClassesWithEfferentUsage(packageToCheck.getClasses()); registerIssue(context, settings, rule, packageToCheck, classes, "Reduce number of packages used by this package to lower instability (allowed: " + maximum + "%, actual: " + instability + "%)"); } } } InstabilityRule(final Settings settings); @Override void define(final NewRepository repository); @Override void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model); }
@Test public void test() { final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(1, sensorContext.allIssues().size()); final Issue issue = sensorContext.allIssues().iterator().next(); final String message = issue.primaryLocation().message(); System.out.println("Message: " + message); Assert.assertEquals(BaseRuleTest.PROJECT_KEY + ":packageA/package-info.java", issue.primaryLocation().inputComponent().key()); Assert.assertEquals( "Reduce number of packages used by this package to lower instability (allowed: 75%, actual: 100%)", message); } @Test public void testClasses() { settings.setProperty(PackageAnalyzerProperties.ISSUE_MODE_KEY, PackageAnalyzerProperties.ISSUE_MODE_CLASS); final Model<Location> model = createModel(); subject.scanModel(sensorContext, activeRule, model); Assert.assertEquals(2, sensorContext.allIssues().size()); final Map<String, Issue> issues = sensorContext.allIssues().stream().collect( Collectors.toMap(issue -> issue.primaryLocation().inputComponent().key(), Function.identity())); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/ClassA.java"); issues.containsKey(BaseRuleTest.PROJECT_KEY + ":packageA/ClassC.java"); }
PackageAnalyzerPlugin implements Plugin { @Override public void define(final Context context) { LOGGER.debug("Defining plugin ..."); context.addExtensions(AbstractnessRule.class, AfferentCouplingRule.class, EfferentCouplingRule.class, InstabilityRule.class, MissingPackageInfoRule.class, NumberOfClassesAndInterfacesRule.class, PackageDependencyCyclesRule.class); context.addExtensions(PackageAnalyzerMetrics.class, PackageAnalyzerComputer.class); context.addExtensions(PackageAnalyzerProperties.definitions()); context.addExtensions(JavaRules.class, JavaSensor.class); LOGGER.debug("Plugin defined"); } @Override void define(final Context context); static final String KEY; }
@Test public void test() { final PackageAnalyzerPlugin subject = new PackageAnalyzerPlugin(); final Plugin.Context context = new Plugin.Context(SonarRuntimeImpl.forSonarQube(Version.create(5, 6), SonarQubeSide.SERVER)); Assert.assertEquals(0, context.getExtensions().size()); subject.define(context); Assert.assertTrue(context.getExtensions().contains(AbstractnessRule.class)); Assert.assertTrue(context.getExtensions().contains(AfferentCouplingRule.class)); Assert.assertTrue(context.getExtensions().contains(EfferentCouplingRule.class)); Assert.assertTrue(context.getExtensions().contains(InstabilityRule.class)); Assert.assertTrue(context.getExtensions().contains(MissingPackageInfoRule.class)); Assert.assertTrue(context.getExtensions().contains(NumberOfClassesAndInterfacesRule.class)); Assert.assertTrue(context.getExtensions().contains(PackageDependencyCyclesRule.class)); Assert.assertTrue(context.getExtensions().contains(JavaRules.class)); Assert.assertTrue(context.getExtensions().contains(JavaSensor.class)); }
Johnson { public synchronized List<List<T>> getElementaryCircuits() { if (elementaryCircuits == null) { calculate(); } return elementaryCircuits; } Johnson(final Map<T, Set<T>> edges); synchronized List<List<T>> getElementaryCircuits(); }
@Test public void testStackOverflowExample() { final Map<String, Set<String>> input = new HashMap<>(); input.put("Node 0", new HashSet<>(Arrays.asList("Node 1", "Node 2"))); input.put("Node 1", new HashSet<>(Arrays.asList("Node 0", "Node 2"))); input.put("Node 2", new HashSet<>(Arrays.asList("Node 0", "Node 1"))); final List<List<String>> circuits = new Johnson<>(input).getElementaryCircuits(); final List<List<String>> ordered = orderCircuits(circuits); printResult(ordered); Assert.assertEquals( Arrays.asList( Arrays.asList("Node 0", "Node 1"), Arrays.asList("Node 0", "Node 1", "Node 2"), Arrays.asList("Node 0", "Node 2"), Arrays.asList("Node 0", "Node 2", "Node 1"), Arrays.asList("Node 1", "Node 2") ) , ordered); } @Test public void testTarjanWikipediaExample() { final Map<String, Set<String>> input = new HashMap<>(); input.put("Node 1", new HashSet<>(Arrays.asList("Node 2"))); input.put("Node 2", new HashSet<>(Arrays.asList("Node 3"))); input.put("Node 3", new HashSet<>(Arrays.asList("Node 1"))); input.put("Node 4", new HashSet<>(Arrays.asList("Node 3", "Node 5"))); input.put("Node 5", new HashSet<>(Arrays.asList("Node 4", "Node 6"))); input.put("Node 6", new HashSet<>(Arrays.asList("Node 3", "Node 7"))); input.put("Node 7", new HashSet<>(Arrays.asList("Node 6"))); input.put("Node 8", new HashSet<>(Arrays.asList("Node 5", "Node 7", "Node 8"))); final List<List<String>> circuits = new Johnson<>(input).getElementaryCircuits(); final List<List<String>> ordered = orderCircuits(circuits); printResult(ordered); Assert.assertEquals( Arrays.asList( Arrays.asList("Node 1", "Node 2", "Node 3"), Arrays.asList("Node 4", "Node 5"), Arrays.asList("Node 6", "Node 7"), Arrays.asList("Node 8") ) , ordered); } @Test public void test() { final Map<String, Set<String>> input = new HashMap<>(); input.put("Node 1", new HashSet<>(Arrays.asList("Node 2"))); input.put("Node 2", new HashSet<>(Arrays.asList("Node 3", "Node 4"))); input.put("Node 3", new HashSet<>(Arrays.asList("Node 4"))); input.put("Node 4", new HashSet<>(Arrays.asList("Node 1"))); input.put("Node 5", Collections.emptySet()); Johnson<String> johson = new Johnson<>(input); johson.getElementaryCircuits(); final List<List<String>> circuits = johson.getElementaryCircuits(); final List<List<String>> ordered = orderCircuits(circuits); printResult(ordered); Assert.assertEquals( Arrays.asList( Arrays.asList("Node 1", "Node 2", "Node 3", "Node 4"), Arrays.asList("Node 1", "Node 2", "Node 4") ) , ordered); }
AbstractSensor implements Sensor { @Override public final void describe(final SensorDescriptor descriptor) { descriptor.name("Package Analyzer Sensor (" + language + ")"); descriptor.onlyOnLanguage(language); descriptor.createIssuesForRuleRepository(BaseRules.getRepositoryKey(language)); } AbstractSensor(final String language, final PackageAnalyzerRule... rules); @Override final void describe(final SensorDescriptor descriptor); @Override final void execute(final SensorContext context); }
@Test public void describe() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor.describe(descriptor); Assert.assertEquals("Package Analyzer Sensor (TEST)", descriptor.name()); Assert.assertEquals(Arrays.asList("TEST"), descriptor.languages()); }
Analyzer { public List<PackageCycle<T>> findPackageCycles(final Model<T> model) { final Map<Package<T>, Set<Package<T>>> edges = createEdges(model.getPackages()); final List<List<Package<T>>> elementaryCircuits = new Johnson<>(edges).getElementaryCircuits(); return createPackageCycles(elementaryCircuits); } List<PackageCycle<T>> findPackageCycles(final Model<T> model); }
@Test public void test() { Model<String> model = new Model<>(); model.addPackage("packageA", "packageA"); model.addPackage("packageB", "packageB"); model.addPackage("packageC", "packageC"); Class<String> classA = model.addClass(Name.of("packageA.ClassA"), false, "ClassA"); classA.addUsage(Name.of("packageB.ClassB")); classA.addUsage(Name.of("packageC.ClassC")); Class<String> classB = model.addClass(Name.of("packageB.ClassB"), false, "ClassB"); classB.addUsage(Name.of("packageA.ClassA")); classB.addUsage(Name.of("packageC.ClassC")); Class<String> classC = model.addClass(Name.of("packageC.ClassC"), false, "ClassC"); classC.addUsage(Name.of("packageA.ClassA")); classC.addUsage(Name.of("packageB.ClassB")); Analyzer<String> analyzer = new Analyzer<>(); List<PackageCycle<String>> packageCycles = analyzer.findPackageCycles(model); List<List<String>> result = new ArrayList<>(); for(PackageCycle<String> packageCycle : packageCycles) { List<String> cycle = new ArrayList<>(); for(Package<String> packageInCycle : packageCycle.getPackagesInCycle()) { cycle.add(packageInCycle.getExternal()); } result.add(cycle); } List<List<String>> ordered = JohnsonTest.orderCircuits(result); Assert.assertEquals( Arrays.asList( Arrays.asList("packageA", "packageB"), Arrays.asList("packageA", "packageB", "packageC"), Arrays.asList("packageA", "packageC"), Arrays.asList("packageA", "packageC", "packageB"), Arrays.asList("packageB", "packageC") ) , ordered); }
Tarjan { public synchronized List<List<T>> getStronglyConnectedComponents() { if (stronglyConnectedComponents == null) { calculate(); } return stronglyConnectedComponents; } Tarjan(final Map<T, Set<T>> edges); synchronized List<List<T>> getStronglyConnectedComponents(); }
@Test public void testWikipediaExample() { final Map<String, Set<String>> input = new HashMap<>(); input.put("Node 1", new HashSet<>(Arrays.asList("Node 2"))); input.put("Node 2", new HashSet<>(Arrays.asList("Node 3"))); input.put("Node 3", new HashSet<>(Arrays.asList("Node 1"))); input.put("Node 4", new HashSet<>(Arrays.asList("Node 3", "Node 5"))); input.put("Node 5", new HashSet<>(Arrays.asList("Node 4", "Node 6"))); input.put("Node 6", new HashSet<>(Arrays.asList("Node 3", "Node 7"))); input.put("Node 7", new HashSet<>(Arrays.asList("Node 6"))); input.put("Node 8", new HashSet<>(Arrays.asList("Node 5", "Node 7", "Node 8"))); final List<List<String>> components = new Tarjan<>(input).getStronglyConnectedComponents(); printResult(components); } @Test public void test() { final Map<String, Set<String>> input = new HashMap<>(); input.put("Node 1", new HashSet<>(Arrays.asList("Node 2"))); input.put("Node 2", new HashSet<>(Arrays.asList("Node 3", "Node 4"))); input.put("Node 3", new HashSet<>(Arrays.asList("Node 4"))); input.put("Node 4", new HashSet<>(Arrays.asList("Node 1"))); input.put("Node 5", Collections.emptySet()); Tarjan<String> tarjan = new Tarjan<>(input); tarjan.getStronglyConnectedComponents(); final List<List<String>> components = tarjan.getStronglyConnectedComponents(); printResult(components); }
AbstractSensor implements Sensor { @Override public final void execute(final SensorContext context) { LOGGER.info("Build package model ..."); final Model<Location> model = buildModel(context); LOGGER.info("Package model built, analyzing model for issues ..."); for (final PackageAnalyzerRule rule : rules) { if (rule.supportsLanguage(language)) { LOGGER.debug("Executing rule: {}", rule); rule.scanModel(context, language, model); } } LOGGER.info("Analysis done"); } AbstractSensor(final String language, final PackageAnalyzerRule... rules); @Override final void describe(final SensorDescriptor descriptor); @Override final void execute(final SensorContext context); }
@Test public void execute() { Assert.assertFalse(sensor.called); Assert.assertFalse(rule1.called); Assert.assertFalse(rule2.called); sensor.execute(null); Assert.assertTrue(sensor.called); Assert.assertTrue(rule1.called); Assert.assertTrue(rule2.called); }
PackageAnalyzerMetrics implements Metrics { @Override @SuppressWarnings("rawtypes") public List<Metric> getMetrics() { return asList(PACKAGE_DEPENDENCY_CYCLES, PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER, PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS); } @Override @SuppressWarnings("rawtypes") List<Metric> getMetrics(); static final Metric<Integer> PACKAGE_DEPENDENCY_CYCLES; static final Metric<String> PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER; static final Metric<String> PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS; }
@Test public void test() { Assert.assertEquals(3, new PackageAnalyzerMetrics().getMetrics().size()); }
PackageAnalyzerComputer implements MeasureComputer { @Override public MeasureComputerDefinition define(final MeasureComputerDefinitionContext definitionContext) { return definitionContext.newDefinitionBuilder() .setInputMetrics(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER.key(), PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key(), PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key()) .setOutputMetrics(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key(), PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key()) .build(); } @Override MeasureComputerDefinition define(final MeasureComputerDefinitionContext definitionContext); @Override void compute(final MeasureComputerContext context); }
@Test public void testDefinition() { final TestMeasureComputerDefinitionContext definitionContext = new TestMeasureComputerDefinitionContext(); final MeasureComputerDefinition definition = subject.define(definitionContext); Assert.assertNotNull(definition); Assert.assertEquals(3, definition.getInputMetrics().size()); Assert.assertTrue(definition.getInputMetrics().contains(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER.key())); Assert.assertTrue(definition.getOutputMetrics().contains(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key())); Assert.assertTrue(definition.getInputMetrics().contains(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key())); Assert.assertEquals(2, definition.getOutputMetrics().size()); Assert.assertTrue(definition.getOutputMetrics().contains(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key())); Assert.assertTrue(definition.getOutputMetrics().contains(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key())); }
PackageAnalyzerComputer implements MeasureComputer { @Override public void compute(final MeasureComputerContext context) { rollupIdentifiers(context); countIdentifiers(context); } @Override MeasureComputerDefinition define(final MeasureComputerDefinitionContext definitionContext); @Override void compute(final MeasureComputerContext context); }
@Test public void testEmpty() { subject.compute(context); Assert.assertEquals("", context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key()).getStringValue()); Assert.assertEquals(0, context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key()).getIntValue()); } @Test public void testOwnIdentifiers() { context.addInputMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER.key(), "1,2,3"); subject.compute(context); Assert.assertEquals("1,2,3", context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key()).getStringValue()); Assert.assertEquals(3, context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key()).getIntValue()); } @Test public void testChildIdentifiers() { context.addChildrenMeasures(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key(), "1,2,3", "2,3,4,5"); subject.compute(context); Assert.assertEquals("1,2,3,4,5", context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key()).getStringValue()); Assert.assertEquals(5, context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key()).getIntValue()); } @Test public void testAllIdentifiers() { context.addInputMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIER.key(), "1,2,3"); context.addChildrenMeasures(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key(), "2,3,4", "3,4,5"); subject.compute(context); Assert.assertEquals("1,2,3,4,5", context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES_IDENTIFIERS.key()).getStringValue()); Assert.assertEquals(5, context.getMeasure(PackageAnalyzerMetrics.PACKAGE_DEPENDENCY_CYCLES.key()).getIntValue()); }