From bf666631fe84f0394a9b948b5088d205bf52db36 Mon Sep 17 00:00:00 2001 From: Stephen Kitt Date: Thu, 1 Jun 2017 00:43:35 -0700 Subject: [PATCH] [KARAF-5178] Use lambdas where appropriate Signed-off-by: Stephen Kitt --- .../apache/karaf/bundle/command/Headers.java | 12 +- .../apache/karaf/bundle/command/LoadTest.java | 139 +++-- .../karaf/bundle/command/ShowBundleTree.java | 23 +- .../karaf/bundle/command/bundletree/Tree.java | 6 +- .../core/internal/BundleWatcherImpl.java | 6 +- .../bundle/command/bundletree/TreeTest.java | 12 +- .../java/org/apache/karaf/client/Main.java | 21 +- .../command/completers/MetaCompleter.java | 34 +- .../download/impl/MavenDownloadManager.java | 79 ++- .../features/internal/region/Subsystem.java | 33 +- .../features/internal/service/Deployer.java | 30 +- .../features/internal/util/MapUtils.java | 14 +- .../region/FeaturesDependenciesTest.java | 7 +- .../internal/region/SubsystemTest.java | 7 +- .../internal/service/DeployerTest.java | 9 +- .../http/core/internal/osgi/Activator.java | 13 +- .../org/apache/karaf/itests/JaasTest.java | 21 +- .../java/org/apache/karaf/itests/JmsTest.java | 2 +- .../apache/karaf/itests/KarafTestSupport.java | 37 +- .../apache/karaf/jaas/command/SuCommand.java | 50 +- .../karaf/jaas/command/SudoCommand.java | 29 +- .../modules/ldap/GSSAPILdapLoginModule.java | 2 +- .../karaf/jdbc/internal/JdbcConnector.java | 14 +- .../hibernate/impl/StatisticsPublisher.java | 10 +- .../apache/karaf/log/command/LoadTest.java | 9 +- .../org/apache/karaf/log/command/LogTail.java | 6 +- .../main/java/org/apache/karaf/main/Main.java | 19 +- .../management/ConnectorServerFactory.java | 34 +- .../karaf/management/JaasAuthenticator.java | 21 +- .../management/KarafMBeanServerGuardTest.java | 552 ++++++++---------- .../profile/impl/ProfileServiceImpl.java | 7 +- .../service/guard/impl/GuardProxyCatalog.java | 33 +- .../guard/tools/ACLConfigurationParser.java | 8 +- .../service/guard/impl/ActivatorTest.java | 10 +- .../guard/impl/GuardProxyCatalogTest.java | 552 +++++++----------- .../guard/impl/GuardingEventHookTest.java | 32 +- .../guard/impl/GuardingFindHookTest.java | 34 +- .../felix/eventadmin/impl/Configuration.java | 27 +- .../karaf/shell/commands/impl/InfoAction.java | 6 +- .../basic/DefaultActionPreparator.java | 6 +- .../shell/commands/meta/ActionMetaData.java | 7 +- .../karaf/shell/compat/CommandTracker.java | 15 +- .../completer/CommandNamesCompleter.java | 7 +- .../console/completer/CommandsCompleter.java | 9 +- .../command/DefaultActionPreparator.java | 7 +- .../impl/action/osgi/MultiServiceTracker.java | 17 +- .../action/osgi/SingleServiceTracker.java | 19 +- .../console/commands/help/HelpCommand.java | 14 +- .../console/osgi/LocalConsoleManager.java | 38 +- .../support/completers/StringsCompleter.java | 8 +- .../shell/ssh/KarafJaasAuthenticator.java | 2 - .../karaf/subsystem/commands/InfoAction.java | 12 +- .../system/internal/SystemServiceImpl.java | 42 +- .../features/GenerateDescriptorMojo.java | 14 +- .../apache/karaf/util/jaas/JaasHelper.java | 20 +- .../servlet/JaasSecurityProvider.java | 20 +- .../internal/servlet/KarafOsgiManager.java | 9 +- .../instance/InstancePluginTest.java | 10 +- 58 files changed, 856 insertions(+), 1380 deletions(-) diff --git a/bundle/core/src/main/java/org/apache/karaf/bundle/command/Headers.java b/bundle/core/src/main/java/org/apache/karaf/bundle/command/Headers.java index d8a4f4449c6..ea830802fcd 100644 --- a/bundle/core/src/main/java/org/apache/karaf/bundle/command/Headers.java +++ b/bundle/core/src/main/java/org/apache/karaf/bundle/command/Headers.java @@ -256,16 +256,8 @@ protected void formatClause(Clause clause, StringBuilder builder, int indent) { String name = clause.getName(); Directive[] directives = clause.getDirectives(); Attribute[] attributes = clause.getAttributes(); - Arrays.sort(directives, new Comparator() { - public int compare(Directive o1, Directive o2) { - return o1.getName().compareTo(o2.getName()); - } - }); - Arrays.sort(attributes, new Comparator() { - public int compare(Attribute o1, Attribute o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Arrays.sort(directives, Comparator.comparing(Directive::getName)); + Arrays.sort(attributes, Comparator.comparing(Attribute::getName)); builder.append(name); for (int i = 0; directives != null && i < directives.length; i++) { if (noUses && directives[i].getName().equalsIgnoreCase("uses")) { diff --git a/bundle/core/src/main/java/org/apache/karaf/bundle/command/LoadTest.java b/bundle/core/src/main/java/org/apache/karaf/bundle/command/LoadTest.java index 27577b9e7cb..e04d66a6646 100644 --- a/bundle/core/src/main/java/org/apache/karaf/bundle/command/LoadTest.java +++ b/bundle/core/src/main/java/org/apache/karaf/bundle/command/LoadTest.java @@ -33,7 +33,6 @@ import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; -import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.osgi.framework.wiring.FrameworkWiring; @@ -87,93 +86,85 @@ public Object execute() throws Exception { locks[b].set(false); } for (int i = 0; i < threads; i++) { - new Thread() { - public void run() { - try { - Random rand = new Random(); - for (int j = 0; j < iterations; j++) { - for (;;) { - int b = rand.nextInt(bundles.length); - if (locks[b].compareAndSet(false, true)) { - try { - // Only touch active bundles - if (bundles[b].getState() != Bundle.ACTIVE) { - continue; - } - if (rand.nextInt(100) < refresh) { - try { - bundles[b].update(); - final CountDownLatch latch = new CountDownLatch(1); - wiring.refreshBundles(Collections.singletonList(bundles[b]), new FrameworkListener() { - public void frameworkEvent(FrameworkEvent event) { - latch.countDown(); - } - }); - latch.await(); - } finally { - while (true) { - try { - bundles[b].start(Bundle.START_TRANSIENT); - break; - } catch (Exception e) { - Thread.sleep(1); - } - } - } - } else { - try { - bundles[b].stop(Bundle.STOP_TRANSIENT); - } finally { - while (true) { - try { - bundles[b].start(Bundle.START_TRANSIENT); - break; - } catch (Exception e) { - Thread.sleep(1); - } + new Thread(() -> { + try { + Random rand = new Random(); + for (int j = 0; j < iterations; j++) { + for (;;) { + int b = rand.nextInt(bundles.length); + if (locks[b].compareAndSet(false, true)) { + try { + // Only touch active bundles + if (bundles[b].getState() != Bundle.ACTIVE) { + continue; + } + if (rand.nextInt(100) < refresh) { + try { + bundles[b].update(); + final CountDownLatch latch1 = new CountDownLatch(1); + wiring.refreshBundles(Collections.singletonList(bundles[b]), + (FrameworkListener) event -> latch1.countDown()); + latch1.await(); + } finally { + while (true) { + try { + bundles[b].start(Bundle.START_TRANSIENT); + break; + } catch (Exception e) { + Thread.sleep(1); } } } - Thread.sleep(rand.nextInt(delay)); - } catch (Exception e) { - boolean ignore = false; - if (e instanceof BundleException && e.getMessage() != null) { - String msg = e.getMessage(); - if ("Cannot acquire global lock to update the bundle.".equals(msg) || - "Unable to acquire global lock for resolve.".equals(msg) || - msg.matches("Bundle .* cannot be update, since it is either starting or stopping.")) { - ignore = true; + } else { + try { + bundles[b].stop(Bundle.STOP_TRANSIENT); + } finally { + while (true) { + try { + bundles[b].start(Bundle.START_TRANSIENT); + break; + } catch (Exception e) { + Thread.sleep(1); + } } } - if (!ignore) { - e.printStackTrace(); + } + Thread.sleep(rand.nextInt(delay)); + } catch (Exception e) { + boolean ignore = false; + if (e instanceof BundleException && e.getMessage() != null) { + String msg = e.getMessage(); + if ("Cannot acquire global lock to update the bundle.".equals(msg) || + "Unable to acquire global lock for resolve.".equals(msg) || + msg.matches("Bundle .* cannot be update, since it is either starting or stopping.")) { + ignore = true; } - } finally { - locks[b].set(false); } + if (!ignore) { + e.printStackTrace(); + } + } finally { + locks[b].set(false); } - break; } + break; } - } catch (Throwable t) { - t.printStackTrace(); - } finally { - latch.countDown(); } + } catch (Throwable t) { + t.printStackTrace(); + } finally { + latch.countDown(); } - }.start(); + }).start(); } - new Thread() { - @Override - public void run() { - try { - latch.await(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.err.println("Load test finished"); + new Thread(() -> { + try { + latch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); } - }.start(); + System.err.println("Load test finished"); + }).start(); return null; } diff --git a/bundle/core/src/main/java/org/apache/karaf/bundle/command/ShowBundleTree.java b/bundle/core/src/main/java/org/apache/karaf/bundle/command/ShowBundleTree.java index 06f7ea70dff..792c9dc2fe0 100644 --- a/bundle/core/src/main/java/org/apache/karaf/bundle/command/ShowBundleTree.java +++ b/bundle/core/src/main/java/org/apache/karaf/bundle/command/ShowBundleTree.java @@ -103,19 +103,16 @@ private void printHeader(Bundle bundle) { */ private void printTree(Tree tree) { System.out.printf("%n"); - tree.write(System.out, new Tree.Converter() { - - public String toString(Node node) { - if (versions) { - return String.format("%s / [%s] [%s]", - node.getValue().getSymbolicName(), - node.getValue().getVersion().toString(), - node.getValue().getBundleId()); - } else { - return String.format("%s [%s]", - node.getValue().getSymbolicName(), - node.getValue().getBundleId()); - } + tree.write(System.out, node -> { + if (versions) { + return String.format("%s / [%s] [%s]", + node.getValue().getSymbolicName(), + node.getValue().getVersion().toString(), + node.getValue().getBundleId()); + } else { + return String.format("%s [%s]", + node.getValue().getSymbolicName(), + node.getValue().getBundleId()); } }); } diff --git a/bundle/core/src/main/java/org/apache/karaf/bundle/command/bundletree/Tree.java b/bundle/core/src/main/java/org/apache/karaf/bundle/command/bundletree/Tree.java index 0b3398a144d..91361bb7428 100644 --- a/bundle/core/src/main/java/org/apache/karaf/bundle/command/bundletree/Tree.java +++ b/bundle/core/src/main/java/org/apache/karaf/bundle/command/bundletree/Tree.java @@ -67,11 +67,7 @@ public void write(PrintStream stream, Converter converter) { * @param writer the writer where to write. */ public void write(PrintWriter writer) { - write(writer, new Converter() { - public String toString(Node node) { - return node.getValue().toString(); - } - }); + write(writer, node -> node.getValue().toString()); } /** diff --git a/bundle/core/src/main/java/org/apache/karaf/bundle/core/internal/BundleWatcherImpl.java b/bundle/core/src/main/java/org/apache/karaf/bundle/core/internal/BundleWatcherImpl.java index f53db2383b0..77b045b187e 100644 --- a/bundle/core/src/main/java/org/apache/karaf/bundle/core/internal/BundleWatcherImpl.java +++ b/bundle/core/src/main/java/org/apache/karaf/bundle/core/internal/BundleWatcherImpl.java @@ -108,11 +108,7 @@ public void run() { if (!updated.isEmpty()) { try { final CountDownLatch latch = new CountDownLatch(1); - wiring.refreshBundles(updated, new FrameworkListener() { - public void frameworkEvent(FrameworkEvent event) { - latch.countDown(); - } - }); + wiring.refreshBundles(updated, (FrameworkListener) event -> latch.countDown()); latch.await(); } catch (InterruptedException e) { running.set(false); diff --git a/bundle/core/src/test/java/org/apache/karaf/bundle/command/bundletree/TreeTest.java b/bundle/core/src/test/java/org/apache/karaf/bundle/command/bundletree/TreeTest.java index 35ae220fb74..4388b63d666 100644 --- a/bundle/core/src/test/java/org/apache/karaf/bundle/command/bundletree/TreeTest.java +++ b/bundle/core/src/test/java/org/apache/karaf/bundle/command/bundletree/TreeTest.java @@ -28,13 +28,11 @@ import java.io.StringWriter; import java.util.Set; -import org.apache.karaf.bundle.command.bundletree.Node; -import org.apache.karaf.bundle.command.bundletree.Tree; import org.junit.Test; /** - * Test cases for {@link org.apache.karaf.shell.dev.util.Tree} - * and {@link org.apache.karaf.shell.dev.util.Node} + * Test cases for {@link org.apache.karaf.bundle.command.bundletree.Tree} + * and {@link org.apache.karaf.bundle.command.bundletree.Node} */ public class TreeTest { @@ -55,11 +53,7 @@ public void writeTreeWithOneChildAndNodeConverter() throws IOException { tree.addChild("child"); StringWriter writer = new StringWriter(); - tree.write(new PrintWriter(writer), new Tree.Converter() { - public String toString(Node node) { - return "my " + node.getValue(); - } - }); + tree.write(new PrintWriter(writer), node -> "my " + node.getValue()); BufferedReader reader = new BufferedReader(new StringReader(writer.getBuffer().toString())); diff --git a/client/src/main/java/org/apache/karaf/client/Main.java b/client/src/main/java/org/apache/karaf/client/Main.java index 8c8f5a549a5..7335a9b9057 100644 --- a/client/src/main/java/org/apache/karaf/client/Main.java +++ b/client/src/main/java/org/apache/karaf/client/Main.java @@ -27,8 +27,6 @@ import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.Reader; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.nio.charset.Charset; @@ -102,12 +100,9 @@ public static void main(String[] args) throws Exception { FilePasswordProvider passwordProvider = null; final Console console = System.console(); if (console != null) { - passwordProvider = new FilePasswordProvider() { - @Override - public String getPassword(String resourceKey) throws IOException { - char[] pwd = console.readPassword("Enter password for " + resourceKey + ": "); - return new String(pwd); - } + passwordProvider = resourceKey -> { + char[] pwd = console.readPassword("Enter password for " + resourceKey + ": "); + return new String(pwd); }; client.setFilePasswordProvider(passwordProvider); client.setUserInteraction(new UserInteraction() { @@ -337,12 +332,10 @@ private static void registerSignalHandler(final Terminal terminal, final PtyCapa Class signalHandlerClass = Class.forName("sun.misc.SignalHandler"); // Implement signal handler Object signalHandler = Proxy.newProxyInstance(Main.class.getClassLoader(), - new Class[]{signalHandlerClass}, new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Size size = terminal.getSize(); - channel.sendWindowChange(size.getColumns(), size.getRows()); - return null; - } + new Class[]{signalHandlerClass}, (proxy, method, args) -> { + Size size = terminal.getSize(); + channel.sendWindowChange(size.getColumns(), size.getRows()); + return null; } ); // Register the signal handler, this code is equivalent to: diff --git a/config/src/main/java/org/apache/karaf/config/command/completers/MetaCompleter.java b/config/src/main/java/org/apache/karaf/config/command/completers/MetaCompleter.java index 6e339168c7e..2aa39b8d056 100644 --- a/config/src/main/java/org/apache/karaf/config/command/completers/MetaCompleter.java +++ b/config/src/main/java/org/apache/karaf/config/command/completers/MetaCompleter.java @@ -21,7 +21,6 @@ import java.util.List; import org.apache.karaf.config.core.impl.MetaServiceCaller; -import org.apache.karaf.config.core.impl.MetatypeCallable; import org.apache.karaf.shell.api.action.lifecycle.Init; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; @@ -34,7 +33,6 @@ import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.osgi.service.metatype.MetaTypeInformation; -import org.osgi.service.metatype.MetaTypeService; @Service public class MetaCompleter implements Completer, BundleListener { @@ -60,27 +58,23 @@ public void bundleChanged(BundleEvent event) { } private synchronized void updateMeta() { - List pids = MetaServiceCaller.withMetaTypeService(context, new MetatypeCallable>() { + List pids = MetaServiceCaller.withMetaTypeService(context, metatypeService -> { + List pids1 = new ArrayList<>(); + Bundle[] bundles = context.getBundles(); + for (Bundle bundle : bundles) { - @Override - public List callWith(MetaTypeService metatypeService) { - List pids = new ArrayList<>(); - Bundle[] bundles = context.getBundles(); - for (Bundle bundle : bundles) { - - MetaTypeInformation info = metatypeService.getMetaTypeInformation(bundle); - if (info == null) { - continue; - } - if (info.getFactoryPids() != null) { - pids.addAll(Arrays.asList(info.getFactoryPids())); - } - if (info.getPids() != null) { - pids.addAll(Arrays.asList(info.getPids())); - } + MetaTypeInformation info = metatypeService.getMetaTypeInformation(bundle); + if (info == null) { + continue; + } + if (info.getFactoryPids() != null) { + pids1.addAll(Arrays.asList(info.getFactoryPids())); + } + if (info.getPids() != null) { + pids1.addAll(Arrays.asList(info.getPids())); } - return pids; } + return pids1; }); if (pids != null) { delegate.getStrings().clear(); diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/download/impl/MavenDownloadManager.java b/features/core/src/main/java/org/apache/karaf/features/internal/download/impl/MavenDownloadManager.java index 2eabb2bfc2f..65f798b4f7a 100644 --- a/features/core/src/main/java/org/apache/karaf/features/internal/download/impl/MavenDownloadManager.java +++ b/features/core/src/main/java/org/apache/karaf/features/internal/download/impl/MavenDownloadManager.java @@ -126,26 +126,23 @@ public void download(final String location, final DownloadCallback downloadCallb allPending++; } final AbstractDownloadTask downloadTask = task; - task.addListener(new FutureListener() { - @Override - public void operationComplete(AbstractDownloadTask future) { - try { - // Call the callback - if (downloadCallback != null) { - downloadCallback.downloaded(downloadTask); - } - // Make sure we log any download error if the callback suppressed it - downloadTask.getFile(); - } catch (Throwable e) { - exception.addSuppressed(e); - } finally { - synchronized (lock) { - downloading.remove(location); - downloaded.put(location, downloadTask); - --allPending; - if (--pending == 0) { - lock.notifyAll(); - } + task.addListener(future -> { + try { + // Call the callback + if (downloadCallback != null) { + downloadCallback.downloaded(downloadTask); + } + // Make sure we log any download error if the callback suppressed it + downloadTask.getFile(); + } catch (Throwable e) { + exception.addSuppressed(e); + } finally { + synchronized (lock) { + downloading.remove(location); + downloaded.put(location, downloadTask); + --allPending; + if (--pending == 0) { + lock.notifyAll(); } } } @@ -191,30 +188,24 @@ public ChainedDownloadTask(ScheduledExecutorService executorService, String url, @Override public void run() { try { - MavenDownloader.this.download(innerUrl, new DownloadCallback() { - @Override - public void downloaded(StreamProvider provider) throws Exception { - try { - AbstractDownloadTask future = (AbstractDownloadTask) provider; - String file = future.getFile().toURI().toURL().toExternalForm(); - String real = url.replace(innerUrl, file); - MavenDownloader.this.download(real, new DownloadCallback() { - @Override - public void downloaded(StreamProvider provider) throws Exception { - try { - setFile(provider.getFile()); - } catch (IOException e) { - setException(e); - } catch (Throwable t) { - setException(new IOException(t)); - } - } - }); - } catch (IOException e) { - setException(e); - } catch (Throwable t) { - setException(new IOException(t)); - } + MavenDownloader.this.download(innerUrl, provider -> { + try { + AbstractDownloadTask future = (AbstractDownloadTask) provider; + String file = future.getFile().toURI().toURL().toExternalForm(); + String real = url.replace(innerUrl, file); + MavenDownloader.this.download(real, provider1 -> { + try { + setFile(provider1.getFile()); + } catch (IOException e) { + setException(e); + } catch (Throwable t) { + setException(new IOException(t)); + } + }); + } catch (IOException e) { + setException(e); + } catch (Throwable t) { + setException(new IOException(t)); } }); } catch (IOException e) { diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/region/Subsystem.java b/features/core/src/main/java/org/apache/karaf/features/internal/region/Subsystem.java index 68db79ad474..88b4412f1ec 100644 --- a/features/core/src/main/java/org/apache/karaf/features/internal/region/Subsystem.java +++ b/features/core/src/main/java/org/apache/karaf/features/internal/region/Subsystem.java @@ -43,7 +43,6 @@ import org.apache.karaf.features.FeaturesService; import org.apache.karaf.features.Library; import org.apache.karaf.features.ScopeFilter; -import org.apache.karaf.features.internal.download.DownloadCallback; import org.apache.karaf.features.internal.download.DownloadManager; import org.apache.karaf.features.internal.download.Downloader; import org.apache.karaf.features.internal.download.StreamProvider; @@ -397,44 +396,28 @@ public void downloadBundles(DownloadManager manager, for (Map.Entry entry : infos.entrySet()) { final BundleInfo bi = entry.getKey(); final String loc = bi.getLocation(); - downloader.download(loc, new DownloadCallback() { - @Override - public void downloaded(StreamProvider provider) throws Exception { - ResourceImpl res = createResource(loc, getMetadata(provider), removeServiceRequirements); - bundles.put(loc, res); - } + downloader.download(loc, provider -> { + bundles.put(loc, createResource(loc, getMetadata(provider), removeServiceRequirements)); }); } for (Clause bundle : Parser.parseClauses(this.bundles.toArray(new String[this.bundles.size()]))) { final String loc = bundle.getName(); - downloader.download(loc, new DownloadCallback() { - @Override - public void downloaded(StreamProvider provider) throws Exception { - ResourceImpl res = createResource(loc, getMetadata(provider), removeServiceRequirements); - bundles.put(loc, res); - } + downloader.download(loc, provider -> { + bundles.put(loc, createResource(loc, getMetadata(provider), removeServiceRequirements)); }); } for (String override : overrides) { final String loc = Overrides.extractUrl(override); - downloader.download(loc, new DownloadCallback() { - @Override - public void downloaded(StreamProvider provider) throws Exception { - ResourceImpl res = createResource(loc, getMetadata(provider), removeServiceRequirements); - bundles.put(loc, res); - } + downloader.download(loc, provider -> { + bundles.put(loc, createResource(loc, getMetadata(provider), removeServiceRequirements)); }); } if (feature != null) { for (Library library : feature.getLibraries()) { if (library.isExport()) { final String loc = library.getLocation(); - downloader.download(loc, new DownloadCallback() { - @Override - public void downloaded(StreamProvider provider) throws Exception { - ResourceImpl res = createResource(loc, getMetadata(provider), removeServiceRequirements); - bundles.put(loc, res); - } + downloader.download(loc, provider -> { + bundles.put(loc, createResource(loc, getMetadata(provider), removeServiceRequirements)); }); } } diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/Deployer.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/Deployer.java index df5e9a188f4..4996b9be6cd 100644 --- a/features/core/src/main/java/org/apache/karaf/features/internal/service/Deployer.java +++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/Deployer.java @@ -1123,7 +1123,7 @@ protected void logWiring(Map> wiring, boolean onlyFeatures) } } List sorted = new ArrayList<>(wires.keySet()); - Collections.sort(sorted, (r1, r2) -> wires.get(r1).size() - wires.get(r2).size()); + sorted.sort(Comparator.comparingInt(r2 -> wires.get(r2).size())); for (Resource r : sorted) { print(" " + ResolverUtil.getSymbolicName(r) + " / " + ResolverUtil.getVersion(r), true); for (Resource w : wires.get(r)) { @@ -1310,30 +1310,15 @@ protected Deployment computeDeployment( } protected MapUtils.Function adapt(final Class clazz) { - return new MapUtils.Function() { - @Override - public T apply(Bundle bundle) { - return bundle.adapt(clazz); - } - }; + return bundle -> bundle.adapt(clazz); } protected MapUtils.Function bundleId() { - return new MapUtils.Function() { - @Override - public Long apply(Bundle bundle) { - return bundle.getBundleId(); - } - }; + return Bundle::getBundleId; } protected MapUtils.Function featureId() { - return new MapUtils.Function() { - @Override - public String apply(Resource resource) { - return getFeatureId(resource); - } - }; + return ResourceUtils::getFeatureId; } protected boolean isUpdateable(Resource resource) { @@ -1404,12 +1389,7 @@ protected List getBundlesToStop(Collection bundles) { } } if (!bundlesToDestroy.isEmpty()) { - Collections.sort(bundlesToDestroy, new Comparator() { - @Override - public int compare(Bundle b1, Bundle b2) { - return Long.compare(b2.getLastModified(), b1.getLastModified()); - } - }); + bundlesToDestroy.sort((b1, b2) -> Long.compare(b2.getLastModified(), b1.getLastModified())); LOGGER.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy); } else { ServiceReference ref = null; diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/util/MapUtils.java b/features/core/src/main/java/org/apache/karaf/features/internal/util/MapUtils.java index be1d9ce7731..32607e45bb5 100644 --- a/features/core/src/main/java/org/apache/karaf/features/internal/util/MapUtils.java +++ b/features/core/src/main/java/org/apache/karaf/features/internal/util/MapUtils.java @@ -74,21 +74,11 @@ public static Map build(Collection col, Function key, F } public static Function compose(final Function f1, final Function f2) { - return new Function() { - @Override - public U apply(S s) { - return f2.apply(f1.apply(s)); - } - }; + return s -> f2.apply(f1.apply(s)); } public static MapUtils.Function map(final Map map) { - return new MapUtils.Function() { - @Override - public U apply(T t) { - return map.get(t); - } - }; + return map::get; } public static boolean contains(Map> mapset, S key, T val) { diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/region/FeaturesDependenciesTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/region/FeaturesDependenciesTest.java index 6b92352635c..c48253482cd 100644 --- a/features/core/src/test/java/org/apache/karaf/features/internal/region/FeaturesDependenciesTest.java +++ b/features/core/src/test/java/org/apache/karaf/features/internal/region/FeaturesDependenciesTest.java @@ -187,12 +187,7 @@ private void dumpWiring(SubsystemResolver resolver) { System.out.println("Wiring"); Map> wiring = resolver.getWiring(); List resources = new ArrayList<>(wiring.keySet()); - Collections.sort(resources, new Comparator() { - @Override - public int compare(Resource o1, Resource o2) { - return getName(o1).compareTo(getName(o2)); - } - }); + resources.sort(Comparator.comparing(this::getName)); for (Resource resource : resources) { System.out.println(" " + getName(resource)); for (Wire wire : wiring.get(resource)) { diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/region/SubsystemTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/region/SubsystemTest.java index 1d560112585..f6b65635b83 100644 --- a/features/core/src/test/java/org/apache/karaf/features/internal/region/SubsystemTest.java +++ b/features/core/src/test/java/org/apache/karaf/features/internal/region/SubsystemTest.java @@ -341,12 +341,7 @@ private void dumpWiring(SubsystemResolver resolver) { System.out.println("Wiring"); Map> wiring = resolver.getWiring(); List resources = new ArrayList<>(wiring.keySet()); - Collections.sort(resources, new Comparator() { - @Override - public int compare(Resource o1, Resource o2) { - return getName(o1).compareTo(getName(o2)); - } - }); + resources.sort(Comparator.comparing(this::getName)); for (Resource resource : resources) { System.out.println(" " + getName(resource)); for (Wire wire : wiring.get(resource)) { diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/service/DeployerTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/service/DeployerTest.java index d06e195af9b..bdad44cb03a 100644 --- a/features/core/src/test/java/org/apache/karaf/features/internal/service/DeployerTest.java +++ b/features/core/src/test/java/org/apache/karaf/features/internal/service/DeployerTest.java @@ -160,12 +160,9 @@ public void testUpdateSimpleFeature() throws Exception { EasyMock.expectLastCall(); installSupport.stopBundle(EasyMock.eq(bundleA), anyInt()); - EasyMock.expectLastCall().andStubAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - bundleA.state = Bundle.RESOLVED; - return null; - } + EasyMock.expectLastCall().andStubAnswer(() -> { + bundleA.state = Bundle.RESOLVED; + return null; }); installSupport.updateBundle(EasyMock.eq(bundleA), EasyMock.anyObject(), EasyMock.anyObject()); EasyMock.expectLastCall().andStubAnswer(new IAnswer() { diff --git a/http/src/main/java/org/apache/karaf/http/core/internal/osgi/Activator.java b/http/src/main/java/org/apache/karaf/http/core/internal/osgi/Activator.java index 5365a9a0c0c..9bff3b4b1a1 100644 --- a/http/src/main/java/org/apache/karaf/http/core/internal/osgi/Activator.java +++ b/http/src/main/java/org/apache/karaf/http/core/internal/osgi/Activator.java @@ -40,14 +40,11 @@ protected void doStart() throws Exception { ServletServiceImpl servletService = new ServletServiceImpl(servletEventHandler); register(ServletService.class, servletService); - listener = new BundleListener() { - @Override - public void bundleChanged(BundleEvent event) { - if (event.getType() == BundleEvent.UNINSTALLED - || event.getType() == BundleEvent.UNRESOLVED - || event.getType() == BundleEvent.STOPPED) { - servletEventHandler.removeEventsForBundle(event.getBundle()); - } + listener = event -> { + if (event.getType() == BundleEvent.UNINSTALLED + || event.getType() == BundleEvent.UNRESOLVED + || event.getType() == BundleEvent.STOPPED) { + servletEventHandler.removeEventsForBundle(event.getBundle()); } }; bundleContext.addBundleListener(listener); diff --git a/itests/src/test/java/org/apache/karaf/itests/JaasTest.java b/itests/src/test/java/org/apache/karaf/itests/JaasTest.java index 35f6c347cbb..9964e446cef 100644 --- a/itests/src/test/java/org/apache/karaf/itests/JaasTest.java +++ b/itests/src/test/java/org/apache/karaf/itests/JaasTest.java @@ -16,13 +16,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.io.IOException; import javax.inject.Inject; import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.LoginContext; import org.apache.felix.fileinstall.ArtifactInstaller; import org.junit.Ignore; @@ -66,16 +63,14 @@ public void testLoginSingleReg() throws Exception { private void doLogin() throws Exception { final String userPassRealm = "karaf"; - LoginContext lc = new LoginContext(userPassRealm, new CallbackHandler() { - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (Callback callback : callbacks) { - if (callback instanceof PasswordCallback) { - PasswordCallback passwordCallback = (PasswordCallback) callback; - passwordCallback.setPassword(userPassRealm.toCharArray()); - } else if (callback instanceof NameCallback) { - NameCallback nameCallback = (NameCallback) callback; - nameCallback.setName(userPassRealm); - } + LoginContext lc = new LoginContext(userPassRealm, callbacks -> { + for (Callback callback : callbacks) { + if (callback instanceof PasswordCallback) { + PasswordCallback passwordCallback = (PasswordCallback) callback; + passwordCallback.setPassword(userPassRealm.toCharArray()); + } else if (callback instanceof NameCallback) { + NameCallback nameCallback = (NameCallback) callback; + nameCallback.setName(userPassRealm); } } }); diff --git a/itests/src/test/java/org/apache/karaf/itests/JmsTest.java b/itests/src/test/java/org/apache/karaf/itests/JmsTest.java index c05e31c5477..21487de3b55 100644 --- a/itests/src/test/java/org/apache/karaf/itests/JmsTest.java +++ b/itests/src/test/java/org/apache/karaf/itests/JmsTest.java @@ -65,7 +65,7 @@ public Option[] config() { @Before public void setup() throws Exception { - await("ActiveMQ transport up").atMost(30, SECONDS).until(() -> jmsTransportPresent()); + await("ActiveMQ transport up").atMost(30, SECONDS).until(this::jmsTransportPresent); mbeanServer = ManagementFactory.getPlatformMBeanServer(); objName = new ObjectName("org.apache.karaf:type=jms,name=root"); } diff --git a/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java b/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java index 71eb3e7c44c..9e7b9b24b6f 100644 --- a/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java +++ b/itests/src/test/java/org/apache/karaf/itests/KarafTestSupport.java @@ -256,20 +256,17 @@ protected String executeCommand(final String command, final Long timeout, final final SessionFactory sessionFactory = getOsgiService(SessionFactory.class); final Session session = sessionFactory.create(System.in, printStream, System.err); - final Callable commandCallable = new Callable() { - @Override - public String call() throws Exception { - try { - if (!silent) { - System.err.println(command); - } - session.execute(command); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); + final Callable commandCallable = () -> { + try { + if (!silent) { + System.err.println(command); } - printStream.flush(); - return byteArrayOutputStream.toString(); + session.execute(command); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); } + printStream.flush(); + return byteArrayOutputStream.toString(); }; FutureTask commandFuture; @@ -277,18 +274,10 @@ public String call() throws Exception { commandFuture = new FutureTask<>(commandCallable); } else { // If principals are defined, run the command callable via Subject.doAs() - commandFuture = new FutureTask<>(new Callable() { - @Override - public String call() throws Exception { - Subject subject = new Subject(); - subject.getPrincipals().addAll(Arrays.asList(principals)); - return Subject.doAs(subject, new PrivilegedExceptionAction() { - @Override - public String run() throws Exception { - return commandCallable.call(); - } - }); - } + commandFuture = new FutureTask<>(() -> { + Subject subject = new Subject(); + subject.getPrincipals().addAll(Arrays.asList(principals)); + return Subject.doAs(subject, (PrivilegedExceptionAction) commandCallable::call); }); } diff --git a/jaas/command/src/main/java/org/apache/karaf/jaas/command/SuCommand.java b/jaas/command/src/main/java/org/apache/karaf/jaas/command/SuCommand.java index 7c6e9dac4eb..7f49dad7407 100644 --- a/jaas/command/src/main/java/org/apache/karaf/jaas/command/SuCommand.java +++ b/jaas/command/src/main/java/org/apache/karaf/jaas/command/SuCommand.java @@ -15,12 +15,10 @@ */ package org.apache.karaf.jaas.command; -import java.io.IOException; import java.security.PrivilegedExceptionAction; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; @@ -52,38 +50,34 @@ public class SuCommand implements Action { @Override public Object execute() throws Exception { Subject subject = new Subject(); - LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() { - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (Callback callback : callbacks) { - if (callback instanceof NameCallback) { - ((NameCallback) callback).setName(user); - } else if (callback instanceof PasswordCallback) { - String password = SuCommand.this.session.readLine("Password: ", '*'); - ((PasswordCallback) callback).setPassword(password.toCharArray()); - } else { - throw new UnsupportedCallbackException(callback); - } + LoginContext loginContext = new LoginContext(realm, subject, callbacks -> { + for (Callback callback : callbacks) { + if (callback instanceof NameCallback) { + ((NameCallback) callback).setName(user); + } else if (callback instanceof PasswordCallback) { + String password = SuCommand.this.session.readLine("Password: ", '*'); + ((PasswordCallback) callback).setPassword(password.toCharArray()); + } else { + throw new UnsupportedCallbackException(callback); } } }); loginContext.login(); - JaasHelper.doAs(subject, new PrivilegedExceptionAction() { - public Object run() throws InterruptedException { - final Session newSession = session.getFactory().create( - System.in, System.out, System.err, SuCommand.this.session.getTerminal(), null, null); - Object oldIgnoreInterrupts = session.get(Session.IGNORE_INTERRUPTS); - try { - session.put(Session.IGNORE_INTERRUPTS, Boolean.TRUE); - String name = "Karaf local console user " + ShellUtil.getCurrentUserName(); - Thread thread = new Thread(newSession, name); - thread.start(); - thread.join(); - } finally { - session.put(Session.IGNORE_INTERRUPTS, oldIgnoreInterrupts); - } - return null; + JaasHelper.doAs(subject, (PrivilegedExceptionAction) () -> { + final Session newSession = session.getFactory().create( + System.in, System.out, System.err, SuCommand.this.session.getTerminal(), null, null); + Object oldIgnoreInterrupts = session.get(Session.IGNORE_INTERRUPTS); + try { + session.put(Session.IGNORE_INTERRUPTS, Boolean.TRUE); + String name = "Karaf local console user " + ShellUtil.getCurrentUserName(); + Thread thread = new Thread(newSession, name); + thread.start(); + thread.join(); + } finally { + session.put(Session.IGNORE_INTERRUPTS, oldIgnoreInterrupts); } + return null; }); loginContext.logout(); diff --git a/jaas/command/src/main/java/org/apache/karaf/jaas/command/SudoCommand.java b/jaas/command/src/main/java/org/apache/karaf/jaas/command/SudoCommand.java index fb5e7e74363..18e57e56fba 100644 --- a/jaas/command/src/main/java/org/apache/karaf/jaas/command/SudoCommand.java +++ b/jaas/command/src/main/java/org/apache/karaf/jaas/command/SudoCommand.java @@ -15,13 +15,11 @@ */ package org.apache.karaf.jaas.command; -import java.io.IOException; import java.security.PrivilegedExceptionAction; import java.util.List; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; @@ -55,17 +53,15 @@ public class SudoCommand implements Action { @Override public Object execute() throws Exception { Subject subject = new Subject(); - LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() { - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (Callback callback : callbacks) { - if (callback instanceof NameCallback) { - ((NameCallback) callback).setName(user); - } else if (callback instanceof PasswordCallback) { - String password = SudoCommand.this.session.readLine("Password: ", '*'); - ((PasswordCallback) callback).setPassword(password.toCharArray()); - } else { - throw new UnsupportedCallbackException(callback); - } + LoginContext loginContext = new LoginContext(realm, subject, callbacks -> { + for (Callback callback : callbacks) { + if (callback instanceof NameCallback) { + ((NameCallback) callback).setName(user); + } else if (callback instanceof PasswordCallback) { + String password = SudoCommand.this.session.readLine("Password: ", '*'); + ((PasswordCallback) callback).setPassword(password.toCharArray()); + } else { + throw new UnsupportedCallbackException(callback); } } }); @@ -78,12 +74,7 @@ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallback } sb.append(s); } - JaasHelper.doAs(subject, new PrivilegedExceptionAction() { - @Override - public Object run() throws Exception { - return session.execute(sb); - } - }); + JaasHelper.doAs(subject, (PrivilegedExceptionAction) () -> session.execute(sb)); loginContext.logout(); return null; diff --git a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModule.java b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModule.java index ba6ed5b29cc..c5fc6443fbf 100644 --- a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModule.java +++ b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModule.java @@ -61,7 +61,7 @@ public boolean login() throws LoginException { context.login(); try { - return Subject.doAs(context.getSubject(), (PrivilegedExceptionAction) () -> doLogin()); + return Subject.doAs(context.getSubject(), (PrivilegedExceptionAction) this::doLogin); } catch (PrivilegedActionException pExcp) { logger.error("error with delegated authentication", pExcp); throw new LoginException(pExcp.getMessage()); diff --git a/jdbc/src/main/java/org/apache/karaf/jdbc/internal/JdbcConnector.java b/jdbc/src/main/java/org/apache/karaf/jdbc/internal/JdbcConnector.java index 4d176c5892f..6715ee8ea95 100644 --- a/jdbc/src/main/java/org/apache/karaf/jdbc/internal/JdbcConnector.java +++ b/jdbc/src/main/java/org/apache/karaf/jdbc/internal/JdbcConnector.java @@ -40,12 +40,7 @@ public class JdbcConnector implements Closeable { public JdbcConnector(final BundleContext bundleContext, final ServiceReference reference) { this.datasource = (CommonDataSource)bundleContext.getService(reference); this.resources = new LinkedList<>(); - this.resources.addFirst(new AutoCloseable() { - @Override - public void close() throws Exception { - bundleContext.ungetService(reference); - } - }); + this.resources.addFirst(() -> bundleContext.ungetService(reference)); } public Connection connect() throws SQLException { @@ -72,12 +67,7 @@ public T register(final T closeable) { } public XAConnection register(final XAConnection closeable) { - register(new AutoCloseable() { - @Override - public void close() throws Exception { - closeable.close(); - } - }); + register(closeable::close); return closeable; } diff --git a/jpa/hibernate/src/main/java/org/apache/karaf/jpa/hibernate/impl/StatisticsPublisher.java b/jpa/hibernate/src/main/java/org/apache/karaf/jpa/hibernate/impl/StatisticsPublisher.java index d4ba4ff6191..6d9016d1584 100644 --- a/jpa/hibernate/src/main/java/org/apache/karaf/jpa/hibernate/impl/StatisticsPublisher.java +++ b/jpa/hibernate/src/main/java/org/apache/karaf/jpa/hibernate/impl/StatisticsPublisher.java @@ -16,8 +16,6 @@ */ package org.apache.karaf.jpa.hibernate.impl; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; import java.lang.reflect.Proxy; import javax.management.MBeanServer; @@ -105,12 +103,8 @@ public EntityManagerFactory addingService(ServiceReference } private Object getStatisticsMBean(final Statistics statistics) { - return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { StatisticsMXBean.class }, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return method.invoke(statistics, args); - } - }); + return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { StatisticsMXBean.class }, + (proxy, method, args) -> method.invoke(statistics, args)); } @Override diff --git a/log/src/main/java/org/apache/karaf/log/command/LoadTest.java b/log/src/main/java/org/apache/karaf/log/command/LoadTest.java index c6dbead01a1..c0ee1c3b720 100644 --- a/log/src/main/java/org/apache/karaf/log/command/LoadTest.java +++ b/log/src/main/java/org/apache/karaf/log/command/LoadTest.java @@ -43,12 +43,9 @@ public Object execute() throws Exception { Thread[] th = new Thread[threads]; for (int i = 0; i < threads; i++) { final int idxThread = i; - th[i] = new Thread(new Runnable() { - @Override - public void run() { - for (int i = 0; i < messages; i++) { - LOGGER.info("Message {} / {}", idxThread, i); - } + th[i] = new Thread(() -> { + for (int i1 = 0; i1 < messages; i1++) { + LOGGER.info("Message {} / {}", idxThread, i1); } }); } diff --git a/log/src/main/java/org/apache/karaf/log/command/LogTail.java b/log/src/main/java/org/apache/karaf/log/command/LogTail.java index 9e6ae616137..dc48e002600 100644 --- a/log/src/main/java/org/apache/karaf/log/command/LogTail.java +++ b/log/src/main/java/org/apache/karaf/log/command/LogTail.java @@ -103,11 +103,7 @@ public void run() { out.flush(); // Tail final BlockingQueue queue = new LinkedBlockingQueue<>(); - PaxAppender appender = new PaxAppender() { - public void doAppend(PaxLoggingEvent event) { - queue.add(event); - } - }; + PaxAppender appender = queue::add; try { logService.addAppender(appender); while (doDisplay) { diff --git a/main/src/main/java/org/apache/karaf/main/Main.java b/main/src/main/java/org/apache/karaf/main/Main.java index 60f082c7223..9d0acdf7b51 100644 --- a/main/src/main/java/org/apache/karaf/main/Main.java +++ b/main/src/main/java/org/apache/karaf/main/Main.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -345,12 +344,10 @@ private void registerSignalHandler() { new Class[] { signalHandlerClass }, - new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + (proxy, method, args) -> { Main.this.destroy(); return null; } - } ); signalClass.getMethod("handle", signalClass, signalHandlerClass).invoke( @@ -650,15 +647,13 @@ public boolean destroy() throws Exception { exiting = true; if (framework.getState() == Bundle.ACTIVE || framework.getState() == Bundle.STARTING) { - new Thread() { - public void run() { - try { - framework.stop(); - } catch (BundleException e) { - System.err.println("Error stopping karaf: " + e.getMessage()); - } + new Thread(() -> { + try { + framework.stop(); + } catch (BundleException e) { + System.err.println("Error stopping karaf: " + e.getMessage()); } - }.start(); + }).start(); } int step = 5000; diff --git a/management/server/src/main/java/org/apache/karaf/management/ConnectorServerFactory.java b/management/server/src/main/java/org/apache/karaf/management/ConnectorServerFactory.java index d32e081e7f2..a15525e1b33 100644 --- a/management/server/src/main/java/org/apache/karaf/management/ConnectorServerFactory.java +++ b/management/server/src/main/java/org/apache/karaf/management/ConnectorServerFactory.java @@ -252,27 +252,25 @@ public void init() throws Exception { try { if (this.threaded) { - Thread connectorThread = new Thread() { - public void run() { - try { - Thread.currentThread().setContextClassLoader(ConnectorServerFactory.class.getClassLoader()); - connectorServer.start(); - } catch (IOException ex) { - if (ex.getCause() instanceof BindException){ - // we want just the port message - int endIndex = ex.getMessage().indexOf("nested exception is"); - // check to make sure we do not get an index out of range - if (endIndex > ex.getMessage().length() || endIndex < 0){ - endIndex = ex.getMessage().length(); - } - throw new RuntimeException("\n" + ex.getMessage().substring(0, endIndex) + - "\nYou may have started two containers. If you need to start a second container or the default ports are already in use " + - "update the config file etc/org.apache.karaf.management.cfg and change the Registry Port and Server Port to unused ports"); + Thread connectorThread = new Thread(() -> { + try { + Thread.currentThread().setContextClassLoader(ConnectorServerFactory.class.getClassLoader()); + connectorServer.start(); + } catch (IOException ex) { + if (ex.getCause() instanceof BindException){ + // we want just the port message + int endIndex = ex.getMessage().indexOf("nested exception is"); + // check to make sure we do not get an index out of range + if (endIndex > ex.getMessage().length() || endIndex < 0){ + endIndex = ex.getMessage().length(); } - throw new RuntimeException("Could not start JMX connector server", ex); + throw new RuntimeException("\n" + ex.getMessage().substring(0, endIndex) + + "\nYou may have started two containers. If you need to start a second container or the default ports are already in use " + + "update the config file etc/org.apache.karaf.management.cfg and change the Registry Port and Server Port to unused ports"); } + throw new RuntimeException("Could not start JMX connector server", ex); } - }; + }); connectorThread.setName("JMX Connector Thread [" + this.serviceUrl + "]"); connectorThread.setDaemon(this.daemon); connectorThread.start(); diff --git a/management/server/src/main/java/org/apache/karaf/management/JaasAuthenticator.java b/management/server/src/main/java/org/apache/karaf/management/JaasAuthenticator.java index 3d74f0a9e93..457d127048c 100644 --- a/management/server/src/main/java/org/apache/karaf/management/JaasAuthenticator.java +++ b/management/server/src/main/java/org/apache/karaf/management/JaasAuthenticator.java @@ -18,13 +18,10 @@ import org.apache.karaf.jaas.boot.principal.RolePrincipal; -import java.io.IOException; import java.security.Principal; import javax.management.remote.JMXAuthenticator; import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; @@ -56,16 +53,14 @@ public Subject authenticate(Object credentials) throws SecurityException { } try { Subject subject = new Subject(); - LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() { - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - for (Callback callback : callbacks) { - if (callback instanceof NameCallback) { - ((NameCallback) callback).setName(params[0]); - } else if (callback instanceof PasswordCallback) { - ((PasswordCallback) callback).setPassword((params[1].toCharArray())); - } else { - throw new UnsupportedCallbackException(callback); - } + LoginContext loginContext = new LoginContext(realm, subject, callbacks -> { + for (int i = 0; i < callbacks.length; i++) { + if (callbacks[i] instanceof NameCallback) { + ((NameCallback) callbacks[i]).setName(params[0]); + } else if (callbacks[i] instanceof PasswordCallback) { + ((PasswordCallback) callbacks[i]).setPassword((params[1].toCharArray())); + } else { + throw new UnsupportedCallbackException(callbacks[i]); } } }); diff --git a/management/server/src/test/java/org/apache/karaf/management/KarafMBeanServerGuardTest.java b/management/server/src/test/java/org/apache/karaf/management/KarafMBeanServerGuardTest.java index 882c0481ad3..5880d3c94df 100644 --- a/management/server/src/test/java/org/apache/karaf/management/KarafMBeanServerGuardTest.java +++ b/management/server/src/test/java/org/apache/karaf/management/KarafMBeanServerGuardTest.java @@ -462,12 +462,10 @@ private ConfigurationAdmin getMockConfigAdmin2(Dictionary... con public void testCurrentUserHasRole() throws Exception { Subject subject = loginWithTestRoles("test"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - assertTrue(JaasHelper.currentUserHasRole("test")); - assertFalse(JaasHelper.currentUserHasRole("toast")); - return null; - } + Subject.doAs(subject, (PrivilegedAction) () -> { + assertTrue(JaasHelper.currentUserHasRole("test")); + assertFalse(JaasHelper.currentUserHasRole("toast")); + return null; }); } @@ -478,12 +476,10 @@ public void testCurrentUserHasCustomRole() throws Exception { lm.login(); lm.commit(); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - assertTrue(JaasHelper.currentUserHasRole(TestRolePrincipal.class.getCanonicalName() + ":foo")); - assertFalse(JaasHelper.currentUserHasRole("foo")); - return null; - } + Subject.doAs(subject, (PrivilegedAction) () -> { + assertTrue(JaasHelper.currentUserHasRole(TestRolePrincipal.class.getCanonicalName() + ":foo")); + assertFalse(JaasHelper.currentUserHasRole("foo")); + return null; }); } @@ -497,33 +493,31 @@ public void testInvoke() throws Throwable { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("editor", "admin"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + Method im = MBeanServer.class.getMethod("invoke", ObjectName.class, String.class, Object[].class, String[].class); + + ObjectName on = ObjectName.getInstance("foo.bar:type=Test"); + + // The following operation should not throw an exception + guard.invoke(null, im, new Object[]{on, "someMethod", new Object[]{"test"}, new String[]{"java.lang.String"}}); + + try { + guard.invoke(null, im, new Object[]{on, "someOtherMethod", new Object[]{}, new String[]{}}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good + } + try { - Method im = MBeanServer.class.getMethod("invoke", ObjectName.class, String.class, Object[].class, String[].class); - - ObjectName on = ObjectName.getInstance("foo.bar:type=Test"); - - // The following operation should not throw an exception - guard.invoke(null, im, new Object[]{on, "someMethod", new Object[]{"test"}, new String[]{"java.lang.String"}}); - - try { - guard.invoke(null, im, new Object[]{on, "someOtherMethod", new Object[]{}, new String[]{}}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - - try { - guard.invoke(null, im, new Object[]{on, "somemethingElse", new Object[]{}, new String[]{}}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - return null; - } catch (Throwable ex) { - throw new RuntimeException(ex); + guard.invoke(null, im, new Object[]{on, "somemethingElse", new Object[]{}, new String[]{}}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good } + return null; + } catch (Throwable ex) { + throw new RuntimeException(ex); } }); } @@ -553,26 +547,24 @@ public void testGetAttributeIs() throws Throwable { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("editor", "admin"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + Method im = MBeanServer.class.getMethod("getAttribute", ObjectName.class, String.class); + + // The following operations should not throw an exception + guard.invoke(mbs, im, new Object[]{on, "Toast"}); + guard.invoke(mbs, im, new Object[]{on, "TestAttr"}); + try { - Method im = MBeanServer.class.getMethod("getAttribute", ObjectName.class, String.class); - - // The following operations should not throw an exception - guard.invoke(mbs, im, new Object[]{on, "Toast"}); - guard.invoke(mbs, im, new Object[]{on, "TestAttr"}); - - try { - guard.invoke(mbs, im, new Object[]{on, "Butter"}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - - return null; - } catch (Throwable ex) { - throw new RuntimeException(ex); + guard.invoke(mbs, im, new Object[]{on, "Butter"}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good } + + return null; + } catch (Throwable ex) { + throw new RuntimeException(ex); } }); } @@ -601,26 +593,24 @@ public void testGetAttributes() throws Throwable { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("editor", "admin"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + Method im = MBeanServer.class.getMethod("getAttributes", ObjectName.class, String[].class); + + // The following operations should not throw an exception + guard.invoke(mbs, im, new Object[]{on, new String[]{"Toast"}}); + guard.invoke(mbs, im, new Object[]{on, new String[]{"TestSomething", "Toast"}}); + try { - Method im = MBeanServer.class.getMethod("getAttributes", ObjectName.class, String[].class); - - // The following operations should not throw an exception - guard.invoke(mbs, im, new Object[]{on, new String[]{"Toast"}}); - guard.invoke(mbs, im, new Object[]{on, new String[]{"TestSomething", "Toast"}}); - - try { - guard.invoke(mbs, im, new Object[]{on, new String[]{"Butter", "Toast"}}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - - return null; - } catch (Throwable ex) { - throw new RuntimeException(ex); + guard.invoke(mbs, im, new Object[]{on, new String[]{"Butter", "Toast"}}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good } + + return null; + } catch (Throwable ex) { + throw new RuntimeException(ex); } }); } @@ -651,26 +641,24 @@ public void testGetAttributes2() throws Throwable { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("editor", "admin"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + Method im = MBeanServer.class.getMethod("getAttributes", ObjectName.class, String[].class); + + // The following operations should not throw an exception + guard.invoke(mbs, im, new Object[]{on, new String[]{"Toast"}}); + guard.invoke(mbs, im, new Object[]{on, new String[]{"TestSomething", "Toast"}}); + try { - Method im = MBeanServer.class.getMethod("getAttributes", ObjectName.class, String[].class); - - // The following operations should not throw an exception - guard.invoke(mbs, im, new Object[]{on, new String[]{"Toast"}}); - guard.invoke(mbs, im, new Object[]{on, new String[]{"TestSomething", "Toast"}}); - - try { - guard.invoke(mbs, im, new Object[]{on, new String[]{"Butter", "Toast"}}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - - return null; - } catch (Throwable ex) { - throw new RuntimeException(ex); + guard.invoke(mbs, im, new Object[]{on, new String[]{"Butter", "Toast"}}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good } + + return null; + } catch (Throwable ex) { + throw new RuntimeException(ex); } }); } @@ -700,33 +688,31 @@ public void testSetAttribute() throws Throwable { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("editor", "admin"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + Method im = MBeanServer.class.getMethod("setAttribute", ObjectName.class, Attribute.class); + + // The following operations should not throw an exception + guard.invoke(mbs, im, new Object[]{on, new Attribute("Something", "v1")}); + guard.invoke(mbs, im, new Object[]{on, new Attribute("Value", 42L)}); + + try { + guard.invoke(mbs, im, new Object[]{on, new Attribute("Other", Boolean.TRUE)}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good + } + try { - Method im = MBeanServer.class.getMethod("setAttribute", ObjectName.class, Attribute.class); - - // The following operations should not throw an exception - guard.invoke(mbs, im, new Object[]{on, new Attribute("Something", "v1")}); - guard.invoke(mbs, im, new Object[]{on, new Attribute("Value", 42L)}); - - try { - guard.invoke(mbs, im, new Object[]{on, new Attribute("Other", Boolean.TRUE)}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - - try { - guard.invoke(mbs, im, new Object[]{on, new Attribute("NonExistent", "v4")}); - fail("Should not have found the MBean Declaration"); - } catch (IllegalStateException ise) { - // good - } - - return null; - } catch (Throwable ex) { - throw new RuntimeException(ex); + guard.invoke(mbs, im, new Object[]{on, new Attribute("NonExistent", "v4")}); + fail("Should not have found the MBean Declaration"); + } catch (IllegalStateException ise) { + // good } + + return null; + } catch (Throwable ex) { + throw new RuntimeException(ex); } }); } @@ -756,37 +742,35 @@ public void testSetAttributes() throws Throwable { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("editor", "admin"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + Method im = MBeanServer.class.getMethod("setAttributes", ObjectName.class, AttributeList.class); + + // The following operations should not throw an exception + Attribute a1 = new Attribute("Something", "v1"); + Attribute a2 = new Attribute("Value", 42L); + guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a1))}); + guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a2, a1))}); + + Attribute a3 = new Attribute("Other", Boolean.TRUE); + try { + guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a1, a3))}); + fail("Should not have allowed the invocation"); + } catch (SecurityException se) { + // good + } + try { - Method im = MBeanServer.class.getMethod("setAttributes", ObjectName.class, AttributeList.class); - - // The following operations should not throw an exception - Attribute a1 = new Attribute("Something", "v1"); - Attribute a2 = new Attribute("Value", 42L); - guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a1))}); - guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a2, a1))}); - - Attribute a3 = new Attribute("Other", Boolean.TRUE); - try { - guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a1, a3))}); - fail("Should not have allowed the invocation"); - } catch (SecurityException se) { - // good - } - - try { - Attribute a4 = new Attribute("NonExistent", "v4"); - guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a4))}); - fail("Should not have found the MBean Declaration"); - } catch (IllegalStateException ise) { - // good - } - - return null; - } catch (Throwable ex) { - throw new RuntimeException(ex); + Attribute a4 = new Attribute("NonExistent", "v4"); + guard.invoke(mbs, im, new Object[]{on, new AttributeList(Arrays.asList(a4))}); + fail("Should not have found the MBean Declaration"); + } catch (IllegalStateException ise) { + // good } + + return null; + } catch (Throwable ex) { + throw new RuntimeException(ex); } }); } @@ -826,16 +810,14 @@ public void testCanInvokeMBean() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on)); - assertFalse(guard.canInvoke(mbs, on2)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on)); + assertFalse(guard.canInvoke(mbs, on2)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -869,15 +851,13 @@ public void testCanInvokeMBean2() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -909,15 +889,13 @@ public void testCanInvokeAnyOverload() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on, "doit")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on, "doit")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -950,15 +928,13 @@ public void testCanInvokeAnyOverload2() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on, "doit")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on, "doit")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -984,15 +960,13 @@ public void testCanInvokeAnyOverload3() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on, "doit")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on, "doit")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1020,15 +994,13 @@ public void testCanGetAttributeAnyOverload() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on, "getFoo")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on, "getFoo")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1056,15 +1028,13 @@ public void testCanGetAttributeAnyOverload2() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on, "getFoo")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on, "getFoo")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1093,15 +1063,13 @@ public void testCanGetAttributeAnyOverload3() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on, "isFoo")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on, "isFoo")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1130,15 +1098,13 @@ public void testCanGetAttributeAnyOverload4() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on, "isFoo")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on, "isFoo")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1166,15 +1132,13 @@ public void testCanSetAttributeAnyOverload() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on, "setFoo")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on, "setFoo")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1202,15 +1166,13 @@ public void testCanSetAttributeAnyOverload2() throws Exception { guard.setConfigAdmin(ca); Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on, "setFoo")); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on, "setFoo")); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1240,15 +1202,13 @@ public void testCanInvokeMBeanGetter() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1278,15 +1238,13 @@ public void testCanInvokeMBeanGetter2() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1316,15 +1274,13 @@ public void testCanInvokeMBeanGetter3() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1354,15 +1310,13 @@ public void testCanInvokeMBeanSetter() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(mbs, on)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(mbs, on)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1392,15 +1346,13 @@ public void testCanInvokeMBeanSetter2() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertFalse(guard.canInvoke(mbs, on)); + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertFalse(guard.canInvoke(mbs, on)); - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1422,20 +1374,18 @@ public void testCanInvokeMethod() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(null, on, "dodo", new String[]{"java.lang.String"})); - assertTrue(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String", "java.lang.String"})); - assertTrue(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String"})); - assertFalse(guard.canInvoke(null, on, "doit", new String[]{"int"})); - assertFalse(guard.canInvoke(null, on, "doit", new String[]{})); - assertFalse(guard.canInvoke(null, on, "uuuh", new String[]{"java.lang.String"})); - - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(null, on, "dodo", new String[]{"java.lang.String"})); + assertTrue(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String", "java.lang.String"})); + assertTrue(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String"})); + assertFalse(guard.canInvoke(null, on, "doit", new String[]{"int"})); + assertFalse(guard.canInvoke(null, on, "doit", new String[]{})); + assertFalse(guard.canInvoke(null, on, "uuuh", new String[]{"java.lang.String"})); + + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } @@ -1457,20 +1407,18 @@ public void testCanInvokeMethod2() throws Exception { Subject subject = loginWithTestRoles("viewer"); - Subject.doAs(subject, new PrivilegedAction() { - public Void run() { - try { - assertTrue(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String"})); - assertTrue(guard.canInvoke(null, on, "doit", new String[]{})); - assertTrue(guard.canInvoke(null, on, "doit", new String[]{"int"})); - assertFalse(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String", "java.lang.String"})); - assertFalse(guard.canInvoke(null, on, "dodo", new String[]{"java.lang.String"})); - assertFalse(guard.canInvoke(null, on, "uuuh", new String[]{"java.lang.String"})); - - return null; - } catch (Throwable th) { - throw new RuntimeException(th); - } + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + assertTrue(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String"})); + assertTrue(guard.canInvoke(null, on, "doit", new String[]{})); + assertTrue(guard.canInvoke(null, on, "doit", new String[]{"int"})); + assertFalse(guard.canInvoke(null, on, "doit", new String[]{"java.lang.String", "java.lang.String"})); + assertFalse(guard.canInvoke(null, on, "dodo", new String[]{"java.lang.String"})); + assertFalse(guard.canInvoke(null, on, "uuuh", new String[]{"java.lang.String"})); + + return null; + } catch (Throwable th) { + throw new RuntimeException(th); } }); } diff --git a/profile/src/main/java/org/apache/karaf/profile/impl/ProfileServiceImpl.java b/profile/src/main/java/org/apache/karaf/profile/impl/ProfileServiceImpl.java index c83e29a522c..9b3b99b5c4c 100644 --- a/profile/src/main/java/org/apache/karaf/profile/impl/ProfileServiceImpl.java +++ b/profile/src/main/java/org/apache/karaf/profile/impl/ProfileServiceImpl.java @@ -71,12 +71,7 @@ protected LockHandle acquireLock(final Lock lock, String message) { } catch (InterruptedException ex) { throw new IllegalStateException(message, ex); } - return new LockHandle() { - @Override - public void close() { - lock.unlock(); - } - }; + return lock::unlock; } protected ReadWriteLock getLock() { diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java index 4dbb1a822c1..3be00bc6c10 100644 --- a/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java +++ b/service/guard/src/main/java/org/apache/karaf/service/guard/impl/GuardProxyCatalog.java @@ -548,28 +548,25 @@ public ProxyManager addingService(ServiceReference reference) { } private Thread newProxyProducingThread(final ProxyManager proxyManager) { - Thread t = new Thread(new Runnable() { - @Override - public void run() { - while (runProxyCreator) { - CreateProxyRunnable proxyCreator = null; - try { - proxyCreator = createProxyQueue.take(); // take waits until there is something on the queue - } catch (InterruptedException ie) { - // part of normal behaviour - } + Thread t = new Thread(() -> { + while (runProxyCreator) { + CreateProxyRunnable proxyCreator = null; + try { + proxyCreator = createProxyQueue.take(); // take waits until there is something on the queue + } catch (InterruptedException ie) { + // part of normal behaviour + } - if (proxyCreator != null) { - try { - proxyCreator.run(proxyManager); - } catch (Exception e) { - LOG.warn("Problem creating secured service proxy", e); - } + if (proxyCreator != null) { + try { + proxyCreator.run(proxyManager); + } catch (Exception e) { + LOG.warn("Problem creating secured service proxy", e); } } - // finished running - proxyCreatorThread = null; } + // finished running + proxyCreatorThread = null; }); t.setName(PROXY_CREATOR_THREAD_NAME); t.setDaemon(true); diff --git a/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java b/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java index 2bf6f03e92f..626a4d4ecd1 100644 --- a/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java +++ b/service/guard/src/main/java/org/apache/karaf/service/guard/tools/ACLConfigurationParser.java @@ -281,11 +281,9 @@ private static List getExactArgOrRegexRoles(Dictionary p } private static List getMethodNameWildcardRoles(Dictionary properties, String methodName) { - SortedMap wildcardRules = new TreeMap<>(new Comparator() { - public int compare(String s1, String s2) { - // returns longer entries before shorter ones... - return s2.length() - s1.length(); - } + SortedMap wildcardRules = new TreeMap<>((s1, s2) -> { + // returns longer entries before shorter ones... + return s2.length() - s1.length(); }); for (Enumeration e = properties.keys(); e.hasMoreElements(); ) { diff --git a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java index 9670eb3586a..f81a23518c6 100644 --- a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java +++ b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/ActivatorTest.java @@ -20,11 +20,9 @@ import static org.junit.Assert.assertNull; import org.easymock.EasyMock; -import org.easymock.IAnswer; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; -import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.hooks.service.EventListenerHook; import org.osgi.framework.hooks.service.FindHook; @@ -50,12 +48,8 @@ public void testStartActivator() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.anyObject(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).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))) diff --git a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardProxyCatalogTest.java b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardProxyCatalogTest.java index 9045ec95d3d..c1dfd3476e7 100644 --- a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardProxyCatalogTest.java +++ b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardProxyCatalogTest.java @@ -227,12 +227,7 @@ public void testCreateProxy() throws Exception { testCreateProxy(Object.class, new TestObjectWithoutInterface()); testCreateProxy(Object.class, new CombinedTestService()); testCreateProxy(Object.class, new FinalTestService()); - testCreateProxy(TestServiceAPI.class, new TestServiceAPI() { - @Override - public String doit() { - return "Doing it"; - } - }); + testCreateProxy(TestServiceAPI.class, (TestServiceAPI) () -> "Doing it"); testCreateProxy(Object.class, new ClassWithFinalMethod()); testCreateProxy(Object.class, new ClassWithPrivateMethod()); } @@ -343,21 +338,18 @@ public void testInvocationBlocking1() throws Exception { // Run with the right credentials so we can test the expected roles Subject subject = new Subject(); subject.getPrincipals().add(new RolePrincipal("b")); - Subject.doAs(subject, new PrivilegedAction() { - @Override - public Object run() { - assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); - if (!runningUnderCoverage) { - try { - ((TestObjectWithoutInterface) proxy).compute(44L); - fail("Should have been blocked"); - } catch (SecurityException se) { - // good - } + Subject.doAs(subject, (PrivilegedAction) () -> { + assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); + if (!runningUnderCoverage) { + try { + ((TestObjectWithoutInterface) proxy).compute(44L); + fail("Should have been blocked"); + } catch (SecurityException se) { + // good } - - return null; } + + return null; }); } @@ -377,21 +369,18 @@ public void testInvocationBlocking2() throws Exception { // Run with the right credentials so we can test the expected roles Subject subject = new Subject(); subject.getPrincipals().add(new RolePrincipal("b")); - Subject.doAs(subject, new PrivilegedAction() { - @Override - public Object run() { - if (!runningUnderCoverage) { - assertEquals(-42L, ((TestObjectWithoutInterface) proxy).compute(42L)); - try { - ((TestObjectWithoutInterface) proxy).compute(44L); - fail("Should have been blocked"); - } catch (SecurityException se) { - // good - } + Subject.doAs(subject, (PrivilegedAction) () -> { + if (!runningUnderCoverage) { + assertEquals(-42L, ((TestObjectWithoutInterface) proxy).compute(42L)); + try { + ((TestObjectWithoutInterface) proxy).compute(44L); + fail("Should have been blocked"); + } catch (SecurityException se) { + // good } - - return null; } + + return null; }); } @@ -425,35 +414,29 @@ public String doit() { // Run with the right credentials so we can test the expected roles Subject subject = new Subject(); subject.getPrincipals().add(new RolePrincipal("c")); - Subject.doAs(subject, new PrivilegedAction() { - @Override - public Object run() { - assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); - return null; - } + Subject.doAs(subject, (PrivilegedAction) () -> { + assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); + return null; }); Subject subject2 = new Subject(); subject2.getPrincipals().add(new RolePrincipal("b")); subject2.getPrincipals().add(new RolePrincipal("f")); - Subject.doAs(subject2, new PrivilegedAction() { - @Override - public Object run() { - try { - assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); - fail("Should have been blocked"); - } catch (SecurityException se) { - // good - } - assertEquals("aaT", ((TestServiceAPI2) proxy).doit("Taa")); - try { - ((TestServiceAPI2) proxy).doit("t"); - fail("Should have been blocked"); - } catch (SecurityException se) { - // good - } - return null; + Subject.doAs(subject2, (PrivilegedAction) () -> { + try { + assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); + fail("Should have been blocked"); + } catch (SecurityException se) { + // good } + assertEquals("aaT", ((TestServiceAPI2) proxy).doit("Taa")); + try { + ((TestServiceAPI2) proxy).doit("t"); + fail("Should have been blocked"); + } catch (SecurityException se) { + // good + } + return null; }); } @@ -467,17 +450,14 @@ public void testInvocationBlocking4() throws Exception { // Run with the right credentials so we can test the expected roles Subject subject = new Subject(); subject.getPrincipals().add(new RolePrincipal("b")); - Subject.doAs(subject, new PrivilegedAction() { - @Override - public Object run() { - assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); - if (!runningUnderCoverage) { - assertEquals(42L, ((TestObjectWithoutInterface) proxy).compute(-42L)); - assertEquals(-44L, ((TestObjectWithoutInterface) proxy).compute(44L)); - } - - return null; + Subject.doAs(subject, (PrivilegedAction) () -> { + assertEquals("Doing it", ((TestServiceAPI) proxy).doit()); + if (!runningUnderCoverage) { + assertEquals(42L, ((TestObjectWithoutInterface) proxy).compute(-42L)); + assertEquals(-44L, ((TestObjectWithoutInterface) proxy).compute(44L)); } + + return null; }); } @@ -492,23 +472,16 @@ public void testInvocationBlocking5() throws Exception { BundleContext bc = mockConfigAdminBundleContext(c1); - final Object proxy = testCreateProxy(bc, new Class [] {TestServiceAPI2.class}, new TestServiceAPI2() { - @Override - public String doit(String s) { - return s.toUpperCase(); - } - }); + final Object proxy = testCreateProxy(bc, new Class [] {TestServiceAPI2.class}, + (TestServiceAPI2) String::toUpperCase); // Invoke the service with role 'c'. Subject subject = new Subject(); subject.getPrincipals().add(new RolePrincipal("c")); - Subject.doAs(subject, new PrivilegedAction() { - @Override - public Object run() { - assertEquals("The invocation under role 'c' should be ok, as there are no rules specified " - + "for this service at all.", "HELLO", ((TestServiceAPI2) proxy).doit("hello")); - return null; - } + Subject.doAs(subject, (PrivilegedAction) () -> { + assertEquals("The invocation under role 'c' should be ok, as there are no rules specified " + + "for this service at all.", "HELLO", ((TestServiceAPI2) proxy).doit("hello")); + return null; }); } @@ -526,29 +499,22 @@ public void testInvocationBlocking6() throws Exception { BundleContext bc = mockConfigAdminBundleContext(c1, c2); - final Object proxy = testCreateProxy(bc, new Class [] {TestServiceAPI2.class}, new TestServiceAPI2() { - @Override - public String doit(String s) { - return s.toUpperCase(); - } - }); + final Object proxy = testCreateProxy(bc, new Class [] {TestServiceAPI2.class}, + (TestServiceAPI2) String::toUpperCase); // Invoke the service with role 'c'. Subject subject = new Subject(); subject.getPrincipals().add(new RolePrincipal("a")); subject.getPrincipals().add(new RolePrincipal("b")); subject.getPrincipals().add(new RolePrincipal("c")); - Subject.doAs(subject, new PrivilegedAction() { - @Override - public Object run() { - try { - ((TestServiceAPI2) proxy).doit("hello"); - fail("The invocation should not process as the 'doit' operation has no roles associated with it"); - } catch (SecurityException se) { - // good - } - return null; + Subject.doAs(subject, (PrivilegedAction) () -> { + try { + ((TestServiceAPI2) proxy).doit("hello"); + fail("The invocation should not process as the 'doit' operation has no roles associated with it"); + } catch (SecurityException se) { + // good } + return null; }); } @@ -567,41 +533,35 @@ public void testInvocationBlocking7() throws Exception { final Object proxy = testCreateProxy(bc, new Class [] {TestServiceAPI3.class}, new TestService3()); Subject s1 = new Subject(); - Subject.doAs(s1, new PrivilegedAction() { - @Override - public Object run() { - TestServiceAPI3 obj = (TestServiceAPI3) proxy; - assertEquals("Should have allowed this invocation for any (or no) role", -7, obj.foo(7)); - try { - obj.foo(); - fail("Should have been blocked"); - } catch (SecurityException se) { - // good - } - try { - obj.bar(); - fail("Should have been blocked"); - } catch (SecurityException se) { - // good - } - - return null; + Subject.doAs(s1, (PrivilegedAction) () -> { + TestServiceAPI3 obj = (TestServiceAPI3) proxy; + assertEquals("Should have allowed this invocation for any (or no) role", -7, obj.foo(7)); + try { + obj.foo(); + fail("Should have been blocked"); + } catch (SecurityException se) { + // good + } + try { + obj.bar(); + fail("Should have been blocked"); + } catch (SecurityException se) { + // good } + + return null; }); Subject s2 = new Subject(); s2.getPrincipals().add(new RolePrincipal("a")); s2.getPrincipals().add(new RolePrincipal("b")); s2.getPrincipals().add(new RolePrincipal("d")); - Subject.doAs(s2, new PrivilegedAction() { - @Override - public Object run() { - TestServiceAPI3 obj = (TestServiceAPI3) proxy; - assertEquals(42, obj.foo()); - assertEquals(99, obj.bar()); - assertEquals(-32767, obj.foo(32767)); - return null; - } + Subject.doAs(s2, (PrivilegedAction) () -> { + TestServiceAPI3 obj = (TestServiceAPI3) proxy; + assertEquals(42, obj.foo()); + assertEquals(99, obj.bar()); + assertEquals(-32767, obj.foo(32767)); + return null; }); } @@ -625,39 +585,30 @@ public String getName() { Subject s1 = new Subject(); s1.getPrincipals().add(new RolePrincipal("role1")); - Subject.doAs(s1, new PrivilegedAction() { - @Override - public Object run() { - try { - ((TestServiceAPI) proxy).doit(); - fail("Should have prevented this invocation as the custom role is required"); - } catch (SecurityException se) { - // good - } - return null; + Subject.doAs(s1, (PrivilegedAction) () -> { + try { + ((TestServiceAPI) proxy).doit(); + fail("Should have prevented this invocation as the custom role is required"); + } catch (SecurityException se) { + // good } + return null; }); Subject s2 = new Subject(); s2.getPrincipals().add(new MyRolePrincipal()); - Subject.doAs(s2, new PrivilegedAction() { - @Override - public Object run() { - ((TestServiceAPI) proxy).doit(); // Should work, the custom role is there - return null; - } + Subject.doAs(s2, (PrivilegedAction) () -> { + ((TestServiceAPI) proxy).doit(); // Should work, the custom role is there + return null; }); Subject s3 = new Subject(); s3.getPrincipals().add(new MyRolePrincipal()); s3.getPrincipals().add(new RolePrincipal("role1")); - Subject.doAs(s3, new PrivilegedAction() { - @Override - public Object run() { - ((TestServiceAPI) proxy).doit(); // Should work, the custom role is there - return null; - } + Subject.doAs(s3, (PrivilegedAction) () -> { + ((TestServiceAPI) proxy).doit(); // Should work, the custom role is there + return null; }); } @@ -683,22 +634,15 @@ public void testProxyCreationThread() throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); final ServiceListener [] pmListenerHolder = new ServiceListener [1]; String pmFilter = "(&(objectClass=" + ProxyManager.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))"; bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(pmFilter)); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - pmListenerHolder[0] = (ServiceListener) EasyMock.getCurrentArguments()[0]; - return null; - } + EasyMock.expectLastCall().andAnswer(() -> { + pmListenerHolder[0] = (ServiceListener) EasyMock.getCurrentArguments()[0]; + return null; }).anyTimes(); EasyMock.expect(bc.getServiceReferences(EasyMock.anyObject(String.class), EasyMock.contains(ConfigurationAdmin.class.getName()))).andReturn(new ServiceReference[] {cmSref}).anyTimes(); @@ -725,28 +669,21 @@ public Object answer() throws Throwable { EasyMock.expect(providerBC.registerService( EasyMock.isA(String[].class), EasyMock.anyObject(), - EasyMock.isA(Dictionary.class))).andAnswer(new IAnswer() { - @Override - public ServiceRegistration answer() throws Throwable { - Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; - ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); - ServiceReference sr = mockServiceReference(props); - EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); - reg.unregister(); - EasyMock.expectLastCall().once(); - EasyMock.replay(reg); - - serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); - - return reg; - } - }).once(); - EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return serviceMap.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> { + Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; + ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); + ServiceReference sr = mockServiceReference(props); + EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); + reg.unregister(); + EasyMock.expectLastCall().once(); + 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); // In some cases the proxy-creating code is looking for a classloader (e.g. when run through @@ -858,19 +795,15 @@ public void testHandleServiceModified() throws Exception { EasyMock.expect(providerBC.registerService( EasyMock.aryEq(new String [] {TestServiceAPI.class.getName(), TestServiceAPI2.class.getName()}), EasyMock.anyObject(), - EasyMock.anyObject(Dictionary.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - final Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; - assertEquals(Boolean.TRUE, props.get(GuardProxyCatalog.PROXY_SERVICE_KEY)); - - ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); - ServiceReference sr = mockServiceReference(props); - EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); - reg.setProperties(EasyMock.isA(Dictionary.class)); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { + EasyMock.anyObject(Dictionary.class))).andAnswer((IAnswer) () -> { + final Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; + assertEquals(Boolean.TRUE, props.get(GuardProxyCatalog.PROXY_SERVICE_KEY)); + + ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); + ServiceReference sr = mockServiceReference(props); + EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); + reg.setProperties(EasyMock.isA(Dictionary.class)); + EasyMock.expectLastCall().andAnswer(() -> { // Push the update into the service reference ArrayList oldKeys = Collections.list(props.keys()); for (String key : oldKeys) { @@ -881,13 +814,11 @@ public Object answer() throws Throwable { props.put(key, newProps.get(key)); } return null; - } - }).once(); - EasyMock.replay(reg); + }).once(); + EasyMock.replay(reg); - return reg; - } - }).anyTimes(); + return reg; + }).anyTimes(); EasyMock.replay(providerBC); @@ -956,19 +887,15 @@ public void testHandleServiceModified2() throws Exception { EasyMock.expect(providerBC.registerService( EasyMock.aryEq(new String [] {TestServiceAPI.class.getName()}), EasyMock.anyObject(), - EasyMock.anyObject(Dictionary.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - final Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; - assertEquals(Boolean.TRUE, props.get(GuardProxyCatalog.PROXY_SERVICE_KEY)); - - ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); - ServiceReference sr = mockServiceReference(props); - EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); - reg.setProperties(EasyMock.isA(Dictionary.class)); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { + EasyMock.anyObject(Dictionary.class))).andAnswer((IAnswer) () -> { + final Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; + assertEquals(Boolean.TRUE, props.get(GuardProxyCatalog.PROXY_SERVICE_KEY)); + + ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); + ServiceReference sr = mockServiceReference(props); + EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); + reg.setProperties(EasyMock.isA(Dictionary.class)); + EasyMock.expectLastCall().andAnswer(() -> { // Push the update into the service reference ArrayList oldKeys = Collections.list(props.keys()); for (String key : oldKeys) { @@ -979,13 +906,11 @@ public Object answer() throws Throwable { props.put(key, newProps.get(key)); } return null; - } - }).once(); - EasyMock.replay(reg); + }).once(); + EasyMock.replay(reg); - return reg; - } - }).anyTimes(); + return reg; + }).anyTimes(); EasyMock.replay(providerBC); @@ -1050,26 +975,19 @@ public void testServiceFactoryBehaviour() throws Exception { EasyMock.expect(providerBC.registerService( EasyMock.isA(String[].class), EasyMock.anyObject(), - EasyMock.isA(Dictionary.class))).andAnswer(new IAnswer() { - @Override - public ServiceRegistration answer() throws Throwable { - Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; - ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); - ServiceReference sr = mockServiceReference(props); - EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); - EasyMock.replay(reg); + EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> { + Dictionary props = (Dictionary) 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]); + serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); - return reg; - } - }).once(); - EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return serviceMap.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + return reg; + }).once(); + EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer( + () -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(providerBC); // In some cases the proxy-creating code is looking for a classloader (e.g. when run through @@ -1161,41 +1079,34 @@ public Dictionary testCreateProxy(BundleContext bc, Class intf, EasyMock.expect(providerBC.registerService( EasyMock.isA(String[].class), EasyMock.anyObject(), - EasyMock.isA(Dictionary.class))).andAnswer(new IAnswer() { - @Override - public ServiceRegistration answer() throws Throwable { - if (!runningUnderCoverage) { - // Some of these checks don't work when running under coverage - assertArrayEquals(new String [] {proxyRegClass.getName()}, - (String []) EasyMock.getCurrentArguments()[0]); - - Object svc = EasyMock.getCurrentArguments()[1]; - assertTrue(svc instanceof ServiceFactory); - } + EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> { + if (!runningUnderCoverage) { + // Some of these checks don't work when running under coverage + assertArrayEquals(new String [] {proxyRegClass.getName()}, + (String []) EasyMock.getCurrentArguments()[0]); + + Object svc = EasyMock.getCurrentArguments()[1]; + assertTrue(svc instanceof ServiceFactory); + } - Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; - for (String key : expectedProxyProps.keySet()) { - assertEquals(expectedProxyProps.get(key), props.get(key)); - } + Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; + for (String key : expectedProxyProps.keySet()) { + assertEquals(expectedProxyProps.get(key), props.get(key)); + } - ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); - ServiceReference sr = mockServiceReference(props); - EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); - reg.unregister(); - EasyMock.expectLastCall().once(); - EasyMock.replay(reg); + ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); + ServiceReference sr = mockServiceReference(props); + EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); + reg.unregister(); + EasyMock.expectLastCall().once(); + EasyMock.replay(reg); - serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); + serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); - return reg; - } - }).once(); - EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return serviceMap.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + return reg; + }).once(); + EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer( + () -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(providerBC); // In some cases the proxy-creating code is looking for a classloader (e.g. when run through @@ -1305,46 +1216,39 @@ public Object testCreateProxy(BundleContext bc, Class [] objectClasses, final Cl EasyMock.expect(providerBC.registerService( EasyMock.isA(String[].class), EasyMock.anyObject(), - EasyMock.isA(Dictionary.class))).andAnswer(new IAnswer() { - @Override - public ServiceRegistration answer() throws Throwable { - if (!runningUnderCoverage) { - // Some of these checks don't work when running under coverage - assertArrayEquals(proxyRegClsMap.keySet().toArray(new String [] {}), - (String []) EasyMock.getCurrentArguments()[0]); - - Object svc = EasyMock.getCurrentArguments()[1]; - assertTrue(svc instanceof ServiceFactory); - } + EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> { + if (!runningUnderCoverage) { + // Some of these checks don't work when running under coverage + assertArrayEquals(proxyRegClsMap.keySet().toArray(new String [] {}), + (String []) EasyMock.getCurrentArguments()[0]); + + Object svc = EasyMock.getCurrentArguments()[1]; + assertTrue(svc instanceof ServiceFactory); + } - Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; - for (String key : expectedProxyProps.keySet()) { - if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) { - assertTrue("The roles property should have been overwritten", - !Arrays.asList("everyone").equals(props.get(key))); - } else { - assertEquals(expectedProxyProps.get(key), props.get(key)); + Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2]; + for (String key : expectedProxyProps.keySet()) { + if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) { + assertTrue("The roles property should have been overwritten", + !Arrays.asList("everyone").equals(props.get(key))); + } else { + assertEquals(expectedProxyProps.get(key), props.get(key)); + } } - } - ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); - ServiceReference sr = mockServiceReference(props); - EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); - reg.unregister(); - EasyMock.expectLastCall().once(); - EasyMock.replay(reg); + ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class); + ServiceReference sr = mockServiceReference(props); + EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes(); + reg.unregister(); + EasyMock.expectLastCall().once(); + EasyMock.replay(reg); - serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); + serviceMap.put(sr, EasyMock.getCurrentArguments()[1]); - return reg; - } - }).once(); - EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return serviceMap.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + return reg; + }).once(); + EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer( + () -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(providerBC); // In some cases the proxy-creating code is looking for a classloader (e.g. when run through @@ -1370,12 +1274,8 @@ public Object answer() throws Throwable { Bundle clientBundle = EasyMock.createNiceMock(Bundle.class); EasyMock.expect(clientBundle.getBundleId()).andReturn(2999L).anyTimes(); EasyMock.expect(clientBundle.getBundleContext()).andReturn(clientBC).anyTimes(); - EasyMock.expect(clientBundle.loadClass(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Class answer() throws Throwable { - return objClsMap.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(clientBundle.loadClass(EasyMock.isA(String.class))).andAnswer( + (IAnswer) () -> objClsMap.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(clientBundle); assertEquals("Precondition", 0, gpc.proxyMap.size()); @@ -1449,12 +1349,8 @@ private BundleContext mockBundleContext(Bundle b) throws InvalidSyntaxException } BundleContext bc = EasyMock.createNiceMock(BundleContext.class); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); EasyMock.replay(bc); return bc; @@ -1462,12 +1358,8 @@ public Filter answer() throws Throwable { private BundleContext openStrictMockBundleContext(Bundle b) throws InvalidSyntaxException { BundleContext bc = EasyMock.createMock(BundleContext.class); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); if (b != null) { EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); } @@ -1503,12 +1395,8 @@ private BundleContext mockConfigAdminBundleContext(Dictionary .. BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); String cmFilter = "(&(objectClass=" + ConfigurationAdmin.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))"; bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(cmFilter)); @@ -1534,18 +1422,10 @@ private ServiceReference mockServiceReference(Bundle providerBundle, ServiceReference sr = EasyMock.createMock(ServiceReference.class); // Make sure the properties are 'live' in that if they change the reference changes too - EasyMock.expect(sr.getPropertyKeys()).andAnswer(new IAnswer() { - @Override - public String[] answer() throws Throwable { - return Collections.list(serviceProps.keys()).toArray(new String [] {}); - } - }).anyTimes(); - EasyMock.expect(sr.getProperty(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return serviceProps.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(sr.getPropertyKeys()).andAnswer( + () -> Collections.list(serviceProps.keys()).toArray(new String [] {})).anyTimes(); + EasyMock.expect(sr.getProperty(EasyMock.isA(String.class))).andAnswer( + () -> serviceProps.get(EasyMock.getCurrentArguments()[0])).anyTimes(); if (providerBundle != null) { EasyMock.expect(sr.getBundle()).andReturn(providerBundle).anyTimes(); } diff --git a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingEventHookTest.java b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingEventHookTest.java index f026cf62e4e..2445a85d467 100644 --- a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingEventHookTest.java +++ b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingEventHookTest.java @@ -28,7 +28,6 @@ import java.util.Map; import org.easymock.EasyMock; -import org.easymock.IAnswer; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; @@ -176,12 +175,8 @@ private BundleContext mockBundleContext(long id) throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(bundle).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(bc); EasyMock.expect(bundle.getBundleContext()).andReturn(bc).anyTimes(); @@ -222,12 +217,8 @@ private BundleContext mockConfigAdminBundleContext(BundleContext frameworkContex BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); EasyMock.expect(bc.getBundle(0L)).andReturn(sb).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); String cmFilter = "(&(objectClass=" + ConfigurationAdmin.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))"; bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(cmFilter)); @@ -243,18 +234,9 @@ private ServiceReference mockServiceReference(final Dictionary sr = EasyMock.createMock(ServiceReference.class); // Make sure the properties are 'live' in that if they change the reference changes too - EasyMock.expect(sr.getPropertyKeys()).andAnswer(new IAnswer() { - @Override - public String[] answer() throws Throwable { - return Collections.list(props.keys()).toArray(new String [] {}); - } - }).anyTimes(); - EasyMock.expect(sr.getProperty(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return props.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(sr.getPropertyKeys()).andAnswer(() -> Collections.list(props.keys()).toArray(new String [] {})).anyTimes(); + EasyMock.expect(sr.getProperty(EasyMock.isA(String.class))).andAnswer( + () -> props.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(sr); return sr; } diff --git a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingFindHookTest.java b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingFindHookTest.java index a8fedf358cf..27422f6a2f0 100644 --- a/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingFindHookTest.java +++ b/service/guard/src/test/java/org/apache/karaf/service/guard/impl/GuardingFindHookTest.java @@ -26,7 +26,6 @@ import java.util.Hashtable; import org.easymock.EasyMock; -import org.easymock.IAnswer; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; @@ -160,13 +159,8 @@ private BundleContext mockBundleContext(long id) throws Exception { BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(bundle).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - Filter filter = FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - return filter; - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(bc); EasyMock.expect(bundle.getBundleContext()).andReturn(bc).anyTimes(); @@ -201,12 +195,8 @@ private BundleContext mockConfigAdminBundleContext(Dictionary .. BundleContext bc = EasyMock.createNiceMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); - EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Filter answer() throws Throwable { - return FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer( + () -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes(); String cmFilter = "(&(objectClass=" + ConfigurationAdmin.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))"; bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(cmFilter)); @@ -223,18 +213,10 @@ private ServiceReference mockServiceReference(final Dictionary sr = EasyMock.createMock(ServiceReference.class); // Make sure the properties are 'live' in that if they change the reference changes too - EasyMock.expect(sr.getPropertyKeys()).andAnswer(new IAnswer() { - @Override - public String[] answer() throws Throwable { - return Collections.list(props.keys()).toArray(new String [] {}); - } - }).anyTimes(); - EasyMock.expect(sr.getProperty(EasyMock.isA(String.class))).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - return props.get(EasyMock.getCurrentArguments()[0]); - } - }).anyTimes(); + EasyMock.expect(sr.getPropertyKeys()).andAnswer( + () -> Collections.list(props.keys()).toArray(new String[] {})).anyTimes(); + EasyMock.expect(sr.getProperty(EasyMock.isA(String.class))).andAnswer( + () -> props.get(EasyMock.getCurrentArguments()[0])).anyTimes(); EasyMock.replay(sr); return sr; } diff --git a/services/eventadmin/src/main/java/org/apache/felix/eventadmin/impl/Configuration.java b/services/eventadmin/src/main/java/org/apache/felix/eventadmin/impl/Configuration.java index c732ae7b775..86631dd3d7b 100644 --- a/services/eventadmin/src/main/java/org/apache/felix/eventadmin/impl/Configuration.java +++ b/services/eventadmin/src/main/java/org/apache/felix/eventadmin/impl/Configuration.java @@ -34,7 +34,6 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; -import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.osgi.service.event.EventAdmin; import org.osgi.service.metatype.MetaTypeProvider; @@ -194,20 +193,13 @@ void updateFromConfigAdmin(final Dictionary config) { // do this in the background as we don't want to stop // the config admin - new Thread() - { - - @Override - public void run() + new Thread(() -> { + synchronized ( Configuration.this ) { - synchronized ( Configuration.this ) - { - Configuration.this.configure( config ); - Configuration.this.startOrUpdate(); - } + Configuration.this.configure( config ); + Configuration.this.startOrUpdate(); } - - }.start(); + }).start(); } @@ -485,14 +477,7 @@ private Object tryToCreateManagedService() { try { - return new ManagedService() - { - @Override - public void updated( Dictionary properties ) throws ConfigurationException - { - updateFromConfigAdmin(properties); - } - }; + return (ManagedService) this::updateFromConfigAdmin; } catch (Throwable t) { diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java index 18c5f737052..3311bd9720a 100644 --- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java +++ b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java @@ -144,11 +144,7 @@ public Object execute() throws Exception { if (keys.size() > 0) { System.out.println(section); - Collections.sort(keys, new Comparator() { - public int compare(Object o1, Object o2) { - return String.valueOf(o1).compareTo(String.valueOf(o2)); - } - }); + keys.sort(Comparator.comparing(String::valueOf)); for (Object key : keys) { printValue(String.valueOf(key), maxNameLen, String.valueOf(properties.get(section).get(key))); diff --git a/shell/console/src/main/java/org/apache/felix/gogo/commands/basic/DefaultActionPreparator.java b/shell/console/src/main/java/org/apache/felix/gogo/commands/basic/DefaultActionPreparator.java index edcfff1eb97..b9538ffc685 100644 --- a/shell/console/src/main/java/org/apache/felix/gogo/commands/basic/DefaultActionPreparator.java +++ b/shell/console/src/main/java/org/apache/felix/gogo/commands/basic/DefaultActionPreparator.java @@ -363,11 +363,7 @@ protected void printUsage(CommandSession session, Action action, Map arguments = new ArrayList<>(argsMap.keySet()); - Collections.sort(arguments, new Comparator() { - public int compare(Argument o1, Argument o2) { - return Integer.valueOf(o1.index()).compareTo(Integer.valueOf(o2.index())); - } - }); + arguments.sort(Comparator.comparing(Argument::index)); Set