src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
RetrofitApiClient { public Result register(final String username, final String password, final String name, final String email) throws IOException { Response<UserCreateResponseDto> response = v2Api.register(username, password, name, email).execute(); return response.body().toRegistrationResult(); } @SuppressWarnings("deprecation") RetrofitApiClient(Builder builder); String getJourneyJson(final String plan,
final String itineraryPoints,
final String leaving,
final String arriving,
final int speed); String retrievePreviousJourneyJson(final String plan,
final long itineraryId); Blog getBlogEntries(); POICategories getPOICategories(); List<POI> getPOIs(final String type,
final double lonW,
final double latS,
final double lonE,
final double latN); List<POI> getPOIs(final String type,
final double lon,
final double lat,
final int radius); GeoPlaces geoCoder(final String search,
final double lonW,
final double latS,
final double lonE,
final double latN); PhotomapCategories getPhotomapCategories(); Photos getPhotos(final double lonW,
final double latS,
final double lonE,
final double latN); Photos getPhoto(final long photoId); UserJourneys getUserJourneys(final String username); Result register(final String username,
final String password,
final String name,
final String email); Signin.Result authenticate(final String identifier,
final String password); Result sendFeedback(final int itinerary,
final String comments,
final String name,
final String email); Upload.Result uploadPhoto(final String username,
final String password,
final double lon,
final double lat,
final long dateTime,
final String category,
final String metaCat,
final String caption,
final String filename); } | @Test public void testRegisterReturnsOk() throws Exception { stubFor(post(urlPathEqualTo("/v2/user.create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBodyFile("registration-ok.json"))); Result result = apiClient.register("arnold", "cyberdyne101", "The Terminator", "[email protected]"); verify(postRequestedFor(urlPathEqualTo("/v2/user.create")) .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded")) .withRequestBody(equalTo("username=arnold&password=cyberdyne101&name=The%20Terminator&email=101%40skynet.com")) .withQueryParam("key", equalTo("myApiKey"))); assertThat(result.ok()).isTrue(); assertThat(result.message()).contains("Your account has been registered"); }
@Test public void testRegisterReturnsError() throws Exception { stubFor(post(urlPathEqualTo("/v2/user.create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBodyFile("api-error.json"))); Result result = apiClient.register("username", "pwd", "name", "[email protected]"); verify(postRequestedFor(urlPathEqualTo("/v2/user.create")) .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded")) .withQueryParam("key", equalTo("myApiKey"))); assertThat(result.ok()).isFalse(); assertThat(result.message()).contains("Your account could not be registered."); } |
RetrofitApiClient { public Signin.Result authenticate(final String identifier, final String password) throws IOException { Response<UserAuthenticateResponseDto> response = v2Api.authenticate(identifier, password).execute(); return response.body().toSigninResult(); } @SuppressWarnings("deprecation") RetrofitApiClient(Builder builder); String getJourneyJson(final String plan,
final String itineraryPoints,
final String leaving,
final String arriving,
final int speed); String retrievePreviousJourneyJson(final String plan,
final long itineraryId); Blog getBlogEntries(); POICategories getPOICategories(); List<POI> getPOIs(final String type,
final double lonW,
final double latS,
final double lonE,
final double latN); List<POI> getPOIs(final String type,
final double lon,
final double lat,
final int radius); GeoPlaces geoCoder(final String search,
final double lonW,
final double latS,
final double lonE,
final double latN); PhotomapCategories getPhotomapCategories(); Photos getPhotos(final double lonW,
final double latS,
final double lonE,
final double latN); Photos getPhoto(final long photoId); UserJourneys getUserJourneys(final String username); Result register(final String username,
final String password,
final String name,
final String email); Signin.Result authenticate(final String identifier,
final String password); Result sendFeedback(final int itinerary,
final String comments,
final String name,
final String email); Upload.Result uploadPhoto(final String username,
final String password,
final double lon,
final double lat,
final long dateTime,
final String category,
final String metaCat,
final String caption,
final String filename); } | @Test public void testAuthenticateReturnsOk() throws Exception { stubFor(post(urlPathEqualTo("/v2/user.authenticate")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBodyFile("authenticate-ok.json"))); Signin.Result result = apiClient.authenticate("precious", "9nazgul"); verify(postRequestedFor(urlPathEqualTo("/v2/user.authenticate")) .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded")) .withRequestBody(equalTo("identifier=precious&password=9nazgul")) .withQueryParam("key", equalTo("myApiKey"))); assertThat(result.ok()).isTrue(); assertThat(result.name()).isEqualTo("Bilbo Baggins"); assertThat(result.email()).isEqualTo("[email protected]"); } |
RetrofitApiClient { public Result sendFeedback(final int itinerary, final String comments, final String name, final String email) throws IOException { Response<SendFeedbackResponseDto> response = v2Api.sendFeedback("routing", itinerary, comments, name, email).execute(); return response.body().toFeedbackResult(); } @SuppressWarnings("deprecation") RetrofitApiClient(Builder builder); String getJourneyJson(final String plan,
final String itineraryPoints,
final String leaving,
final String arriving,
final int speed); String retrievePreviousJourneyJson(final String plan,
final long itineraryId); Blog getBlogEntries(); POICategories getPOICategories(); List<POI> getPOIs(final String type,
final double lonW,
final double latS,
final double lonE,
final double latN); List<POI> getPOIs(final String type,
final double lon,
final double lat,
final int radius); GeoPlaces geoCoder(final String search,
final double lonW,
final double latS,
final double lonE,
final double latN); PhotomapCategories getPhotomapCategories(); Photos getPhotos(final double lonW,
final double latS,
final double lonE,
final double latN); Photos getPhoto(final long photoId); UserJourneys getUserJourneys(final String username); Result register(final String username,
final String password,
final String name,
final String email); Signin.Result authenticate(final String identifier,
final String password); Result sendFeedback(final int itinerary,
final String comments,
final String name,
final String email); Upload.Result uploadPhoto(final String username,
final String password,
final double lon,
final double lat,
final long dateTime,
final String category,
final String metaCat,
final String caption,
final String filename); } | @Test public void testSendFeedbackReturnsOk() throws Exception { stubFor(post(urlPathEqualTo("/v2/feedback.add")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBodyFile("feedback-ok.json"))); Result result = apiClient.sendFeedback(1234, "Comments I want to make", "My Name", "[email protected]"); verify(postRequestedFor(urlPathEqualTo("/v2/feedback.add")) .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded")) .withRequestBody(matching("type=routing&itinerary=1234&comments=Comments%20I%20want%20to%20make&name=My%20Name&email=ballboy%40wimbledon.com")) .withQueryParam("key", equalTo("myApiKey"))); assertThat(result.ok()).isTrue(); assertThat(result.message()).contains("Thank you for submitting this feedback"); } |
MixPanelOutputConnector extends AbstractPipelineComponent implements OutputConnector, Configurable<JSONObject> { protected void setUserProfile(JSONObject payload) throws JSONException, IOException { JSONObject properties = payload.optJSONObject("properties"); MixpanelAPI mixpanel = getMixpanelAPI(); MessageBuilder messageBuilder = new MessageBuilder(token); String distinct_id = payload.getString("distinct_id"); if (properties == null) { properties = new JSONObject(); } JSONObject mixPanelMessage = messageBuilder.set(distinct_id, properties); String ip = payload.optString("ip", null); if (ip != null) { JSONUtil.setValue(mixPanelMessage, ip, "message", "$ip"); } Long time = payload.optLong("time", 0L); if (time != 0L) { JSONUtil.setValue(mixPanelMessage, time, "message", "$time"); } sendMessageToMixpanel(mixpanel, mixPanelMessage); } @Override void setConfiguration(JSONObject jsonObject); @Override Message send(Message message); } | @Test public void test_set_profile() throws Exception { MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() { @Override protected MixpanelAPI getMixpanelAPI() { return new MixpanelAPI(null, mockMixpanelServer.getServerURL() + "/engage"); } }; mixPanelOutputConnector.setPipelineContext(getMockPipelineContext()); mockMixpanelServer.addRequestResponse(new RequestResponse() .setExpectedRequestURI(mockMixpanelServer.getServerURL() + "/engage") .setExpectedRequestParam("data", "W3siJHRpbWUiOjEyNDU2MTM4ODUwMDAsIiRkaXN0aW5jdF9pZCI6IjUwNDc5YjI0NjcxYmYiLCIkc2V0Ijp7Ik5hbWUiOiJNYXJrIERvd25lcyIsIkVtYWlsIjoibWRAeC5jb20ifSwiJGlwIjoiMTI3LjAuMC4xIn1d") .setResponsePayload("1") ); mixPanelOutputConnector.setUserProfile(new JSONObject(SAMPLE_SET_PROFILE)); mockMixpanelServer.waitForAllRequestsToComplete(); mockMixpanelServer.assertAllRequestsCompleteOK(); } |
MixPanelOutputConnector extends AbstractPipelineComponent implements OutputConnector, Configurable<JSONObject> { protected void logActivity(JSONObject payload) throws JSONException, IOException { String eventName = payload.getString("event"); JSONObject properties = payload.getJSONObject("properties"); Long time = properties.optLong("time", 0L); if (time == 0L) { time = System.currentTimeMillis(); } time = time/1000; properties.put("time", time); MixpanelAPI mixpanel = getMixpanelAPI(); MessageBuilder messageBuilder = new MessageBuilder(token); String distinct_id = properties.getString("distinct_id"); JSONObject mixPanelMessage = messageBuilder.event(distinct_id, eventName, properties); sendMessageToMixpanel(mixpanel, mixPanelMessage); } @Override void setConfiguration(JSONObject jsonObject); @Override Message send(Message message); } | @Test public void test_event() throws Exception { MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() { @Override protected MixpanelAPI getMixpanelAPI() { return new MixpanelAPI(mockMixpanelServer.getServerURL() + "/track", null); } }; mixPanelOutputConnector.setPipelineContext(getMockPipelineContext()); mockMixpanelServer.addRequestResponse(new RequestResponse() .setExpectedRequestURI(mockMixpanelServer.getServerURL() + "/track?ip=0") .setExpectedRequestParam("data", "W3siZXZlbnQiOiJnYW1lIiwicHJvcGVydGllcyI6eyJ0aW1lIjoxMjQ1NjEzODg1LCJkaXN0aW5jdF9pZCI6IjUwNDc5YjI0NjcxYmYiLCJ0b2tlbiI6ImUzYmM0MTAwMzMwYzM1NzIyNzQwZmI4YzZmNWFiZGRjIiwiYWN0aW9uIjoicGxheSIsIm1wX2xpYiI6ImpkayIsImlwIjoiMTIzLjEyMy4xMjMuMTIzIn19XQ==") .setResponsePayload("1") ); mixPanelOutputConnector.logActivity(new JSONObject(SAMPLE_EVENT)); mockMixpanelServer.waitForAllRequestsToComplete(); mockMixpanelServer.assertAllRequestsCompleteOK(); } |
MixPanelOutputConnector extends AbstractPipelineComponent implements OutputConnector, Configurable<JSONObject> { protected void deleteUserProfile(JSONObject payload) throws JSONException, IOException { MixpanelAPI mixpanel = getMixpanelAPI(); MessageBuilder messageBuilder = new MessageBuilder(token); String distinct_id = payload.getString("distinct_id"); JSONObject mixPanelMessage = messageBuilder.set(distinct_id, null); JSONUtil.removeValue(mixPanelMessage, "message", "$set"); JSONUtil.setValue(mixPanelMessage, "", "message", "$delete"); Long time = payload.optLong("time", 0L); if (time != 0L) { JSONUtil.setValue(mixPanelMessage, time, "message", "$time"); } sendMessageToMixpanel(mixpanel, mixPanelMessage); } @Override void setConfiguration(JSONObject jsonObject); @Override Message send(Message message); } | @Test public void test_delete_profile() throws Exception { MixPanelOutputConnector mixPanelOutputConnector = new MixPanelOutputConnector() { @Override protected MixpanelAPI getMixpanelAPI() { return new MixpanelAPI(null, mockMixpanelServer.getServerURL() + "/engage"); } }; mixPanelOutputConnector.setPipelineContext(getMockPipelineContext()); mockMixpanelServer.addRequestResponse(new RequestResponse() .setExpectedRequestURI(mockMixpanelServer.getServerURL() + "/engage") .setExpectedRequestParam("data", "W3siJHRpbWUiOjEyNDU2MTM4ODUwMDAsIiRkaXN0aW5jdF9pZCI6IjUwNDc5YjI0NjcxYmYiLCIkZGVsZXRlIjoiIn1d") .setResponsePayload("1") ); mixPanelOutputConnector.deleteUserProfile(new JSONObject(SAMPLE_DELETE_PROFILE)); mockMixpanelServer.waitForAllRequestsToComplete(); mockMixpanelServer.assertAllRequestsCompleteOK(); } |
RxSwtPlugins { public static Scheduler onMainThreadScheduler(Scheduler scheduler) { if (scheduler == null) { throw new NullPointerException("scheduler == null"); } Function<Scheduler, Scheduler> f = onMainThreadHandler; if (f == null) { return scheduler; } return apply(f, scheduler); } private RxSwtPlugins(); static void setInitMainThreadSchedulerHandler(Function<Callable<Scheduler>, Scheduler> handler); static Scheduler initMainThreadScheduler(Callable<Scheduler> scheduler); static void setMainThreadSchedulerHandler(Function<Scheduler, Scheduler> handler); static Scheduler onMainThreadScheduler(Scheduler scheduler); static Function<Callable<Scheduler>, Scheduler> getInitMainThreadSchedulerHandler(); static Function<Scheduler, Scheduler> getOnMainThreadSchedulerHandler(); static void reset(); } | @Test(expected = NullPointerException.class) public void testNullSchedulerThrowsNPE() { RxSwtPlugins.onMainThreadScheduler(null); } |
Preconditions { public static boolean checkWidget(Observer<?> observer, Widget widget) { if (null == widget) { observer.onError(new NullPointerException("The given widget was null")); return false; } else if (widget.isDisposed()) { observer.onError(new IllegalStateException("The given widget is diposed")); return false; } else if (!(Thread.currentThread().equals(widget.getDisplay().getThread()))) { observer.onError(new IllegalStateException( "Expected to be called on the main thread but was " + Thread.currentThread().getName())); return false; } return true; } private Preconditions(); static boolean checkWidget(Observer<?> observer, Widget widget); static boolean checkDisplay(Observer<?> observer, Display display); } | @Test public void testCheckWidgetWithNullWidget() { TestObserver<?> testObserver = getEmptySubscribedTestObserver(); boolean checkWidget = Preconditions.checkWidget(testObserver, null); assertThat(checkWidget, is(false)); testObserver.assertError(NullPointerException.class); testObserver.assertErrorMessage("The given widget was null"); }
@Test public void testCheckWidgetCalledFromMainThread() { TestObserver<?> testObserver = TestObserver.create(); boolean checkWidget = Preconditions.checkWidget(testObserver, shell); assertThat(checkWidget, is(true)); testObserver.assertNoErrors(); }
@Test public void testCheckWidgetCalledFromNonMainThread() throws InterruptedException, TimeoutException { TestObserver<?> testObserver = getEmptySubscribedTestObserver(); AtomicBoolean atomic = new AtomicBoolean(false); Thread thread = new Thread(() -> { boolean checkWidget = Preconditions.checkWidget(testObserver, shell); assertThat(checkWidget, is(false)); testObserver.assertError(IllegalStateException.class); testObserver.assertErrorMessage( "Expected to be called on the main thread but was " + Thread.currentThread().getName()); atomic.set(true); }); thread.start(); await().untilTrue(atomic); }
@Test public void testCheckWidgetWithDisposedWidget() { TestObserver<?> testObserver = getEmptySubscribedTestObserver(); shell.dispose(); boolean checkWidget = Preconditions.checkWidget(testObserver, shell); assertThat(checkWidget, is(false)); testObserver.assertError(IllegalStateException.class); testObserver.assertErrorMessage("The given widget is diposed"); } |
RxSwtPlugins { static Scheduler callRequireNonNull(Callable<Scheduler> s) { try { Scheduler scheduler = s.call(); if (scheduler == null) { throw new NullPointerException("Scheduler Callable returned null"); } return scheduler; } catch (Throwable ex) { throw Exceptions.propagate(ex); } } private RxSwtPlugins(); static void setInitMainThreadSchedulerHandler(Function<Callable<Scheduler>, Scheduler> handler); static Scheduler initMainThreadScheduler(Callable<Scheduler> scheduler); static void setMainThreadSchedulerHandler(Function<Scheduler, Scheduler> handler); static Scheduler onMainThreadScheduler(Scheduler scheduler); static Function<Callable<Scheduler>, Scheduler> getInitMainThreadSchedulerHandler(); static Function<Scheduler, Scheduler> getOnMainThreadSchedulerHandler(); static void reset(); } | @Test(expected = NullPointerException.class) public void testcallRequireNonNullThrowsNPE() { RxSwtPlugins.callRequireNonNull(null); } |
RxSwtPlugins { static Scheduler applyRequireNonNull(Function<Callable<Scheduler>, Scheduler> f, Callable<Scheduler> s) { Scheduler scheduler = apply(f,s); if (scheduler == null) { throw new NullPointerException("Scheduler Callable returned null"); } return scheduler; } private RxSwtPlugins(); static void setInitMainThreadSchedulerHandler(Function<Callable<Scheduler>, Scheduler> handler); static Scheduler initMainThreadScheduler(Callable<Scheduler> scheduler); static void setMainThreadSchedulerHandler(Function<Scheduler, Scheduler> handler); static Scheduler onMainThreadScheduler(Scheduler scheduler); static Function<Callable<Scheduler>, Scheduler> getInitMainThreadSchedulerHandler(); static Function<Scheduler, Scheduler> getOnMainThreadSchedulerHandler(); static void reset(); } | @Test(expected = NullPointerException.class) public void testapplyRequireNonNullThrowsNPE() { RxSwtPlugins.applyRequireNonNull(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(Callable<Scheduler> t) throws Exception { return null; } }, null); } |
RxSwtPlugins { public static Scheduler initMainThreadScheduler(Callable<Scheduler> scheduler) { if (scheduler == null) { throw new NullPointerException("scheduler == null"); } Function<Callable<Scheduler>, Scheduler> f = onInitMainThreadHandler; if (f == null) { return callRequireNonNull(scheduler); } return applyRequireNonNull(f, scheduler); } private RxSwtPlugins(); static void setInitMainThreadSchedulerHandler(Function<Callable<Scheduler>, Scheduler> handler); static Scheduler initMainThreadScheduler(Callable<Scheduler> scheduler); static void setMainThreadSchedulerHandler(Function<Scheduler, Scheduler> handler); static Scheduler onMainThreadScheduler(Scheduler scheduler); static Function<Callable<Scheduler>, Scheduler> getInitMainThreadSchedulerHandler(); static Function<Scheduler, Scheduler> getOnMainThreadSchedulerHandler(); static void reset(); } | @Test public void overrideInitMainSchedulerThrowsWhenSchedulerCallableIsNull() { try { RxSwtPlugins.initMainThreadScheduler(null); fail(); } catch (NullPointerException e) { assertEquals("scheduler == null", e.getMessage()); } }
@Test public void overrideInitMainSchedulerThrowsWhenSchedulerCallableReturnsNull() { Callable<Scheduler> nullResultCallable = new Callable<Scheduler>() { @Override public Scheduler call() throws Exception { return null; } }; try { RxSwtPlugins.initMainThreadScheduler(nullResultCallable); fail(); } catch (NullPointerException e) { assertEquals("Scheduler Callable returned null", e.getMessage()); } } |
SwtSchedulers { public static Scheduler defaultDisplayThread() { return RxSwtPlugins.onMainThreadScheduler(DEFAULT_DISPLAY_THREAD); } private SwtSchedulers(); static Scheduler defaultDisplayThread(); static Scheduler from(Display display); } | @Test public void testMainThreadCallsThroughToHookTest() { final AtomicInteger called = new AtomicInteger(); final Scheduler newScheduler = new EmptyScheduler(); RxSwtPlugins.setMainThreadSchedulerHandler(new Function<Scheduler, Scheduler>() { @Override public Scheduler apply(Scheduler scheduler) { called.getAndIncrement(); return newScheduler; } }); assertSame(newScheduler, SwtSchedulers.defaultDisplayThread()); assertEquals(1, called.get()); assertSame(newScheduler, SwtSchedulers.defaultDisplayThread()); assertEquals(2, called.get()); } |
SwtSchedulers { public static Scheduler from(Display display) { return RxSwtPlugins.onMainThreadScheduler(new DisplayScheduler(display)); } private SwtSchedulers(); static Scheduler defaultDisplayThread(); static Scheduler from(Display display); } | @Test public void fromNullThrows() { try { SwtSchedulers.from(null); } catch (NullPointerException e) { fail("Calling SwtSchedulers.from(null) should not result in an NPE, but use the default display."); } } |
OsgiLocator { public static <T> Class<T> locate(Class<T> factoryId) { return locate(factoryId, factoryId.getName()); } private OsgiLocator(); static void unregister(String id, Callable<Class> factory); static void register(String id, Callable<Class> factory); static Class<T> locate(Class<T> factoryId); static Class<T> locate(Class<T> factoryClass, String factoryId); static List<Class<? extends T>> locateAll(Class<T> factoryId); static List<Class<? extends T>> locateAll(Class<T> factoryClass, String factoryId); static final long DEFAULT_TIMEOUT; static final String TIMEOUT; } | @Test public void testLocatorWithSystemProperty() { System.setProperty(OsgiLocator.TIMEOUT, "0"); System.setProperty("Factory", "org.apache.karaf.specs.locator.MockCallable"); Class clazz = OsgiLocator.locate(Object.class, "Factory"); assertNotNull("Expected to find a class", clazz); assertEquals("Got the wrong class", MockCallable.class.getName(), clazz.getName()); System.setProperty("Factory", "org.apache.karaf.specs.locator"); clazz = OsgiLocator.locate(Object.class, "Factory"); assertNull("Did not expect to find a class", clazz); }
@Test public void testLocatorWithoutSystemProperty() { System.setProperty(OsgiLocator.TIMEOUT, "0"); System.clearProperty("Factory"); Class clazz = OsgiLocator.locate(Object.class, "Factory"); assertNotNull("Expected to find a class", clazz); assertEquals("Got the wrong class", MockCallable2.class.getName(), clazz.getName()); }
@Test public void testLocatorWithSystemPropertyAndTimeout() { long timeout = 1000; System.setProperty(OsgiLocator.TIMEOUT, Long.toString(timeout)); System.setProperty("Factory", "org.apache.karaf.specs.locator.MockCallable"); Class clazz = OsgiLocator.locate(Object.class, "Factory"); assertNotNull("Expected to find a class", clazz); assertEquals("Got the wrong class.", MockCallable.class.getName(), clazz.getName()); System.setProperty("Factory", "org.apache.karaf.specs.locator"); long t0 = System.currentTimeMillis(); clazz = OsgiLocator.locate(Object.class, "Factory"); long t1 = System.currentTimeMillis(); assertNull("Did not expect to find a class", clazz); assertTrue("Timeout issue", (t1 - t0) > timeout / 2); }
@Test public void testLocatorWithoutSystemPropertyAndTimeout() { long timeout = 1000; System.setProperty(OsgiLocator.TIMEOUT, Long.toString(timeout)); System.clearProperty("Factory"); long t0 = System.currentTimeMillis(); Class clazz = OsgiLocator.locate(Object.class, "Factory"); long t1 = System.currentTimeMillis(); assertNotNull("Expected to find a class", clazz); assertEquals("Got the wrong class", MockCallable2.class.getName(), clazz.getName()); assertTrue("Timeout issue", (t1 - t0) < timeout / 2); } |
RunMojo extends MojoSupport { void deploy(BundleContext bundleContext, Object featureService) throws MojoExecutionException { if (deployProjectArtifact) { File artifact = getProjectArtifact(); File attachedFeatureFile = getAttachedFeatureFile(project); boolean artifactExists = artifact != null && artifact.exists(); if (!artifactExists) { artifact = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".jar"); artifactExists = artifact != null && artifact.exists(); } boolean attachedFeatureFileExists = attachedFeatureFile != null && attachedFeatureFile.exists(); if (attachedFeatureFileExists) { getLog().info("Deploying features repository " + attachedFeatureFile.getAbsolutePath()); addFeaturesAttachmentAsFeatureRepository(featureService, attachedFeatureFile); } else if (artifactExists) { try { getLog().info("Deploying bundle " + artifact.getAbsolutePath()); Bundle bundle = bundleContext.installBundle(artifact.toURI().toURL().toString()); bundle.start(); } catch (Exception e) { throw new MojoExecutionException("Can't deploy project artifact in container", e); } } else { throw new MojoExecutionException("No artifact to deploy"); } getLog().info("Artifact deployed"); } } void execute(); static void extract(File sourceFile, File targetFolder); } | @Test public void testDeployWithNullArtifact() throws SecurityException, IllegalArgumentException, IllegalAccessException { BundleContext context = mock(BundleContext.class); Artifact artifact = mock(Artifact.class); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setArtifact(artifact); setPrivateField(mojo, "project", project); try { mojo.deploy(context, null); fail("Expected MojoExecutionException"); } catch (MojoExecutionException e) { assertEquals("No artifact to deploy", e.getMessage()); } }
@Test public void testDeployWithNonExistingArtifact() throws SecurityException, IllegalArgumentException, IllegalAccessException { BundleContext context = mock(BundleContext.class); Artifact artifact = mock(Artifact.class); File artifactFile = mock(File.class); expect(artifact.getFile()).andReturn(artifactFile); expect(artifactFile.exists()).andReturn(false).times(2); replay(artifactFile); replay(artifact); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setArtifact(artifact); setPrivateField(mojo, "project", project); try { mojo.deploy(context, null); fail("Expected MojoExecutionException"); } catch (MojoExecutionException e) { assertEquals("No artifact to deploy", e.getMessage()); } }
@Test public void testDeployWithExistingArtifactButProjectNotBundle() throws SecurityException, IllegalArgumentException, IllegalAccessException { BundleContext context = mock(BundleContext.class); Artifact artifact = mock(Artifact.class); File artifactFile = mock(File.class); expect(artifactFile.exists()).andReturn(true).times(2); expect(artifactFile.getAbsolutePath()).andReturn("foo.jar").times(1); expect(artifactFile.toURI()).andReturn(URI.create("file: replay(artifactFile); expect(artifact.getFile()).andReturn(artifactFile); replay(artifact); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setArtifact(artifact); setPrivateField(mojo, "project", project); try { mojo.deploy(context, null); fail("Expected MojoExecutionException"); } catch (MojoExecutionException e) { assertEquals("Can't deploy project artifact in container", e.getMessage()); } }
@Test public void testDeployWithExistingArtifactFailsInInstall() throws SecurityException, IllegalArgumentException, IllegalAccessException { BundleContext context = mock(BundleContext.class); Artifact artifact = mock(Artifact.class); File artifactFile = niceMock(File.class); expect(artifactFile.exists()).andReturn(true).times(2); replay(artifactFile); expect(artifact.getFile()).andReturn(artifactFile); replay(artifact); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setPackaging("bundle"); project.setArtifact(artifact); setPrivateField(mojo, "project", project); try { mojo.deploy(context, null); fail("Expected MojoExecutionException"); } catch (MojoExecutionException e) { assertEquals("Can't deploy project artifact in container", e.getMessage()); } }
@Test public void testDeployWithExistingArtifact() throws SecurityException, IllegalArgumentException, IllegalAccessException, IOException, BundleException, MojoExecutionException { BundleContext context = niceMock(BundleContext.class); Bundle bundle = niceMock(Bundle.class); expect(context.installBundle(anyString())).andReturn(bundle); replay(context); Artifact artifact = mock(Artifact.class); File artifactFile = File.createTempFile("fake-bundle", ".jar"); try { expect(artifact.getFile()).andReturn(artifactFile); replay(artifact); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setPackaging("bundle"); project.setArtifact(artifact); setPrivateField(mojo, "project", project); replay(bundle); mojo.deploy(context, null); verify(bundle); } finally { artifactFile.delete(); } }
@Test public void testDeployWithPomArtifactAndAttachedFeatureXmlNoFeatureService() throws SecurityException, IllegalArgumentException, IllegalAccessException, IOException, BundleException, MojoExecutionException { File artifactFeaturesAttachmentFile = File.createTempFile("someproject-features", ".xml"); try { BundleContext context = niceMock(BundleContext.class); Bundle bundle = niceMock(Bundle.class); expect(context.installBundle(anyString())).andReturn(bundle); replay(context); Artifact artifact = niceMock(Artifact.class); replay(artifact); Artifact artifactFeaturesAttachment = mock(Artifact.class); expect(artifactFeaturesAttachment.getFile()).andReturn(artifactFeaturesAttachmentFile); expect(artifactFeaturesAttachment.getClassifier()).andReturn("features"); expect(artifactFeaturesAttachment.getType()).andReturn("xml"); replay(artifactFeaturesAttachment); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setPackaging("pom"); project.setArtifact(artifact); project.addAttachedArtifact(artifactFeaturesAttachment); setPrivateField(mojo, "project", project); replay(bundle); try { mojo.deploy(context, null); fail("Expected MojoExecutionException"); } catch (MojoExecutionException e) { assertEquals("Failed to find the FeatureService when adding a feature repository", e.getMessage()); } } finally { artifactFeaturesAttachmentFile.delete(); } }
@SuppressWarnings("unchecked") @Test public void testDeployWithPomArtifactAndAttachedFeatureXmlRepoRegistrationFails() throws Exception { File artifactFeaturesAttachmentFile = File.createTempFile("someproject-features", ".xml"); try { FeaturesService featureService = niceMock(FeaturesService.class); featureService.addRepository(anyObject(URI.class)); EasyMock.expectLastCall().andThrow(new Exception("Not a feature repository")); replay(featureService); ServiceReference<FeaturesService> ref = niceMock(ServiceReference.class); BundleContext context = niceMock(BundleContext.class); expect(context.getServiceReference(eq(FeaturesService.class))).andReturn(ref); expect(context.getService(eq(ref))).andReturn(featureService); replay(context); Artifact artifact = niceMock(Artifact.class); replay(artifact); Artifact artifactFeaturesAttachment = mock(Artifact.class); expect(artifactFeaturesAttachment.getFile()).andReturn(artifactFeaturesAttachmentFile); expect(artifactFeaturesAttachment.getClassifier()).andReturn("features"); expect(artifactFeaturesAttachment.getType()).andReturn("xml"); replay(artifactFeaturesAttachment); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setPackaging("pom"); project.setArtifact(artifact); project.addAttachedArtifact(artifactFeaturesAttachment); setPrivateField(mojo, "project", project); try { mojo.deploy(context, featureService); fail("Expected MojoExecutionException"); } catch (MojoExecutionException e) { assertEquals("Failed to register attachment as feature repository", e.getMessage()); } } finally { artifactFeaturesAttachmentFile.delete(); } }
@SuppressWarnings("unchecked") @Test public void testDeployWithPomArtifactAndAttachedFeatureXmlAndNoFeatures() throws Exception { File artifactFeaturesAttachmentFile = File.createTempFile("someproject-features", ".xml"); try { FeaturesService featureService = niceMock(FeaturesService.class); replay(featureService); ServiceReference<FeaturesService> ref = niceMock(ServiceReference.class); BundleContext context = niceMock(BundleContext.class); expect(context.getServiceReference(eq(FeaturesService.class))).andReturn(ref); expect(context.getService(eq(ref))).andReturn(featureService); replay(context); Artifact artifact = niceMock(Artifact.class); replay(artifact); Artifact artifactFeaturesAttachment = mock(Artifact.class); expect(artifactFeaturesAttachment.getFile()).andReturn(artifactFeaturesAttachmentFile); expect(artifactFeaturesAttachment.getClassifier()).andReturn("features"); expect(artifactFeaturesAttachment.getType()).andReturn("xml"); replay(artifactFeaturesAttachment); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setPackaging("pom"); project.setArtifact(artifact); project.addAttachedArtifact(artifactFeaturesAttachment); setPrivateField(mojo, "project", project); mojo.deploy(context, featureService); verify(featureService); } finally { artifactFeaturesAttachmentFile.delete(); } }
@SuppressWarnings("unchecked") @Test public void testDeployWithPomArtifactAndAttachedFeatureXml() throws Exception { File artifactFeaturesAttachmentFile = File.createTempFile("someproject-features", ".xml"); try { FeaturesService featureService = niceMock(FeaturesService.class); replay(featureService); ServiceReference<FeaturesService> ref = niceMock(ServiceReference.class); BundleContext context = niceMock(BundleContext.class); expect(context.getServiceReference(eq(FeaturesService.class))).andReturn(ref); expect(context.getService(eq(ref))).andReturn(featureService); replay(context); Artifact artifact = niceMock(Artifact.class); replay(artifact); Artifact artifactFeaturesAttachment = mock(Artifact.class); expect(artifactFeaturesAttachment.getFile()).andReturn(artifactFeaturesAttachmentFile); expect(artifactFeaturesAttachment.getClassifier()).andReturn("features"); expect(artifactFeaturesAttachment.getType()).andReturn("xml"); replay(artifactFeaturesAttachment); RunMojo mojo = new RunMojo(); MavenProject project = new MavenProject(); project.setPackaging("pom"); project.setArtifact(artifact); project.addAttachedArtifact(artifactFeaturesAttachment); setPrivateField(mojo, "project", project); setPrivateField(mojo, "featuresToInstall", "liquibase-core, ukelonn-db-derby-test, ukelonn"); String[] featureRepos = { "mvn:org.ops4j.pax.jdbc/pax-jdbc-features/LATEST/xml/features" }; setPrivateField(mojo, "featureRepositories", featureRepos); mojo.deploy(context, featureService); verify(featureService); } finally { artifactFeaturesAttachmentFile.delete(); } }
@Test public void testDeployWithDeployProjectArtifactFalse() throws SecurityException, IllegalArgumentException, IllegalAccessException, MojoExecutionException { BundleContext context = mock(BundleContext.class); RunMojo mojo = new RunMojo(); setPrivateField(mojo, "deployProjectArtifact", false); mojo.deploy(context, null); } |
RunMojo extends MojoSupport { void addFeatures(Object featureService) throws MojoExecutionException { if (featuresToInstall != null) { try { Class<? extends Object> serviceClass = featureService.getClass(); Method installFeatureMethod = serviceClass.getMethod("installFeature", String.class); String[] features = featuresToInstall.split(" *, *"); for (String feature : features) { installFeatureMethod.invoke(featureService, feature); Thread.sleep(1000L); } } catch (Exception e) { throw new MojoExecutionException("Failed to add features to karaf", e); } } } void execute(); static void extract(File sourceFile, File targetFolder); } | @Test public void testAddFeaturesNullFeaturesToInstall() throws MojoExecutionException { FeaturesService featureService = mock(FeaturesService.class); replay(featureService); RunMojo mojo = new RunMojo(); mojo.addFeatures(featureService); verify(featureService); }
@Test public void testAddFeaturesNullFeatureService() throws SecurityException, IllegalArgumentException, IllegalAccessException { RunMojo mojo = new RunMojo(); setPrivateField(mojo, "featuresToInstall", "liquibase-core, ukelonn-db-derby-test, ukelonn"); try { mojo.addFeatures(null); } catch (MojoExecutionException e) { assertEquals("Failed to add features to karaf", e.getMessage()); } }
@Test public void testAddFeatures() throws Exception { FeaturesService featureService = mock(FeaturesService.class); featureService.installFeature(anyString()); EasyMock.expectLastCall().times(3); replay(featureService); RunMojo mojo = new RunMojo(); setPrivateField(mojo, "featuresToInstall", "liquibase-core, ukelonn-db-derby-test, ukelonn"); mojo.addFeatures(featureService); verify(featureService); } |
ServerKeyVerifierImpl implements ServerKeyVerifier { @Override public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress, PublicKey serverKey) { PublicKey knownKey; try { knownKey = knownHostsManager.getKnownKey(remoteAddress, serverKey.getAlgorithm()); } catch (InvalidKeySpecException e) { System.err.println("Invalid key stored for host " + remoteAddress + ". Terminating session."); return false; } if (knownKey == null) { boolean confirm; if (!quiet) { System.out.println("Connecting to unknown server. Add this server to known hosts ? (y/n)"); confirm = getConfirmation(); } else { System.out.println("Connecting to unknown server. Automatically adding to known hosts."); confirm = true; } if (confirm) { knownHostsManager.storeKeyForHost(remoteAddress, serverKey); System.out.println("Storing the server key in known_hosts."); } else { System.out.println("Aborting connection"); } return confirm; } boolean verifed = (knownKey.equals(serverKey)); if (!verifed) { System.err.println("Server key for host " + remoteAddress + " does not match the stored key !! Terminating session."); System.err.println(keyChangedMessage); } return verifed; } ServerKeyVerifierImpl(KnownHostsManager knownHostsManager, boolean quiet); @Override boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress,
PublicKey serverKey); } | @Test public void testKnownAndCorrectKey() throws NoSuchAlgorithmException, InvalidKeySpecException { SocketAddress address = LOCALHOST; PublicKey validServerKey = createPubKey(); KnownHostsManager knowHostsManager = EasyMock.createMock(KnownHostsManager.class); EasyMock.expect(knowHostsManager.getKnownKey(address, ALGORITHM)).andReturn(validServerKey); EasyMock.replay(knowHostsManager); ServerKeyVerifierImpl verifier = new ServerKeyVerifierImpl(knowHostsManager, true); boolean verified = verifier.verifyServerKey(null, address, validServerKey); Assert.assertTrue("Key should be verified as the key is known and matches the key we verify", verified); }
@Test public void testKnownAndIncorrectKey() throws NoSuchAlgorithmException, InvalidKeySpecException { SocketAddress address = LOCALHOST; PublicKey validServerKey = createPubKey(); PublicKey otherServerKey = createPubKey(); KnownHostsManager knowHostsManager = EasyMock.createMock(KnownHostsManager.class); EasyMock.expect(knowHostsManager.getKnownKey(address, ALGORITHM)).andReturn(otherServerKey); EasyMock.replay(knowHostsManager); ServerKeyVerifierImpl verifier = new ServerKeyVerifierImpl(knowHostsManager, true); boolean verified = verifier.verifyServerKey(null, address, validServerKey); Assert.assertFalse("Key should not be verified as the key is known and does not match the key we verify", verified); }
@Test public void testNewKey() throws NoSuchAlgorithmException, InvalidKeySpecException { SocketAddress address = LOCALHOST; PublicKey validServerKey = createPubKey(); KnownHostsManager knowHostsManager = EasyMock.createMock(KnownHostsManager.class); EasyMock.expect(knowHostsManager.getKnownKey(address, ALGORITHM)).andReturn(null); knowHostsManager.storeKeyForHost(address, validServerKey); EasyMock.expectLastCall(); EasyMock.replay(knowHostsManager); ServerKeyVerifierImpl verifier = new ServerKeyVerifierImpl(knowHostsManager, true); boolean verified = verifier.verifyServerKey(null, address, validServerKey); Assert.assertTrue("Key should be verified as the key is new", verified); } |
RunMojo extends MojoSupport { @SuppressWarnings({ "rawtypes", "unchecked" }) Object findFeatureService(BundleContext bundleContext) { ServiceReference ref = bundleContext.getServiceReference(FeaturesService.class); if (ref != null) { Object featureService = bundleContext.getService(ref); return featureService; } return null; } void execute(); static void extract(File sourceFile, File targetFolder); } | @Test public void testFindFeatureServiceNullServiceRef() { BundleContext context = niceMock(BundleContext.class); replay(context); RunMojo mojo = new RunMojo(); Object service = mojo.findFeatureService(context); assertNull(service); }
@SuppressWarnings("unchecked") @Test public void testFindFeatureService() { FeaturesService featureService = niceMock(FeaturesService.class); replay(featureService); ServiceReference<FeaturesService> ref = niceMock(ServiceReference.class); BundleContext context = niceMock(BundleContext.class); expect(context.getServiceReference(eq(FeaturesService.class))).andReturn(ref); expect(context.getService(eq(ref))).andReturn(featureService); replay(context); RunMojo mojo = new RunMojo(); Object service = mojo.findFeatureService(context); assertNotNull(service); } |
ClientConfig { public String getUser() { return user; } ClientConfig(String[] args); String getHost(); int getPort(); String getUser(); void setUser(String user); String getPassword(); int getLevel(); int getRetryAttempts(); int getRetryDelay(); String getCommand(); void setCommand(String command); boolean isBatch(); String getFile(); String getKeyFile(); long getIdleTimeout(); } | @Test public void testDefaultUser() throws Exception { String etc = System.getProperty("karaf.etc"); System.setProperty("karaf.etc", "src/test/resources/etc1"); ClientConfig cc = new ClientConfig(new String[0]); assertThat(cc.getUser(), equalTo("karaf")); cc = new ClientConfig(new String[] { "-u", "different-one" }); assertThat(cc.getUser(), equalTo("different-one")); System.setProperty("karaf.etc", "src/test/resources/etc2"); cc = new ClientConfig(new String[0]); assertThat(cc.getUser(), equalTo("test")); if (etc != null) { System.setProperty("karaf.etc", etc); } } |
StoredWiringResolver implements ResolverHook { void load() { try { Files.createDirectories(path); Files.list(path).forEach(p -> { String name = p.getFileName().toString(); if (name.matches("[0-9]+")) { long id = Long.parseLong(name); try (BufferedReader reader = Files.newBufferedReader(p)) { wiring.put(id, new BundleWires(id, reader)); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } catch (IOException e) { throw new UncheckedIOException(e); } } StoredWiringResolver(Path path); @Override void filterResolvable(Collection<BundleRevision> candidates); @Override void filterSingletonCollisions(BundleCapability singleton,
Collection<BundleCapability> collisionCandidates); @Override void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates); @Override void end(); } | @Test public void load() { Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertTrue(wiringResolver.wiring.containsKey(1L)); Assert.assertTrue(wiringResolver.wiring.containsKey(5L)); Assert.assertTrue(wiringResolver.wiring.containsKey(9L)); } |
StoredWiringResolver implements ResolverHook { @Override public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) { long[] requirementSourceBundleIds = getRequirementBundleIds(requirement); Set<BundleCapability> goodCapabilityCandidates = new HashSet<>(); for ( long requirementBundleId : requirementSourceBundleIds ) { BundleWires bundleWires = wiring.get(requirementBundleId); goodCapabilityCandidates.addAll( bundleWires.filterCandidates( requirement, candidates ) ); } candidates.retainAll( goodCapabilityCandidates ); } StoredWiringResolver(Path path); @Override void filterResolvable(Collection<BundleRevision> candidates); @Override void filterSingletonCollisions(BundleCapability singleton,
Collection<BundleCapability> collisionCandidates); @Override void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates); @Override void end(); } | @Test public void filterMatches() { List<BundleCapability> candidates = new ArrayList<>(); long sourceBundleId = 1L; long targetBundleId = 2L; String targetBundleVersion = "1.0.1"; BundleCapability candidate1 = mockBundleCapability(targetBundleId, targetBundleVersion); candidates.add(candidate1); BundleCapability candidate2 = mockBundleCapability(targetBundleId, "2.1.0"); candidates.add(candidate2); BundleRequirement req = packageRequirement(sourceBundleId, false); c.replay(); wiringResolver.filterMatches(req, candidates); c.verify(); assertEquals(1, candidates.size()); assertEquals(candidate1, candidates.iterator().next()); }
@Test public void filterMatchesFragmentBundle() { List<BundleCapability> candidates = new ArrayList<>(); long sourceBundleId = 5L; long targetBundleId = 2L; String targetBundleVersion = "1.0.1"; BundleCapability candidate1 = mockBundleCapability(targetBundleId, targetBundleVersion); candidates.add(candidate1); BundleCapability candidate2 = mockBundleCapability(targetBundleId, "2.1.0"); candidates.add(candidate2); BundleRequirement req = packageRequirement(sourceBundleId, true); c.replay(); wiringResolver.filterMatches(req, candidates); c.verify(); assertEquals(1, candidates.size()); assertEquals(candidate1, candidates.iterator().next()); } |
StoredWiringResolver implements ResolverHook { synchronized void update(Bundle bundle) { BundleWires bw = new BundleWires(bundle); bw.save(path); wiring.put(bundle.getBundleId(), bw); } StoredWiringResolver(Path path); @Override void filterResolvable(Collection<BundleRevision> candidates); @Override void filterSingletonCollisions(BundleCapability singleton,
Collection<BundleCapability> collisionCandidates); @Override void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates); @Override void end(); } | @Test public void updateNew() { long newBundleId = 25L; File file = new File(TEST_RESOURCES_WIRINGS + newBundleId); Bundle bundle = wiredMockBundle(newBundleId, Collections.emptyList() ); c.replay(); Assert.assertFalse(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertFalse(wiringResolver.wiring.containsKey(newBundleId)); wiringResolver.update(bundle); c.verify(); Assert.assertTrue(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS + 1, wiringResolver.wiring.size()); Assert.assertTrue(wiringResolver.wiring.containsKey(newBundleId)); }
@Test public void updateExisting() { long newBundleId = 9L; File file = new File(TEST_RESOURCES_WIRINGS + newBundleId); BundleWire wire = mockBundleWire(PackageNamespace.PACKAGE_NAMESPACE, PACKAGE_FILTER, mockBundleCapability(25L, "1.7.8")); Bundle bundle = wiredMockBundle(newBundleId, Collections.singletonList(wire)); c.replay(); Assert.assertTrue(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertTrue(wiringResolver.wiring.containsKey(newBundleId)); wiringResolver.update(bundle); c.verify(); Assert.assertTrue(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertTrue(wiringResolver.wiring.containsKey(newBundleId)); } |
StoredWiringResolver implements ResolverHook { synchronized void delete(Bundle bundle) { if (wiring.get(bundle.getBundleId()) != null) { wiring.remove(bundle.getBundleId()).delete(path); } } StoredWiringResolver(Path path); @Override void filterResolvable(Collection<BundleRevision> candidates); @Override void filterSingletonCollisions(BundleCapability singleton,
Collection<BundleCapability> collisionCandidates); @Override void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates); @Override void end(); } | @Test public void delete() { long newBundleId = 25L; File file = new File(TEST_RESOURCES_WIRINGS + newBundleId); Bundle bundle = wiredMockBundle(newBundleId, Collections.emptyList() ); c.replay(); wiringResolver.update(bundle); Assert.assertTrue(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS + 1, wiringResolver.wiring.size()); Assert.assertTrue(wiringResolver.wiring.containsKey(newBundleId)); wiringResolver.delete(bundle); c.verify(); Assert.assertFalse(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertFalse(wiringResolver.wiring.containsKey(newBundleId)); }
@Test public void deleteNonExisting() { long otherBundleId = 30L; File file = new File(TEST_RESOURCES_WIRINGS + otherBundleId); Bundle bundle = mockBundle(otherBundleId); c.replay(); Assert.assertFalse(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertFalse(wiringResolver.wiring.containsKey(otherBundleId)); wiringResolver.delete(bundle); c.verify(); Assert.assertFalse(file.exists()); Assert.assertEquals(EXPECTED_STOCK_WIRINGS, wiringResolver.wiring.size()); Assert.assertFalse(wiringResolver.wiring.containsKey(otherBundleId)); } |
BundleWires { Set<BundleCapability> filterCandidates( BundleRequirement requirement, Collection<BundleCapability> candidates) { Set<String> wiredCapabilityIds = wiring.get(getRequirementId(requirement)); return candidates.stream() .filter( capability -> isCapabilityWiredToBundle( wiredCapabilityIds, capability ) ) .collect( Collectors.toSet() ); } BundleWires(Bundle bundle); BundleWires(long bundleId, BufferedReader reader); } | @Test public void testFilterCandidates() throws IOException { BundleWires wires = readFromFile(); BundleRequirement req = packageRequirement(packageFilter); BundleCapability candidate1 = bundleCap(targetBundleId, targetBundleVersion, true ); List<BundleCapability> candidates = new ArrayList<>(); candidates.add(candidate1); BundleCapability matchingCandidate = bundleCap(targetBundleId, "1.1.0", true ); candidates.add(matchingCandidate); c.replay(); Set<BundleCapability> goodCandidates = wires.filterCandidates( req, candidates ); assertEquals(1, goodCandidates.size()); assertEquals(candidate1, goodCandidates.iterator().next()); c.verify(); }
@Test public void testFilterCandidatesSelfSatisfiedCapability() throws IOException { Bundle bundle = wiredBundle( Collections.emptyList() ); BundleCapability candidate1 = bundleCap(1, targetBundleVersion, false ); List<BundleCapability> candidates = new ArrayList<>(); candidates.add(candidate1); BundleCapability matchingCandidate = bundleCap(2, "1.1.0", false ); candidates.add(matchingCandidate); BundleRequirement req = packageRequirement(packageFilter); c.replay(); BundleWires wires = new BundleWires(bundle); Set<BundleCapability> goodCandidates = wires.filterCandidates( req, candidates ); assertEquals(1, goodCandidates.size()); assertEquals(candidate1, goodCandidates.iterator().next()); c.verify(); } |
JmxRepository { public CompositeData asCompositeData() { return data; } JmxRepository(Repository repository); CompositeData asCompositeData(); static TabularData tableFrom(Collection<JmxRepository> repositories); static final CompositeType REPOSITORY; static final TabularType REPOSITORY_TABLE; } | @Test public void testJmxRepositoryCompositeData() throws Exception { Features features = new Features(); features.setName("test-1.0.0"); features.getRepository().add("mvn:org.test/test-dependency/1.0.0/xml/features"); features.getFeature().add(new Feature("test-feature", "1.0.0")); URI uri = new URI("mvn:org.test/test/1.0.0/xml/features"); Repository repository = new RepositoryImpl(uri, features, true); JmxRepository jmxRepository = new JmxRepository(repository); CompositeData compositeData = jmxRepository.asCompositeData(); assertEquals("test-1.0.0", compositeData.get(REPOSITORY_NAME)); assertEquals(uri.toString(), compositeData.get(REPOSITORY_URI)); assertTrue((Boolean) compositeData.get(REPOSITORY_BLACKLISTED)); String[] repositoryUris = (String[]) compositeData.get(REPOSITORY_REPOSITORIES); assertEquals(1, repositoryUris.length); assertEquals("mvn:org.test/test-dependency/1.0.0/xml/features", repositoryUris[0]); TabularData repositoryFeatures = (TabularData) compositeData.get(REPOSITORY_FEATURES); assertEquals(1, repositoryFeatures.size()); assertNotNull(repositoryFeatures.get(new Object[] {"test-feature", "1.0.0"})); } |
JmxFeature { public CompositeData asCompositeData() { return data; } JmxFeature(Feature feature, boolean installed, boolean required); CompositeData asCompositeData(); static TabularData tableFrom(Collection<JmxFeature> features); static final CompositeType FEATURE; static final TabularType FEATURE_TABLE; static final CompositeType FEATURE_IDENTIFIER; static final TabularType FEATURE_IDENTIFIER_TABLE; static final CompositeType FEATURE_CONFIG_ELEMENT; static final TabularType FEATURE_CONFIG_ELEMENT_TABLE; static final CompositeType FEATURE_CONFIG; static final TabularType FEATURE_CONFIG_TABLE; static final CompositeType FEATURE_CONFIG_FILES; static final TabularType FEATURE_CONFIG_FILES_TABLE; } | @Test public void testJmxFeatureCompositeData() throws Exception { Feature feature = new Feature(); feature.setName("test-feature"); feature.setVersion("1.0.0"); feature.setBlacklisted(true); Dependency dependency = new Dependency(); dependency.setName("test-dependent-feature"); dependency.setVersion("1.0.0"); feature.getFeature().add(dependency); Bundle bundle = new Bundle(); bundle.setLocation("mvn:org.test/test/1.0.0"); feature.getBundle().add(bundle); Config config = new Config(); config.setName(FEATURE_CONFIG_PID); config.setValue("org.test.pid"); config.setAppend(false); config.getProperties().put("test-key", "test-value"); feature.getConfig().add(config); ConfigFile configFile = new ConfigFile(); configFile.setFinalname("test-configfile.cfg"); feature.getConfigfile().add(configFile); JmxFeature jmxFeature = new JmxFeature(feature, true, true); CompositeData compositeData = jmxFeature.asCompositeData(); assertEquals("test-feature", compositeData.get(FEATURE_NAME)); assertEquals("1.0.0", compositeData.get(FEATURE_VERSION)); assertTrue((Boolean) compositeData.get(FEATURE_INSTALLED)); assertTrue((Boolean) compositeData.get(FEATURE_BLACKLISTED)); assertTrue((Boolean) compositeData.get(FEATURE_REQUIRED)); TabularData featureDependencies = (TabularData) compositeData.get(FEATURE_DEPENDENCIES); assertEquals(1, featureDependencies.size()); assertNotNull(featureDependencies.get(new Object[] {"test-dependent-feature", "1.0.0"})); String[] bundleUrls = (String[]) compositeData.get(FEATURE_BUNDLES); assertEquals(new String[] {"mvn:org.test/test/1.0.0"}, bundleUrls); TabularData featureConfigs = (TabularData) compositeData.get(FEATURE_CONFIGURATIONS); assertEquals(1, featureConfigs.size()); assertNotNull(featureConfigs.get(new Object[] {FEATURE_CONFIG_PID})); TabularData featureConfigFiles = (TabularData) compositeData.get(FEATURE_CONFIGURATIONFILES); assertEquals(1, featureConfigFiles.size()); assertNotNull(featureConfigFiles.get(new Object[] {"test-configfile.cfg"})); } |
Overrides { @Deprecated public static <T extends Resource> void override(Map<String, T> resources, Collection<String> overrides) { for (Clause override : Parser.parseClauses(overrides.toArray(new String[overrides.size()]))) { String overrideRange = override.getAttribute(OVERRIDE_RANGE); T over = resources.get(override.getName()); if (over == null) { continue; } for (String uri : new ArrayList<>(resources.keySet())) { Resource res = resources.get(uri); if (shouldOverride(res, over, overrideRange)) { resources.put(uri, over); } } } } private Overrides(); @Deprecated static void override(Map<String, T> resources, Collection<String> overrides); static void override(Map<String, T> resources, Map<String, T> overridenFrom); static Set<String> loadOverrides(String overridesUrl); static String extractUrl(String override); static final String OVERRIDE_RANGE; } | @Test public void testDifferentVendors() throws IOException { Map<String, Resource> map = asResourceMap(c100, c101, c110); assertEquals(c100, map.get(getUri(c100))); Overrides.override(map, Arrays.asList(getUri(c101), getUri(c110))); assertEquals(c101, map.get(getUri(c100))); }
@Test public void testMatching101() throws IOException { Map<String, Resource> map = asResourceMap(b100, b101, b110); assertEquals(b100, map.get(getUri(b100))); Overrides.override(map, Arrays.asList(getUri(b101), getUri(b110))); assertEquals(b101, map.get(getUri(b100))); }
@Test public void testMatching102() throws IOException { Map<String, Resource> map = asResourceMap(b100, b101, b102, b110); assertEquals(b100, map.get(getUri(b100))); Overrides.override(map, Arrays.asList(getUri(b101), getUri(b102), getUri(b110))); assertEquals(b102, map.get(getUri(b100))); }
@Test public void testMatchingRange() throws IOException { Map<String, Resource> map = asResourceMap(b100, b101, b110); assertEquals(b100, map.get(getUri(b100))); Overrides.override(map, Arrays.asList(getUri(b101), getUri(b110) + ";range=\"[1.0, 2.0)\"")); assertEquals(b110, map.get(getUri(b100))); }
@Test public void testNotMatching() throws IOException { Map<String, Resource> map = asResourceMap(b100, b110); assertEquals(b100, map.get(getUri(b100))); Overrides.override(map, Collections.singletonList(getUri(b110))); assertEquals(b100, map.get(getUri(b100))); } |
KarafJaasAuthenticator implements PasswordAuthenticator, PublickeyAuthenticator { public boolean authenticate(final String username, final String password, final ServerSession session) { CallbackHandler callbackHandler = callbacks -> { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { ((NameCallback) callback).setName(username); } else if (callback instanceof PasswordCallback) { ((PasswordCallback) callback).setPassword(password.toCharArray()); } else { throw new UnsupportedCallbackException(callback); } } }; return doLogin(session, callbackHandler); } KarafJaasAuthenticator(String realm, String role, Class<?>[] roleClasses); boolean authenticate(final String username, final String password, final ServerSession session); boolean authenticate(final String username, final PublicKey key, final ServerSession session); static final Session.AttributeKey<Subject> SUBJECT_ATTRIBUTE_KEY; } | @Test public void authenticateOk() { final KarafJaasAuthenticator authenticator = new KarafJaasAuthenticator("karaf", "test", new Class<?>[]{RolePrincipal.class}); assertTrue(authenticator.authenticate("test", "test", session)); }
@Test public void authenticateKo() { final KarafJaasAuthenticator authenticator = new KarafJaasAuthenticator("karaf", "test", new Class<?>[]{RolePrincipal.class}); assertFalse(authenticator.authenticate("testko", "test", session)); }
@Test public void invalidRole() { final KarafJaasAuthenticator authenticator = new KarafJaasAuthenticator("karaf", "test", new Class<?>[]{RolePrincipal.class}); assertFalse(authenticator.authenticate("customRole", "test", session)); }
@Test public void noRole() { final KarafJaasAuthenticator authenticator = new KarafJaasAuthenticator("karaf", "test", new Class<?>[0]); assertFalse(authenticator.authenticate("norole", "test", session)); }
@Test public void customRole() { final KarafJaasAuthenticator authenticator = new KarafJaasAuthenticator("karaf", "test", new Class<?>[]{UserPrincipal.class}); assertTrue(authenticator.authenticate("customRole", "test", session)); } |
Overrides { public static Set<String> loadOverrides(String overridesUrl) { Set<String> overrides = new LinkedHashSet<>(); try { if (overridesUrl != null) { try ( InputStream is = new URL(overridesUrl).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)) ) { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.isEmpty() && !line.startsWith("#")) { overrides.add(line); } } } } } catch (FileNotFoundException e) { LOGGER.debug("Unable to load overrides bundles list {}", e.toString()); } catch (Exception e) { LOGGER.debug("Unable to load overrides bundles list", e); } return overrides; } private Overrides(); @Deprecated static void override(Map<String, T> resources, Collection<String> overrides); static void override(Map<String, T> resources, Map<String, T> overridenFrom); static Set<String> loadOverrides(String overridesUrl); static String extractUrl(String override); static final String OVERRIDE_RANGE; } | @Test public void testLoadOverrides() { Set<String> overrides = Overrides.loadOverrides(getClass().getResource("overrides.properties").toExternalForm()); assertEquals(2, overrides.size()); Clause karafAdminCommand = null; Clause karafAdminCore = null; for (Clause clause : Parser.parseClauses(overrides.toArray(new String[overrides.size()]))) { if (clause.getName().equals("mvn:org.apache.karaf.admin/org.apache.karaf.admin.command/2.3.0.61033X")) { karafAdminCommand = clause; } if (clause.getName().equals("mvn:org.apache.karaf.admin/org.apache.karaf.admin.core/2.3.0.61033X")) { karafAdminCore = clause; } } assertNotNull("Missing admin.command bundle override", karafAdminCommand); assertNotNull("Missing admin.core bundle override", karafAdminCore); assertNotNull("Missing range on admin.core override", karafAdminCore.getAttribute(Overrides.OVERRIDE_RANGE)); } |
FeatureConfigInstaller { protected static String substFinalName(String finalname) { final String markerVarBeg = "${"; final String markerVarEnd = "}"; boolean startsWithVariable = finalname.startsWith(markerVarBeg) && finalname.contains(markerVarEnd); final String dummyKey = ""; try { finalname = InterpolationHelper.substVars(finalname, dummyKey, null, null, null, true, true, false); } catch (final IllegalArgumentException ex) { LOGGER.info("Substitution failed. Skip substitution of variables of configuration final name ({}).", finalname); } if (!startsWithVariable || finalname.startsWith(markerVarBeg)) { final String basePath = System.getProperty("karaf.base"); finalname = basePath + File.separator + finalname; } while (finalname.contains(markerVarBeg) && finalname.contains(markerVarEnd)) { int beg = finalname.indexOf(markerVarBeg); int end = finalname.indexOf(markerVarEnd); final String rem = finalname.substring(beg, end + markerVarEnd.length()); finalname = finalname.replace(rem, ""); } return finalname; } FeatureConfigInstaller(ConfigurationAdmin configAdmin); FeatureConfigInstaller(ConfigurationAdmin configAdmin, boolean configCfgStore); void installFeatureConfigs(Feature feature); void uninstallFeatureConfigs(Feature feature); } | @Test public void testSubstFinalName() { final String karafBase = "/tmp/karaf.base"; final String karafEtc = karafBase + "/etc"; final String foo = "/foo"; System.setProperty("karaf.base", karafBase); System.setProperty("karaf.etc", karafEtc); System.setProperty("foo", foo); substEqual("etc/test.cfg", karafBase + File.separator + "etc/test.cfg"); substEqual("/etc/test.cfg", karafBase + File.separator + "/etc/test.cfg"); substEqual("${karaf.etc}/test.cfg", karafEtc + "/test.cfg"); substEqual("${karaf.base}/etc/test.cfg", karafBase + "/etc/test.cfg"); substEqual("etc/${foo}/test.cfg", karafBase + File.separator + "etc/" + foo + "/test.cfg"); substEqual("${foo}/test.cfg", foo + "/test.cfg"); substEqual("etc${bar}/${bar}test.cfg", karafBase + File.separator + "etc/test.cfg"); substEqual("${bar}/etc/test.cfg${bar}", karafBase + File.separator + "/etc/test.cfg"); substEqual("${karaf.base}${bar}/etc/test.cfg", karafBase + "/etc/test.cfg"); substEqual("etc${}/${foo}/test.cfg", karafBase + File.separator + "etc substEqual("${foo}${bar}/${bar}${foo}", foo + "/" + foo); } |
Blacklist { public void blacklistBundle(LocationPattern locationPattern) { bundleBlacklist.add(locationPattern); } Blacklist(); Blacklist(List<String> blacklist); Blacklist(String blacklistUrl); boolean isRepositoryBlacklisted(String uri); boolean isFeatureBlacklisted(String name, String version); boolean isBundleBlacklisted(String uri); void merge(Blacklist others); Clause[] getClauses(); void blacklist(Features featuresModel); void blacklistRepository(LocationPattern locationPattern); void blacklistFeature(FeaturePattern featurePattern); void blacklistBundle(LocationPattern locationPattern); List<LocationPattern> getRepositoryBlacklist(); List<FeaturePattern> getFeatureBlacklist(); List<LocationPattern> getBundleBlacklist(); static Logger LOG; static final String BLACKLIST_URL; static final String BLACKLIST_TYPE; static final String TYPE_FEATURE; static final String TYPE_BUNDLE; static final String TYPE_REPOSITORY; } | @Test public void testBlacklistBundle() throws IOException { String blacklisted = "mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jasypt/1.7_1"; Stream<Feature> features = blacklistWith(blacklisted); Stream<BundleInfo> bundles = features.flatMap(f -> f.getBundles().stream()); assertTrue(bundles.noneMatch(b -> b.getLocation().equals(blacklisted) && !b.isBlacklisted())); } |
FeaturesServiceImpl implements FeaturesService, Deployer.DeployCallback { @Override public Feature[] getFeatures(String nameOrId) throws Exception { return getFeatures(FeatureReq.parseNameAndRange(nameOrId)); } FeaturesServiceImpl(StateStorage storage,
FeatureRepoFinder featureFinder,
ConfigurationAdmin configurationAdmin,
Resolver resolver,
BundleInstallSupport installSupport,
org.osgi.service.repository.Repository globalRepository,
FeaturesServiceConfig cfg); void stop(); @Override void registerListener(FeaturesListener listener); @Override void unregisterListener(FeaturesListener listener); @Override void registerListener(DeploymentListener listener); @Override void unregisterListener(DeploymentListener listener); @Override void callListeners(FeatureEvent event); @Override void callListeners(DeploymentEvent event); @Override URI getRepositoryUriFor(String name, String version); @Override String[] getRepositoryNames(); @Override Feature[] repositoryProvidedFeatures(URI uri); @Override void validateRepository(URI uri); @Override boolean isRepositoryUriBlacklisted(URI uri); @Override void addRepository(URI uri); @Override void addRepository(URI uri, boolean install); @Override void removeRepository(URI uri); @Override void removeRepository(URI uri, boolean uninstall); @Override void restoreRepository(URI uri); @Override void refreshRepository(URI uri); @Override void refreshRepositories(Set<URI> uris); @Override Repository[] listRepositories(); @Override Repository[] listRequiredRepositories(); @Override Repository getRepository(String name); @Override Repository getRepository(URI uri); @Override String getRepositoryName(URI uri); @Override Feature getFeature(String name); @Override Feature getFeature(String name, String version); @Override Feature[] getFeatures(String nameOrId); @Override Feature[] getFeatures(String name, String version); @Override Feature[] listFeatures(); @Override Feature[] listInstalledFeatures(); @Override Feature[] listRequiredFeatures(); @Override boolean isInstalled(Feature f); @Override FeatureState getState(String featureId); @Override boolean isRequired(Feature f); @Override void installFeature(String name); @Override void installFeature(String name, String version); @Override void installFeature(String name, EnumSet<Option> options); @Override void installFeature(String name, String version, EnumSet<Option> options); @Override void installFeature(Feature feature, EnumSet<Option> options); @Override void installFeatures(Set<String> features, EnumSet<Option> options); @Override void uninstallFeature(String name, String version); @Override void uninstallFeature(String name, String version, EnumSet<Option> options); @Override void uninstallFeature(String name); @Override void uninstallFeature(String name, EnumSet<Option> options); @Override void uninstallFeatures(Set<String> features, EnumSet<Option> options); @Override void setResolutionOutputFile(String outputFile); @Override void installFeatures(Set<String> featuresIn, String region, EnumSet<Option> options); @Override void uninstallFeatures(Set<String> featuresIn, String region, EnumSet<Option> options); @Override void updateFeaturesState(Map<String, Map<String, FeatureState>> stateChanges, EnumSet<Option> options); @Override void addRequirements(Map<String, Set<String>> requirements, EnumSet<Option> options); @Override void removeRequirements(Map<String, Set<String>> requirements, EnumSet<Option> options); @Override void updateReposAndRequirements(Set<URI> repos, Map<String, Set<String>> requirements, EnumSet<Option> options); @Override Repository createRepository(URI uri); @Override Map<String, Set<String>> listRequirements(); @Override void print(String message, boolean verbose); void saveState(State state); @Override void persistResolveRequest(Deployer.DeploymentRequest request); @Override void refreshPackages(Collection<Bundle> bundles); @Override Bundle installBundle(String region, String uri, InputStream is); @Override void updateBundle(Bundle bundle, String uri, InputStream is); @Override void uninstall(Bundle bundle); @Override void startBundle(Bundle bundle); @Override void stopBundle(Bundle bundle, int options); @Override void setBundleStartLevel(Bundle bundle, int startLevel); @Override void resolveBundles(Set<Bundle> bundles, Map<Resource, List<Wire>> wiring, Map<Resource, Bundle> resToBnd); @Override void replaceDigraph(Map<String, Map<String, Map<String, Set<String>>>> policies, Map<String, Set<Long>> bundles); @Override void installConfigs(Feature feature); @Override void deleteConfigs(Feature feature); @Override void installLibraries(Feature feature); @Override void bundleBlacklisted(BundleInfo bundleInfo); @Override String getFeatureXml(Feature feature); @Override void refreshFeatures(EnumSet<Option> options); } | @Test public void testListFeatureWithoutVersion() throws Exception { Feature transactionFeature = feature("transaction", "1.0.0"); FeaturesServiceImpl impl = featuresServiceWithFeatures(transactionFeature); assertNotNull(impl.getFeatures("transaction", null)); assertSame(transactionFeature, impl.getFeatures("transaction", org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)[0]); }
@Test public void testGetFeatureStripVersion() throws Exception { Feature transactionFeature = feature("transaction", "1.0.0"); FeaturesServiceImpl impl = featuresServiceWithFeatures(transactionFeature); Feature[] features = impl.getFeatures("transaction", " 1.0.0 "); assertEquals(1, features.length); Feature feature = features[0]; assertNotNull(feature); assertSame("transaction", feature.getName()); }
@Test public void testGetFeatureNotAvailable() throws Exception { Feature transactionFeature = feature("transaction", "1.0.0"); FeaturesServiceImpl impl = featuresServiceWithFeatures(transactionFeature); assertEquals(0, impl.getFeatures("activemq", org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION).length); }
@Test public void testGetFeatureHighestAvailable() throws Exception { FeaturesServiceImpl impl = featuresServiceWithFeatures(feature("transaction", "1.0.0"), feature("transaction", "2.0.0")); assertNotNull(impl.getFeatures("transaction", org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)); assertEquals("2.0.0", impl.getFeatures("transaction", org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)[0].getVersion()); } |
FeaturesServiceImpl implements FeaturesService, Deployer.DeployCallback { @Override public Feature getFeature(String name) throws Exception { Feature[] features = getFeatures(name); if (features.length < 1) { return null; } else { return features[0]; } } FeaturesServiceImpl(StateStorage storage,
FeatureRepoFinder featureFinder,
ConfigurationAdmin configurationAdmin,
Resolver resolver,
BundleInstallSupport installSupport,
org.osgi.service.repository.Repository globalRepository,
FeaturesServiceConfig cfg); void stop(); @Override void registerListener(FeaturesListener listener); @Override void unregisterListener(FeaturesListener listener); @Override void registerListener(DeploymentListener listener); @Override void unregisterListener(DeploymentListener listener); @Override void callListeners(FeatureEvent event); @Override void callListeners(DeploymentEvent event); @Override URI getRepositoryUriFor(String name, String version); @Override String[] getRepositoryNames(); @Override Feature[] repositoryProvidedFeatures(URI uri); @Override void validateRepository(URI uri); @Override boolean isRepositoryUriBlacklisted(URI uri); @Override void addRepository(URI uri); @Override void addRepository(URI uri, boolean install); @Override void removeRepository(URI uri); @Override void removeRepository(URI uri, boolean uninstall); @Override void restoreRepository(URI uri); @Override void refreshRepository(URI uri); @Override void refreshRepositories(Set<URI> uris); @Override Repository[] listRepositories(); @Override Repository[] listRequiredRepositories(); @Override Repository getRepository(String name); @Override Repository getRepository(URI uri); @Override String getRepositoryName(URI uri); @Override Feature getFeature(String name); @Override Feature getFeature(String name, String version); @Override Feature[] getFeatures(String nameOrId); @Override Feature[] getFeatures(String name, String version); @Override Feature[] listFeatures(); @Override Feature[] listInstalledFeatures(); @Override Feature[] listRequiredFeatures(); @Override boolean isInstalled(Feature f); @Override FeatureState getState(String featureId); @Override boolean isRequired(Feature f); @Override void installFeature(String name); @Override void installFeature(String name, String version); @Override void installFeature(String name, EnumSet<Option> options); @Override void installFeature(String name, String version, EnumSet<Option> options); @Override void installFeature(Feature feature, EnumSet<Option> options); @Override void installFeatures(Set<String> features, EnumSet<Option> options); @Override void uninstallFeature(String name, String version); @Override void uninstallFeature(String name, String version, EnumSet<Option> options); @Override void uninstallFeature(String name); @Override void uninstallFeature(String name, EnumSet<Option> options); @Override void uninstallFeatures(Set<String> features, EnumSet<Option> options); @Override void setResolutionOutputFile(String outputFile); @Override void installFeatures(Set<String> featuresIn, String region, EnumSet<Option> options); @Override void uninstallFeatures(Set<String> featuresIn, String region, EnumSet<Option> options); @Override void updateFeaturesState(Map<String, Map<String, FeatureState>> stateChanges, EnumSet<Option> options); @Override void addRequirements(Map<String, Set<String>> requirements, EnumSet<Option> options); @Override void removeRequirements(Map<String, Set<String>> requirements, EnumSet<Option> options); @Override void updateReposAndRequirements(Set<URI> repos, Map<String, Set<String>> requirements, EnumSet<Option> options); @Override Repository createRepository(URI uri); @Override Map<String, Set<String>> listRequirements(); @Override void print(String message, boolean verbose); void saveState(State state); @Override void persistResolveRequest(Deployer.DeploymentRequest request); @Override void refreshPackages(Collection<Bundle> bundles); @Override Bundle installBundle(String region, String uri, InputStream is); @Override void updateBundle(Bundle bundle, String uri, InputStream is); @Override void uninstall(Bundle bundle); @Override void startBundle(Bundle bundle); @Override void stopBundle(Bundle bundle, int options); @Override void setBundleStartLevel(Bundle bundle, int startLevel); @Override void resolveBundles(Set<Bundle> bundles, Map<Resource, List<Wire>> wiring, Map<Resource, Bundle> resToBnd); @Override void replaceDigraph(Map<String, Map<String, Map<String, Set<String>>>> policies, Map<String, Set<Long>> bundles); @Override void installConfigs(Feature feature); @Override void deleteConfigs(Feature feature); @Override void installLibraries(Feature feature); @Override void bundleBlacklisted(BundleInfo bundleInfo); @Override String getFeatureXml(Feature feature); @Override void refreshFeatures(EnumSet<Option> options); } | @Test public void testGetFeature() throws Exception { Feature transactionFeature = feature("transaction", "1.0.0"); FeaturesServiceImpl impl = featuresServiceWithFeatures(transactionFeature); assertNotNull(impl.getFeatures("transaction", org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)); assertSame(transactionFeature, impl.getFeatures("transaction", org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)[0]); } |
BootFeaturesInstaller { protected List<Set<String>> parseBootFeatures(String bootFeatures) { List<Set<String>> stages = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(bootFeatures, " \t\r\n,()", true); int paren = 0; Set<String> stage = new LinkedHashSet<>(); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.equals("(")) { if (paren == 0) { if (!stage.isEmpty()) { stages.add(stage); stage = new LinkedHashSet<>(); } paren++; } else { throw new IllegalArgumentException("Bad syntax in boot features: '" + bootFeatures + "'"); } } else if (token.equals(")")) { if (paren == 1) { if (!stage.isEmpty()) { stages.add(stage); stage = new LinkedHashSet<>(); } paren--; } else { throw new IllegalArgumentException("Bad syntax in boot features: '" + bootFeatures + "'"); } } else if (!token.matches("[ \t\r\n]+|,")) { stage.add(token); } } if (!stage.isEmpty()) { stages.add(stage); } return stages; } BootFeaturesInstaller(BundleContext bundleContext,
FeaturesServiceImpl featuresService,
String[] repositories,
String features,
boolean asynchronous); void start(); } | @Test public void testParser() { BootFeaturesInstaller installer = new BootFeaturesInstaller(null, null, new String[0], "", false); Assert.assertEquals(asList(setOf("test1", "test2"), setOf("test3")), installer.parseBootFeatures(" ( test1 , test2 ) , test3 ")); Assert.assertEquals(Collections.singletonList(setOf("test1", "test2", "test3")), installer.parseBootFeatures(" test1 , test2, test3")); Assert.assertEquals(asList(setOf("test1"), setOf("test2"), setOf("test3")), installer.parseBootFeatures("(test1), (test2), test3")); }
@Test public void testParseBootFeatures() throws Exception { String features = "foo, jim, (ssh, shell, jaas, feature, framework), (system, bundle, management, service), (instance, package, log, deployer, diagnostic, config, kar), bar, zad"; BootFeaturesInstaller bootFeatures = new BootFeaturesInstaller(null, null, null, null, false); List<Set<String>> stages = bootFeatures.parseBootFeatures(features); Assert.assertEquals(5, stages.size()); for (String f : Arrays.asList("foo", "jim")) { Assert.assertTrue("Should contain '" + f + "'", stages.get(0).contains(f)); } for (String f : Arrays.asList("ssh", "shell", "jaas", "feature", "framework")) { Assert.assertTrue("Should contain '" + f + "'", stages.get(1).contains(f)); } for (String f : Arrays.asList("system", "bundle", "management", "service")) { Assert.assertTrue("Should contain '" + f + "'", stages.get(2).contains(f)); } for (String f : Arrays.asList("instance", "package", "log", "deployer", "diagnostic", "config", "kar")) { Assert.assertTrue("Should contain '" + f + "'", stages.get(3).contains(f)); } for (String f : Arrays.asList("bar", "zad")) { Assert.assertTrue("Should contain '" + f + "'", stages.get(4).contains(f)); } } |
BootFeaturesInstaller { protected void installBootFeatures() { try { addRepositories(); List<Set<String>> stagedFeatures = parseBootFeatures(features); for (Set<String> features : stagedFeatures) { featuresService.installFeatures(features, EnumSet.of(FeaturesService.Option.NoFailOnFeatureNotFound)); } featuresService.bootDone(); publishBootFinished(); } catch (Throwable e) { if (e instanceof IllegalStateException) { try { bundleContext.getBundle(); } catch (IllegalStateException ies) { return; } } LOGGER.error("Error installing boot features", e); } } BootFeaturesInstaller(BundleContext bundleContext,
FeaturesServiceImpl featuresService,
String[] repositories,
String features,
boolean asynchronous); void start(); } | @Test public void testDefaultBootFeatures() throws Exception { FeaturesServiceImpl impl = createMock(FeaturesServiceImpl.class); Capture<Set<String>> featuresCapture = newCapture(); impl.installFeatures(capture(featuresCapture), eq(EnumSet.of(Option.NoFailOnFeatureNotFound))); expectLastCall(); impl.bootDone(); expectLastCall(); replay(impl); BootFeaturesInstaller bootFeatures = new BootFeaturesInstaller(null, impl, new String[0], "config,standard,region", false); bootFeatures.installBootFeatures(); verify(impl); List<String> features = new ArrayList<>(featuresCapture.getValue()); Assert.assertEquals("config", features.get(0)); Assert.assertEquals("standard", features.get(1)); Assert.assertEquals("region", features.get(2)); }
@Test public void testStagedBoot() throws Exception { FeaturesServiceImpl impl = createStrictMock(FeaturesServiceImpl.class); impl.installFeatures(setOf("transaction"), EnumSet.of(Option.NoFailOnFeatureNotFound)); expectLastCall(); impl.installFeatures(setOf("ssh"), EnumSet.of(Option.NoFailOnFeatureNotFound)); expectLastCall(); impl.bootDone(); expectLastCall(); replay(impl); BootFeaturesInstaller bootFeatures = new BootFeaturesInstaller(null, impl , new String[0], "(transaction), ssh", false); bootFeatures.installBootFeatures(); verify(impl); }
@Test public void testStartDoesNotFailWithOneInvalidUri() throws Exception { FeaturesServiceImpl impl = createStrictMock(FeaturesServiceImpl.class); impl.addRepository(URI.create(INEXISTANT_REPO)); expectLastCall().andThrow(new IllegalArgumentException("Part of the test. Can be ignored.")); impl.bootDone(); expectLastCall(); replay(impl); String[] repositories = new String[] { INEXISTANT_REPO }; BootFeaturesInstaller bootFeatures = new BootFeaturesInstaller(null, impl, repositories, "", false); Logger logger = Logger.getLogger(BootFeaturesInstaller.class.getName()); logger.setLevel(Level.OFF); bootFeatures.installBootFeatures(); logger.setLevel(Level.INFO); verify(impl); } |
DownloadManagerHelper { public static void setExtraProtocols( Collection<String> protocols ){ StringBuilder sb = new StringBuilder( DEFAULT_IGNORED_PROTOCOL_PATTERN ); for (String proto : protocols) { sb.append("|").append(proto); } setIgnoredProtocolPattern(sb.toString()); } private DownloadManagerHelper(); static Pattern getIgnoredProtocolPattern(); static void setExtraProtocols( Collection<String> protocols ); static String stripUrl(String url); static String stripStartLevel(String url); static String stripInlinedMavenRepositoryUrl(String url); static String removeInlinedMavenRepositoryUrl(String url); } | @Test public void testSetExtraProtocols(){ assertEquals("^(jar|war|war-i|warref|webbundle|wrap|spring|blueprint):.*$", DownloadManagerHelper.getIgnoredProtocolPattern().toString()); List<String> extraProtocols = new ArrayList<>(); extraProtocols.add( "extra1" ); extraProtocols.add( "extra2" ); DownloadManagerHelper.setExtraProtocols( extraProtocols ); assertEquals("^(jar|war|war-i|warref|webbundle|wrap|spring|blueprint|extra1|extra2):.*$", DownloadManagerHelper.getIgnoredProtocolPattern().toString()); } |
SimpleMavenResolver implements ArtifactResolver { public URI resolve(URI artifactUri) { for (File bundleDir : mavenRepos) { File file = findFile(bundleDir, artifactUri); if (file != null) { return file.toURI(); } } throw new RuntimeException("Could not resolve " + artifactUri); } SimpleMavenResolver(List<File> mavenRepos); URI resolve(URI artifactUri); } | @Test public void testResolve() throws URISyntaxException { File basedir = new File(getClass().getClassLoader().getResource("foo").getPath()).getParentFile(); File home = new File(basedir, "test-karaf-home"); File system = new File(home, "system"); SimpleMavenResolver resolver = new SimpleMavenResolver(Collections.singletonList(system)); resolver.resolve(new URI(ARTIFACT_COORDS)); } |
Statements { public String[] getLockCreateSchemaStatements(long moment) { if (lockCreateSchemaStatements == null) { lockCreateSchemaStatements = new String[] { "CREATE TABLE " + getFullLockTableName() + " (MOMENT " + getMomentColumnDataType() + ", NODE " + getNodeColumnDataType() + ")", "INSERT INTO " + getFullLockTableName() + " (MOMENT, NODE) VALUES (" + moment + ", '" + getNodeName() + "')", }; } return lockCreateSchemaStatements; } String[] getLockCreateSchemaStatements(long moment); void setLockCreateSchemaStatements(String[] lockCreateSchemaStatements); String getLockCreateStatement(); void setLockCreateStatement(String lockCreateStatement); String getLockUpdateStatement(long moment); void setLockUpdateStatement(String lockUpdateStatement); void setLockVerifySelectionNotEmptyStatement(String lockVerifySelectionNotEmptyStatement); String getLockVerifySelectionNotEmptyStatement(); String getFullLockTableName(); void setMomentColumnDataType(String momentColumnDataType); String getMomentColumnDataType(); String getNodeName(); void setNodeName(String nodeName); String getNodeColumnDataType(); void setNodeColumnDataType(String nodeColumnDataType); String getTablePrefix(); void setTablePrefix(String tablePrefix); String getTableName(); void setTableName(String tableName); } | @Test public void getDefaultLockCreateSchemaStatements() { assertArrayEquals(new String[] {DEFAULT_CREATE_TABLE_STMT, DEFAULT_POPULATE_TABLE_STMT}, statements.getLockCreateSchemaStatements(1)); }
@Test public void getCustomLockCreateSchemaStatements() { customizeStatements(); String[] expectedCreateSchemaStmts = new String[] { "CREATE TABLE test.LOCK_TABLE (MOMENT NUMBER(20), NODE VARCHAR2(30))", "INSERT INTO test.LOCK_TABLE (MOMENT, NODE) VALUES (2, 'node_1')"}; assertArrayEquals(expectedCreateSchemaStmts, statements.getLockCreateSchemaStatements(2)); } |
Statements { public String getLockCreateStatement() { if (lockCreateStatement == null) { lockCreateStatement = "SELECT * FROM " + getFullLockTableName() + " FOR UPDATE"; } return lockCreateStatement; } String[] getLockCreateSchemaStatements(long moment); void setLockCreateSchemaStatements(String[] lockCreateSchemaStatements); String getLockCreateStatement(); void setLockCreateStatement(String lockCreateStatement); String getLockUpdateStatement(long moment); void setLockUpdateStatement(String lockUpdateStatement); void setLockVerifySelectionNotEmptyStatement(String lockVerifySelectionNotEmptyStatement); String getLockVerifySelectionNotEmptyStatement(); String getFullLockTableName(); void setMomentColumnDataType(String momentColumnDataType); String getMomentColumnDataType(); String getNodeName(); void setNodeName(String nodeName); String getNodeColumnDataType(); void setNodeColumnDataType(String nodeColumnDataType); String getTablePrefix(); void setTablePrefix(String tablePrefix); String getTableName(); void setTableName(String tableName); } | @Test public void getDefaultLockCreateStatement() { assertEquals("SELECT * FROM KARAF_LOCK FOR UPDATE", statements.getLockCreateStatement()); }
@Test public void getCustomLockCreateStatement() { customizeStatements(); assertEquals("SELECT * FROM test.LOCK_TABLE FOR UPDATE", statements.getLockCreateStatement()); } |
Statements { public String getLockUpdateStatement(long moment) { if (lockUpdateStatement == null) { lockUpdateStatement = "UPDATE " + getFullLockTableName() + " SET MOMENT = " + moment; } return lockUpdateStatement; } String[] getLockCreateSchemaStatements(long moment); void setLockCreateSchemaStatements(String[] lockCreateSchemaStatements); String getLockCreateStatement(); void setLockCreateStatement(String lockCreateStatement); String getLockUpdateStatement(long moment); void setLockUpdateStatement(String lockUpdateStatement); void setLockVerifySelectionNotEmptyStatement(String lockVerifySelectionNotEmptyStatement); String getLockVerifySelectionNotEmptyStatement(); String getFullLockTableName(); void setMomentColumnDataType(String momentColumnDataType); String getMomentColumnDataType(); String getNodeName(); void setNodeName(String nodeName); String getNodeColumnDataType(); void setNodeColumnDataType(String nodeColumnDataType); String getTablePrefix(); void setTablePrefix(String tablePrefix); String getTableName(); void setTableName(String tableName); } | @Test public void getDefaultLockUpdateStatement() { assertEquals("UPDATE KARAF_LOCK SET MOMENT = 1", statements.getLockUpdateStatement(1)); }
@Test public void getCustomLockUpdateStatement() { customizeStatements(); assertEquals("UPDATE test.LOCK_TABLE SET MOMENT = 2", statements.getLockUpdateStatement(2)); } |
OracleJDBCLock extends DefaultJDBCLock { @Override public boolean lock() { return acquireLock(); } OracleJDBCLock(Properties props); @Override boolean lock(); } | @Test @Override public void lockShouldReturnTrueItTheTableIsNotLocked() throws Exception { initShouldNotCreateTheSchemaIfItAlreadyExists(); reset(connection, metaData, statement, preparedStatement, resultSet); expect(connection.isClosed()).andReturn(false); expect(connection.prepareStatement("SELECT * FROM " + tableName + " FOR UPDATE")).andReturn(preparedStatement); preparedStatement.setQueryTimeout(10); expect(preparedStatement.execute()).andReturn(true); preparedStatement.close(); expect(connection.isClosed()).andReturn(false); expect(connection.prepareStatement("SELECT COUNT(*) FROM " + tableName)).andReturn(preparedStatement); preparedStatement.setQueryTimeout(10); expect(preparedStatement.executeQuery()).andReturn(resultSet); expect(resultSet.next()).andReturn(Boolean.TRUE); expect(resultSet.getInt(1)).andReturn(1); preparedStatement.close(); replay(connection, metaData, statement, preparedStatement, resultSet); boolean lockAcquired = lock.lock(); verify(connection, metaData, statement, preparedStatement, resultSet); assertTrue(lockAcquired); }
@Test @Override public void lockShouldReturnFalseIfAnotherRowIsLocked() throws Exception { initShouldNotCreateTheSchemaIfItAlreadyExists(); reset(connection, metaData, statement, preparedStatement, resultSet); expect(connection.isClosed()).andReturn(false); expect(connection.prepareStatement("SELECT * FROM " + tableName + " FOR UPDATE")).andReturn(preparedStatement); preparedStatement.setQueryTimeout(10); expect(preparedStatement.execute()).andThrow(new SQLException()); preparedStatement.close(); replay(connection, metaData, statement, preparedStatement, resultSet); boolean lockAcquired = lock.lock(); verify(connection, metaData, statement, preparedStatement, resultSet); assertFalse(lockAcquired); }
@Test @Override public void lockShouldReturnFalseIfTheRowIsAlreadyLocked() throws Exception { initShouldNotCreateTheSchemaIfItAlreadyExists(); reset(connection, metaData, statement, preparedStatement, resultSet); expect(connection.isClosed()).andReturn(false); expect(connection.prepareStatement("SELECT * FROM " + tableName + " FOR UPDATE")).andReturn(preparedStatement); preparedStatement.setQueryTimeout(10); expect(preparedStatement.execute()).andThrow(new SQLException()); preparedStatement.close(); replay(connection, metaData, statement, preparedStatement, resultSet); boolean lockAcquired = lock.lock(); verify(connection, metaData, statement, preparedStatement, resultSet); assertFalse(lockAcquired); }
@Test public void lockShouldReturnFalseIfTableIsEmpty() throws Exception { initShouldNotCreateTheSchemaIfItAlreadyExists(); reset(connection, metaData, statement, preparedStatement, resultSet); expect(connection.isClosed()).andReturn(false); expect(connection.prepareStatement("SELECT * FROM " + tableName + " FOR UPDATE")).andReturn(preparedStatement); preparedStatement.setQueryTimeout(10); expect(preparedStatement.execute()).andReturn(true); preparedStatement.close(); expect(connection.isClosed()).andReturn(false); expect(connection.prepareStatement("SELECT COUNT(*) FROM " + tableName)).andReturn(preparedStatement); preparedStatement.setQueryTimeout(10); expect(preparedStatement.executeQuery()).andReturn(resultSet); expect(resultSet.next()).andReturn(Boolean.TRUE); expect(resultSet.getInt(1)).andReturn(0); preparedStatement.close(); replay(connection, metaData, statement, preparedStatement, resultSet); boolean lockAcquired = lock.lock(); verify(connection, metaData, statement, preparedStatement, resultSet); assertFalse(lockAcquired); } |
FastDateFormat { public String getDate(long now, String pattern) { sameDay(now); String date = cache.get(pattern); if (date == null) { if (MMM_D2.equals(pattern)) { StringBuffer sb = new StringBuffer(); FieldPosition fp = new FieldPosition(DateFormat.Field.DAY_OF_MONTH); SimpleDateFormat sdf = new SimpleDateFormat("MMM dd", locale); sdf.setCalendar(Calendar.getInstance(timeZone, locale)); sdf.format(new Date(now), sb, fp); if (sb.charAt(fp.getBeginIndex()) == '0') { sb.setCharAt(fp.getBeginIndex(), ' '); } date = sb.toString(); } else { SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale); sdf.setCalendar(Calendar.getInstance(timeZone, locale)); date = sdf.format(new Date(now)); } cache.put(pattern, date); } return date; } FastDateFormat(); FastDateFormat(TimeZone timeZone, Locale locale); boolean sameDay(long now); String getDate(long now, String pattern); void writeTime(long now, boolean writeMillis, Appendable buffer); static final String YYYY_MM_DD; static final String MMM_D2; static final String XXX; } | @Test public void test() throws Exception { FastDateFormat cal = new FastDateFormat(); long time = new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-05").getTime(); assertEquals("Nov 5", cal.getDate(time, FastDateFormat.MMM_D2)); assertEquals("2017-11-05", cal.getDate(time, FastDateFormat.YYYY_MM_DD)); time += TimeUnit.DAYS.toMillis(5) + TimeUnit.HOURS.toMillis(1); assertEquals("Nov 10", cal.getDate(time, FastDateFormat.MMM_D2)); assertEquals("2017-11-10", cal.getDate(time, FastDateFormat.YYYY_MM_DD)); }
@Test public void testTimeZone() throws Exception { long time = new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-05").getTime(); FastDateFormat cal = new FastDateFormat(TimeZone.getTimeZone("GMT+5"), Locale.ENGLISH); assertEquals("+05:00", cal.getDate(time, FastDateFormat.XXX)); } |
FileUtil { public static void unjar(JarInputStream jis, File dir) throws IOException { byte[] buffer = new byte[4096]; for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { if (je.getName().startsWith("/")) { throw new IOException("JAR resource cannot contain absolute paths."); } File target = new File(dir, je.getName()); if (!target.getCanonicalPath().startsWith(dir.getCanonicalPath())) { throw new IOException("JAR resource cannot contain paths with .. characters"); } if (je.isDirectory()) { if (!target.exists()) { if (!target.mkdirs()) { throw new IOException("Unable to create target directory: " + target); } } continue; } int lastIndex = je.getName().lastIndexOf('/'); String name = (lastIndex >= 0) ? je.getName().substring(lastIndex + 1) : je.getName(); String destination = (lastIndex >= 0) ? je.getName().substring(0, lastIndex) : ""; destination = destination.replace('/', File.separatorChar); copy(jis, dir, name, destination, buffer); } } static void downloadSource(
PrintStream out, PrintStream err,
URL srcURL, String dirStr, boolean extract); static void unjar(JarInputStream jis, File dir); static void copy(
InputStream is, File dir, String destName, String destDir, byte[] buffer); } | @Test public void goodExtractTest() throws Exception { File base = new File("target/test"); base.mkdirs(); File goodKarFile = new File(base, "good.kar"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(goodKarFile)); ZipEntry entry = new ZipEntry("foo.bar"); zos.putNextEntry(entry); byte[] data = "Test Data".getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); zos.close(); JarInputStream jis = new JarInputStream(new FileInputStream(goodKarFile)); FileUtil.unjar(jis, base); goodKarFile.delete(); }
@Test public void badExtractTest() throws Exception { File base = new File("target/test"); base.mkdirs(); File badKarFile = new File(base, "bad.kar"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(badKarFile)); ZipEntry entry = new ZipEntry("../../../../../../../../../tmp/foo.bar"); zos.putNextEntry(entry); byte[] data = "Test Data".getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); zos.close(); JarInputStream jis = new JarInputStream(new FileInputStream(badKarFile)); try { FileUtil.unjar(jis, base); fail("Failure expected on extracting a jar with relative file paths"); } catch (Exception ex) { } badKarFile.delete(); } |
LogServiceLog4j2XmlImpl implements LogServiceInternal { static void insertIndented(Element loggers, Element element, boolean atBeginning) { NodeList loggerElements = loggers.getElementsByTagName("*"); if (atBeginning && loggerElements.getLength() > 0) { Node insertBefore = loggers.getFirstChild(); if (insertBefore != null) { if (insertBefore.getNodeType() == Node.TEXT_NODE) { String indent = loggers.getFirstChild().getTextContent(); Node node = loggers.getOwnerDocument().createTextNode(indent); loggers.insertBefore(node, insertBefore); } loggers.insertBefore(element, insertBefore); } else { loggers.appendChild(element); } } else { Node insertAfter = loggerElements.getLength() > 0 ? loggerElements.item(loggerElements.getLength() - 1) : null; if (insertAfter != null) { if (insertAfter.getPreviousSibling() != null && insertAfter.getPreviousSibling().getNodeType() == Node.TEXT_NODE) { String indent = insertAfter.getPreviousSibling().getTextContent(); Node node = loggers.getOwnerDocument().createTextNode(indent); if (insertAfter.getNextSibling() != null) { loggers.insertBefore(node, insertAfter.getNextSibling()); insertAfter = node; } else { loggers.appendChild(node); } } if (insertAfter.getNextSibling() != null) { loggers.insertBefore(element, insertAfter.getNextSibling()); } else { loggers.appendChild(element); } } else { if (loggers.getPreviousSibling() != null && loggers.getPreviousSibling().getNodeType() == Node.TEXT_NODE) { String indent = loggers.getPreviousSibling().getTextContent(); String prev = indent; if (indent.endsWith("\t")) { indent += "\t"; } else { int nl = indent.lastIndexOf('\n'); if (nl >= 0) { indent = indent + indent.substring(nl + 1); } else { indent += "\t"; } } if (loggers.getFirstChild() != null && loggers.getPreviousSibling().getNodeType() == Node.TEXT_NODE) { loggers.removeChild(loggers.getFirstChild()); } loggers.appendChild(loggers.getOwnerDocument().createTextNode(indent)); loggers.appendChild(element); loggers.appendChild(loggers.getOwnerDocument().createTextNode(prev)); } else { loggers.appendChild(element); } } } } LogServiceLog4j2XmlImpl(String file); Map<String, String> getLevel(String logger); void setLevel(String logger, String level); } | @Test public void testInsertIndentedTabs() throws Exception { String xml = "<Configuration>\n" + "\t<Loggers>\n" + "\t</Loggers>\n" + "</Configuration>"; String out = insertIndented(xml, false); assertEquals( "<Configuration>\n" + "\t<Loggers>\n" + "\t\t<Logger/>\n" + "\t</Loggers>\n" + "</Configuration>", out); out = insertIndented(xml, true); assertEquals( "<Configuration>\n" + "\t<Loggers>\n" + "\t\t<Logger/>\n" + "\t</Loggers>\n" + "</Configuration>", out); }
@Test public void testInsertIndentedSpaces() throws Exception { String xml = "<Configuration>\n" + " <Loggers>\n" + " </Loggers>\n" + "</Configuration>"; String out = insertIndented(xml, false); assertEquals( "<Configuration>\n" + " <Loggers>\n" + " <Logger/>\n" + " </Loggers>\n" + "</Configuration>", out); out = insertIndented(xml, true); assertEquals( "<Configuration>\n" + " <Loggers>\n" + " <Logger/>\n" + " </Loggers>\n" + "</Configuration>", out); }
@Test public void testInsertIndentedTabsWithRoot() throws Exception { String xml = "<Configuration>\n" + "\t<Loggers>\n" + "\t\t<Root/>\n" + "\t</Loggers>\n" + "</Configuration>"; String out = insertIndented(xml, false); assertEquals( "<Configuration>\n" + "\t<Loggers>\n" + "\t\t<Root/>\n" + "\t\t<Logger/>\n" + "\t</Loggers>\n" + "</Configuration>", out); out = insertIndented(xml, true); assertEquals( "<Configuration>\n" + "\t<Loggers>\n" + "\t\t<Logger/>\n" + "\t\t<Root/>\n" + "\t</Loggers>\n" + "</Configuration>", out); }
@Test public void testInsertIndentedSpacesWithRoot() throws Exception { String xml = "<Configuration>\n" + " <Loggers>\n" + " <Root/>\n" + " </Loggers>\n" + "</Configuration>"; String out = insertIndented(xml, false); assertEquals( "<Configuration>\n" + " <Loggers>\n" + " <Root/>\n" + " <Logger/>\n" + " </Loggers>\n" + "</Configuration>", out); out = insertIndented(xml, true); assertEquals( "<Configuration>\n" + " <Loggers>\n" + " <Logger/>\n" + " <Root/>\n" + " </Loggers>\n" + "</Configuration>", out); } |
LogServiceLog4j2Impl implements LogServiceInternal { public Map<String, String> getLevel(String logger) { Map<String, String> loggers = new TreeMap<>(); String root = (String) config.get(ROOT_LOGGER_LEVEL); loggers.put(ROOT_LOGGER, root); if (ROOT_LOGGER.equals(logger)) { return loggers; } Map<String, String> names = new HashMap<>(); Map<String, String> levels = new HashMap<>(); for (String key : config.keySet()) { String loggerName = getMatching(namePattern, key); if (loggerName != null) { names.put(loggerName, config.get(key).toString()); } loggerName = getMatching(levelPattern, key); if (loggerName != null) { levels.put(loggerName, config.get(key).toString()); } } for (Map.Entry<String, String> e : names.entrySet()) { loggers.put(e.getValue(), levels.get(e.getKey())); } if (ALL_LOGGER.equalsIgnoreCase(logger)) { return loggers; } String l = logger; String val; for (;;) { val = loggers.get(l != null ? l : ROOT_LOGGER); if (val != null || l == null) { return Collections.singletonMap(logger, val); } int idx = l.lastIndexOf('.'); if (idx < 0) { l = null; } else { l = l.substring(0, idx); } } } LogServiceLog4j2Impl(Dictionary<String, Object> config); Map<String, String> getLevel(String logger); void setLevel(String logger, String level); } | @Test public void testLoggerNameWithNumbers() { final String name = "some_logger_name"; final String logger = "org.ops4j.pax.web"; final String level = "WARN"; final Dictionary<String, Object> config = new Hashtable<>(); config.put(ROOT_LOGGER, "INFO"); config.put(LOGGER_PREFIX + name + NAME_SUFFIX, logger); config.put(LOGGER_PREFIX + name + LEVEL_SUFFIX, level); final LogServiceInternal logServiceInternal = new LogServiceLog4j2Impl(config); assertThat(logServiceInternal.getLevel(logger), hasEntry(logger, level)); } |
EventCollector implements EventHandler { @Override public synchronized void handleEvent(Event event) { events.addLast(event); if (events.size() > maxSize) { events.removeFirst(); } consumers.forEach(c -> c.accept(event)); } EventCollector(); @Override synchronized void handleEvent(Event event); Stream<Event> getEvents(); synchronized void addConsumer(Consumer<Event> eventConsumer); synchronized void removeConsumer(Consumer<Event> eventConsumer); } | @Test public void testHandleEvent() throws Exception { EventCollector collector = new EventCollector(); assertThat(collector.getEvents().count(), equalTo(0l)); collector.handleEvent(event("myTopic")); assertThat(collector.getEvents().count(), equalTo(1l)); assertThat(collector.getEvents().findFirst().get().getTopic(), equalTo("myTopic")); } |
EventDisplayCommand implements Action { @Override public Object execute() throws Exception { EventPrinter printer = new EventPrinter(session.getConsole(), verbose); collector.getEvents().filter(matchTopic(topicFilter)).forEach(printer); return null; } @Override Object execute(); } | @Test public void testExecute() throws Exception { IMocksControl c = createControl(); EventDisplayCommand display = new EventDisplayCommand(); display.session = c.createMock(Session.class); expect(display.session.getConsole()).andReturn(System.out); display.collector = new EventCollector(); display.collector.handleEvent(new Event("myTopic", new HashMap<>())); c.replay(); display.execute(); c.verify(); } |
EventTailCommand implements Action { @Override public Object execute() throws Exception { EventPrinter printer = new EventPrinter(session.getConsole(), verbose); Consumer<Event> filteredPrinter = executeIf(matchTopic(topicFilter), printer); collector.addConsumer(filteredPrinter); try { waitTillInterrupted(); } catch (InterruptedException e) { collector.removeConsumer(filteredPrinter); } return null; } @Override Object execute(); } | @Test public void testTail() throws Exception { EventTailCommand tail = new EventTailCommand(); tail.session = mock(Session.class); tail.collector = new EventCollector(); PrintStream out = System.out; expect(tail.session.getConsole()).andReturn(out); exception = null; replay(tail.session); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { try { tail.execute(); } catch (Exception e) { exception = e; } }); tail.collector.handleEvent(event()); Thread.sleep(200); executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); if (exception != null) { throw exception; } verify(tail.session); } |
EventPrinter implements Consumer<Event> { @Override public void accept(Event event) { out.println(getTimeStamp(event) + " - " + event.getTopic()); if (verbose) { for (String key : event.getPropertyNames()) { if (!key.equals("event.topics") && !key.equals("timestamp")) { out.println(key + ": " + getPrintValue(event, key)); } } out.println(); out.flush(); } } EventPrinter(PrintStream out, boolean verbose); @Override void accept(Event event); } | @Test public void testPrint() throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); new EventPrinter(out, false).accept(event()); String result = baos.toString("utf-8"); assertThat(result, equalTo("2016-01-01 12:00:00 - myTopic\n")); }
@Test public void testPrintVerbose() throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); new EventPrinter(out, true).accept(event()); String result = baos.toString("utf-8"); assertThat(result, equalTo("2016-01-01 12:00:00 - myTopic\n" + "a: b\n" + "c: [d, e]\n\n")); } |
EventSendCommand implements Action { @Override public Object execute() throws Exception { eventAdmin.sendEvent(new Event(topic, parse(properties))); return null; } @Override Object execute(); } | @Test public void testExecute() throws Exception { EventSendCommand send = new EventSendCommand(); send.eventAdmin = mock(EventAdmin.class); Capture<Event> eventCapture = newCapture(); send.eventAdmin.sendEvent(capture(eventCapture)); expectLastCall(); replay(send.eventAdmin); send.topic = "myTopic"; send.properties = Collections.singletonList("a=b"); send.execute(); verify(send.eventAdmin); Event event = eventCapture.getValue(); assertThat(event.getTopic(), equalTo("myTopic")); assertThat(event.getProperty("a"), equalTo("b")); } |
EventSendCommand implements Action { static Map<String, String> parse(List<String> propList) { Map<String, String> properties = new HashMap<>(); if (propList != null) { for (String keyValue : propList) { int splitAt = keyValue.indexOf("="); if (splitAt <= 0) { throw new IllegalArgumentException("Invalid property " + keyValue); } else { String key = keyValue.substring(0, splitAt); String value = keyValue.substring(splitAt + 1); properties.put(key, value); } } } return properties; } @Override Object execute(); } | @Test public void testParse() { List<String> propList = Arrays.asList("a=b","b=c"); Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("a", "b"); expectedMap.put("b", "c"); Map<String, String> props = EventSendCommand.parse(propList); assertThat(props.size(), equalTo(2)); assertThat(props.get("a"), equalTo("b")); assertThat(props.get("b"), equalTo("c")); }
@Test public void testParseNull() { Map<String, String> props = EventSendCommand.parse(null); assertNotNull(props); assertThat(props.size(), equalTo(0)); }
@Test(expected=IllegalArgumentException.class) public void testParseNoKeyValue() { EventSendCommand.parse(Collections.singletonList("=")); }
@Test(expected=IllegalArgumentException.class) public void testParseNoKey() { EventSendCommand.parse(Collections.singletonList("=b")); }
@Test public void testParseStrange() { Map<String, String> props = EventSendCommand.parse(Arrays.asList("a=b","c=d=3", "e=")); assertThat(props.size(), equalTo(3)); assertThat(props.get("a"), equalTo("b")); assertThat(props.get("c"), equalTo("d=3")); assertThat(props.get("e"), equalTo("")); } |
Tree extends Node<T> { public void write(PrintStream stream) { write(new PrintWriter(stream)); } Tree(T root); void write(PrintStream stream); void write(PrintStream stream, Converter<T> converter); void write(PrintWriter writer); void write(PrintWriter writer, Converter<T> converter); } | @Test public void writeTreeWithOneChildAndNodeConverter() throws IOException { Tree<String> tree = new Tree<>("root"); tree.addChild("child"); StringWriter writer = new StringWriter(); tree.write(new PrintWriter(writer), node -> "my " + node.getValue()); BufferedReader reader = new BufferedReader(new StringReader(writer.getBuffer().toString())); assertEquals("my root" , reader.readLine()); assertEquals("+- my child" , reader.readLine()); } |
MavenConfigService { static String getLocalRepoFromConfig(Dictionary<String, Object> dict) { String path = null; if (dict != null) { path = (String) dict.get("org.ops4j.pax.url.mvn.localRepository"); if (path == null) { String settings = (String) dict.get("org.ops4j.pax.url.mvn.settings"); if (settings != null) { path = getLocalRepositoryFromSettings(new File(settings)); } } } return path; } MavenConfigService(ConfigurationAdmin configurationAdmin); } | @Test public void testLocalRepoEmpty() throws Exception { Hashtable<String, Object> config = new Hashtable<>(); assertEquals(null, MavenConfigService.getLocalRepoFromConfig(config)); }
@Test public void testLocalRepoExplicit() throws Exception { Hashtable<String, Object> config = new Hashtable<>(); config.put("org.ops4j.pax.url.mvn.localRepository", "foo/bar"); assertEquals("foo/bar", MavenConfigService.getLocalRepoFromConfig(config)); }
@Test public void testLocalRepoFromSettings() throws Exception { Hashtable<String, Object> config = new Hashtable<>(); config.put("org.ops4j.pax.url.mvn.settings", getClass().getResource("/settings.xml").getPath()); assertEquals("foo/bar", MavenConfigService.getLocalRepoFromConfig(config)); }
@Test public void testLocalRepoFromSettingsNs() throws Exception { Hashtable<String, Object> config = new Hashtable<>(); config.put("org.ops4j.pax.url.mvn.settings", getClass().getResource("/settings2.xml").getPath()); assertEquals("foo/bar", MavenConfigService.getLocalRepoFromConfig(config)); } |
SshUtils { public static List<NamedFactory<Cipher>> buildCiphers(String[] names) { ServerConfig defaults = new ServerConfig(); List<NamedFactory<Cipher>> avail = defaults.getCipherFactories(); return filter(Cipher.class, avail, names); } static List<NamedFactory<S>> filter(Class<S> type,
Collection<NamedFactory<S>> factories, String[] names); static List<KeyExchangeFactory> filter(List<KeyExchangeFactory> factories, String[] names); static List<NamedFactory<Mac>> buildMacs(String[] names); static List<NamedFactory<Cipher>> buildCiphers(String[] names); static List<KeyExchangeFactory> buildKexAlgorithms(String[] names); } | @Test public void testCiphersDefault() throws IOException { String ciphers = "aes128-ctr,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc"; List<NamedFactory<Cipher>> list = SshUtils.buildCiphers(ciphers.split(",")); for (String cipher : ciphers.split(",")) { boolean found = false; for (NamedFactory<Cipher> factory : list) { if (factory.getName().equalsIgnoreCase(cipher)) { found = true; break; } } if (!found) { Assert.fail("Configured default cipher '" + cipher + "' cannot be resolved"); } } } |
SshUtils { public static List<NamedFactory<Mac>> buildMacs(String[] names) { return filter(Mac.class, new ServerConfig().getMacFactories(), names); } static List<NamedFactory<S>> filter(Class<S> type,
Collection<NamedFactory<S>> factories, String[] names); static List<KeyExchangeFactory> filter(List<KeyExchangeFactory> factories, String[] names); static List<NamedFactory<Mac>> buildMacs(String[] names); static List<NamedFactory<Cipher>> buildCiphers(String[] names); static List<KeyExchangeFactory> buildKexAlgorithms(String[] names); } | @Test public void testMacsDefault() throws IOException { String macs = "hmac-sha2-512,hmac-sha2-256,hmac-sha1"; List<NamedFactory<Mac>> list = SshUtils.buildMacs(macs.split(",")); for (String mac : macs.split(",")) { boolean found = false; for (NamedFactory<Mac> factory : list) { if (factory.getName().equalsIgnoreCase(mac)) { found = true; break; } } if (!found) { Assert.fail("Configured default HMAC '" + mac + "' cannot be resolved"); } } } |
SshUtils { public static List<KeyExchangeFactory> buildKexAlgorithms(String[] names) { ServerConfig defaults = new ServerConfig(); List<KeyExchangeFactory> avail = defaults.getKeyExchangeFactories(); return filter(avail, names); } static List<NamedFactory<S>> filter(Class<S> type,
Collection<NamedFactory<S>> factories, String[] names); static List<KeyExchangeFactory> filter(List<KeyExchangeFactory> factories, String[] names); static List<NamedFactory<Mac>> buildMacs(String[] names); static List<NamedFactory<Cipher>> buildCiphers(String[] names); static List<KeyExchangeFactory> buildKexAlgorithms(String[] names); } | @Test public void testKexAlgorithmsDefault() throws IOException { String kexAlgorithms = "diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1"; List<KeyExchangeFactory> list = SshUtils.buildKexAlgorithms(kexAlgorithms.split(",")); for (String kex : kexAlgorithms.split(",")) { boolean found = false; for (KeyExchangeFactory factory : list) { if (factory.getName().equalsIgnoreCase(kex)) { found = true; break; } } if (!found) { Assert.fail("Configured default key exchange algorithm '" + kex + "' cannot be resolved"); } } } |
HttpMBeanImpl extends StandardMBean implements HttpMBean { @Override public TabularData getServlets() throws MBeanException { try { CompositeType servletType = new CompositeType("Servlet", "HTTP Servlet", new String[]{"Bundle-ID", "Servlet", "Servlet Name", "State", "Alias", "URL"}, new String[]{"ID of the bundle that registered the servlet", "Class name of the servlet", "Servlet Name", "Current state of the servlet", "Aliases of the servlet", "URL of the servlet"}, new OpenType[]{SimpleType.LONG, SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.STRING}); TabularType tableType = new TabularType("Servlets", "Table of all HTTP servlets", servletType, new String[]{"Bundle-ID", "Servlet Name", "State"}); TabularData table = new TabularDataSupport(tableType); List<ServletInfo> servletInfos = servletService.getServlets(); for (ServletInfo info : servletInfos) { CompositeData data = new CompositeDataSupport(servletType, new String[]{"Bundle-ID", "Servlet", "Servlet Name", "State", "Alias", "URL"}, new Object[]{info.getBundleId(), info.getClassName(), info.getName(), info.getStateString(), info.getAlias(), Arrays.toString(info.getUrls())}); table.put(data); } return table; } catch (Exception e) { throw new MBeanException(null, e.toString()); } } HttpMBeanImpl(ServletService servletService, ProxyService proxyService); @Override TabularData getServlets(); @Override Map<String, Proxy> getProxies(); @Override Collection<String> getProxyBalancingPolicies(); @Override void addProxy(String url, String proxyTo, String balancingPolicy); @Override void removeProxy(String url); } | @Test public void testRegisterMBean() throws Exception { HttpMBeanImpl httpMBean = new HttpMBeanImpl(new ServletServiceImpl(new ServletEventHandler()), new ProxyServiceImpl(null, null, null)); MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); mbeanServer.registerMBean(httpMBean, new ObjectName("org.apache.karaf:type=http,name=root")); TabularData data = httpMBean.getServlets(); } |
MavenConfigurationSupport implements Action { protected File nextSequenceFile(File dataDir, Pattern pattern, String fileNameFormat) { File[] files = dataDir.listFiles((dir, name) -> pattern.matcher(name).matches()); File result = null; if (files != null && files.length > 0) { List<String> names = new ArrayList<>(Arrays.stream(files).map(File::getName) .collect(TreeSet::new, TreeSet::add, TreeSet::addAll)); names.add(String.format(fileNameFormat, System.currentTimeMillis())); while (names.size() > MAX_SEQUENCE_SIZE) { String name = names.remove(0); new File(dataDir, name).delete(); } result = new File(dataDir, names.get(names.size() - 1)); } if (result == null) { result = new File(dataDir, String.format(fileNameFormat, new Date().getTime())); } return result; } @Override final Object execute(); static Logger LOG; } | @Test public void sequenceFiles() throws IOException { File dataDir = new File("target/data"); FileUtils.deleteDirectory(dataDir); dataDir.mkdirs(); MavenConfigurationSupport support = new MavenConfigurationSupport() { @Override protected void doAction(String prefix, Dictionary<String, Object> config) throws Exception { } }; File newFile = support.nextSequenceFile(dataDir, Pattern.compile("file-(\\d+).txt"), "file-%04d.txt"); assertTrue(Pattern.compile("^file-\\d+\\.txt$").matcher(newFile.getName()).matches()); try (FileWriter fw = new FileWriter(new File(dataDir, "file-abcd.txt"))) { fw.write("~"); } newFile = support.nextSequenceFile(dataDir, Pattern.compile("file-(\\d+).txt"), "file-%04d.txt"); assertTrue(Pattern.compile("^file-\\d+\\.txt$").matcher(newFile.getName()).matches()); try (FileWriter fw = new FileWriter(new File(dataDir, "file-0004.txt"))) { fw.write("~"); } newFile = support.nextSequenceFile(dataDir, Pattern.compile("file-(\\d+).txt"), "file-%04d.txt"); assertTrue(Pattern.compile("^file-\\d+\\.txt$").matcher(newFile.getName()).matches()); } |
MavenRepositoryURL { public String asRepositorySpec() { StringBuilder sb = new StringBuilder(); sb.append(m_repositoryURL.toString()); if (m_id != null) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_ID).append("=").append(m_id); } if (!m_releasesEnabled) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_DISALLOW_RELEASES); } if (m_snapshotsEnabled) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_ALLOW_SNAPSHOTS); } if (m_releasesEnabled) { if (!m_snapshotsEnabled) { if (m_releasesUpdatePolicy != null) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_RELEASES_UPDATE).append("=").append(m_releasesUpdatePolicy); } if (m_releasesChecksumPolicy != null) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_RELEASES_CHECKSUM).append("=").append(m_releasesChecksumPolicy); } } } if (m_snapshotsEnabled) { if (!m_releasesEnabled) { if (m_snapshotsUpdatePolicy != null) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_SNAPSHOTS_UPDATE).append("=").append(m_snapshotsUpdatePolicy); } if (m_snapshotsChecksumPolicy != null) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_SNAPSHOTS_CHECKSUM).append("=").append(m_snapshotsChecksumPolicy); } } } if (m_snapshotsEnabled && m_releasesEnabled) { if (m_releasesUpdatePolicy != null && Objects.equals(m_releasesUpdatePolicy, m_snapshotsUpdatePolicy)) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_UPDATE).append("=").append(m_releasesUpdatePolicy); } if (m_releasesChecksumPolicy != null && Objects.equals(m_releasesChecksumPolicy, m_snapshotsChecksumPolicy)) { sb.append(ServiceConstants.SEPARATOR_OPTIONS).append(ServiceConstants.OPTION_CHECKSUM).append("=").append(m_releasesChecksumPolicy); } } return sb.toString(); } MavenRepositoryURL( final String repositorySpec ); String getId(); URL getURL(); void setURL(URL url); File getFile(); boolean isReleasesEnabled(); void setReleasesEnabled(boolean enabled); boolean isSnapshotsEnabled(); void setSnapshotsEnabled(boolean enabled); String getReleasesUpdatePolicy(); String getSnapshotsUpdatePolicy(); String getReleasesChecksumPolicy(); String getSnapshotsChecksumPolicy(); void setReleasesUpdatePolicy(String policy); void setSnapshotsUpdatePolicy(String policy); void setReleasesChecksumPolicy(String policy); void setSnapshotsChecksumPolicy(String policy); FROM getFrom(); boolean isMulti(); boolean isFileRepository(); @Override String toString(); String asRepositorySpec(); } | @Test public void uris() throws MalformedURLException { String uri1, uri2; MavenRepositoryURL mavenURI; uri1 = "http: uri2 = "http: mavenURI = new MavenRepositoryURL(uri1); assertThat(mavenURI.asRepositorySpec(), equalTo(uri2)); uri1 = "http: uri2 = "http: mavenURI = new MavenRepositoryURL(uri1); assertThat(mavenURI.asRepositorySpec(), equalTo(uri2)); uri1 = "http: uri2 = "http: mavenURI = new MavenRepositoryURL(uri1); assertThat(mavenURI.asRepositorySpec(), equalTo(uri2)); uri1 = "http: uri2 = "http: mavenURI = new MavenRepositoryURL(uri1); assertThat(mavenURI.asRepositorySpec(), equalTo(uri2)); uri1 = "http: uri2 = "http: mavenURI = new MavenRepositoryURL(uri1); assertThat(mavenURI.asRepositorySpec(), equalTo(uri2)); uri1 = "http: uri2 = "http: mavenURI = new MavenRepositoryURL(uri1); assertThat(mavenURI.asRepositorySpec(), equalTo(uri2)); } |
FilterParser { public Expression parse(String filter) { return parse(new ExprTokenizer(filter)); } Expression parse(String filter); } | @Test public void testSimpleItem() { Expression expr = new FilterParser().parse(" (a= b)"); SimpleItem item = (SimpleItem) expr; checkItem(item, "a", FilterType.equal, "b"); }
@Test public void testNotSimpleItem() { NotExpression not = (NotExpression) new FilterParser().parse("(!(a=b))"); checkItem(not.expression, "a", FilterType.equal, "b"); }
@Test public void testPackageImport() { AndExpression expr = (AndExpression) new FilterParser().parse("(&(osgi.wiring.package=org.mypackage)(version>=1.9.0)(!(version>=2.0.0)))"); Assert.assertEquals(3, expr.expressions.length); checkItem(expr.expressions[0], "osgi.wiring.package", FilterType.equal, "org.mypackage"); checkItem(expr.expressions[1], "version", FilterType.gt, "1.9.0"); NotExpression notVersion = (NotExpression)expr.expressions[2]; checkItem(notVersion.expression, "version", FilterType.gt, "2.0.0"); }
@Test public void testPackageImportNoVersions() { Expression expr = new FilterParser().parse("(osgi.wiring.package=org.mypackage)"); checkItem(expr, "osgi.wiring.package", FilterType.equal, "org.mypackage"); } |
SyncopeLoginModule extends AbstractKarafLoginModule { protected List<String> extractingRolesSyncope1(String response) throws Exception { List<String> roles = new ArrayList<>(); if (response != null && !response.isEmpty()) { int index = response.indexOf("<memberships>"); if (index != -1) { response = response.substring(index + "<memberships>".length()); index = response.indexOf("</memberships>"); response = response.substring(0, index); index = response.indexOf("<roleName>"); while (index != -1) { response = response.substring(index + "<roleName>".length()); int end = response.indexOf("</roleName>"); if (end == -1) { index = -1; } String role = response.substring(0, end); roles.add(role); response = response.substring(end + "</roleName>".length()); index = response.indexOf("<roleName>"); } } } return roles; } void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options); boolean login(); final static String ADDRESS; final static String VERSION; final static String USE_ROLES_FOR_SYNCOPE2; final static String ADMIN_USER; final static String ADMIN_PASSWORD; } | @Test public void testRolesExtractionSyncope1() throws Exception { String syncopeResponse = read("syncope1Response.xml"); SyncopeLoginModule syncopeLoginModule = new SyncopeLoginModule(); List<String> roles = syncopeLoginModule.extractingRolesSyncope1(syncopeResponse); assertThat(roles, contains("admin", "another")); } |
SyncopeLoginModule extends AbstractKarafLoginModule { @SuppressWarnings("unchecked") protected List<String> extractingRolesSyncope2(String response) throws Exception { List<String> roles = new ArrayList<>(); if (response != null && !response.isEmpty()) { JSONParser parser = new JSONParser(response); if (useRolesForSyncope2) { return (List<String>) parser.getParsed().get("roles"); } else { List<Map<String, String>> memberships = (List<Map<String, String>>) parser.getParsed().get("memberships"); if (memberships != null) { for (Map<String, String> membership : memberships) { if (membership.containsKey("groupName")) { roles.add(membership.get("groupName")); } } } } } return roles; } void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options); boolean login(); final static String ADDRESS; final static String VERSION; final static String USE_ROLES_FOR_SYNCOPE2; final static String ADMIN_USER; final static String ADMIN_PASSWORD; } | @Test public void testGroupsExtractionSyncope2() throws Exception { String syncopeResponse = read("syncope2Response.json"); SyncopeLoginModule syncopeLoginModule = new SyncopeLoginModule(); List<String> roles = syncopeLoginModule.extractingRolesSyncope2(syncopeResponse); assertThat(roles, contains("manager")); } |
AbstractAuditLoginModule implements LoginModule { protected String getPrincipalInfo() { String principalInfo; List<String> principalInfos = subject.getPrincipals(ClientPrincipal.class).stream().map(ClientPrincipal::getName).collect(toList()); if (principalInfos.size() > 0) { principalInfo = String.join(", ", principalInfos); } else { principalInfo = "no client principals found"; } return principalInfo; } void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options); boolean login(); boolean commit(); boolean abort(); boolean logout(); } | @Test public void getPrincipalInfo() { LogAuditLoginModule module = new LogAuditLoginModule(); Map<String, String> options = new HashMap<>(); options.put("logger", "test"); Subject subject = new Subject(); subject.getPrincipals().add(new ClientPrincipal("ssh", "/127.0.0.1")); subject.getPrincipals().add(new ClientPrincipal("ssh", "/127.0.0.2")); subject.getPrincipals().add((UserPrincipal) () -> "noexist"); module.initialize(subject, new NamePasswordCallbackHandler("myuser", "mypassword"), null, options); Assert.assertEquals("ssh(/127.0.0.1), ssh(/127.0.0.2)", module.getPrincipalInfo()); } |
ManageRealmCommand extends JaasCommandSupport { @SuppressWarnings("unchecked") @Override public Object execute() throws Exception { if (realmName == null && index <= 0) { System.err.println("A valid realm or the realm index need to be specified"); return null; } JaasRealm oldRealm = (JaasRealm) this.session.get(JAAS_REALM); AppConfigurationEntry oldEntry = (AppConfigurationEntry) this.session.get(JAAS_ENTRY); if (oldRealm != null && !oldRealm.getName().equals(realmName) && !force) { System.err.println("Another JAAS Realm is being edited. Cancel/update first, or use the --force option."); } else if (oldEntry != null && !oldEntry.getLoginModuleName().equals(moduleName) && !force) { System.err.println("Another JAAS Login Module is being edited. Cancel/update first, or use the --force option."); } else { JaasRealm realm = null; AppConfigurationEntry entry = null; if (index > 0) { List<JaasRealm> realms = getRealms(hidden); if (realms != null && realms.size() > 0) { int i = 1; realms_loop: for (JaasRealm r : realms) { AppConfigurationEntry[] entries = r.getEntries(); if (entries != null) { for (AppConfigurationEntry entry1 : entries) { if (i == index) { realm = r; entry = entry1; break realms_loop; } i++; } } } } } else { List<JaasRealm> realms = getRealms(hidden); if (realms != null && realms.size() > 0) { for (JaasRealm r : realms) { if (r.getName().equals(realmName)) { realm = r; AppConfigurationEntry[] entries = realm.getEntries(); if (entries != null) { for (AppConfigurationEntry e : entries) { String moduleClass = (String) e.getOptions().get(ProxyLoginModule.PROPERTY_MODULE); if (moduleName == null) { if (getBackingEngine(e) != null) { entry = e; break; } } else { if (moduleName.equals(e.getLoginModuleName()) || moduleName.equals(moduleClass)) { if (getBackingEngine(e) != null) { entry = e; break; } } } } if (entry != null) { break; } } } } } } if (realm == null) { System.err.println("JAAS realm has not been found."); return null; } if (entry == null) { System.err.println("JAAS module has not been found."); return null; } Queue<JaasCommandSupport> commands = null; commands = (Queue<JaasCommandSupport>) this.session.get(JAAS_CMDS); if (commands == null) { commands = new LinkedList<>(); } this.session.put(JAAS_REALM, realm); this.session.put(JAAS_ENTRY, entry); this.session.put(JAAS_CMDS, commands); } return null; } @SuppressWarnings("unchecked") @Override Object execute(); } | @Test public void testRealmAdd() throws Exception { RealmAddCommand cmd = new RealmAddCommand(); cmd.setRealmname("myDummyRealm"); Session session = createMock(Session.class); BundleContext bundleContext = createMock(BundleContext.class); Bundle bundle = createMock(Bundle.class); cmd.setContext(bundleContext); cmd.setSession(session); Object[] mocks = { session, bundleContext, bundle }; expect(bundleContext.registerService(anyObject(Class.class), (Object)anyObject(), anyObject())).andReturn(null).anyTimes(); replay(mocks); cmd.execute(); verify(mocks); }
@Test public void testModuleAdd() throws Exception { RealmAddCommand cmd = new RealmAddCommand(); cmd.setRealmname("myDummyRealm"); ModuleAddCommand addCmd = new ModuleAddCommand(); addCmd.setLoginModule(DummyClass.class.getName()); addCmd.setPropertiesList(Collections.emptyList()); Session session = createMock(Session.class); BundleContext bundleContext = createMock(BundleContext.class); Bundle bundle = createMock(Bundle.class); cmd.setContext(bundleContext); cmd.setSession(session); addCmd.setSession(session); Object[] mocks = { session, bundleContext, bundle }; expect(session.get(ManageRealmCommand.JAAS_ENTRY)).andReturn(null).anyTimes(); expect(session.get(ManageRealmCommand.JAAS_CMDS)).andReturn(null).anyTimes(); expect(bundleContext.getBundle()).andReturn(bundle).anyTimes(); expect(bundle.getBundleId()).andReturn(4711L).anyTimes(); Capture<Object> captureSingleArgument = newCapture(); expect(bundleContext.registerService(anyObject(Class.class), (Object)capture(captureSingleArgument), anyObject())).andReturn(null).anyTimes(); expect(session.get(ManageRealmCommand.JAAS_REALM)).andAnswer(() -> captureSingleArgument.getValue()).anyTimes(); replay(mocks); cmd.execute(); addCmd.execute(); verify(mocks); assertNotNull((Config) captureSingleArgument.getValue()); assertEquals(2, ((Config) captureSingleArgument.getValue()).getModules().length); } |
ObjectClassMatcher { static String getShortName(String name) { int idx = name.lastIndexOf("."); if (idx + 1 > name.length()) { idx = 0; } return name.substring(idx + 1); } private ObjectClassMatcher(); } | @Test public void testGetShortName() { Assert.assertEquals("TestClass", ObjectClassMatcher.getShortName("org.apache.TestClass")); Assert.assertEquals("", ObjectClassMatcher.getShortName("test.")); Assert.assertEquals("TestClass", ObjectClassMatcher.getShortName("TestClass")); } |
ObjectClassMatcher { static boolean matchesName(String name, String pattern) { return name.equals(pattern) || getShortName(name).equals(pattern); } private ObjectClassMatcher(); } | @Test public void testMatchesName() { Assert.assertTrue(ObjectClassMatcher.matchesName("org.apache.TestClass", "TestClass")); Assert.assertTrue(ObjectClassMatcher.matchesName("TestClass", "TestClass")); } |
ObjectClassMatcher { static boolean matchesAtLeastOneName(String[] names, String pattern) { for (String objectClass : names) { if (matchesName(objectClass, pattern)) { return true; } } return false; } private ObjectClassMatcher(); } | @Test public void testMatchesAtLeastOneName() { Assert.assertTrue(ObjectClassMatcher.matchesAtLeastOneName(new String[]{"other", "org.apache.TestClass"}, "TestClass")); Assert.assertFalse(ObjectClassMatcher.matchesAtLeastOneName(new String[]{"TestClass2"}, "TestClass")); } |
ACLConfigurationParser { public static List<String> parseRoles(String roleStr) { int hashIdx = roleStr.indexOf('#'); if (hashIdx >= 0) { roleStr = roleStr.substring(0, hashIdx); } List<String> roles = new ArrayList<>(); for (String role : roleStr.split("[,]")) { String trimmed = role.trim(); if (trimmed.length() > 0) { roles.add(trimmed); } } return roles; } static Specificity getRolesForInvocation(String methodName, Object[] params, String[] signature,
Dictionary<String, Object> config, List<String> addToRoles); static Specificity getRolesForInvocationForAlias(String methodName, Object[] params, String[] signature,
Dictionary<String, Object> config, List<String> addToRoles); static void getCompulsoryRoles(List<String> roles); static List<String> parseRoles(String roleStr); } | @Test public void testParseRoles() { assertEquals(Collections.singletonList("some_role"), ACLConfigurationParser.parseRoles(" some_role ")); assertEquals(Arrays.asList("a","b","C"), ACLConfigurationParser.parseRoles("a,b,C")); assertEquals(Collections.emptyList(), ACLConfigurationParser.parseRoles("# test comment")); } |
ACLConfigurationParser { public static Specificity getRolesForInvocation(String methodName, Object[] params, String[] signature, Dictionary<String, Object> config, List<String> addToRoles) { Dictionary<String, Object> properties = trimKeys(config); String pid = (String)properties.get("service.pid"); Specificity s = getRolesBasedOnSignature(methodName, params, signature, properties, addToRoles); if (s != Specificity.NO_MATCH) { return s; } s = getRolesBasedOnSignature(methodName, params, null, properties, addToRoles); if (s != Specificity.NO_MATCH) { return s; } List<String> roles = getMethodNameWildcardRoles(properties, methodName); if (roles != null) { addToRoles.addAll(roles); return Specificity.WILDCARD_MATCH; } else if (compulsoryRoles != null && !pid.contains("jmx.acl")){ addToRoles.addAll(ACLConfigurationParser.parseRoles(compulsoryRoles)); return Specificity.NAME_MATCH; } else { return Specificity.NO_MATCH; } } static Specificity getRolesForInvocation(String methodName, Object[] params, String[] signature,
Dictionary<String, Object> config, List<String> addToRoles); static Specificity getRolesForInvocationForAlias(String methodName, Object[] params, String[] signature,
Dictionary<String, Object> config, List<String> addToRoles); static void getCompulsoryRoles(List<String> roles); static List<String> parseRoles(String roleStr); } | @Test public void testGetRolesForInvocation() { Dictionary<String, Object> config = new Hashtable<>(); config.put("foo", "r1, r2"); config.put("bar(java.lang.String, int)[/aa/,/42/]", "ra"); config.put("bar(java.lang.String, int)[/bb/,/42/]", "rb"); config.put("bar(java.lang.String, int)[\"cc\", \"17\"]", "rc"); config.put("bar(java.lang.String, int)", "rd"); config.put("bar(java.lang.String)", "re"); config.put("bar", "rf"); config.put("ba*", "rg #Wildcard"); List<String> roles1 = new ArrayList<>(); assertEquals(Specificity.NAME_MATCH, ACLConfigurationParser.getRolesForInvocation("foo", new Object [] {}, new String [] {}, config, roles1)); assertEquals(Arrays.asList("r1", "r2"), roles1); List<String> roles2 = new ArrayList<>(); assertEquals(Specificity.NAME_MATCH, ACLConfigurationParser.getRolesForInvocation("foo", new Object [] {"test"}, new String [] {"java.lang.String"}, config, roles2)); assertEquals(Arrays.asList("r1", "r2"), roles2); List<String> roles3 = new ArrayList<>(); assertEquals(Specificity.NO_MATCH, ACLConfigurationParser.getRolesForInvocation("test", new Object [] {}, new String [] {}, config, roles3)); assertEquals(0, roles3.size()); List<String> roles4 = new ArrayList<>(); assertEquals(Specificity.ARGUMENT_MATCH, ACLConfigurationParser.getRolesForInvocation("bar", new Object [] {"aa", 42}, new String [] {"java.lang.String", "int"}, config, roles4)); assertEquals(Collections.singletonList("ra"), roles4); List<String> roles5 = new ArrayList<>(); assertEquals(Specificity.ARGUMENT_MATCH, ACLConfigurationParser.getRolesForInvocation("bar", new Object [] {"bb", 42}, new String [] {"java.lang.String", "int"}, config, roles5)); assertEquals(Collections.singletonList("rb"), roles5); List<String> roles6 = new ArrayList<>(); assertEquals(Specificity.ARGUMENT_MATCH, ACLConfigurationParser.getRolesForInvocation("bar", new Object [] {"cc", 17}, new String [] {"java.lang.String", "int"}, config, roles6)); assertEquals(Collections.singletonList("rc"), roles6); List<String> roles7 = new ArrayList<>(); assertEquals(Specificity.SIGNATURE_MATCH, ACLConfigurationParser.getRolesForInvocation("bar", new Object [] {"aaa", 42}, new String [] {"java.lang.String", "int"}, config, roles7)); assertEquals(Collections.singletonList("rd"), roles7); List<String> roles8 = new ArrayList<>(); assertEquals(Specificity.SIGNATURE_MATCH, ACLConfigurationParser.getRolesForInvocation("bar", new Object [] {"aa"}, new String [] {"java.lang.String"}, config, roles8)); assertEquals(Collections.singletonList("re"), roles8); List<String> roles9 = new ArrayList<>(); assertEquals(Specificity.NAME_MATCH, ACLConfigurationParser.getRolesForInvocation("bar", new Object [] {42}, new String [] {"int"}, config, roles9)); assertEquals(Collections.singletonList("rf"), roles9); List<String> roles10 = new ArrayList<>(); assertEquals(Specificity.WILDCARD_MATCH, ACLConfigurationParser.getRolesForInvocation("barr", new Object [] {42}, new String [] {"int"}, config, roles10)); assertEquals(Collections.singletonList("rg"), roles10); } |
GuardingEventHook implements EventListenerHook { @Override public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) { if (servicesFilter == null) { return; } ServiceReference<?> sr = event.getServiceReference(); if (!servicesFilter.match(sr)) { return; } boolean proxificationDone = false; BundleContext system = bundleContext.getBundle(0).getBundleContext(); for (Iterator<BundleContext> i = listeners.keySet().iterator(); i.hasNext(); ) { BundleContext bc = i.next(); if (bc == bundleContext || bc == system) { continue; } if (proxificationDone || (proxificationDone = guardProxyCatalog.handleProxificationForHook(sr))) { i.remove(); } } } GuardingEventHook(BundleContext bundleContext, GuardProxyCatalog guardProxyCatalog, Filter securedServicesFilter); @Override void event(ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners); } | @SuppressWarnings("unchecked") @Test public void testEventHookEvents() throws Exception { BundleContext frameworkBC = mockBundleContext(0L); Dictionary<String, Object> config = new Hashtable<>(); config.put("service.guard", "(service.id=*)"); BundleContext hookBC = mockConfigAdminBundleContext(frameworkBC, config); GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC); Filter serviceFilter = FrameworkUtil.createFilter("(foo=bar)"); GuardingEventHook geh = new GuardingEventHook(hookBC, gpc, serviceFilter); Dictionary<String, Object> props = new Hashtable<>(); props.put(Constants.SERVICE_ID, 13L); ServiceReference<?> sref = mockServiceReference(props); BundleContext client1BC = mockBundleContext(123L); Map<BundleContext, Collection<ListenerInfo>> listeners = new HashMap<>(); listeners.put(client1BC, Collections.emptyList()); assertEquals("Precondition", 0, gpc.proxyMap.size()); geh.event(new ServiceEvent(ServiceEvent.REGISTERED, sref), listeners); assertEquals("No proxy should have been created because the service doesn't match the filter", 0, gpc.proxyMap.size()); assertEquals("Nothing should have been removed from the listeners", 1, listeners.size()); long service2ID = 887L; Dictionary<String, Object> props2 = new Hashtable<>(); props2.put(Constants.SERVICE_ID, service2ID); props2.put("a", "b"); props2.put("foo", "bar"); ServiceReference<?> sref2 = mockServiceReference(props2); ServiceEvent se2 = new ServiceEvent(ServiceEvent.REGISTERED, sref2); Map<BundleContext, Collection<ListenerInfo>> listeners2 = new Hashtable<>(); listeners2.put(frameworkBC, Collections.emptyList()); listeners2.put(hookBC, Collections.emptyList()); geh.event(se2, listeners2); assertEquals("No proxies to be created for the hook bundle or the system bundle", 0, gpc.proxyMap.size()); assertEquals("Nothing should have been removed from the listeners", 2, listeners2.size()); Map<BundleContext, Collection<ListenerInfo>> listeners3 = new HashMap<>(); listeners3.put(client1BC, Collections.emptyList()); geh.event(se2, listeners3); assertEquals("The service should be hidden from these listeners", 0, listeners3.size()); assertEquals("Proxy should have been created for this client", 1, gpc.proxyMap.size()); assertEquals(Long.valueOf(service2ID), gpc.proxyMap.keySet().iterator().next()); props2.put("a", "c"); Map<BundleContext, Collection<ListenerInfo>> listeners4 = new HashMap<>(); BundleContext client2BC = mockBundleContext(11); listeners4.put(client2BC, Collections.emptyList()); listeners4.put(client1BC, Collections.emptyList()); geh.event(new ServiceEvent(ServiceEvent.MODIFIED, sref2), listeners4); assertEquals("The service should be hidden from these listeners", 0, listeners4.size()); assertEquals("There should not be an additional proxy for client 2", 1, gpc.proxyMap.size()); assertNotNull(gpc.proxyMap.get(service2ID)); long service3ID = 1L; Dictionary<String, Object> props3 = new Hashtable<>(); props3.put(Constants.SERVICE_ID, service3ID); props3.put("foo", "bar"); ServiceReference<?> sref3 = mockServiceReference(props3); Map<BundleContext, Collection<ListenerInfo>> listeners5 = new HashMap<>(); listeners5.put(client1BC, Collections.emptyList()); listeners5.put(client1BC, Collections.emptyList()); geh.event(new ServiceEvent(ServiceEvent.REGISTERED, sref3), listeners5); assertEquals("There should be an additional procy for client1 to the new service", 2, gpc.proxyMap.size()); assertEquals("The service should be hidden from these listeners", 0, listeners5.size()); assertNotNull(gpc.proxyMap.get(service2ID)); assertNotNull(gpc.proxyMap.get(service3ID)); }
@SuppressWarnings("unchecked") @Test public void testEventHookProxyEvents() throws Exception { BundleContext frameworkBC = mockBundleContext(0L); Dictionary<String, Object> config = new Hashtable<>(); config.put("service.guard", "(service.id=*)"); BundleContext hookBC = mockConfigAdminBundleContext(frameworkBC, config); GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC); Filter serviceFilter = FrameworkUtil.createFilter("(service.id=*)"); GuardingEventHook geh = new GuardingEventHook(hookBC, gpc, serviceFilter); BundleContext client1BC = mockBundleContext(123L); Dictionary<String, Object> props = new Hashtable<>(); props.put(Constants.SERVICE_ID, 13L); props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); ServiceReference<?> sref = mockServiceReference(props); Map<BundleContext, Collection<ListenerInfo>> listeners = new HashMap<>(); listeners.put(client1BC, Collections.emptyList()); assertEquals("Precondition", 0, gpc.proxyMap.size()); geh.event(new ServiceEvent(ServiceEvent.REGISTERED, sref), listeners); assertEquals("No changes expected for the proxy map.", 0, gpc.proxyMap.size()); assertEquals("The event should be delivered to the client", 1, listeners.size()); Map<BundleContext, Collection<ListenerInfo>> listeners2 = new HashMap<>(); listeners2.put(mockBundleContext(51L), Collections.emptyList()); geh.event(new ServiceEvent(ServiceEvent.REGISTERED, sref), listeners2); assertEquals("No changes expected for the proxy map.", 0, gpc.proxyMap.size()); assertEquals("The event should be delivered to the client", 1, listeners2.size()); }
@Test public void testEventHookNoFilter() throws Exception { BundleContext hookBC = mockBundleContext(5L); GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC); GuardingEventHook geh = new GuardingEventHook(hookBC, gpc, null); geh.event(null, null); } |
Activator implements BundleActivator { @Override public void start(BundleContext bundleContext) throws Exception { String f = System.getProperty(GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP); Filter securedServicesFilter; if (f == null) { logger.info("No role-based security for services as its system property is not set: {}", GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP); return; } else { securedServicesFilter = bundleContext.createFilter(f); logger.info("Adding role-based security to services with filter: {}", f); } guardProxyCatalog = new GuardProxyCatalog(bundleContext); guardingEventHook = new GuardingEventHook(bundleContext, guardProxyCatalog, securedServicesFilter); bundleContext.registerService(EventListenerHook.class, guardingEventHook, null); guardingFindHook = new GuardingFindHook(bundleContext, guardProxyCatalog, securedServicesFilter); bundleContext.registerService(FindHook.class, guardingFindHook, null); } @Override void start(BundleContext bundleContext); @Override void stop(BundleContext bundleContext); } | @SuppressWarnings("unchecked") @Test public void testStartActivator() throws Exception { Properties oldProps = new Properties(); oldProps.putAll(System.getProperties()); try { System.setProperty(GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP, "(foo=bar)"); Bundle b = EasyMock.createMock(Bundle.class); EasyMock.expect(b.getBundleId()).andReturn(768L).anyTimes(); EasyMock.replay(b); BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); EasyMock.expect(bc.createFilter(EasyMock.anyObject(String.class))).andAnswer( () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.expect(bc.registerService( EasyMock.eq(EventListenerHook.class), EasyMock.isA(EventListenerHook.class), EasyMock.isNull(Dictionary.class))) .andReturn(null); EasyMock.expect(bc.registerService( EasyMock.eq(FindHook.class), EasyMock.isA(FindHook.class), EasyMock.isNull(Dictionary.class))) .andReturn(null); EasyMock.replay(bc); Activator a = new Activator(); a.start(bc); assertNotNull(a.guardProxyCatalog); assertNotNull(a.guardingEventHook); assertNotNull(a.guardingFindHook); EasyMock.verify(bc); } finally { System.setProperties(oldProps); } }
@Test public void testStartActivatorNoServicesSecured() throws Exception { Properties oldProps = new Properties(); oldProps.putAll(System.getProperties()); try { Properties newProps = removeProperties(System.getProperties(), GuardProxyCatalog.KARAF_SECURED_SERVICES_SYSPROP); System.setProperties(newProps); BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.replay(bc); Activator a = new Activator(); a.start(bc); assertNull(a.guardProxyCatalog); } finally { System.setProperties(oldProps); } } |
Activator implements BundleActivator { @Override public void stop(BundleContext bundleContext) throws Exception { if (guardProxyCatalog != null) { guardProxyCatalog.close(); } } @Override void start(BundleContext bundleContext); @Override void stop(BundleContext bundleContext); } | @Test public void testStopActivator() throws Exception { Activator a = new Activator(); a.guardProxyCatalog = EasyMock.createMock(GuardProxyCatalog.class); a.guardProxyCatalog.close(); EasyMock.expectLastCall().once(); EasyMock.replay(a.guardProxyCatalog); a.stop(EasyMock.createMock(BundleContext.class)); EasyMock.verify(a.guardProxyCatalog); } |
GuardingFindHook implements FindHook { public void find(BundleContext bundleContext, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) { if (servicesFilter == null) { return; } if (this.bundleContext.equals(bundleContext) || bundleContext.getBundle().getBundleId() == 0) { return; } for (Iterator<ServiceReference<?>> i = references.iterator(); i.hasNext(); ) { ServiceReference<?> sr = i.next(); if (!servicesFilter.match(sr)) { continue; } if (guardProxyCatalog.handleProxificationForHook(sr)) { i.remove(); } } } GuardingFindHook(BundleContext bundleContext, GuardProxyCatalog guardProxyCatalog, Filter securedServicesFilter); void find(BundleContext bundleContext, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references); } | @SuppressWarnings("unchecked") @Test public void testFindHook() throws Exception { Dictionary<String, Object> config = new Hashtable<>(); config.put("service.guard", "(|(moo=foo)(foo=*))"); BundleContext hookBC = mockConfigAdminBundleContext(config); GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC); Filter serviceFilter = FrameworkUtil.createFilter("(foo=*)"); GuardingFindHook gfh = new GuardingFindHook(hookBC, gpc, serviceFilter); BundleContext clientBC = mockBundleContext(31L); Dictionary<String, Object> props = new Hashtable<>(); props.put(Constants.SERVICE_ID, 16L); props.put("moo", "foo"); ServiceReference<?> sref = mockServiceReference(props); Collection<ServiceReference<?>> refs = new ArrayList<>(); refs.add(sref); assertEquals("Precondition", 0, gpc.proxyMap.size()); gfh.find(clientBC, null, null, true, refs); assertEquals("The service doesn't match the filter so should have no effect", 0, gpc.proxyMap.size()); assertEquals("The service doesn't match the filter so should be presented to the client", Collections.singletonList(sref), refs); long service2ID = 17L; Dictionary<String, Object> props2 = new Hashtable<>(); props2.put(Constants.SERVICE_ID, service2ID); props2.put("foo", new Object()); ServiceReference<?> sref2 = mockServiceReference(props2); Collection<ServiceReference<?>> refs2 = new ArrayList<>(); refs2.add(sref2); gfh.find(clientBC, null, null, true, refs2); assertEquals("The service should be hidden from the client", 0, refs2.size()); assertEquals("The service should have caused a proxy creation", 1, gpc.proxyMap.size()); assertEquals("A proxy creation job should have been created", 1, gpc.createProxyQueue.size()); assertEquals(sref2.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next()); Collection<ServiceReference<?>> refs3 = new ArrayList<>(); refs3.add(sref2); gfh.find(hookBC, null, null, true, refs3); assertEquals("The service should not be hidden from the hook bundle", Collections.singletonList(sref2), refs3); assertEquals("No proxy creation caused in this case", 1, gpc.proxyMap.size()); assertEquals("No change expected", sref2.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next()); gfh.find(mockBundleContext(0L), null, null, true, refs3); assertEquals("The service should not be hidden from the framework bundle", Collections.singletonList(sref2), refs3); assertEquals("No proxy creation caused in this case", 1, gpc.proxyMap.size()); assertEquals("No change expected", sref2.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next()); gpc.createProxyQueue.clear(); gfh.find(clientBC, null, null, true, refs3); assertEquals("The service should be hidden from the client", 0, refs3.size()); assertEquals("There is already a proxy for this client, no need for an additional one", 1, gpc.proxyMap.size()); assertEquals("No additional jobs should have been scheduled", 0, gpc.createProxyQueue.size()); assertEquals("No change expected", sref2.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next()); Collection<ServiceReference<?>> refs4 = new ArrayList<>(); refs4.add(sref2); BundleContext client2BC = mockBundleContext(32768L); gfh.find(client2BC, null, null, true, refs4); assertEquals("The service should be hidden for this new client", 0, refs4.size()); assertEquals("No proxy creation job should have been created", 0, gpc.createProxyQueue.size()); assertEquals("No proxy creation caused in this case", 1, gpc.proxyMap.size()); assertEquals("No change expected", sref2.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next()); }
@SuppressWarnings("unchecked") @Test public void testFindHookProxyServices() throws Exception { Dictionary<String, Object> config = new Hashtable<>(); config.put("service.guard", "(service.id=*)"); BundleContext hookBC = mockConfigAdminBundleContext(config); GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC); Filter serviceFilter = FrameworkUtil.createFilter("(service.id=*)"); GuardingFindHook gfh = new GuardingFindHook(hookBC, gpc, serviceFilter); BundleContext clientBC = mockBundleContext(31L); Dictionary<String, Object> props = new Hashtable<>(); props.put(Constants.SERVICE_ID, 16L); props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); ServiceReference<?> sref = mockServiceReference(props); Collection<ServiceReference<?>> refs = new ArrayList<>(); refs.add(sref); gfh.find(clientBC, null, null, false, refs); assertEquals("No proxy should have been created for the proxy find", 0, gpc.proxyMap.size()); assertEquals("As the proxy is for this bundle is should be visible and remain on the list", Collections.singletonList(sref), refs); }
@Test public void testNullFilter() throws Exception { BundleContext hookBC = mockBundleContext(5L); GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC); GuardingFindHook gfh = new GuardingFindHook(hookBC, gpc, null); gfh.find(null, null, null, true, null); } |
GuardProxyCatalog implements ServiceListener { GuardProxyCatalog(BundleContext bc) throws Exception { LOG.trace("Starting GuardProxyCatalog"); myBundleContext = bc; compulsoryRoles = System.getProperty(GuardProxyCatalog.KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY); if (compulsoryRoles == null) { LOG.info("No compulsory roles for a karaf command without the ACL as its system property is not set: {}", GuardProxyCatalog.KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY); } bc.addServiceListener(this); Filter caFilter = getNonProxyFilter(bc, ConfigurationAdmin.class); LOG.trace("Creating Config Admin Tracker using filter {}", caFilter); configAdminTracker = new ServiceTracker<>(bc, caFilter, null); configAdminTracker.open(); Filter pmFilter = getNonProxyFilter(bc, ProxyManager.class); LOG.trace("Creating Proxy Manager Tracker using filter {}", pmFilter); proxyManagerTracker = new ServiceTracker<>(bc, pmFilter, new ServiceProxyCreatorCustomizer()); proxyManagerTracker.open(); } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; } | @Test public void testGuardProxyCatalog() throws Exception { Bundle b = EasyMock.createMock(Bundle.class); EasyMock.expect(b.getBundleId()).andReturn(9823L).anyTimes(); EasyMock.replay(b); BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); bc.addServiceListener(EasyMock.isA(ServiceListener.class)); EasyMock.expectLastCall().once(); String caFilter = "(&(objectClass=org.osgi.service.cm.ConfigurationAdmin)" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))"; EasyMock.expect(bc.createFilter(caFilter)).andReturn(FrameworkUtil.createFilter(caFilter)).anyTimes(); String pmFilter = "(&(objectClass=org.apache.aries.proxy.ProxyManager)" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))"; EasyMock.expect(bc.createFilter(pmFilter)).andReturn(FrameworkUtil.createFilter(pmFilter)).anyTimes(); EasyMock.replay(bc); GuardProxyCatalog gpc = new GuardProxyCatalog(bc); assertTrue("Service Tracker for ConfigAdmin should be opened", gpc.configAdminTracker.getTrackingCount() != -1); assertTrue("Service Tracker for ProxyManager should be opened", gpc.proxyManagerTracker.getTrackingCount() != -1); EasyMock.verify(bc); EasyMock.reset(bc); bc.removeServiceListener(EasyMock.isA(ServiceListener.class)); EasyMock.expectLastCall().once(); EasyMock.replay(bc); gpc.close(); assertEquals("Service Tracker for ConfigAdmin should be closed", -1, gpc.configAdminTracker.getTrackingCount()); assertEquals("Service Tracker for ProxyManager should be closed", -1, gpc.proxyManagerTracker.getTrackingCount()); EasyMock.verify(bc); } |
GuardProxyCatalog implements ServiceListener { boolean isProxy(ServiceReference<?> sr) { return sr.getProperty(PROXY_SERVICE_KEY) != null; } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; } | @Test public void testIsProxy() throws Exception { BundleContext bc = mockBundleContext(); GuardProxyCatalog gpc = new GuardProxyCatalog(bc); Dictionary<String, Object> props = new Hashtable<>(); props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); assertTrue(gpc.isProxy(mockServiceReference(props))); assertFalse(gpc.isProxy(mockServiceReference(new Hashtable<>()))); } |
GuardProxyCatalog implements ServiceListener { boolean handleProxificationForHook(ServiceReference<?> sr) { if (isProxy(sr)) { return false; } proxyIfNotAlreadyProxied(sr); return true; } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; } | @SuppressWarnings("unchecked") @Test public void testHandleProxificationForHook() throws Exception { Dictionary<String, Object> config = new Hashtable<>(); config.put(Constants.SERVICE_PID, GuardProxyCatalog.SERVICE_ACL_PREFIX + "foo"); config.put(GuardProxyCatalog.SERVICE_GUARD_KEY, "(a>=5)"); BundleContext bc = mockConfigAdminBundleContext(config); GuardProxyCatalog gpc = new GuardProxyCatalog(bc); Dictionary<String, Object> props = new Hashtable<>(); props.put(Constants.SERVICE_ID, 13L); props.put("a", "6"); props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); ServiceReference<?> sref2 = mockServiceReference(props); assertFalse("Should not hide an existing proxy for this client", gpc.handleProxificationForHook(sref2)); assertEquals("No proxy should have been created", 0, gpc.proxyMap.size()); Dictionary<String, Object> props4 = new Hashtable<>(); props4.put(Constants.SERVICE_ID, 15L); props4.put("a", "7"); ServiceReference<?> sref4 = mockServiceReference(props4); assertTrue("Should hide a service that needs to be proxied", gpc.handleProxificationForHook(sref4)); assertEquals("Should trigger proxy creation", 1, gpc.proxyMap.size()); } |
GuardProxyCatalog implements ServiceListener { @Override public void serviceChanged(ServiceEvent event) { ServiceReference<?> sr = event.getServiceReference(); if (event.getType() == ServiceEvent.REGISTERED) { return; } if (isProxy(sr)) { return; } Long orgServiceID = (Long) sr.getProperty(Constants.SERVICE_ID); if (event.getType() == ServiceEvent.UNREGISTERING) { handleOriginalServiceUnregistering(orgServiceID); } if ((event.getType() & (ServiceEvent.MODIFIED | ServiceEvent.MODIFIED_ENDMATCH)) > 0) { handleOriginalServiceModifed(orgServiceID, sr); } } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; } | @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testHandleServiceUnregistering() throws Exception { BundleContext clientBC = openStrictMockBundleContext(mockBundle(12345L)); BundleContext client2BC = openStrictMockBundleContext(mockBundle(6L)); EasyMock.replay(clientBC); EasyMock.replay(client2BC); Hashtable<String, Object> props = new Hashtable<>(); long originalServiceID = 12345678901234L; props.put(Constants.SERVICE_ID, Long.valueOf(originalServiceID)); props.put("foo", "bar"); ServiceReference<?> originalRef = mockServiceReference(props); Hashtable<String, Object> props2 = new Hashtable<>(); long anotherServiceID = 5123456789012345L; props2.put(Constants.SERVICE_ID, anotherServiceID); ServiceReference<?> anotherRef = mockServiceReference(props2); GuardProxyCatalog gpc = new GuardProxyCatalog(mockBundleContext()); ServiceRegistration<?> proxyReg = EasyMock.createMock(ServiceRegistration.class); EasyMock.expect(proxyReg.getReference()).andReturn((ServiceReference) mockServiceReference(props)).anyTimes(); proxyReg.unregister(); EasyMock.expectLastCall().once(); EasyMock.replay(proxyReg); ServiceRegistrationHolder srh = new GuardProxyCatalog.ServiceRegistrationHolder(); srh.registration = proxyReg; ServiceRegistration<?> proxy2Reg = EasyMock.createMock(ServiceRegistration.class); EasyMock.replay(proxy2Reg); ServiceRegistrationHolder srh2 = new GuardProxyCatalog.ServiceRegistrationHolder(); srh2.registration = proxy2Reg; gpc.proxyMap.put(originalServiceID, srh); gpc.proxyMap.put(anotherServiceID, srh2); assertEquals("Precondition", 2, gpc.proxyMap.size()); gpc.createProxyQueue.put(new MockCreateProxyRunnable(originalServiceID)); gpc.createProxyQueue.put(new MockCreateProxyRunnable(777)); assertEquals("Precondition", 2, gpc.createProxyQueue.size()); gpc.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, originalRef)); assertEquals("Registered events should be ignored", 2, gpc.proxyMap.size()); assertEquals("Registered events should be ignored", 2, gpc.createProxyQueue.size()); Hashtable<String, Object> proxyProps = new Hashtable<>(props); proxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); ServiceReference<?> proxyRef = mockServiceReference(proxyProps); gpc.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, proxyRef)); assertEquals("Unregistering the proxy should be ignored by the listener", 2, gpc.proxyMap.size()); assertEquals("Unregistering the proxy should be ignored by the listener", 2, gpc.createProxyQueue.size()); gpc.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, originalRef)); assertEquals("The proxy for this service should have been removed", 1, gpc.proxyMap.size()); assertEquals(anotherRef.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next()); assertEquals("The create proxy job for this service should have been removed", 1, gpc.createProxyQueue.size()); assertEquals(777, gpc.createProxyQueue.iterator().next().getOriginalServiceID()); EasyMock.verify(proxyReg); EasyMock.verify(proxy2Reg); } |
WikiParser { public void parse(Reader reader) throws IOException { BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { parse(line); } } } WikiParser(WikiVisitor visitor); void parse(Reader reader); void parse(String line); } | @Test public void parseTestDoc() throws IOException { WikiVisitor visitor = EasyMock.createStrictMock(WikiVisitor.class); visitor.startPara(0); visitor.heading(1, "myTestdoc"); visitor.endPara(); visitor.startPara(0); visitor.endPara(); visitor.startPara(0); visitor.text("Some text"); visitor.endPara(); visitor.startPara(0); visitor.enumeration("enumeration"); visitor.endPara(); visitor.startPara(0); visitor.enumeration("enumeration"); visitor.text("- wit"); visitor.text("h additional text"); visitor.endPara(); visitor.startPara(1); visitor.text("some text "); visitor.link("a link", ""); visitor.text(" some more text"); visitor.endPara(); visitor.startPara(0); visitor.text("h1 is no heading"); visitor.endPara(); visitor.startPara(0); visitor.text("some "); visitor.bold(true); visitor.text("bold"); visitor.bold(false); visitor.text(" text"); visitor.endPara(); visitor.startPara(0); visitor.text("and a line for KARAF-6650 "); visitor.text("h"); visitor.endPara(); EasyMock.replay(visitor); WikiParser parser = new WikiParser(visitor); parser.parse(new StringReader(TESTDOC)); EasyMock.verify(visitor); }
@Test public void parseHeadingSpecialCases() throws IOException { WikiVisitor visitor = EasyMock.createStrictMock(WikiVisitor.class); visitor.startPara(0); EasyMock.expectLastCall(); visitor.heading(1, ""); visitor.endPara(); visitor.startPara(0); visitor.text("hf."); visitor.endPara(); EasyMock.replay(visitor); WikiParser parser = new WikiParser(visitor); parser.parse(new StringReader(HEADINGCASES)); EasyMock.verify(visitor); } |
GuardProxyCatalog implements ServiceListener { void proxyIfNotAlreadyProxied(final ServiceReference<?> originalRef) { final long orgServiceID = (Long) originalRef.getProperty(Constants.SERVICE_ID); final ServiceRegistrationHolder registrationHolder = new ServiceRegistrationHolder(); ServiceRegistrationHolder previousHolder = proxyMap.putIfAbsent(orgServiceID, registrationHolder); if (previousHolder != null) { return; } LOG.trace("Will create proxy of service {}({})", originalRef.getProperty(Constants.OBJECTCLASS), orgServiceID); CreateProxyRunnable cpr = new CreateProxyRunnable() { @Override public long getOriginalServiceID() { return orgServiceID; } @Override public void run(final ProxyManager pm) throws Exception { String[] objectClassProperty = (String[]) originalRef.getProperty(Constants.OBJECTCLASS); ServiceFactory<Object> sf = new ProxyServiceFactory(pm, originalRef); registrationHolder.registration = originalRef.getBundle().getBundleContext().registerService( objectClassProperty, sf, proxyPropertiesRoles()); Dictionary<String, Object> actualProxyProps = copyProperties(registrationHolder.registration.getReference()); LOG.debug("Created proxy of service {} under {} with properties {}", orgServiceID, actualProxyProps.get(Constants.OBJECTCLASS), actualProxyProps); } private Dictionary<String, Object> proxyPropertiesRoles() throws Exception { Dictionary<String, Object> p = proxyProperties(originalRef); Set<String> roles = getServiceInvocationRoles(originalRef); if (roles != null) { roles.remove(ROLE_WILDCARD); p.put(SERVICE_GUARD_ROLES_PROPERTY, roles); } else { p.remove(SERVICE_GUARD_ROLES_PROPERTY); } return p; } }; try { createProxyQueue.put(cpr); } catch (InterruptedException e) { LOG.warn("Problem scheduling a proxy creator for service {}({})", originalRef.getProperty(Constants.OBJECTCLASS), orgServiceID, e); e.printStackTrace(); } } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; } | @Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void testServiceFactoryBehaviour() throws Exception { final Map<ServiceReference, Object> serviceMap = new HashMap<>(); TestServiceAPI testService = new TestService(); BundleContext bc = mockConfigAdminBundleContext(); GuardProxyCatalog gpc = new GuardProxyCatalog(bc); long serviceID = 117L; final Hashtable<String, Object> serviceProps = new Hashtable<>(); serviceProps.put(Constants.OBJECTCLASS, new String [] {TestServiceAPI.class.getName()}); serviceProps.put(Constants.SERVICE_ID, serviceID); serviceProps.put("bar", 42L); BundleContext providerBC = EasyMock.createMock(BundleContext.class); EasyMock.expect(providerBC.registerService( EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> { Dictionary<String,Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2]; ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); ServiceReference sr = mockServiceReference(props); EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); EasyMock.replay(reg); serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); return reg; }).once(); EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer( () -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(providerBC); BundleWiring bw = EasyMock.createMock(BundleWiring.class); EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes(); EasyMock.replay(bw); Bundle providerBundle = EasyMock.createNiceMock(Bundle.class); EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes(); EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes(); EasyMock.replay(providerBundle); ServiceReference sr = mockServiceReference(providerBundle, serviceProps); BundleContext clientBC = EasyMock.createMock(BundleContext.class); EasyMock.expect(clientBC.getService(sr)).andReturn(testService).anyTimes(); EasyMock.replay(clientBC); Bundle clientBundle = EasyMock.createNiceMock(Bundle.class); EasyMock.expect(clientBundle.getBundleContext()).andReturn(clientBC).anyTimes(); EasyMock.replay(clientBundle); gpc.proxyIfNotAlreadyProxied(sr); GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID); GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take(); assertEquals(117L, runnable.getOriginalServiceID()); ProxyManager pm = getProxyManager(); runnable.run(pm); ServiceReference<?> proxySR = holder.registration.getReference(); EasyMock.verify(providerBC); ServiceFactory proxyServiceSF = (ServiceFactory) serviceMap.get(proxySR); TestServiceAPI proxyService = (TestServiceAPI) proxyServiceSF.getService(clientBundle, null); assertNotSame("The proxy should not be the same object as the original service", testService, proxyService); assertEquals("Doing it", proxyService.doit()); EasyMock.reset(clientBC); EasyMock.expect(clientBC.ungetService(sr)).andReturn(true).once(); EasyMock.replay(clientBC); proxyServiceSF.ungetService(clientBundle, null, proxyService); EasyMock.verify(clientBC); } |
ConfigMBeanImpl extends StandardMBean implements ConfigMBean { @Override public void install(String url, String finalname, boolean override) throws MBeanException { if (finalname.contains("..")) { throw new IllegalArgumentException("For security reason, relative path is not allowed in config file final name"); } try { File etcFolder = new File(System.getProperty("karaf.etc")); File file = new File(etcFolder, finalname); if (file.exists()) { if (!override) { throw new IllegalArgumentException("Configuration file {} already exists " + finalname); } } try (InputStream is = new BufferedInputStream(new URL(url).openStream())) { if (!file.exists()) { File parentFile = file.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } file.createNewFile(); } try (FileOutputStream fop = new FileOutputStream(file)) { StreamUtils.copy(is, fop); } } catch (RuntimeException | MalformedURLException e) { throw e; } } catch (Exception e) { throw new MBeanException(null, e.toString()); } } ConfigMBeanImpl(); @Override List<String> getConfigs(); @Override void create(String pid); @Override void install(String url, String finalname, boolean override); @Override void delete(String pid); @Override boolean exists(String pid); @Override @SuppressWarnings("rawtypes") Map<String, String> listProperties(String pid); @Override void deleteProperty(String pid, String key); @Override void appendProperty(String pid, String key, String value); @Override void setProperty(String pid, String key, String value); @Override String getProperty(String pid, String key); @Override void update(String pid, Map<String, String> properties); @Override void append(String pid, Map<String, String> properties); @Override void delete(String pid, List<String> properties); void setConfigRepo(ConfigRepository configRepo); @Override String createFactoryConfiguration(String factoryPid); @Override String createFactoryConfiguration(String factoryPid, String alias); @Override String createFactoryConfiguration(String factoryPid, Map<String, String> properties); @Override String createFactoryConfiguration(String factoryPid, String alias, Map<String, String> properties); } | @Test public void testInstall() throws Exception { System.setProperty("karaf.etc", "./target/test-classes"); ConfigMBeanImpl configMBean = new ConfigMBeanImpl(); configMBean.install("file:./target/test-classes/test.cfg", "foo.cfg", true); File output = new File("target/test-classes/foo.cfg"); Assert.assertTrue(output.exists()); StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new FileReader(output)); String line = null; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } Assert.assertTrue(builder.toString().contains("foo=bar")); } |
KarafConfigurationPlugin implements ConfigurationPlugin { @Override public void modifyConfiguration(ServiceReference<?> reference, Dictionary<String, Object> properties) { final Object pid = properties.get(Constants.SERVICE_PID); for (Enumeration<String> keys = properties.keys(); keys.hasMoreElements(); ) { String key = keys.nextElement(); String env = (pid + "." + key).toUpperCase().replaceAll("\\.", "_"); String sys = pid + "." + key; if (System.getenv(env) != null) { String value = InterpolationHelper.substVars(System.getenv(env), null,null, convertDictionaryToMap(properties)); if (properties.get(key) != null && (properties.get(key) instanceof Number)) { properties.put(key, Integer.parseInt(value)); } else { properties.put(key, value); } } else if (System.getProperty(sys) != null) { String value = InterpolationHelper.substVars(System.getProperty(sys), null, null, convertDictionaryToMap(properties)); if (properties.get(key) != null && (properties.get(key) instanceof Number)) { properties.put(key, Integer.parseInt(value)); } else { properties.put(key, value); } } } } @Override void modifyConfiguration(ServiceReference<?> reference, Dictionary<String, Object> properties); static final String PLUGIN_ID; static final int PLUGIN_RANKING; } | @Test public void testSystemProperty() throws Exception { System.setProperty("org.apache.karaf.shell.sshPort", "8102"); KarafConfigurationPlugin plugin = new KarafConfigurationPlugin(); Dictionary<String, Object> properties = new Hashtable<>(); properties.put(Constants.SERVICE_PID, "org.apache.karaf.shell"); properties.put("foo", "bar"); properties.put("sshPort", 8101); plugin.modifyConfiguration(null, properties); Assert.assertEquals(8102, properties.get("sshPort")); Assert.assertEquals("bar", properties.get("foo")); }
@Test public void testAppending() throws Exception { System.setProperty("org.apache.karaf.features.repositories", "${repositories},third"); KarafConfigurationPlugin plugin = new KarafConfigurationPlugin(); Dictionary<String, Object> properties = new Hashtable<>(); properties.put(Constants.SERVICE_PID, "org.apache.karaf.features"); properties.put("repositories", "first,second"); properties.put("foo", "bar"); plugin.modifyConfiguration(null, properties); Assert.assertEquals("first,second,third", properties.get("repositories")); Assert.assertEquals("bar", properties.get("foo")); } |
KarArtifactInstaller implements ArtifactInstaller { public boolean canHandle(File file) { if (file.getName().endsWith(KAR_SUFFIX)) { LOGGER.info("Found a .kar file to deploy."); return true; } else if (file.isFile() && file.getName().endsWith(ZIP_SUFFIX)) { LOGGER.debug("Found a .zip file to deploy; checking contents to see if it's a Karaf archive."); ZipFile zipFile = null; try { zipFile = new ZipFile(file); if (zipFile.getEntry("META-INF/KARAF.MF") != null) { LOGGER.info("Found a Karaf archive with .zip prefix; will deploy."); return true; } } catch (Exception e) { LOGGER.warn("Problem extracting zip file '{}'; ignoring.", file.getName(), e); } finally { try { if (zipFile != null) { zipFile.close(); } } catch (IOException e) { LOGGER.warn("Problem closing zip file '{}'; ignoring.", file.getName(), e); } } } return false; } void install(File file); void uninstall(File file); void update(File file); boolean canHandle(File file); KarService getKarService(); void setKarService(KarService karService); static final String FEATURE_CLASSIFIER; } | @Test public void shouldHandleKarFile() throws Exception { assertTrue(karArtifactInstaller.canHandle(new File(goodKarFile))); }
@Test public void shouldHandleZipFileWithKarafManifest() throws Exception { assertTrue(karArtifactInstaller.canHandle(new File(zipFileWithKarafManifest))); }
@Test public void shouldIgnoreZipFileWithoutKarafManifest() throws Exception { assertFalse(karArtifactInstaller.canHandle(new File(zipFileWithoutKarafManifest))); }
@Test public void shouldIgnoreBadZipFile() throws Exception { assertFalse(karArtifactInstaller.canHandle(new File(badZipFile))); } |
SystemServiceImpl implements SystemService { @Override public void setName(String name) { try { String karafEtc = bundleContext.getProperty("karaf.etc"); File etcDir = new File(karafEtc); File syspropsFile = new File(etcDir, "system.properties"); FileInputStream fis = new FileInputStream(syspropsFile); Properties props = new Properties(); props.load(fis); fis.close(); props.setProperty("karaf.name", name); FileOutputStream fos = new FileOutputStream(syspropsFile); props.store(fos, ""); fos.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } void setBundleContext(BundleContext bundleContext); BundleContext getBundleContext(); void halt(); void halt(String time); void reboot(); void reboot(String time, Swipe cleanup); void setStartLevel(int startLevel); int getStartLevel(); @Override String getVersion(); @Override String getName(); @Override void setName(String name); FrameworkType getFramework(); void setFramework(FrameworkType framework); void setFrameworkDebug(boolean debug); @Override String setSystemProperty(String key, String value, boolean persist); } | @Test public void testSetName() throws URISyntaxException, IOException { SystemServiceImpl system = new SystemServiceImpl(); BundleContext bundleContext = EasyMock.createMock(BundleContext.class); URL propUrl = this.getClass().getClassLoader().getResource("etc/system.properties"); File propfile = new File(propUrl.toURI()); EasyMock.expect(bundleContext.getProperty("karaf.etc")).andReturn(propfile.getParentFile().getParent() + "/etc"); EasyMock.replay(bundleContext); system.setBundleContext(bundleContext); system.setName(NEW_NAME); EasyMock.verify(bundleContext); Properties props = new Properties(propfile); String nameAfter = props.getProperty("karaf.name"); Assert.assertEquals(NEW_NAME, nameAfter); } |
Builder { public Builder pidsToExtract(List<String> pidsToExtract) { if (pidsToExtract != null) { for (String pid : pidsToExtract) { this.pidsToExtract.add(pid.trim()); } } return this; } static Builder newInstance(); Builder defaultStage(Stage stage); Builder defaultAddAll(boolean addAll); Builder profilesUris(String... profilesUri); Builder libraries(String... libraries); Builder kars(String... kars); Builder kars(boolean addAll, String... kars); Builder kars(Stage stage, boolean addAll, String... kars); Builder repositories(String... repositories); Builder repositories(boolean addAll, String... repositories); Builder repositories(Stage stage, boolean addAll, String... repositories); Builder features(String... features); Builder features(Stage stage, String... features); Builder bundles(String... bundles); Builder bundles(Stage stage, String... bundles); Builder profiles(String... profiles); Builder profiles(Stage stage, String... profiles); Builder homeDirectory(Path homeDirectory); Builder javase(String javase); Builder environment(String environment); Builder useReferenceUrls(); Builder useReferenceUrls(boolean useReferenceUrls); Builder resolverParallelism(final int resolverParallelism); void writeProfiles(boolean writeProfiles); void generateConsistencyReport(String generateConsistencyReport); void setConsistencyReportProjectName(String consistencyReportProjectName); void setConsistencyReportProjectVersion(String consistencyReportProjectVersion); Builder karafVersion(KarafVersion karafVersion); Builder defaultStartLevel(int defaultStartLevel); Builder setFeaturesProcessing(Path featuresProcessing); Builder ignoreDependencyFlag(); Builder ignoreDependencyFlag(boolean ignoreDependencyFlag); Builder offline(); Builder offline(boolean offline); Builder localRepository(String localRepository); Builder mavenRepositories(String mavenRepositories); Builder resolverWrapper(Function<MavenResolver, MavenResolver> wrapper); Builder staticFramework(); Builder staticFramework(String version); Builder blacklistProfiles(Collection<String> profiles); Builder blacklistFeatures(Collection<String> features); Builder blacklistBundles(Collection<String> bundles); Builder extraProtocols(Collection<String> protocols); Builder blacklistRepositories(Collection<String> repositories); Builder blacklistPolicy(BlacklistPolicy policy); Builder propertyEdits(KarafPropertyEdits propertyEdits); Builder pidsToExtract(List<String> pidsToExtract); Builder translatedUrls(Map<String, String> translatedUrls); Builder config(String key, String value); Builder system(String key, String value); List<String> getBlacklistedProfileNames(); List<String> getBlacklistedFeatureIdentifiers(); List<String> getBlacklistedBundleURIs(); List<String> getBlacklistedRepositoryURIs(); BlacklistPolicy getBlacklistPolicy(); List<String> getPidsToExtract(); void generateAssembly(); void generateConsistencyReport(Map<String, Features> repositories, Set<Feature> allInstalledFeatures, Profile installedProfile, File result); String sanitize(String uri); static final String ORG_OPS4J_PAX_URL_MVN_PID; } | @Test public void testPidsToExtract() { String pidsToExtract = "\n" + " !jmx.acl.*,\n" + " !org.apache.karaf.command.acl.*,\n" + " *\n" + " "; List<String> p2e = Arrays.asList(pidsToExtract.split(",")); Builder builder = Builder.newInstance().pidsToExtract(p2e); assertThat(builder.getPidsToExtract().get(0), equalTo("!jmx.acl.*")); assertThat(builder.getPidsToExtract().get(1), equalTo("!org.apache.karaf.command.acl.*")); assertThat(builder.getPidsToExtract().get(2), equalTo("*")); } |
Profiles { public static Profile getEffective(final Profile profile) { return getEffective(profile, true); } private Profiles(); static Map<String, Profile> loadProfiles(final Path root); static void deleteProfile(Path root, String id); static void writeProfile(Path root, Profile profile); static Profile getOverlay(Profile profile, Map<String, Profile> profiles); static Profile getOverlay(Profile profile, Map<String, Profile> profiles, String environment); static Profile getEffective(final Profile profile); static Profile getEffective(final Profile profile, boolean finalSubstitution); static Profile getEffective(final Profile profile,
final Collection<PlaceholderResolver> resolvers); static Profile getEffective(final Profile profile,
final Collection<PlaceholderResolver> resolvers,
boolean finalSubstitution); static final String PROFILE_FOLDER_SUFFIX; } | @Test public void testProfilePlaceholderResolver() { Profile profile = ProfileBuilder.Factory.create("test") .addConfiguration("pid1", "foo", "b${profile:pid2/bar}") .addConfiguration("pid2", "bar", "a${rep}") .addConfiguration("pid2", "rep", "h") .getProfile(); Profile effective = Profiles.getEffective(profile); assertEquals("bah", effective.getConfiguration("pid1").get("foo")); }
@Test(expected = IllegalArgumentException.class) public void testProfilePlaceholderResolverWithCycle() { Profile profile = ProfileBuilder.Factory.create("test") .addConfiguration("pid1", "foo", "b${profile:pid2/bar}") .addConfiguration("pid2", "bar", "a${rep}") .addConfiguration("pid2", "rep", "h${profile:pid1/foo}") .getProfile(); Profile effective = Profiles.getEffective(profile); effective.getConfiguration("pid1").get("foo"); }
@Test public void testNonSubstitution() { Profile profile = ProfileBuilder.Factory.create("test") .addConfiguration("pid1", "key", "${foo}/${bar}") .getProfile(); Profile effective = Profiles.getEffective(profile, false); assertEquals("${foo}/${bar}", effective.getConfiguration("pid1").get("key")); } |
Profiles { public static Profile getOverlay(Profile profile, Map<String, Profile> profiles) { return getOverlay(profile, profiles, null); } private Profiles(); static Map<String, Profile> loadProfiles(final Path root); static void deleteProfile(Path root, String id); static void writeProfile(Path root, Profile profile); static Profile getOverlay(Profile profile, Map<String, Profile> profiles); static Profile getOverlay(Profile profile, Map<String, Profile> profiles, String environment); static Profile getEffective(final Profile profile); static Profile getEffective(final Profile profile, boolean finalSubstitution); static Profile getEffective(final Profile profile,
final Collection<PlaceholderResolver> resolvers); static Profile getEffective(final Profile profile,
final Collection<PlaceholderResolver> resolvers,
boolean finalSubstitution); static final String PROFILE_FOLDER_SUFFIX; } | @Test public void testProfilesOverlayComments() { String pid1 = "# My comment\nfoo = bar\n"; Profile parent = ProfileBuilder.Factory.create("parent") .addFileConfiguration("pid1.cfg", pid1.getBytes()) .getProfile(); Profile profile = ProfileBuilder.Factory.create("test") .addConfiguration("pid1", "foo", "bar2") .addParent("parent") .getProfile(); Map<String, Profile> profiles = new HashMap<>(); profiles.put(parent.getId(), parent); profiles.put(profile.getId(), profile); Profile overlay = Profiles.getOverlay(profile, profiles); String outPid1 = new String(overlay.getFileConfiguration("pid1.cfg")); assertEquals(String.format("%1$s%n%2$s%n","# My comment","foo = bar2"), outPid1); }
@Test public void overlayProfiles() { Profile p1 = ProfileBuilder.Factory.create("p1") .addAttribute("p1a1", "p1v1") .addConfiguration("p1p1", "p1p1p1", "p1p1v1") .addConfiguration("pp1", "pp1p1", "p1p1v1") .getProfile(); Profile p2 = ProfileBuilder.Factory.create("p2") .addAttribute("p2a1", "p2v1") .addConfiguration("p2p1", "p2p1p1", "p2p1v1") .addConfiguration("pp1", "pp1p1", "p2p1v1") .getProfile(); Profile c1 = ProfileBuilder.Factory.create("c2") .addParents(Arrays.asList("p1", "p2")) .getProfile(); assertThat(c1.getAttributes().get("p1a1"), nullValue()); assertThat(c1.getAttributes().get("p2a1"), nullValue()); assertThat(c1.getConfigurations().size(), equalTo(1)); assertTrue(c1.getConfigurations().containsKey("profile")); Map<String, Profile> parents = new LinkedHashMap<>(); parents.put("p1", p1); parents.put("p2", p2); Profile oc1 = Profiles.getOverlay(c1, parents); assertThat(oc1.getAttributes().get("p1a1"), equalTo("p1v1")); assertThat(oc1.getAttributes().get("p2a1"), equalTo("p2v1")); assertThat(oc1.getConfigurations().size(), equalTo(4)); assertTrue(oc1.getConfigurations().containsKey("p1p1")); assertTrue(oc1.getConfigurations().containsKey("p2p1")); assertTrue(oc1.getConfigurations().containsKey("pp1")); assertTrue(oc1.getConfigurations().containsKey("profile")); }
@Test public void inheritanceOrder() { Profile gp1 = ProfileBuilder.Factory.create("gp1") .addAttribute("a", "1") .addFileConfiguration("f", new byte[] { 0x01 }) .addAttribute("b", "1") .addAttribute("c", "1") .addConfiguration("p", "p", "1") .addConfiguration("p", "px", "1") .getProfile(); Profile gp2 = ProfileBuilder.Factory.create("gp2") .addAttribute("a", "2") .addAttribute("c", "2") .addFileConfiguration("f", new byte[] { 0x02 }) .addConfiguration("p", "p", "2") .getProfile(); Profile p1 = ProfileBuilder.Factory.create("p1") .addParents(Arrays.asList("gp1", "gp2")) .addAttribute("a", "3") .addFileConfiguration("f", new byte[] { 0x03 }) .addConfiguration("p", "p", "3") .getProfile(); Profile p2 = ProfileBuilder.Factory.create("p2") .addAttribute("a", "4") .addAttribute("b", "4") .addFileConfiguration("f", new byte[] { 0x04 }) .addConfiguration("p", "p", "4") .getProfile(); Profile c = ProfileBuilder.Factory.create("p2") .addParents(Arrays.asList("p1", "p2")) .addAttribute("a", "5") .addFileConfiguration("f", new byte[] { 0x05 }) .addConfiguration("p", "p", "5") .getProfile(); Map<String, Profile> parents = new LinkedHashMap<>(); parents.put("gp1", gp1); parents.put("gp2", gp2); parents.put("p1", p1); parents.put("p2", p2); Profile overlay = Profiles.getOverlay(c, parents); assertThat(overlay.getAttributes().get("a"), equalTo("5")); assertThat(overlay.getAttributes().get("b"), equalTo("4")); assertThat(overlay.getAttributes().get("c"), equalTo("2")); assertThat(overlay.getConfiguration("p").get("p"), equalTo("5")); assertThat(overlay.getConfiguration("p").get("px"), equalTo("1")); assertThat(overlay.getFileConfiguration("f"), equalTo(new byte[] { 0x05 })); } |
InstanceServiceImpl implements InstanceService { void addFeaturesFromSettings(File featuresCfg, final InstanceSettings settings) throws IOException { FileLockUtils.execute(featuresCfg, properties -> { appendToPropList(properties, "featuresBoot", settings.getFeatures()); appendToPropList(properties, "featuresRepositories", settings.getFeatureURLs()); }, true); } InstanceServiceImpl(); File getStorageLocation(); void setStorageLocation(File storage); long getStopTimeout(); void setStopTimeout(long stopTimeout); synchronized Instance createInstance(final String name, final InstanceSettings settings, final boolean printOutput); Instance[] getInstances(); Instance getInstance(final String name); void startInstance(final String name, final String javaOpts); void restartInstance(final String name, final String javaOpts); void stopInstance(final String name); void destroyInstance(final String name); void renameInstance(final String oldName, final String newName, final boolean printOutput); synchronized Instance cloneInstance(final String name, final String cloneName, final InstanceSettings settings, final boolean printOutput); void changeInstanceSshHost(String name, String host); static final String STORAGE_FILE; static final String BACKUP_EXTENSION; static final String DEFAULT_JAVA_OPTS; } | @Test public void testHandleFeatures() throws Exception { InstanceServiceImpl as = new InstanceServiceImpl(); File f = tempFolder.newFile(getName() + ".test"); Properties p = new Properties(); p.put("featuresBoot", "abc,def "); p.put("featuresRepositories", "somescheme: try (OutputStream os = new FileOutputStream(f)) { p.store(os, "Test comment"); } InstanceSettings s = new InstanceSettings(8122, 1122, 44444, null, null, null, Collections.singletonList("test")); as.addFeaturesFromSettings(f, s); Properties p2 = new Properties(); try (InputStream is = new FileInputStream(f)) { p2.load(is); } assertEquals(2, p2.size()); assertEquals("abc,def,test", p2.get("featuresBoot")); assertEquals("somescheme: } |
InstanceServiceImpl implements InstanceService { public void renameInstance(final String oldName, final String newName, final boolean printOutput) throws Exception { execute(state -> { if (state.instances.get(newName) != null) { throw new IllegalArgumentException("Instance " + newName + " already exists"); } InstanceState instance = state.instances.get(oldName); if (instance == null) { throw new IllegalArgumentException("Instance " + oldName + " not found"); } if (instance.root) { throw new IllegalArgumentException("Root instance cannot be renamed"); } checkPid(instance); if (instance.pid != 0) { throw new IllegalStateException("Instance not stopped"); } println("Renaming instance " + SimpleAnsi.INTENSITY_BOLD + oldName + SimpleAnsi.INTENSITY_NORMAL + " to " + SimpleAnsi.INTENSITY_BOLD + newName + SimpleAnsi.INTENSITY_NORMAL); String oldLocationPath = instance.loc; File oldLocation = new File(oldLocationPath); String basedir = oldLocation.getParent(); File newLocation = new File(basedir, newName); oldLocation.renameTo(newLocation); HashMap<String, String> props = new HashMap<>(); props.put(oldName, newName); props.put(oldLocationPath, newLocation.getPath()); filterResource(newLocation, "etc/system.properties", props); filterResource(newLocation, "bin/karaf", props); filterResource(newLocation, "bin/start", props); filterResource(newLocation, "bin/stop", props); filterResource(newLocation, "bin/karaf.bat", props); filterResource(newLocation, "bin/start.bat", props); filterResource(newLocation, "bin/stop.bat", props); instance.name = newName; instance.loc = newLocation.getPath(); state.instances.put(newName, instance); state.instances.remove(oldName); InstanceImpl proxy = InstanceServiceImpl.this.proxies.remove(oldName); if (proxy == null) { proxy = new InstanceImpl(InstanceServiceImpl.this, newName); } else { proxy.doSetName(newName); } InstanceServiceImpl.this.proxies.put(newName, proxy); return null; }, true); } InstanceServiceImpl(); File getStorageLocation(); void setStorageLocation(File storage); long getStopTimeout(); void setStopTimeout(long stopTimeout); synchronized Instance createInstance(final String name, final InstanceSettings settings, final boolean printOutput); Instance[] getInstances(); Instance getInstance(final String name); void startInstance(final String name, final String javaOpts); void restartInstance(final String name, final String javaOpts); void stopInstance(final String name); void destroyInstance(final String name); void renameInstance(final String oldName, final String newName, final boolean printOutput); synchronized Instance cloneInstance(final String name, final String cloneName, final InstanceSettings settings, final boolean printOutput); void changeInstanceSshHost(String name, String host); static final String STORAGE_FILE; static final String BACKUP_EXTENSION; static final String DEFAULT_JAVA_OPTS; } | @Test public void testRenameInstance() throws Exception { InstanceServiceImpl service = new InstanceServiceImpl(); service.setStorageLocation(tempFolder.newFolder("instances")); InstanceSettings settings = new InstanceSettings(8122, 1122, 44444, getName(), null, null, null); service.createInstance(getName(), settings, true); service.renameInstance(getName(), getName() + "b", true); assertNotNull(service.getInstance(getName() + "b")); } |
Kar { public void extract(File repoDir, File resourceDir) { InputStream is = null; JarInputStream zipIs = null; FeatureDetector featureDetector = new FeatureDetector(); this.featureRepos = new ArrayList<>(); this.shouldInstallFeatures = true; try { is = karUri.toURL().openStream(); repoDir.mkdirs(); if (!repoDir.isDirectory()) { throw new RuntimeException("The KAR file " + karUri + " is already installed"); } LOGGER.debug("Uncompress the KAR file {} into directory {}", karUri, repoDir); zipIs = new JarInputStream(is); boolean scanForRepos = true; Manifest manifest = zipIs.getManifest(); if (manifest != null) { Attributes attr = manifest.getMainAttributes(); String featureStartSt = (String)attr .get(new Attributes.Name(MANIFEST_ATTR_KARAF_FEATURE_START)); if ("false".equals(featureStartSt)) { shouldInstallFeatures = false; } String featureReposAttr = (String)attr .get(new Attributes.Name(MANIFEST_ATTR_KARAF_FEATURE_REPOS)); if (featureReposAttr != null) { featureRepos.add(new URI(featureReposAttr)); scanForRepos = false; } } ZipEntry entry = zipIs.getNextEntry(); while (entry != null) { if (entry.getName().contains("..") || entry.getName().contains("%2e%2e")) { LOGGER.warn("kar entry {} contains a .. relative path. For security reasons, it's not allowed.", entry.getName()); } else { if (entry.getName().startsWith("repository/")) { String path = entry.getName().substring("repository/".length()); File destFile = new File(repoDir, path); extract(zipIs, entry, destFile); if (scanForRepos && featureDetector.isFeaturesRepository(destFile)) { Map map = new HashMap<>(); String uri = Parser.pathToMaven(path, map); if (map.get("classifier") != null && ((String) map.get("classifier")).equalsIgnoreCase("features")) featureRepos.add(URI.create(uri)); else featureRepos.add(destFile.toURI()); } } if (entry.getName().startsWith("resources/")) { String path = entry.getName().substring("resources/".length()); File destFile = new File(resourceDir, path); extract(zipIs, entry, destFile); } } entry = zipIs.getNextEntry(); } } catch (Exception e) { throw new RuntimeException("Error extracting kar file " + karUri + " into dir " + repoDir + ": " + e.getMessage(), e); } finally { closeStream(zipIs); closeStream(is); } } Kar(URI karUri); void extract(File repoDir, File resourceDir); String getKarName(); URI getKarUri(); boolean isShouldInstallFeatures(); List<URI> getFeatureRepos(); static final Logger LOGGER; static final String MANIFEST_ATTR_KARAF_FEATURE_START; static final String MANIFEST_ATTR_KARAF_FEATURE_REPOS; } | @Test public void karExtractTest() throws Exception { File base = new File("target/test"); base.mkdirs(); Kar kar = new Kar(new URI("https: File repoDir = new File("target/test/framework-repo"); repoDir.mkdirs(); File resourcesDir = new File("target/test/framework-resources"); resourcesDir.mkdirs(); kar.extract(repoDir, resourcesDir); File[] repoDirFiles = repoDir.listFiles(); Assert.assertEquals(1, repoDirFiles.length); Assert.assertEquals("org", repoDirFiles[0].getName()); File[] resourceDirFiles = resourcesDir.listFiles(); Assert.assertEquals(6, resourceDirFiles.length); }
@Test public void badKarExtractTest() throws Exception { File base = new File("target/test"); base.mkdirs(); File badKarFile = new File(base,"bad.kar"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(badKarFile)); ZipEntry entry = new ZipEntry("../../../../foo.bar"); zos.putNextEntry(entry); byte[] data = "Test Data".getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); zos.close(); Kar kar = new Kar(new URI("file:target/test/bad.kar")); File repoDir = new File("target/test/repo"); repoDir.mkdirs(); File resourceDir = new File("target/test/resources"); resourceDir.mkdirs(); kar.extract(repoDir, resourceDir); File[] repoDirFiles = repoDir.listFiles(); Assert.assertEquals(0, repoDirFiles.length); File[] resourceDirFiles = resourceDir.listFiles(); Assert.assertEquals(0, resourceDirFiles.length); badKarFile.delete(); }
@Test public void badEncodedKarExtractTest() throws Exception { File base = new File("target/test"); base.mkdirs(); File badKarFile = new File(base,"badencoded.kar"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(badKarFile)); ZipEntry entry = new ZipEntry("%2e%2e/%2e%2e/%2e%2e/%2e%2e/foo.bar"); zos.putNextEntry(entry); byte[] data = "Test Data".getBytes(); zos.write(data, 0, data.length); zos.closeEntry(); zos.close(); Kar kar = new Kar(new URI("file:target/test/badencoded.kar")); File repoDir = new File("target/test/repo"); repoDir.mkdirs(); File resourceDir = new File("target/test/resources"); resourceDir.mkdirs(); kar.extract(repoDir, resourceDir); File[] repoDirFiles = repoDir.listFiles(); Assert.assertEquals(0, repoDirFiles.length); File[] resourceDirFiles = resourceDir.listFiles(); Assert.assertEquals(0, resourceDirFiles.length); badKarFile.delete(); } |
ShellUtil { public static String getValueString(Object obj) { if (obj == null) { return "null"; } else if (obj instanceof boolean[]) { return Arrays.toString((boolean[]) obj); } else if (obj instanceof byte[]) { return Arrays.toString((byte[]) obj); } else if (obj instanceof char[]) { return Arrays.toString((char[]) obj); } else if (obj instanceof double[]) { return Arrays.toString((double[]) obj); } else if (obj instanceof float[]) { return Arrays.toString((float[]) obj); } else if (obj instanceof int[]) { return Arrays.toString((int[]) obj); } else if (obj instanceof long[]) { return Arrays.toString((long[]) obj); } else if (obj instanceof short[]) { return Arrays.toString((short[]) obj); } else if (obj instanceof Collection<?>) { Object[] array = ((Collection<?>) obj).toArray(); return getValueString(array); } else if (obj.getClass().isArray()) { Object[] array = (Object[]) obj; StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < array.length; i++) { if (i != 0) { sb.append(", "); } sb.append(getValueString(array[i])); } sb.append("]"); return sb.toString(); } else { return obj.toString(); } } static String getBundleName(Bundle bundle); static String getUnderlineString(String s); static String getValueString(Object obj); static boolean isASystemBundle(BundleContext bundleContext, Bundle bundle); static boolean getBoolean(Session session, String name); static void logException(Session session, Throwable t); static String getCurrentUserName(); static Map<String, String> getKsColorMap(Session session); static Map<String, String> getColorMap(Session session, String name, String def); static final String DEFAULT_KS_COLORS; } | @Test public void testGetValueStringWithCustomCollection() { List<Integer> data = new AbstractList<Integer>() { int[] values = new int[15]; int size = 0; @Override public boolean add(Integer e) { values[size] = e; size++; return true; } @Override public Integer get(int index) { if ( index >= size ) throw new IndexOutOfBoundsException(); return values[index]; } @Override public int size() { return size; } @Override public String toString() { return "Custom" + super.toString(); } }; data.add(5); assertEquals("[5]", ShellUtil.getValueString(data)); }
@Test public void testGetValueString() { Object data; data = "Hello World"; assertEquals("Hello World", ShellUtil.getValueString(data)); data = new int[] { 1, 2, 3, 5, 7, 9 }; assertEquals("[1, 2, 3, 5, 7, 9]", ShellUtil.getValueString(data)); data = new short[] { 1, 2, 3, 5, 7, 9 }; assertEquals("[1, 2, 3, 5, 7, 9]", ShellUtil.getValueString(data)); data = new long[] { 1, 2, 3, 5, 7, 9 }; assertEquals("[1, 2, 3, 5, 7, 9]", ShellUtil.getValueString(data)); data = new byte[] { 1, 2, 3, 5, 7, 9 }; assertEquals("[1, 2, 3, 5, 7, 9]", ShellUtil.getValueString(data)); data = new float[] { 1, 2, 3, 5, 7, 9 }; assertEquals("[1.0, 2.0, 3.0, 5.0, 7.0, 9.0]", ShellUtil.getValueString(data)); data = new double[] { 1, 2, 3, 5, 7, 9 }; assertEquals("[1.0, 2.0, 3.0, 5.0, 7.0, 9.0]", ShellUtil.getValueString(data)); data = new boolean[] { true, true, false }; assertEquals("[true, true, false]", ShellUtil.getValueString(data)); data = new char[] { 'a', 'c', 'e' }; assertEquals("[a, c, e]", ShellUtil.getValueString(data)); data = new Object[] { new int[] { 1, 2, 3, 5, 8 }, new char[] { 'h', 'e', 'l', 'l', 'o' }, "World" }; assertEquals("[[1, 2, 3, 5, 8], [h, e, l, l, o], World]", ShellUtil.getValueString(data)); data = Arrays.asList(5, 10, 15, 25); assertEquals("[5, 10, 15, 25]", ShellUtil.getValueString(data)); data = new LinkedHashSet<>(Arrays.asList(5, 10, 15, 25)); assertEquals("[5, 10, 15, 25]", ShellUtil.getValueString(data)); data = new int[][] { { 1, 2, 3 }, { 5, 7, 9 } }; assertEquals("[[1, 2, 3], [5, 7, 9]]", ShellUtil.getValueString(data)); } |
DockerClient { public Info info() throws Exception { URL dockerUrl = new URL(this.url + "/info"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); Info info = mapper.readValue(connection.getInputStream(), Info.class); return info; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testDockerInfo() throws Exception { Info info = dockerClient.info(); System.out.println("Info:"); System.out.println("\tDriver: " + info.getDriver()); System.out.println("\tDriver Status: " + info.getDriverStatus()); System.out.println("\tExecution Driver: " + info.getExecutionDriver()); System.out.println("\tIndex Server Address: " + info.getIndexServerAddress()); System.out.println("\tInit Path: " + info.getInitPath()); System.out.println("\tInit SHA1: " + info.getInitSha1()); System.out.println("\tKernel Version: " + info.getKernelVersion()); System.out.println("\tContainers: " + info.getContainers()); System.out.println("\tImages: " + info.getImages()); System.out.println("\tNFD: " + info.getNfd()); System.out.println("\tNGoRoutines: " + info.getNgoroutines()); System.out.println("\tMemory Limit enabled: " + info.isMemoryLimit()); System.out.println("\tSwap Limit enabled: " + info.isSwapLimit()); } |
DockerClient { public Version version() throws Exception { URL dockerUrl = new URL(this.url + "/version"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); Version version = mapper.readValue(connection.getInputStream(), Version.class); return version; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testDockerVersion() throws Exception { Version version = dockerClient.version(); System.out.println("Version:"); System.out.println("\tAPI version: " + version.getApiVersion()); System.out.println("\tArch: " + version.getArch()); System.out.println("\tBuild Time: " + version.getBuildTime()); System.out.println("\tExperimental: " + version.getExperimental()); System.out.println("\tGit Commit: " + version.getGitCommit()); System.out.println("\tGo Version: " + version.getGoVersion()); System.out.println("\tKernel Version: " + version.getKernelVersion()); System.out.println("\tOS: " + version.getOs()); System.out.println("\tVersion: " + version.getVersion()); } |
DockerClient { public List<Image> images(boolean showAll) throws Exception { URL dockerUrl = new URL(this.url + "/images/json?all=" + showAll); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); List<Image> images = mapper.readValue(connection.getInputStream(), new TypeReference<List<Image>>(){}); return images; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testListImages() throws Exception { for (Image image : dockerClient.images(true)) { System.out.println("----"); System.out.println("Image ID: " + image.getId()); System.out.println("Created: " + image.getCreated()); System.out.println("Size: " + image.getSize()); System.out.println("Virtual size: " + image.getVirtualSize()); System.out.println("RepoTags: " + image.getRepoTags()); System.out.println("Labels: " + image.getLabels()); System.out.println("Containers: " + image.getContainers()); } } |
DockerClient { public List<ImageHistory> history(String name) throws Exception { URL dockerUrl = new URL(this.url + "/images/" + name + "/history"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); List<ImageHistory> images = mapper.readValue(connection.getInputStream(), new TypeReference<List<ImageHistory>>(){}); return images; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testHistoryImage() throws Exception { for (ImageHistory history : dockerClient.history("sha256:f3ea90d50ffd7851cb984764409326b82593c612fe6e6dc7933d9568f735084b")) { System.out.println("----"); System.out.println("ID: " + history.getId()); System.out.println("Created: " + history.getCreated()); System.out.println("Created by: " + history.getCreatedBy()); System.out.println("Comment: " + history.getComment()); System.out.println("Size: " + history.getSize()); System.out.println("Tags: " + history.getTags()); } } |
DockerClient { public List<ImageSearch> search(String term) throws Exception { URL dockerUrl = new URL(this.url + "/images/search?term=" + term); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); List<ImageSearch> images = mapper.readValue(connection.getInputStream(), new TypeReference<List<ImageSearch>>(){}); return images; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testSearchImages() throws Exception { List<ImageSearch> images = dockerClient.search("karaf"); for (ImageSearch image : images) { System.out.println("----"); System.out.println("Image Name: " + image.getName()); System.out.println("Image Star Count: " + image.getStarCount()); System.out.println("Image Automated: " + image.isAutomated()); System.out.println("Image Official: " + image.isOfficial()); System.out.println("Image Description: " + image.getDescription()); } } |
DockerClient { public void pull(String name, String tag, boolean verbose) throws Exception { URL dockerUrl = new URL(this.url + "/images/create?fromImage=" + name + "&tag=" + tag); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { LOGGER.debug(line); if (verbose) { System.out.println(line); } } if (connection.getResponseCode() != 200) { throw new IllegalStateException("Can't pull image " + name + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testPullImage() throws Exception { dockerClient.pull("mkroli/karaf", "latest", true); } |
DockerClient { public void rmi(String name, boolean force, boolean noprune) throws Exception { URL dockerUrl = new URL(this.url + "/images/" + name + "?force=" + force + "&noprune=" + noprune); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("DELETE"); if (connection.getResponseCode() != 200) { throw new IllegalStateException("Can't remove image " + name + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testRemoveImage() throws Exception { dockerClient.rmi("sha256:f3ea90d50ffd7851cb984764409326b82593c612fe6e6dc7933d9568f735084b", true, false); } |
DockerClient { public void create(ContainerConfig config, String name) throws Exception { URL dockerUrl = new URL(this.url + "/containers/create?name=" + name); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), config); if (connection.getResponseCode() != 201) { throw new IllegalStateException("Can't create Docker container " + name + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testCreateContainer() throws Exception { ContainerConfig config = new ContainerConfig(); config.setImage("java:8-jre-alpine"); config.setAttachStderr(true); config.setAttachStdin(true); config.setAttachStdout(true); config.setTty(true); dockerClient.create(config, "test"); }
@Test @Ignore("Need a running Docker daemon") public void testCreateKarafContainer() throws Exception { ContainerConfig config = new ContainerConfig(); config.setTty(true); config.setAttachStdout(true); config.setAttachStderr(true); config.setAttachStdin(true); config.setImage("karaf:latest"); config.setHostname("docker"); config.setUser(""); config.setCmd(new String[]{ "/bin/karaf" }); config.setWorkingDir(""); config.setOpenStdin(true); config.setStdinOnce(true); Map<String, Map<String, String>> exposedPorts = new HashMap<>(); Map<String, String> exposedPort = new HashMap<>(); exposedPorts.put("8101/tcp", exposedPort); config.setExposedPorts(exposedPorts); HostConfig hostConfig = new HostConfig(); hostConfig.setPrivileged(false); hostConfig.setPublishAllPorts(false); File dock = new File("/tmp/docker", "karaf"); if (dock.exists()) { hostConfig.setBinds(new String[]{dock.getAbsolutePath() + ":/opt/apache-karaf"}); } hostConfig.setNetworkMode("bridge"); hostConfig.setLxcConf(new String[]{}); Map<String, List<HostPortBinding>> portBindings = new HashMap<>(); List<HostPortBinding> hostPortBindings = new ArrayList<>(); HostPortBinding hostPortBinding = new HostPortBinding(); hostPortBinding.setHostIp(""); hostPortBinding.setHostPort("8101"); hostPortBindings.add(hostPortBinding); portBindings.put("8101/tcp", hostPortBindings); hostConfig.setPortBindings(portBindings); config.setHostConfig(hostConfig); dockerClient.create(config, "karaf"); } |
DockerClient { public void start(String id) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/start"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't start Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testStartContainer() throws Exception { dockerClient.start("test"); } |
DockerClient { public void stop(String id, int timeToWait) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/stop?t=" + timeToWait); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't stop Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; } | @Test @Ignore("Need a running Docker daemon") public void testStopContainer() throws Exception { dockerClient.stop("test", 30); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.