You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@karaf.apache.org by cs...@apache.org on 2017/08/17 14:29:53 UTC

[01/27] karaf git commit: Change Blacklist into an ordinary class [Forced Update!]

Repository: karaf
Updated Branches:
  refs/heads/model_features a59edf056 -> 6576f4765 (forced update)


Change Blacklist into an ordinary class


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/eb95bce7
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/eb95bce7
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/eb95bce7

Branch: refs/heads/model_features
Commit: eb95bce7d5a1bcf23a5bda919209394ffcf3c01a
Parents: e442a1b
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Mon Aug 14 18:46:07 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Mon Aug 14 18:46:07 2017 +0200

----------------------------------------------------------------------
 .../features/internal/service/Blacklist.java    |  90 +++++++---------
 .../internal/service/FeaturesServiceImpl.java   |  28 +----
 .../internal/service/RepositoryCache.java       |  19 +---
 .../internal/service/RepositoryImpl.java        |  23 ++--
 .../internal/service/BlacklistTest.java         |  67 ++++--------
 .../profile/assembly/ArtifactInstaller.java     |  84 +++++++++++++++
 .../assembly/AssemblyDeployCallback.java        |  11 +-
 .../apache/karaf/profile/assembly/Builder.java  | 104 +++----------------
 8 files changed, 185 insertions(+), 241 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/features/core/src/main/java/org/apache/karaf/features/internal/service/Blacklist.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/Blacklist.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/Blacklist.java
index 0d804a7..f7f4aab 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/Blacklist.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/Blacklist.java
@@ -16,12 +16,18 @@
  */
 package org.apache.karaf.features.internal.service;
 
+import static java.util.stream.Collectors.toSet;
+
 import java.io.BufferedReader;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URL;
-import java.util.*;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
 
 import org.apache.felix.utils.manifest.Clause;
 import org.apache.felix.utils.manifest.Parser;
@@ -47,25 +53,38 @@ public class Blacklist {
     public static final String TYPE_REPOSITORY = "repository";
 
     private static final Logger LOGGER = LoggerFactory.getLogger(Blacklist.class);
-
-    private Blacklist() {
+    private Clause[] clauses;
+    
+    public Blacklist() {
+        this(Collections.emptyList());
     }
 
-    public static void blacklist(Features features, String blacklisted) {
-        Set<String> blacklist = loadBlacklist(blacklisted);
-        blacklist(features, blacklist);
+    public Blacklist(List<String> blacklist) {
+        this.clauses = org.apache.felix.utils.manifest.Parser.parseClauses(blacklist.toArray(new String[blacklist.size()]));
     }
-
-    public static void blacklist(Features features, Collection<String> blacklist) {
-        Clause[] clauses = Parser.parseClauses(blacklist.toArray(new String[blacklist.size()]));
-        blacklist(features, clauses);
+    
+    public Blacklist(String blacklistUrl) {
+        Set<String> blacklist = new HashSet<>();
+        if (blacklistUrl != null) {
+            try (InputStream is = new URL(blacklistUrl).openStream();
+                BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
+                reader.lines() //
+                    .map(line -> line.trim()) //
+                    .filter(line -> line.isEmpty() || line.startsWith("#")).collect(toSet());
+            } catch (FileNotFoundException e) {
+                LOGGER.debug("Unable to load blacklist bundles list", e.toString());
+            } catch (Exception e) {
+                LOGGER.debug("Unable to load blacklist bundles list", e);
+            }
+        }
+        this.clauses = Parser.parseClauses(blacklist.toArray(new String[blacklist.size()]));
     }
 
-    public static void blacklist(Features features, Clause[] clauses) {
-        features.getFeature().removeIf(feature -> blacklist(feature, clauses));
+    public void blacklist(Features features) {
+        features.getFeature().removeIf(feature -> blacklist(feature));
     }
 
-    public static boolean blacklist(Feature feature, Clause[] clauses) {
+    public boolean blacklist(Feature feature) {
         for (Clause clause : clauses) {
             // Check feature name
             if (clause.getName().equals(feature.getName())) {
@@ -83,16 +102,16 @@ public class Blacklist {
                 }
             }
             // Check bundles
-            blacklist(feature.getBundle(), clauses);
+            blacklist(feature.getBundle());
             // Check conditional bundles
             for (Conditional cond : feature.getConditional()) {
-                blacklist(cond.getBundle(), clauses);
+                blacklist(cond.getBundle());
             }
         }
         return false;
     }
 
-    private static void blacklist(List<Bundle> bundles, Clause[] clauses) {
+    private void blacklist(List<Bundle> bundles) {
         for (Iterator<Bundle> iterator = bundles.iterator(); iterator.hasNext();) {
             Bundle info = iterator.next();
             for (Clause clause : clauses) {
@@ -111,33 +130,7 @@ public class Blacklist {
         }
     }
 
-    public static Set<String> loadBlacklist(String blacklistUrl) {
-        Set<String> blacklist = new HashSet<>();
-        try {
-            if (blacklistUrl != null) {
-                try (
-                        InputStream is = new URL(blacklistUrl).openStream()
-                ) {
-                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
-                    String line;
-                    while ((line = reader.readLine()) != null) {
-                        line = line.trim();
-                        if (!line.isEmpty() && !line.startsWith("#")) {
-                            blacklist.add(line);
-                        }
-                    }
-                }
-            }
-        } catch (FileNotFoundException e) {
-            LOGGER.debug("Unable to load blacklist bundles list", e.toString());
-        } catch (Exception e) {
-            LOGGER.debug("Unable to load blacklist bundles list", e);
-        }
-        return blacklist;
-    }
-
-    public static boolean isFeatureBlacklisted(List<String> blacklist, String name, String version) {
-        Clause[] clauses = Parser.parseClauses(blacklist.toArray(new String[blacklist.size()]));
+    public boolean isFeatureBlacklisted(String name, String version) {
         for (Clause clause : clauses) {
             if (clause.getName().equals(name)) {
                 // Check feature version
@@ -157,16 +150,11 @@ public class Blacklist {
         return false;
     }
 
-    public static boolean isBundleBlacklisted(List<String> blacklist, String uri) {
-        return isBlacklisted(blacklist, uri, TYPE_BUNDLE);
-    }
-
-    public static boolean isBlacklisted(List<String> blacklist, String uri, String btype) {
-        Clause[] clauses = Parser.parseClauses(blacklist.toArray(new String[blacklist.size()]));
-        return isBlacklisted(clauses, uri, btype);
+    public boolean isBundleBlacklisted(String uri) {
+        return isBlacklisted(uri, TYPE_BUNDLE);
     }
 
-    public static boolean isBlacklisted(Clause[] clauses, String uri, String btype) {
+    public boolean isBlacklisted(String uri, String btype) {
         for (Clause clause : clauses) {
             String url = clause.getName();
             if (clause.getAttribute(BLACKLIST_URL) != null) {

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
index 6a000cd..90f4969 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
@@ -49,7 +49,6 @@ import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
-import org.apache.felix.utils.manifest.Clause;
 import org.apache.felix.utils.version.VersionCleaner;
 import org.apache.felix.utils.version.VersionRange;
 import org.apache.felix.utils.version.VersionTable;
@@ -145,7 +144,8 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         this.resolver = resolver;
         this.installSupport = installSupport;
         this.globalRepository = globalRepository;
-        this.repositories = new RepositoryCache(cfg.blacklisted);
+        Blacklist blacklist = new Blacklist(cfg.blacklisted);
+        this.repositories = new RepositoryCache(blacklist);
         this.cfg = cfg;
         this.executor = Executors.newSingleThreadExecutor(ThreadUtils.namedThreadFactory("features"));
         loadState();
@@ -260,8 +260,9 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
                 repositories.addAll(state.repositories);
                 installedFeatures.putAll(copy(state.installedFeatures));
             }
+            Blacklist blacklist = new Blacklist(cfg.blacklisted);
             for (String uri : repositories) {
-                Repository repository = new RepositoryImpl(URI.create(uri), cfg.blacklisted);
+                Repository repository = new RepositoryImpl(URI.create(uri), blacklist);
                 listener.repositoryEvent(new RepositoryEvent(repository, RepositoryEvent.EventType.RepositoryAdded, true));
             }
             for (Map.Entry<String, Set<String>> entry : installedFeatures.entrySet()) {
@@ -981,27 +982,6 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         return repositories.create(uri, true, true);
     }
 
-    private Map<String, Feature> loadAllFeatures(Set<URI> uris) throws Exception {
-        //the outer map's key is feature name, the inner map's key is feature version
-        Map<String, Feature> map = new HashMap<>();
-        // Two phase load:
-        // * first load dependent repositories
-        Set<URI> loaded = new HashSet<>();
-        List<URI> toLoad = new ArrayList<>(uris);
-        Clause[] blacklisted = repositories.getBlacklisted();
-        while (!toLoad.isEmpty()) {
-            URI uri = toLoad.remove(0);
-            if (loaded.add(uri)) {
-                Repository repo = new RepositoryImpl(uri, blacklisted);
-                Collections.addAll(toLoad, repo.getRepositories());
-                for (Feature f : repo.getFeatures()) {
-                    map.put(f.getId(), f);
-                }
-            }
-        }
-        return map;
-    }
-
     @Override
     public Map<String, Set<String>> listRequirements() {
         synchronized (lock) {

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
index f92b0bc..4898566 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
@@ -27,30 +27,19 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import org.apache.felix.utils.manifest.Clause;
-import org.apache.felix.utils.manifest.Parser;
 import org.apache.karaf.features.Repository;
 
 public class RepositoryCache {
 
     private final Map<String, Repository> repositoryCache = new HashMap<>();
-    private final Clause[] blacklisted;
+    private final Blacklist blacklist;
     
-    public RepositoryCache(String blacklisted) {
-        this.blacklisted = loadBlacklist(blacklisted);
+    public RepositoryCache(Blacklist blacklist) {
+        this.blacklist = blacklist;
     }
 
-    public Clause[] getBlacklisted() {
-        return blacklisted;
-    }
-
-    private static Clause[] loadBlacklist(String blacklisted) {
-        Set<String> blacklistStrings = Blacklist.loadBlacklist(blacklisted);
-        return Parser.parseClauses(blacklistStrings.toArray(new String[blacklistStrings.size()]));
-    }
-    
     public Repository create(URI uri, boolean load, boolean validate) throws Exception {
-        RepositoryImpl repo = new RepositoryImpl(uri, blacklisted);
+        RepositoryImpl repo = new RepositoryImpl(uri, blacklist);
         if (load)
             repo.load(validate);
         return repo;

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
index a839a50..0bdc174 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
@@ -22,10 +22,7 @@ import java.io.InputStream;
 import java.io.InterruptedIOException;
 import java.net.URI;
 import java.util.Objects;
-import java.util.Set;
 
-import org.apache.felix.utils.manifest.Clause;
-import org.apache.felix.utils.manifest.Parser;
 import org.apache.karaf.features.Feature;
 import org.apache.karaf.features.Repository;
 import org.apache.karaf.features.internal.model.Features;
@@ -37,22 +34,16 @@ import org.apache.karaf.features.internal.model.JaxbUtil;
 public class RepositoryImpl implements Repository {
 
     private final URI uri;
-    private final Clause[] blacklisted;
+    private final Blacklist blacklist;
     private Features features;
-
+    
     public RepositoryImpl(URI uri) {
-        this(uri, (Clause[]) null);
-    }
-
-    public RepositoryImpl(URI uri, String blacklisted) {
-        this.uri = uri;
-        Set<String> blacklistStrings = Blacklist.loadBlacklist(blacklisted);
-        this.blacklisted = Parser.parseClauses(blacklistStrings.toArray(new String[blacklistStrings.size()]));
+        this(uri, null);
     }
 
-    public RepositoryImpl(URI uri, Clause[] blacklisted) {
+    public RepositoryImpl(URI uri, Blacklist blacklist) {
         this.uri = uri;
-        this.blacklisted = blacklisted != null ? blacklisted : new Clause[0];
+        this.blacklist = blacklist;
     }
 
     public URI getURI() {
@@ -97,7 +88,9 @@ public class RepositoryImpl implements Repository {
                     InputStream inputStream = new InterruptibleInputStream(uri.toURL().openStream())
             ) {
                 features = JaxbUtil.unmarshal(uri.toASCIIString(), inputStream, validate);
-                Blacklist.blacklist(features, blacklisted);
+                if (blacklist != null) {
+                    blacklist.blacklist(features);
+                }
             } catch (Exception e) {
                 throw new IOException(e.getMessage() + " : " + uri, e);
             }

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
----------------------------------------------------------------------
diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
index e2d0a49..9d09e56 100644
--- a/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
+++ b/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
@@ -16,77 +16,52 @@
  */
 package org.apache.karaf.features.internal.service;
 
+import static org.junit.Assert.assertTrue;
+
 import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.Collections;
+import java.util.stream.Stream;
 
-import org.apache.karaf.features.internal.model.Bundle;
+import org.apache.karaf.features.BundleInfo;
 import org.apache.karaf.features.internal.model.Feature;
 import org.apache.karaf.features.internal.model.Features;
 import org.apache.karaf.features.internal.model.JaxbUtil;
 import org.junit.Test;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-
 public class BlacklistTest {
 
     @Test
     public void testBlacklistFeatureWithRange() {
-        URL url = getClass().getResource("f02.xml");
-        Features features = JaxbUtil.unmarshal(url.toExternalForm(), true);
-
-        List<String> blacklist = new ArrayList<>();
-        blacklist.add("spring;range=\"[2,3)\"");
-
-        Blacklist.blacklist(features, blacklist);
-        for (Feature feature : features.getFeature()) {
-            assertNotEquals("spring/2.5.6.SEC02", feature.getId());
-        }
+        Stream<Feature> features = blacklistWith("spring;range=\"[2,3)\"");
+        assertTrue(features.noneMatch(f -> f.getId().equals("spring/2.5.6.SEC02")));
     }
 
     @Test
     public void testBlacklistFeatureWithVersion() {
-        URL url = getClass().getResource("f02.xml");
-        Features features = JaxbUtil.unmarshal(url.toExternalForm(), true);
-
-        List<String> blacklist = new ArrayList<>();
-        blacklist.add("spring;range=2.5.6.SEC02");
-
-        Blacklist.blacklist(features, blacklist);
-        for (Feature feature : features.getFeature()) {
-            assertNotEquals("spring/2.5.6.SEC02", feature.getId());
-        }
+        Stream<Feature> features = blacklistWith("spring;range=2.5.6.SEC02");
+        assertTrue(features.noneMatch(f -> f.getId().equals("spring/2.5.6.SEC02")));
     }
 
     @Test
     public void testBlacklistFeatureWithoutVersion() {
-        URL url = getClass().getResource("f02.xml");
-        Features features = JaxbUtil.unmarshal(url.toExternalForm(), true);
-
-        List<String> blacklist = new ArrayList<>();
-        blacklist.add("spring");
-
-        Blacklist.blacklist(features, blacklist);
-        for (Feature feature : features.getFeature()) {
-            assertFalse(feature.getId().startsWith("spring/"));
-        }
+        Stream<Feature> features = blacklistWith("spring");
+        assertTrue(features.noneMatch(f -> f.getId().startsWith("spring/")));
     }
 
     @Test
     public void testBlacklistBundle() {
+        String blacklisted = "mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jasypt/1.7_1";
+        Stream<Feature> features = blacklistWith(blacklisted);
+        Stream<BundleInfo> bundles = features.flatMap(f -> f.getBundles().stream());
+        assertTrue(bundles.noneMatch(b -> b.getLocation().equals(blacklisted)));
+    }
+
+    private Stream<Feature> blacklistWith(String blacklistClause) {
         URL url = getClass().getResource("f02.xml");
         Features features = JaxbUtil.unmarshal(url.toExternalForm(), true);
 
-        List<String> blacklist = new ArrayList<>();
-        blacklist.add("mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jasypt/1.7_1");
-
-        Blacklist.blacklist(features, blacklist);
-        for (Feature feature : features.getFeature()) {
-            for (Bundle bundle : feature.getBundle()) {
-                assertNotEquals("mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jasypt/1.7_1",
-                                bundle.getLocation());
-            }
-        }
+        Blacklist blacklist = new Blacklist(Collections.singletonList(blacklistClause));
+        blacklist.blacklist(features);
+        return features.getFeature().stream();
     }
 }

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/profile/src/main/java/org/apache/karaf/profile/assembly/ArtifactInstaller.java
----------------------------------------------------------------------
diff --git a/profile/src/main/java/org/apache/karaf/profile/assembly/ArtifactInstaller.java b/profile/src/main/java/org/apache/karaf/profile/assembly/ArtifactInstaller.java
new file mode 100644
index 0000000..2dcf2be
--- /dev/null
+++ b/profile/src/main/java/org/apache/karaf/profile/assembly/ArtifactInstaller.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.profile.assembly;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+import org.apache.karaf.features.internal.download.Downloader;
+import org.apache.karaf.features.internal.download.impl.DownloadManagerHelper;
+import org.apache.karaf.features.internal.service.Blacklist;
+import org.apache.karaf.util.maven.Parser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ArtifactInstaller {
+    private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactInstaller.class);
+
+    private Path systemDirectory;
+    private Downloader downloader;
+    private Blacklist blacklist;
+
+    public ArtifactInstaller(Path systemDirectory, Downloader downloader, List<String> blacklisted) {
+        this.systemDirectory = systemDirectory;
+        this.downloader = downloader;
+        this.blacklist = new Blacklist(blacklisted);
+    }
+    
+    public void installArtifact(String location) throws Exception {
+        LOGGER.info("      adding maven artifact: " + location);
+        location = DownloadManagerHelper.stripUrl(location);
+        if (location.startsWith("mvn:")) {
+            if (location.endsWith("/")) {
+                // for bad formed URL (like in Camel for mustache-compiler), we remove the trailing /
+                location = location.substring(0, location.length() - 1);
+            }
+            downloader.download(location, provider -> {
+                String uri = provider.getUrl();
+                if (blacklist.isBundleBlacklisted(uri)) {
+                    throw new RuntimeException("Bundle " + uri + " is blacklisted");
+                }
+                Path path = pathFromProviderUrl(systemDirectory, uri);
+                synchronized (provider) {
+                    Files.createDirectories(path.getParent());
+                    Files.copy(provider.getFile().toPath(), path, StandardCopyOption.REPLACE_EXISTING);
+                }
+            });
+        } else {
+            LOGGER.warn("Ignoring non maven artifact " + location);
+        }
+    }
+    
+    public static Path pathFromProviderUrl(Path systemDirectory, String url) throws MalformedURLException {
+        String pathString;
+        if (url.startsWith("file:")) {
+            return Paths.get(URI.create(url));
+        }
+        else if (url.startsWith("mvn:")) {
+            pathString = Parser.pathFromMaven(url);
+        }
+        else {
+            pathString = url;
+        }
+        return systemDirectory.resolve(pathString);
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/profile/src/main/java/org/apache/karaf/profile/assembly/AssemblyDeployCallback.java
----------------------------------------------------------------------
diff --git a/profile/src/main/java/org/apache/karaf/profile/assembly/AssemblyDeployCallback.java b/profile/src/main/java/org/apache/karaf/profile/assembly/AssemblyDeployCallback.java
index b87410f..2be1d6f 100644
--- a/profile/src/main/java/org/apache/karaf/profile/assembly/AssemblyDeployCallback.java
+++ b/profile/src/main/java/org/apache/karaf/profile/assembly/AssemblyDeployCallback.java
@@ -36,13 +36,13 @@ import org.apache.felix.utils.properties.Properties;
 import org.apache.karaf.features.DeploymentEvent;
 import org.apache.karaf.features.FeatureEvent;
 import org.apache.karaf.features.FeaturesService;
-import org.apache.karaf.features.internal.model.Library;
 import org.apache.karaf.features.internal.download.DownloadManager;
 import org.apache.karaf.features.internal.download.Downloader;
 import org.apache.karaf.features.internal.model.Config;
 import org.apache.karaf.features.internal.model.ConfigFile;
 import org.apache.karaf.features.internal.model.Feature;
 import org.apache.karaf.features.internal.model.Features;
+import org.apache.karaf.features.internal.model.Library;
 import org.apache.karaf.features.internal.service.Blacklist;
 import org.apache.karaf.features.internal.service.Deployer;
 import org.apache.karaf.features.internal.service.State;
@@ -63,6 +63,8 @@ public class AssemblyDeployCallback extends StaticInstallSupport implements Depl
 
     private final DownloadManager manager;
     private final Builder builder;
+    private Blacklist featureBlacklist;
+    private Blacklist bundleBlacklist;
     private final Path homeDirectory;
     private final int defaultStartLevel;
     private final Path etcDirectory;
@@ -72,9 +74,12 @@ public class AssemblyDeployCallback extends StaticInstallSupport implements Depl
 
     private final Map<String, Bundle> bundles = new HashMap<>();
 
+
     public AssemblyDeployCallback(DownloadManager manager, Builder builder, BundleRevision systemBundle, Collection<Features> repositories) throws Exception {
         this.manager = manager;
         this.builder = builder;
+        this.featureBlacklist = new Blacklist(builder.getBlacklistedFeatures());
+        this.bundleBlacklist = new Blacklist(builder.getBlacklistedBundles());
         this.homeDirectory = builder.homeDirectory;
         this.etcDirectory = homeDirectory.resolve("etc");
         this.systemDirectory = homeDirectory.resolve("system");
@@ -190,7 +195,7 @@ public class AssemblyDeployCallback extends StaticInstallSupport implements Depl
     }
     
     private void assertNotBlacklisted(org.apache.karaf.features.Feature feature) {
-        if (Blacklist.isFeatureBlacklisted(builder.getBlacklistedFeatures(), feature.getName(), feature.getVersion())) {
+        if (featureBlacklist.isFeatureBlacklisted(feature.getName(), feature.getVersion())) {
             if (builder.getBlacklistPolicy() == Builder.BlacklistPolicy.Fail) {
                 throw new RuntimeException("Feature " + feature.getId() + " is blacklisted");
             }
@@ -208,7 +213,7 @@ public class AssemblyDeployCallback extends StaticInstallSupport implements Depl
     @Override
     public Bundle installBundle(String region, String uri, InputStream is) throws BundleException {
         // Check blacklist
-        if (Blacklist.isBundleBlacklisted(builder.getBlacklistedBundles(), uri)) {
+        if (bundleBlacklist.isBundleBlacklisted(uri)) {
             if (builder.getBlacklistPolicy() == Builder.BlacklistPolicy.Fail) {
                 throw new RuntimeException("Bundle " + uri + " is blacklisted");
             }

http://git-wip-us.apache.org/repos/asf/karaf/blob/eb95bce7/profile/src/main/java/org/apache/karaf/profile/assembly/Builder.java
----------------------------------------------------------------------
diff --git a/profile/src/main/java/org/apache/karaf/profile/assembly/Builder.java b/profile/src/main/java/org/apache/karaf/profile/assembly/Builder.java
index e20080c..27b83a6 100644
--- a/profile/src/main/java/org/apache/karaf/profile/assembly/Builder.java
+++ b/profile/src/main/java/org/apache/karaf/profile/assembly/Builder.java
@@ -64,7 +64,6 @@ 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;
-import org.apache.karaf.features.internal.download.impl.DownloadManagerHelper;
 import org.apache.karaf.features.internal.model.Bundle;
 import org.apache.karaf.features.internal.model.Conditional;
 import org.apache.karaf.features.internal.model.Config;
@@ -85,7 +84,6 @@ import org.apache.karaf.profile.ProfileBuilder;
 import org.apache.karaf.profile.impl.Profiles;
 import org.apache.karaf.tools.utils.KarafPropertiesEditor;
 import org.apache.karaf.tools.utils.model.KarafPropertyEdits;
-import org.apache.karaf.profile.versioning.VersionUtils;
 import org.apache.karaf.util.config.PropertiesLoader;
 import org.apache.karaf.util.maven.Parser;
 import org.ops4j.pax.url.mvn.MavenResolver;
@@ -812,27 +810,28 @@ public class Builder {
         for (String feature : installedEffective.getFeatures()) {
             addFeatures(allInstalledFeatures, feature, installedFeatures, true);
         }
+        ArtifactInstaller installer = new ArtifactInstaller(systemDirectory, downloader, blacklistedBundles);
         for (Feature feature : installedFeatures) {
             LOGGER.info("   Feature {} is defined as an installed feature", feature.getId());
             for (Bundle bundle : feature.getBundle()) {
                 if (!ignoreDependencyFlag || !bundle.isDependency()) {
-                    installArtifact(downloader, bundle.getLocation().trim());
+                    installer.installArtifact(bundle.getLocation().trim());
                 }
             }
             // Install config files
             for (ConfigFile configFile : feature.getConfigfile()) {
-                installArtifact(downloader, configFile.getLocation().trim());
+                installer.installArtifact(configFile.getLocation().trim());
             }
             for (Conditional cond : feature.getConditional()) {
                 for (Bundle bundle : cond.getBundle()) {
                     if (!ignoreDependencyFlag || !bundle.isDependency()) {
-                        installArtifact(downloader, bundle.getLocation().trim());
+                        installer.installArtifact(bundle.getLocation().trim());
                     }
                 }
             }
         }
         for (String location : installedEffective.getBundles()) {
-            installArtifact(downloader, location);
+            installer.installArtifact(location);
         }
         downloader.await();
     }
@@ -908,8 +907,9 @@ public class Builder {
             prereqs.put("spring:", Arrays.asList("deployer", "spring"));
             prereqs.put("wrap:", Arrays.asList("wrap"));
             prereqs.put("war:", Arrays.asList("war"));
+            ArtifactInstaller installer = new ArtifactInstaller(systemDirectory, downloader, blacklistedBundles);
             for (String location : locations) {
-                installArtifact(downloader, location);
+                installer.installArtifact(location);
                 for (Map.Entry<String, List<String>> entry : prereqs.entrySet()) {
                     if (location.startsWith(entry.getKey())) {
                         for (String prereq : entry.getValue()) {
@@ -932,11 +932,11 @@ public class Builder {
                 // Install config files
                 for (Config config : content.getConfig()) {
                     if (config.isExternal()) {
-                        installArtifact(downloader, config.getValue().trim());
+                        installer.installArtifact(config.getValue().trim());
                     }
                 }
                 for (ConfigFile configFile : content.getConfigfile()) {
-                    installArtifact(downloader, configFile.getLocation().trim());
+                    installer.installArtifact(configFile.getLocation().trim());
                 }
                 // Extract configs
                 for (Config config : content.getConfig()) {
@@ -1239,30 +1239,6 @@ public class Builder {
         return startupEffective;
     }
 
-    private void installArtifact(Downloader downloader, String location) throws Exception {
-        LOGGER.info("      adding maven artifact: " + location);
-        location = DownloadManagerHelper.stripUrl(location);
-        if (location.startsWith("mvn:")) {
-            if (location.endsWith("/")) {
-                // for bad formed URL (like in Camel for mustache-compiler), we remove the trailing /
-                location = location.substring(0, location.length() - 1);
-            }
-            downloader.download(location, provider -> {
-                String uri = provider.getUrl();
-                if (Blacklist.isBundleBlacklisted(blacklistedBundles, uri)) {
-                    throw new RuntimeException("Bundle " + uri + " is blacklisted");
-                }
-                Path path = pathFromProviderUrl(uri);
-                synchronized (provider) {
-                    Files.createDirectories(path.getParent());
-                    Files.copy(provider.getFile().toPath(), path, StandardCopyOption.REPLACE_EXISTING);
-                }
-            });
-        } else {
-            LOGGER.warn("Ignoring non maven artifact " + location);
-        }
-    }
-
     private void addFeatures(Set<Feature> allFeatures, String feature, Set<Feature> features, boolean mandatory) {
         String name;
         VersionRange range;
@@ -1294,42 +1270,6 @@ public class Builder {
         }
     }
 
-    private String getFeatureSt(Dependency dep) {
-        String version = dep.getVersion() == null || "0.0.0".equals(dep.getVersion()) ? "" : "/" + dep.getVersion();
-        return dep.getName() + version;
-    }
-
-    /**
-     * Checks if a given feature f matches the featureRef.
-     * TODO Need to also check for version ranges. Currently ranges are ignored and all features matching the name
-     * are copied in that case.
-     *  
-     * @param f
-     * @param featureRef
-     * @return
-     */
-    private boolean matches(Feature f, Dependency featureRef) {
-        if (!f.getName().equals(featureRef.getName())) {
-            return false;
-        }
-
-        final String featureRefVersion = featureRef.getVersion();
-
-        if (featureRefVersion == null) {
-            return true;
-        }
-
-        if (featureRefVersion.equals("0.0.0")) {
-            return true;
-        }
-
-        if (featureRefVersion.startsWith("[")) {
-            return true;
-        }
-
-        return VersionUtils.versionEquals(f.getVersion(), featureRefVersion);
-    }
-
     private List<String> getStaged(Stage stage, Map<String, Stage> data) {
         List<String> staged = new ArrayList<>();
         for (String s : data.keySet()) {
@@ -1360,14 +1300,14 @@ public class Builder {
         blacklist.addAll(blacklistedFeatures);
         final List<String> blacklistRepos = new ArrayList<>();
         blacklistRepos.addAll(blacklistedRepositories);
-        final Clause[] clauses = org.apache.felix.utils.manifest.Parser.parseClauses(blacklist.toArray(new String[blacklist.size()]));
-        final Clause[] clausesRepos = org.apache.felix.utils.manifest.Parser.parseClauses(blacklistRepos.toArray(new String[blacklistRepos.size()]));
+        final Blacklist blacklistOther = new Blacklist(blacklist);
+        final Blacklist repoBlacklist = new Blacklist(blacklistRepos);
         for (String repository : repositories) {
             downloader.download(repository, new DownloadCallback() {
                 @Override
                 public void downloaded(final StreamProvider provider) throws Exception {
                     String url = provider.getUrl();
-                    if (Blacklist.isBlacklisted(clausesRepos, url, TYPE_REPOSITORY)) {
+                    if (repoBlacklist.isBlacklisted(url, TYPE_REPOSITORY)) {
                         LOGGER.info("      feature repository " + url + " is blacklisted");
                         return;
                     }
@@ -1375,7 +1315,7 @@ public class Builder {
                         if (!loaded.containsKey(provider.getUrl())) {
                             if (install) {
                                 synchronized (provider) {
-                                    Path path = pathFromProviderUrl(url);
+                                    Path path = ArtifactInstaller.pathFromProviderUrl(systemDirectory, url);
                                     Files.createDirectories(path.getParent());
                                     LOGGER.info("      adding feature repository: " + url);
                                     Files.copy(provider.getFile().toPath(), path, StandardCopyOption.REPLACE_EXISTING);
@@ -1384,7 +1324,7 @@ public class Builder {
                             try (InputStream is = provider.open()) {
                                 Features featuresModel = JaxbUtil.unmarshal(url, is, false);
                                 if (blacklistPolicy == BlacklistPolicy.Discard) {
-                                    Blacklist.blacklist(featuresModel, clauses);
+                                    blacklistOther.blacklist(featuresModel);
                                 }
                                 loaded.put(provider.getUrl(), featuresModel);
                                 for (String innerRepository : featuresModel.getRepository()) {
@@ -1476,6 +1416,7 @@ public class Builder {
         return request;
     }
 
+    @SuppressWarnings("rawtypes")
     private BundleRevision getSystemBundle() throws Exception {
         Path configPropPath = etcDirectory.resolve("config.properties");
         Properties configProps = PropertiesLoader.loadPropertiesOrFail(configPropPath.toFile());
@@ -1505,6 +1446,7 @@ public class Builder {
         return new FakeBundleRevision(headers, "system-bundle", 0L);
     }
 
+    @SuppressWarnings("rawtypes")
     private Map<String, String> getHeaders(StreamProvider provider) throws IOException {
         try (
                 ZipInputStream zis = new ZipInputStream(provider.open())
@@ -1524,18 +1466,6 @@ public class Builder {
         throw new IllegalArgumentException("Resource " + provider.getUrl() + " does not contain a manifest");
     }
 
-    private Path pathFromProviderUrl(String url) throws MalformedURLException {
-        String pathString;
-        if (url.startsWith("file:")) {
-            return Paths.get(URI.create(url));
-        }
-        else if (url.startsWith("mvn:")) {
-            pathString = Parser.pathFromMaven(url);
-        }
-        else {
-            pathString = url;
-        }
-        return systemDirectory.resolve(pathString);
-    }
+
 
 }


[03/27] karaf git commit: Suppress logging exception in test

Posted by cs...@apache.org.
Suppress logging exception in test


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/54974034
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/54974034
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/54974034

Branch: refs/heads/model_features
Commit: 549740347157bc15cf62de17018fe2c1818eb601
Parents: a75faba
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 15:39:48 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 15:39:48 2017 +0200

----------------------------------------------------------------------
 .../apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java   | 7 +++++++
 1 file changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/54974034/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
index e2c374a..ea29eef 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
@@ -27,6 +27,7 @@ import org.apache.felix.utils.properties.Properties;
 import org.apache.karaf.jaas.boot.principal.RolePrincipal;
 import org.apache.karaf.jaas.boot.principal.UserPrincipal;
 import org.apache.karaf.jaas.modules.NamePasswordCallbackHandler;
+import org.apache.log4j.Level;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -202,12 +203,18 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         module.initialize(subject, new NamePasswordCallbackHandler("admin", "blahblah"), null, options);
 
         assertEquals("Precondition", 0, subject.getPrincipals().size());
+        org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LDAPLoginModule.class);
+        Level oldLevel = logger.getLevel();
+        logger.setLevel(Level.OFF);
         try {
             module.login();
             fail("Should have thrown LoginException");
         } catch (LoginException e) {
             assertTrue(e.getMessage().startsWith("Authentication failed"));
+        } finally {
+            logger.setLevel(oldLevel);
         }
+        
     }
 
     @Test


[14/27] karaf git commit: Use matcher in tests

Posted by cs...@apache.org.
Use matcher in tests


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/6aa806d2
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/6aa806d2
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/6aa806d2

Branch: refs/heads/model_features
Commit: 6aa806d2ad0df30d162693f8daa013dc6b0f110f
Parents: 01d0aae
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 11:34:37 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 11:34:37 2017 +0200

----------------------------------------------------------------------
 .../karaf/jaas/modules/PrincipalAssert.java     | 40 ------------
 .../karaf/jaas/modules/PrincipalHelper.java     | 29 +++++++++
 .../karaf/jaas/modules/ldap/LdapCacheTest.java  | 67 +++++++++-----------
 .../properties/PropertiesBackingEngineTest.java |  2 +-
 .../properties/PropertiesLoginModuleTest.java   | 14 ++--
 5 files changed, 67 insertions(+), 85 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/6aa806d2/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java
deleted file mode 100644
index c19fd2b..0000000
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *       http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *  under the License.
- */
-package org.apache.karaf.jaas.modules;
-
-import static java.util.stream.Collectors.toList;
-
-import java.security.Principal;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import javax.security.auth.Subject;
-
-import org.junit.Assert;
-
-public class PrincipalAssert {
-    
-    public static List<String> names(List<? extends Principal> principals) {
-        return principals.stream().map(r->r.getName()).collect(toList());
-    }
-    
-    public static void assertPrincipalNamed(Subject subject, Class<? extends Principal> clazz, String expectedName) {
-        Long numMatching = subject.getPrincipals(clazz).stream()
-            .filter(pr -> expectedName.equals(pr.getName()))
-            .collect(Collectors.counting());
-        Assert.assertEquals("Expected " + clazz.getSimpleName() + " principal in subject with name=" + expectedName, 
-                            1l, numMatching.intValue());
-    }
-}

http://git-wip-us.apache.org/repos/asf/karaf/blob/6aa806d2/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalHelper.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalHelper.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalHelper.java
new file mode 100644
index 0000000..9893193
--- /dev/null
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalHelper.java
@@ -0,0 +1,29 @@
+/*
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *  under the License.
+ */
+package org.apache.karaf.jaas.modules;
+
+import static java.util.stream.Collectors.toList;
+
+import java.security.Principal;
+import java.util.Collection;
+import java.util.List;
+
+public class PrincipalHelper {
+    
+    public static List<String> names(Collection<? extends Principal> principals) {
+        return principals.stream().map(r->r.getName()).collect(toList());
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/6aa806d2/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
index 1b88a16..b9d252d 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
@@ -15,6 +15,16 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
+import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+
+import javax.naming.NamingException;
 import javax.naming.directory.Attribute;
 import javax.naming.directory.Attributes;
 import javax.naming.directory.BasicAttribute;
@@ -22,9 +32,6 @@ import javax.naming.directory.BasicAttributes;
 import javax.naming.directory.DirContext;
 import javax.security.auth.Subject;
 import javax.security.auth.callback.CallbackHandler;
-import java.io.File;
-import java.io.IOException;
-import java.security.Principal;
 
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
@@ -42,9 +49,6 @@ import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
 @RunWith(FrameworkRunner.class)
 @CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")})
 @CreateDS(name = "LdapLoginModuleTest-class",
@@ -78,42 +82,16 @@ public class LdapCacheTest extends AbstractLdapTestUnit {
 
         assertEquals(2, subject.getPrincipals().size());
 
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof UserPrincipal) {
-                assertEquals("admin", pr.getName());
-                foundUser = true;
-            } else if (pr instanceof RolePrincipal) {
-                assertEquals("admin", pr.getName());
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("admin"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
 
-        DirContext context = new LDAPCache(new LDAPOptions(options)).open();
-
-        // Make "admin" user a member of a new "another" group
-
-//        dn: cn=admin,ou=groups,dc=example,dc=com
-//        objectClass: top
-//        objectClass: groupOfNames
-//        cn: admin
-//        member: cn=admin,ou=people,dc=example,dc=com
-        Attributes entry = new BasicAttributes();
-        entry.put(new BasicAttribute("cn", "another"));
-        Attribute oc = new BasicAttribute("objectClass");
-        oc.add("top");
-        oc.add("groupOfNames");
-        entry.put(oc);
-        Attribute mb = new BasicAttribute("member");
-        mb.add("cn=admin,ou=people,dc=example,dc=com");
-        entry.put(mb);
-        context.createSubcontext("cn=another,ou=groups,dc=example,dc=com", entry);
+        LDAPCache ldapCache = new LDAPCache(new LDAPOptions(options));
+        DirContext context = ldapCache.open();
+        addUserToGroup(context, "cn=admin,ou=people,dc=example,dc=com", "another");
+        ldapCache.close();
 
         Thread.sleep(100);
 
@@ -126,6 +104,19 @@ public class LdapCacheTest extends AbstractLdapTestUnit {
         assertEquals("Postcondition", 3, subject.getPrincipals().size());
     }
 
+    private void addUserToGroup(DirContext context, String userCn, String group) throws NamingException {
+        Attributes entry = new BasicAttributes();
+        entry.put(new BasicAttribute("cn", group));
+        Attribute oc = new BasicAttribute("objectClass");
+        oc.add("top");
+        oc.add("groupOfNames");
+        entry.put(oc);
+        Attribute mb = new BasicAttribute("member");
+        mb.add(userCn);
+        entry.put(mb);
+        context.createSubcontext("cn=" + group +",ou=groups,dc=example,dc=com", entry);
+    }
+
     protected Properties ldapLoginModuleOptions() throws IOException {
         String basedir = System.getProperty("basedir");
         if (basedir == null) {

http://git-wip-us.apache.org/repos/asf/karaf/blob/6aa806d2/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
index 0c811da..c1360d6 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
@@ -16,7 +16,7 @@
  */
 package org.apache.karaf.jaas.modules.properties;
 
-import static org.apache.karaf.jaas.modules.PrincipalAssert.names;
+import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
 import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;

http://git-wip-us.apache.org/repos/asf/karaf/blob/6aa806d2/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
index 26d90a7..9d43fba 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
@@ -16,7 +16,9 @@
  */
 package org.apache.karaf.jaas.modules.properties;
 
-import static org.apache.karaf.jaas.modules.PrincipalAssert.assertPrincipalNamed;
+import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.Assert.assertThat;
 
 import java.io.File;
 import java.io.IOException;
@@ -61,8 +63,8 @@ public class PropertiesLoginModuleTest {
 
             Assert.assertEquals(2, subject.getPrincipals().size());
 
-            assertPrincipalNamed(subject, UserPrincipal.class, "abc");
-            assertPrincipalNamed(subject, RolePrincipal.class, "myrole");
+            assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("abc"));
+            assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("myrole"));
 
             Assert.assertTrue(module.logout());
             Assert.assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -122,9 +124,9 @@ public class PropertiesLoginModuleTest {
             Assert.assertTrue(module.commit());
 
             Assert.assertEquals(3, subject.getPrincipals().size());
-            assertPrincipalNamed(subject, UserPrincipal.class, "pqr");
-            assertPrincipalNamed(subject, GroupPrincipal.class, "group1");
-            assertPrincipalNamed(subject, RolePrincipal.class, "r1");
+            assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("pqr"));
+            assertThat(names(subject.getPrincipals(GroupPrincipal.class)), containsInAnyOrder("group1"));
+            assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("r1"));
         } finally {
             if (!f.delete()) {
                 Assert.fail("Could not delete temporary file: " + f);


[12/27] karaf git commit: Fix warnings

Posted by cs...@apache.org.
Fix warnings


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/713d25d4
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/713d25d4
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/713d25d4

Branch: refs/heads/model_features
Commit: 713d25d4ffd40ad669a53b5d1fa9d8b497fc8b57
Parents: 767012d
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 23:30:07 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 23:30:07 2017 +0200

----------------------------------------------------------------------
 .../apache/karaf/jaas/modules/ldap/LDAPBackingEngine.java    | 5 ++---
 .../java/org/apache/karaf/jaas/modules/ldap/LDAPCache.java   | 8 ++++----
 .../java/org/apache/karaf/jaas/modules/ldap/LDAPOptions.java | 6 +++---
 3 files changed, 9 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/713d25d4/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPBackingEngine.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPBackingEngine.java b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPBackingEngine.java
index 5bd3072..4ee865e 100644
--- a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPBackingEngine.java
+++ b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPBackingEngine.java
@@ -33,7 +33,6 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
-import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 /**
@@ -87,10 +86,10 @@ public class LDAPBackingEngine implements BackingEngine {
             LOGGER.debug("  base DN: " + options.getUserBaseDn());
             LOGGER.debug("  filter: " + filter);
 
-            NamingEnumeration namingEnumeration = context.search(options.getUserBaseDn(), filter, controls);
+            NamingEnumeration<SearchResult> namingEnumeration = context.search(options.getUserBaseDn(), filter, controls);
             try {
                 while (namingEnumeration.hasMore()) {
-                    SearchResult result = (SearchResult) namingEnumeration.next();
+                    SearchResult result = namingEnumeration.next();
 
                     // We need to do the following because slashes are handled badly. For example, when searching
                     // for a user with lots of special characters like cn=admin,=+<>#;\

http://git-wip-us.apache.org/repos/asf/karaf/blob/713d25d4/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPCache.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPCache.java b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPCache.java
index f80af8c..7566165 100644
--- a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPCache.java
+++ b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPCache.java
@@ -165,14 +165,14 @@ public class LDAPCache implements Closeable, NamespaceChangeListener, ObjectChan
         LOGGER.debug("  base DN: " + options.getUserBaseDn());
         LOGGER.debug("  filter: " + filter);
 
-        NamingEnumeration namingEnumeration = context.search(options.getUserBaseDn(), filter, controls);
+        NamingEnumeration<SearchResult> namingEnumeration = context.search(options.getUserBaseDn(), filter, controls);
         try {
             if (!namingEnumeration.hasMore()) {
                 LOGGER.warn("User " + user + " not found in LDAP.");
                 return null;
             }
             LOGGER.debug("Found the user DN.");
-            SearchResult result = (SearchResult) namingEnumeration.next();
+            SearchResult result = namingEnumeration.next();
 
             // We need to do the following because slashes are handled badly. For example, when searching
             // for a user with lots of special characters like cn=admin,=+<>#;\
@@ -250,11 +250,11 @@ public class LDAPCache implements Closeable, NamespaceChangeListener, ObjectChan
             LOGGER.debug("  base DN: " + options.getRoleBaseDn());
             LOGGER.debug("  filter: " + filter);
 
-            NamingEnumeration namingEnumeration = context.search(options.getRoleBaseDn(), filter, controls);
+            NamingEnumeration<SearchResult> namingEnumeration = context.search(options.getRoleBaseDn(), filter, controls);
             try {
                 List<String> rolesList = new ArrayList<>();
                 while (namingEnumeration.hasMore()) {
-                    SearchResult result = (SearchResult) namingEnumeration.next();
+                    SearchResult result = namingEnumeration.next();
                     Attributes attributes = result.getAttributes();
                     Attribute roles1 = attributes.get(options.getRoleNameAttribute());
                     if (roles1 != null) {

http://git-wip-us.apache.org/repos/asf/karaf/blob/713d25d4/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPOptions.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPOptions.java b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPOptions.java
index 90c3333..38b4d44 100644
--- a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPOptions.java
+++ b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/ldap/LDAPOptions.java
@@ -165,13 +165,13 @@ public class LDAPOptions {
 
     protected void setupSsl(Hashtable<String, Object> env) throws NamingException {
         BundleContext bundleContext = FrameworkUtil.getBundle(LDAPOptions.class).getBundleContext();
-        ServiceReference ref = null;
+        ServiceReference<KeystoreManager> ref = null;
         try {
             LOGGER.debug("Setting up SSL");
             env.put(Context.SECURITY_PROTOCOL, "ssl");
             env.put("java.naming.ldap.factory.socket", ManagedSSLSocketFactory.class.getName());
-            ref = bundleContext.getServiceReference(KeystoreManager.class.getName());
-            KeystoreManager manager = (KeystoreManager) bundleContext.getService(ref);
+            ref = bundleContext.getServiceReference(KeystoreManager.class);
+            KeystoreManager manager = bundleContext.getService(ref);
             SSLSocketFactory factory = manager.createSSLFactory(
                     getSslProvider(), getSslProtocol(), getSslAlgorithm(), getSslKeystore(),
                     getSslKeyAlias(), getSslTrustStore(), getSslTimeout());


[25/27] karaf git commit: [KARAF-5300] Reuse and extract feature matching code

Posted by cs...@apache.org.
[KARAF-5300] Reuse and extract feature matching code


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/6576f476
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/6576f476
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/6576f476

Branch: refs/heads/model_features
Commit: 6576f476581367a83e7c42ac0e516bb710d3d7db
Parents: 69fcb36
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Thu Aug 10 15:30:59 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Thu Aug 17 16:29:30 2017 +0200

----------------------------------------------------------------------
 .../internal/service/FeaturesServiceImpl.java   | 79 +++++++++++---------
 1 file changed, 43 insertions(+), 36 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/6576f476/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
index 2767bc8..574998a 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
@@ -520,15 +520,15 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     @Override
     public Feature[] getFeatures(String nameOrId) throws Exception {
-        return getFeatures(new FeatureReq(nameOrId));
+        return toArray(getFeatures(new FeatureReq(nameOrId)));
     }
 
     @Override
     public Feature[] getFeatures(String name, String version) throws Exception {
-        return getFeatures(new FeatureReq(name, version));
+        return toArray(getFeatures(new FeatureReq(name, version)));
     }
     
-    private Feature[] getFeatures(FeatureReq featureReq) throws Exception {
+    private Collection<Feature> getFeatures(FeatureReq featureReq) throws Exception {
         List<Feature> features = new ArrayList<>();
         Pattern pattern = Pattern.compile(featureReq.getName());
         Map<String, Map<String, Feature>> allFeatures = getFeatureCache();
@@ -541,6 +541,10 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
                 }
             }
         }
+        return features;
+    }
+    
+    private Feature[] toArray(Collection<Feature> features) {
         return features.toArray(new Feature[features.size()]);
     }
 
@@ -819,33 +823,33 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
     private Set<FeatureReq> computeFeaturesToAdd(EnumSet<Option> options, 
                                                  Set<FeatureReq> toInstall) throws Exception {
         Feature[] installedFeatures = listInstalledFeatures();
-        Map<String, Map<String, Feature>> allFeatures = getFeatureCache();
         Set<FeatureReq> toAdd = new HashSet<>();
-        for (FeatureReq feature : toInstall) {
-            Pattern pattern = Pattern.compile(feature.getName());
-            boolean matched = false;
-            for (String fKey : allFeatures.keySet()) {
-                Matcher matcher = pattern.matcher(fKey);
-                if (matcher.matches()) {
-                    Feature f = getFeatureMatching(fKey, feature.getVersionRange());
-                    if (f != null) {
-                        toAdd.add(new FeatureReq(f));
-                        for (Feature installedFeature : installedFeatures) {
-                            if (installedFeature.getName().equals(f.getName()) && installedFeature.getVersion().equals(f.getVersion())) {
-                                LOGGER.info("The specified feature: '{}' version '{}' {}",f.getName(),f.getVersion(),f.getVersion().endsWith("SNAPSHOT") ? "has been upgraded": "is already installed");
-                            }
-                        }
-                        matched = true;
+        for (FeatureReq featureReq : toInstall) {
+            Collection<Feature> matching = getFeatures(featureReq);
+            for (Feature f: matching) {
+                toAdd.add(new FeatureReq(f));
+                for (Feature installedFeature : installedFeatures) {
+                    if (isSameFeature(f, installedFeature)) {
+                        logInstalledOrUpdated(f);
                     }
                 }
             }
-            if (!matched && !options.contains(Option.NoFailOnFeatureNotFound)) {
-                throw new IllegalArgumentException("No matching features for " + feature);
+            if (matching.isEmpty() && !options.contains(Option.NoFailOnFeatureNotFound)) {
+                throw new IllegalArgumentException("No matching features for " + featureReq);
             }
         }
         return toAdd;
     }
 
+    private void logInstalledOrUpdated(Feature f) {
+        String msg = f.getVersion().endsWith("SNAPSHOT") ? "has been upgraded": "is already installed";
+        LOGGER.info("The specified feature: '{}' version '{}' {}", f.getName(), f.getVersion(), msg);
+    }
+
+    private boolean isSameFeature(Feature a, Feature b) {
+        return b.getName().equals(a.getName()) && b.getVersion().equals(a.getVersion());
+    }
+
     private Set<FeatureReq> computeFeaturesToRemoveOnUpdate(Set<FeatureReq> featuresToAdd,
                                              Set<FeatureReq> existingFeatures) throws Exception {
         Set<String> namesToAdd = featuresToAdd.stream().map(f -> f.getName()).collect(toSet());
@@ -869,34 +873,37 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         if (region == null || region.isEmpty()) {
             region = ROOT_REGION;
         }
-        Set<String> requiredForRegion = required.computeIfAbsent(region, k -> new HashSet<>());
+        Set<String> requirements = required.computeIfAbsent(region, k -> new HashSet<>());
+        Set<FeatureReq> existingFeatures = requirements.stream().map(r -> toFeatureReq(r)).collect(toSet());
         Set<FeatureReq> featuresToRemove = new HashSet<>();
         for (FeatureReq feature : featureReqs) {
-            Pattern pattern = Pattern.compile(feature.getName());
-            List<FeatureReq> toRemove = new ArrayList<>();
-            for (String existingFeature : requiredForRegion) {
-               FeatureReq existingFeatureReq = toFeatureReq(existingFeature);
-               if (existingFeatureReq != null) {
-                   Matcher matcher = pattern.matcher(existingFeatureReq.getName());
-                   if (matcher.matches() && feature.getVersionRange().includes(existingFeatureReq.getVersionRange().getLeft())) {
-                       toRemove.add(existingFeatureReq);
-                   }
-               }
-            }
-
+            List<FeatureReq> toRemove = getMatching(existingFeatures, feature);
             if (toRemove.isEmpty()) {
                 throw new IllegalArgumentException("Feature named '" + feature + "' is not installed");
             }
             featuresToRemove.addAll(toRemove);
         }
         print("Removing features: " + join(featuresToRemove), options.contains(Option.Verbose));
-        featuresToRemove.stream().forEach(f->requiredForRegion.remove(toRequirement(f)));
-        if (requiredForRegion.isEmpty()) {
+        featuresToRemove.stream().forEach(f -> requirements.remove(toRequirement(f)));
+        if (requirements.isEmpty()) {
             required.remove(region);
         }
         doProvisionInThread(required, emptyMap(), state, getFeaturesById(), options);
     }
 
+    private List<FeatureReq> getMatching(Set<FeatureReq> existingFeatures, FeatureReq feature) {
+        Pattern pattern = Pattern.compile(feature.getName());
+        List<FeatureReq> matching = new ArrayList<>();
+        for (FeatureReq existingFeatureReq : existingFeatures) {
+            Matcher matcher = pattern.matcher(existingFeatureReq.getName());
+            Version existingVersion = existingFeatureReq.getVersionRange().getLeft();  
+            if (matcher.matches() && feature.getVersionRange().includes(existingVersion)) {
+                matching.add(existingFeatureReq);
+            }
+        }
+        return matching;
+    }
+
     private FeatureReq toFeatureReq(String featureReq) {
         if (!featureReq.startsWith(FEATURE_OSGI_REQUIREMENT_PREFIX)) {
             return null;


[07/27] karaf git commit: Suppress logging of WriteToClosedSessionException

Posted by cs...@apache.org.
Suppress logging of WriteToClosedSessionException


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/b4969149
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/b4969149
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/b4969149

Branch: refs/heads/model_features
Commit: b4969149f8888f1dc52890f0a4c204258e904e84
Parents: ecf6a8d
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 17:13:07 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 17:13:07 2017 +0200

----------------------------------------------------------------------
 jaas/modules/src/test/resources/log4j.properties | 3 +++
 1 file changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/b4969149/jaas/modules/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/resources/log4j.properties b/jaas/modules/src/test/resources/log4j.properties
index a75bae2..485e43b 100644
--- a/jaas/modules/src/test/resources/log4j.properties
+++ b/jaas/modules/src/test/resources/log4j.properties
@@ -20,6 +20,9 @@
 #
 log4j.rootLogger=INFO, console, file
 
+# Suppress logging of WriteToClosedSessionException
+log4j.logger.org.apache.directory.server.ldap.LdapProtocolHandler=OFF
+
 # Console will only display warnings
 log4j.appender.console=org.apache.log4j.ConsoleAppender
 log4j.appender.console.layout=org.apache.log4j.PatternLayout


[08/27] karaf git commit: Avoid excessive logging

Posted by cs...@apache.org.
Avoid excessive logging


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/fcf9b7c1
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/fcf9b7c1
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/fcf9b7c1

Branch: refs/heads/model_features
Commit: fcf9b7c19b9c9edf56aa75ab29675a30c237e741
Parents: b496914
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 17:47:03 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 17:47:03 2017 +0200

----------------------------------------------------------------------
 jaas/jasypt/src/test/resources/log4j.properties | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/fcf9b7c1/jaas/jasypt/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/jaas/jasypt/src/test/resources/log4j.properties b/jaas/jasypt/src/test/resources/log4j.properties
index e1cbdd1..3822bad 100644
--- a/jaas/jasypt/src/test/resources/log4j.properties
+++ b/jaas/jasypt/src/test/resources/log4j.properties
@@ -18,7 +18,7 @@
 #
 # The logging properties used during tests..
 #
-log4j.rootLogger=DEBUG, console, file
+log4j.rootLogger=INFO, console, file
 
 # Console will only display warnnings
 log4j.appender.console=org.apache.log4j.ConsoleAppender


[16/27] karaf git commit: Use simple PrintStream

Posted by cs...@apache.org.
Use simple PrintStream


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/e973e3c7
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/e973e3c7
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/e973e3c7

Branch: refs/heads/model_features
Commit: e973e3c73cd431492bfc6ed6f1fb336f4f71ceaa
Parents: 71b136e
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 11:50:58 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 11:50:58 2017 +0200

----------------------------------------------------------------------
 .../modules/ldap/GSSAPILdapLoginModuleTest.java | 77 +++++++++-----------
 1 file changed, 33 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/e973e3c7/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
index b0152f1..11daa72 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
@@ -14,9 +14,24 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
-import org.apache.commons.io.FileUtils;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.security.Principal;
+import java.util.Collections;
+
+import javax.security.auth.Subject;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.kerberos.KerberosTicket;
+import javax.security.auth.login.LoginException;
+
 import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.SystemUtils;
 import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
 import org.apache.directory.api.ldap.model.entry.DefaultEntry;
 import org.apache.directory.api.ldap.model.entry.Entry;
@@ -53,22 +68,6 @@ import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import javax.security.auth.Subject;
-import javax.security.auth.kerberos.KerberosPrincipal;
-import javax.security.auth.kerberos.KerberosTicket;
-import javax.security.auth.login.LoginException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.security.Principal;
-import java.util.Collections;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
 @RunWith(FrameworkRunner.class)
 @CreateDS(name = "GSSAPILdapLoginModuleTest-class",
         partitions =
@@ -317,34 +316,24 @@ public class GSSAPILdapLoginModuleTest extends AbstractKerberosITest {
 
     private String createKrb5Conf(ChecksumType checksumType, EncryptionType encryptionType, boolean isTcp) throws IOException {
         File file = folder.newFile("krb5.conf");
-
-        String data = "";
-
-        data += "[libdefaults]" + SystemUtils.LINE_SEPARATOR;
-        data += "default_realm = " + REALM + SystemUtils.LINE_SEPARATOR;
-        data += "default_tkt_enctypes = " + encryptionType.getName() + SystemUtils.LINE_SEPARATOR;
-        data += "default_tgs_enctypes = " + encryptionType.getName() + SystemUtils.LINE_SEPARATOR;
-        data += "permitted_enctypes = " + encryptionType.getName() + SystemUtils.LINE_SEPARATOR;
-        //        data += "default_checksum = " + checksumType.getName() + SystemUtils.LINE_SEPARATOR;
-        //        data += "ap_req_checksum_type = " + checksumType.getName() + SystemUtils.LINE_SEPARATOR;
-        data += "default-checksum_type = " + checksumType.getName() + SystemUtils.LINE_SEPARATOR;
-
+        PrintStream out = new PrintStream(file);
+        out.println("[libdefaults]");
+        out.println("default_realm = " + REALM);
+        out.println("default_tkt_enctypes = " + encryptionType.getName());
+        out.println("default_tgs_enctypes = " + encryptionType.getName());
+        out.println("permitted_enctypes = " + encryptionType.getName());
+        out.println("default-checksum_type = " + checksumType.getName());
         if (isTcp) {
-            data += "udp_preference_limit = 1" + SystemUtils.LINE_SEPARATOR;
+            out.println("udp_preference_limit = 1");
         }
-
-
-        data += "[realms]" + SystemUtils.LINE_SEPARATOR;
-        data += REALM + " = {" + SystemUtils.LINE_SEPARATOR;
-        data += "kdc = " + HOSTNAME + ":" + kdcServer.getTransports()[0].getPort() + SystemUtils.LINE_SEPARATOR;
-        data += "}" + SystemUtils.LINE_SEPARATOR;
-
-        data += "[domain_realm]" + SystemUtils.LINE_SEPARATOR;
-        data += "." + Strings.lowerCaseAscii(REALM) + " = " + REALM + SystemUtils.LINE_SEPARATOR;
-        data += Strings.lowerCaseAscii(REALM) + " = " + REALM + SystemUtils.LINE_SEPARATOR;
-
-        FileUtils.writeStringToFile(file, data, Charset.defaultCharset());
-
+        out.println("[realms]");
+        out.println(REALM + " = {");
+        out.println("kdc = " + HOSTNAME + ":" + kdcServer.getTransports()[0].getPort());
+        out.println("}");
+        out.println("[domain_realm]");
+        out.println("." + Strings.lowerCaseAscii(REALM) + " = " + REALM);
+        out.println(Strings.lowerCaseAscii(REALM) + " = " + REALM);
+        out.close();
         return file.getAbsolutePath();
     }
 


[02/27] karaf git commit: [KARAF-5308] Use upfront loading for repositories

Posted by cs...@apache.org.
[KARAF-5308] Use upfront loading for repositories


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/a75fabaf
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/a75fabaf
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/a75fabaf

Branch: refs/heads/model_features
Commit: a75fabaf071b8274c7f266affa7ce7cdd87a2a22
Parents: eb95bce
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 15:39:26 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 15:39:26 2017 +0200

----------------------------------------------------------------------
 .../internal/service/FeaturesServiceImpl.java   | 15 ++++----
 .../internal/service/RepositoryCache.java       |  7 ++--
 .../internal/service/RepositoryImpl.java        | 25 +++++--------
 .../apache/karaf/features/RepositoryTest.java   |  3 +-
 .../internal/service/BlacklistTest.java         | 23 ++++++------
 .../features/internal/service/DeployerTest.java |  5 ---
 .../service/FeaturesValidationTest.java         | 37 +++++++++++---------
 7 files changed, 52 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
index 90f4969..27ccf97 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
@@ -254,15 +254,14 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
     public void registerListener(FeaturesListener listener) {
         listeners.add(listener);
         try {
-            Set<String> repositories = new TreeSet<>();
+            Set<String> repositoriesList = new TreeSet<>();
             Map<String, Set<String>> installedFeatures = new TreeMap<>();
             synchronized (lock) {
-                repositories.addAll(state.repositories);
+                repositoriesList.addAll(state.repositories);
                 installedFeatures.putAll(copy(state.installedFeatures));
             }
-            Blacklist blacklist = new Blacklist(cfg.blacklisted);
-            for (String uri : repositories) {
-                Repository repository = new RepositoryImpl(URI.create(uri), blacklist);
+            for (String uri : repositoriesList) {
+                Repository repository = repositories.create(URI.create(uri), false);
                 listener.repositoryEvent(new RepositoryEvent(repository, RepositoryEvent.EventType.RepositoryAdded, true));
             }
             for (Map.Entry<String, Set<String>> entry : installedFeatures.entrySet()) {
@@ -357,7 +356,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     @Override
     public void addRepository(URI uri, boolean install) throws Exception {
-        Repository repository = repositories.create(uri, true, true);
+        Repository repository = repositories.create(uri, true);
         synchronized (lock) {
             repositories.addRepository(repository);
             featureCache = null;
@@ -610,7 +609,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
             }
             try {
                 if (repo == null) {
-                    repo = repositories.create(URI.create(uri), true, false);
+                    repo = repositories.create(URI.create(uri), false);
                     synchronized (lock) {
                         repositories.addRepository(repo);
                     }
@@ -979,7 +978,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     @Override
     public Repository createRepository(URI uri) throws Exception {
-        return repositories.create(uri, true, true);
+        return repositories.create(uri, true);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
index 4898566..801ffeb 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryCache.java
@@ -38,11 +38,8 @@ public class RepositoryCache {
         this.blacklist = blacklist;
     }
 
-    public Repository create(URI uri, boolean load, boolean validate) throws Exception {
-        RepositoryImpl repo = new RepositoryImpl(uri, blacklist);
-        if (load)
-            repo.load(validate);
-        return repo;
+    public Repository create(URI uri, boolean validate) throws Exception {
+        return new RepositoryImpl(uri, blacklist, validate);
     }
 
     public void addRepository(Repository repository) throws Exception {

http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
index 0bdc174..0e9d703 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/RepositoryImpl.java
@@ -38,51 +38,44 @@ public class RepositoryImpl implements Repository {
     private Features features;
     
     public RepositoryImpl(URI uri) {
-        this(uri, null);
+        this(uri, null, false);
     }
 
-    public RepositoryImpl(URI uri, Blacklist blacklist) {
+    public RepositoryImpl(URI uri, Blacklist blacklist, boolean validate) {
         this.uri = uri;
         this.blacklist = blacklist;
+        load(validate);
     }
 
     public URI getURI() {
         return uri;
     }
 
-    public String getName() throws IOException {
-        load();
+    public String getName() {
         return features.getName();
     }
 
-    public URI[] getRepositories() throws IOException {
-        load();
+    public URI[] getRepositories() {
         return features.getRepository().stream()
                 .map(String::trim)
                 .map(URI::create)
                 .toArray(URI[]::new);
     }
 
-    public URI[] getResourceRepositories() throws IOException {
-        load();
+    public URI[] getResourceRepositories() {
         return features.getResourceRepository().stream()
                 .map(String::trim)
                 .map(URI::create)
                 .toArray(URI[]::new);
     }
 
-    public Feature[] getFeatures() throws IOException {
-        load();
+    public Feature[] getFeatures() {
         return features.getFeature()
                 .toArray(new Feature[features.getFeature().size()]);
     }
 
 
-    public void load() throws IOException {
-        load(false);
-    }
-
-    public void load(boolean validate) throws IOException {
+    private void load(boolean validate) {
         if (features == null) {
             try (
                     InputStream inputStream = new InterruptibleInputStream(uri.toURL().openStream())
@@ -92,7 +85,7 @@ public class RepositoryImpl implements Repository {
                     blacklist.blacklist(features);
                 }
             } catch (Exception e) {
-                throw new IOException(e.getMessage() + " : " + uri, e);
+                throw new RuntimeException(e.getMessage() + " : " + uri, e);
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/test/java/org/apache/karaf/features/RepositoryTest.java
----------------------------------------------------------------------
diff --git a/features/core/src/test/java/org/apache/karaf/features/RepositoryTest.java b/features/core/src/test/java/org/apache/karaf/features/RepositoryTest.java
index c630c6f..a6c7ede 100644
--- a/features/core/src/test/java/org/apache/karaf/features/RepositoryTest.java
+++ b/features/core/src/test/java/org/apache/karaf/features/RepositoryTest.java
@@ -177,9 +177,8 @@ public class RepositoryTest extends TestCase {
 
     public void testShowWrongUriInException() throws Exception {
         String uri = "src/test/resources/org/apache/karaf/shell/features/repo1.xml";
-        RepositoryImpl r = new RepositoryImpl(new URI(uri));
         try {
-            r.load();
+            new RepositoryImpl(new URI(uri));
         } catch (Exception e) {
             assertTrue(e.getMessage().contains(uri));
         }

http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
----------------------------------------------------------------------
diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
index 9d09e56..956d04b 100644
--- a/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
+++ b/features/core/src/test/java/org/apache/karaf/features/internal/service/BlacklistTest.java
@@ -18,14 +18,14 @@ package org.apache.karaf.features.internal.service;
 
 import static org.junit.Assert.assertTrue;
 
-import java.net.URL;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.stream.Stream;
 
 import org.apache.karaf.features.BundleInfo;
-import org.apache.karaf.features.internal.model.Feature;
-import org.apache.karaf.features.internal.model.Features;
-import org.apache.karaf.features.internal.model.JaxbUtil;
+import org.apache.karaf.features.Feature;
 import org.junit.Test;
 
 public class BlacklistTest {
@@ -56,12 +56,15 @@ public class BlacklistTest {
         assertTrue(bundles.noneMatch(b -> b.getLocation().equals(blacklisted)));
     }
 
-    private Stream<Feature> blacklistWith(String blacklistClause) {
-        URL url = getClass().getResource("f02.xml");
-        Features features = JaxbUtil.unmarshal(url.toExternalForm(), true);
-
+    private Stream<org.apache.karaf.features.Feature> blacklistWith(String blacklistClause) {
+        URI uri;
+        try {
+            uri = getClass().getResource("f02.xml").toURI();
+        } catch (URISyntaxException e) {
+            throw new RuntimeException(e);
+        }
         Blacklist blacklist = new Blacklist(Collections.singletonList(blacklistClause));
-        blacklist.blacklist(features);
-        return features.getFeature().stream();
+        RepositoryImpl features = new RepositoryImpl(uri, blacklist, true);
+        return Arrays.asList(features.getFeatures()).stream();
     }
 }

http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/test/java/org/apache/karaf/features/internal/service/DeployerTest.java
----------------------------------------------------------------------
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 c9cc4ae..a08d7c5 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
@@ -71,7 +71,6 @@ public class DeployerTest {
         TestDownloadManager manager = new TestDownloadManager(getClass(), dataDir);
 
         RepositoryImpl repo = new RepositoryImpl(getClass().getResource(dataDir + "/features.xml").toURI());
-        repo.load(true);
         Feature f100 = repo.getFeatures()[0];
         Feature f101 = repo.getFeatures()[1];
 
@@ -145,7 +144,6 @@ public class DeployerTest {
         TestDownloadManager manager = new TestDownloadManager(getClass(), dataDir);
 
         RepositoryImpl repo = new RepositoryImpl(getClass().getResource(dataDir + "/features.xml").toURI());
-        repo.load(true);
         Feature f100 = repo.getFeatures()[0];
         Feature f101 = repo.getFeatures()[1];
 
@@ -247,7 +245,6 @@ public class DeployerTest {
         TestDownloadManager manager = new TestDownloadManager(getClass(), dataDir);
 
         RepositoryImpl repo = new RepositoryImpl(getClass().getResource(dataDir + "/features.xml").toURI());
-        repo.load(true);
         Feature f1 = repo.getFeatures()[0];
 
         Bundle serviceBundle = createTestBundle(1, Bundle.ACTIVE, dataDir, "a100");
@@ -318,7 +315,6 @@ public class DeployerTest {
         TestDownloadManager manager = new TestDownloadManager(getClass(), dataDir);
 
         RepositoryImpl repo = new RepositoryImpl(getClass().getResource(dataDir + "/features.xml").toURI());
-        repo.load(true);
         Feature f1 = repo.getFeatures()[0];
         Feature f2 = repo.getFeatures()[1];
 
@@ -479,7 +475,6 @@ public class DeployerTest {
         TestDownloadManager manager = new TestDownloadManager(getClass(), dataDir);
 
         RepositoryImpl repo = new RepositoryImpl(getClass().getResource(dataDir + "/features.xml").toURI());
-        repo.load(true);
 
         Map<String, Bundle> bundles = new HashMap<>();
         bundles.put("a100", createTestBundle(1, Bundle.ACTIVE, dataDir, "a100"));

http://git-wip-us.apache.org/repos/asf/karaf/blob/a75fabaf/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesValidationTest.java
----------------------------------------------------------------------
diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesValidationTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesValidationTest.java
index 09badc5..e21c854 100644
--- a/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesValidationTest.java
+++ b/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesValidationTest.java
@@ -24,28 +24,28 @@ import static org.junit.Assert.fail;
 
 import java.net.URI;
 
+import org.apache.karaf.features.Feature;
 import org.apache.karaf.features.Library;
-import org.apache.karaf.features.internal.model.Features;
-import org.apache.karaf.features.internal.model.JaxbUtil;
+import org.apache.karaf.features.Repository;
 import org.junit.Test;
 
 public class FeaturesValidationTest {
 
     @Test
     public void testNs10() throws Exception {
-        Features features = unmarshalAndValidate("f02.xml");
+        Repository features = unmarshalAndValidate("f02.xml");
         assertNotNull(features);
     }
 
     @Test
     public void testNs10NoName() throws Exception {
-        Features features = unmarshalAndValidate("f03.xml");
+        Repository features = unmarshalAndValidate("f03.xml");
         assertNotNull(features);
     }
 
     @Test
     public void testNs11() throws Exception {
-        Features features = unmarshalAndValidate("f04.xml");;
+        Repository features = unmarshalAndValidate("f04.xml");;
         assertNotNull(features);
     }
 
@@ -61,27 +61,30 @@ public class FeaturesValidationTest {
 
     @Test
     public void testNs12Unmarshall() throws Exception {
-        Features features = unmarshalAndValidate("f06.xml");
+        Repository features = unmarshalAndValidate("f06.xml");
         assertNotNull(features);
     }
 
     @Test
     public void testNs13() throws Exception {
-        Features features = unmarshalAndValidate("f07.xml");
+        Repository features = unmarshalAndValidate("f07.xml");
         assertNotNull(features);
-        assertEquals("2.5.6.SEC02", features.getFeature().get(0).getVersion());
-        assertTrue(features.getFeature().get(1).isHidden());
-        assertNotNull(features.getFeature().get(1).getLibraries());
-        assertEquals(1, features.getFeature().get(0).getLibraries().size());
-        assertEquals("my-library", features.getFeature().get(0).getLibraries().get(0).getLocation());
-        assertEquals(Library.TYPE_ENDORSED, features.getFeature().get(0).getLibraries().get(0).getType());
-        assertFalse(features.getFeature().get(0).getLibraries().get(0).isExport());
-        assertTrue(features.getFeature().get(0).getLibraries().get(0).isDelegate());
+        Feature f0 = features.getFeatures()[0];
+        Feature f1 = features.getFeatures()[1];
+        assertEquals("2.5.6.SEC02", f0.getVersion());
+        assertTrue(f1.isHidden());
+        assertNotNull(f1.getLibraries());
+        assertEquals(1, f0.getLibraries().size());
+        Library lib = f0.getLibraries().get(0);
+        assertEquals("my-library", lib.getLocation());
+        assertEquals(Library.TYPE_ENDORSED, lib.getType());
+        assertFalse(lib.isExport());
+        assertTrue(lib.isDelegate());
     }
 
-    private Features unmarshalAndValidate(String path) throws Exception {
+    private Repository unmarshalAndValidate(String path) throws Exception {
         URI uri = getClass().getResource(path).toURI();
-        return JaxbUtil.unmarshal(uri.toASCIIString(), true);
+        return new RepositoryImpl(uri, null, true);
     }
 
 }


[10/27] karaf git commit: Do not print each classpath Element

Posted by cs...@apache.org.
Do not print each classpath Element


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/1bf544b9
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/1bf544b9
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/1bf544b9

Branch: refs/heads/model_features
Commit: 1bf544b95aa03ad6f4c4ec6a9060b047430615a5
Parents: 011c9b0
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 17:48:10 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 17:48:10 2017 +0200

----------------------------------------------------------------------
 .../org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java   | 1 -
 1 file changed, 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/1bf544b9/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
----------------------------------------------------------------------
diff --git a/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java b/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
index 2d44bfd..7b0fd37 100644
--- a/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
+++ b/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
@@ -194,7 +194,6 @@ public class GenerateServiceMetadata extends AbstractMojo {
                 File file = artifact.getFile();
                 if ( file != null ) {
                     urls.add( file.toURI().toURL() );
-                    System.out.println("classpath: " + file);
                 }
             }
             ClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());


[27/27] karaf git commit: [KARAF-5300] Use FeatureReq instead of string for FeaturesService

Posted by cs...@apache.org.
[KARAF-5300] Use FeatureReq instead of string for FeaturesService


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/3b900267
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/3b900267
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/3b900267

Branch: refs/heads/model_features
Commit: 3b900267c4710302198cd66c02a869e1b74ff0f0
Parents: 8f94e29
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 9 17:39:06 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Thu Aug 17 16:29:30 2017 +0200

----------------------------------------------------------------------
 .../features/internal/service/FeatureReq.java   |  84 ++++++++
 .../internal/service/FeaturesServiceImpl.java   | 204 ++++++++-----------
 .../service/FeaturesServiceImplTest.java        |  46 ++++-
 .../karaf/features/internal/service/f09.xml     |  24 +++
 4 files changed, 229 insertions(+), 129 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/3b900267/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
new file mode 100644
index 0000000..2e1f652
--- /dev/null
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.karaf.features.internal.service;
+
+import org.apache.karaf.features.Feature;
+import org.osgi.framework.Version;
+import org.osgi.framework.VersionRange;
+
+/**
+ * Requirement for a feature
+ */
+public class FeatureReq {
+    public static final String VERSION_SEPARATOR = "/";
+    private static Version HIGHEST = new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
+    private static final VersionRange RANGE_ALL = new VersionRange(VersionRange.LEFT_CLOSED, Version.emptyVersion, HIGHEST, VersionRange.RIGHT_CLOSED);
+    private String name;
+    private VersionRange versionRange;
+    
+    public FeatureReq(String nameAndRange) {
+        String[] parts = nameAndRange.trim().split(VERSION_SEPARATOR);
+        this.name = parts[0];
+        this.versionRange = (parts.length == 1) ? RANGE_ALL : range(parts[1]);
+    }
+    
+    public FeatureReq(String name, String versionRange) {
+        this.name = name;
+        this.versionRange = range(versionRange);
+    }
+    
+    private VersionRange range(String versionRange) {
+        if (versionRange == null) {
+            return RANGE_ALL;
+        }
+        versionRange = versionRange.trim();
+        if ("0.0.0".equals(versionRange)) {
+            return RANGE_ALL;
+        }
+        if (versionRange.contains(",")) {
+            return new VersionRange(versionRange);
+        } else {
+            return exactVersion(versionRange);
+        }
+    }
+
+    private static VersionRange exactVersion(String versionRange) {
+        return new VersionRange(VersionRange.LEFT_CLOSED, new Version(versionRange), new Version(versionRange), VersionRange.RIGHT_CLOSED);
+    }
+
+    public FeatureReq(String name, VersionRange versionRange) {
+        this.name = name;
+        this.versionRange = versionRange;
+    }
+    
+    public FeatureReq(Feature feature) {
+        this(feature.getName(), exactVersion(feature.getVersion()));
+    }
+    
+    public String getName() {
+        return name;
+    }
+    
+    public VersionRange getVersionRange() {
+        return versionRange;
+    }
+    
+    @Override
+    public String toString() {
+        return this.name + "/" + this.getVersionRange().toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/3b900267/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
index 27ccf97..5562390 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
@@ -32,7 +32,6 @@ import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Hashtable;
-import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -50,7 +49,6 @@ import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
 import org.apache.felix.utils.version.VersionCleaner;
-import org.apache.felix.utils.version.VersionRange;
 import org.apache.felix.utils.version.VersionTable;
 import org.apache.karaf.features.DeploymentEvent;
 import org.apache.karaf.features.DeploymentListener;
@@ -76,6 +74,7 @@ import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleException;
 import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.Version;
+import org.osgi.framework.VersionRange;
 import org.osgi.resource.Resource;
 import org.osgi.resource.Wire;
 import org.osgi.service.cm.Configuration;
@@ -519,22 +518,22 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     @Override
     public Feature[] getFeatures(String nameOrId) throws Exception {
-        String[] parts = nameOrId.split(VERSION_SEPARATOR);
-        String name = parts.length > 0 ? parts[0] : nameOrId;
-        String version = parts.length > 1 ? parts[1] : null;
-        return getFeatures(name, version);
+        return getFeatures(new FeatureReq(nameOrId));
     }
 
     @Override
     public Feature[] getFeatures(String name, String version) throws Exception {
+        return getFeatures(new FeatureReq(name, version));
+    }
+    
+    private Feature[] getFeatures(FeatureReq featureReq) throws Exception {
         List<Feature> features = new ArrayList<>();
-        Pattern pattern = Pattern.compile(name);
+        Pattern pattern = Pattern.compile(featureReq.getName());
         Map<String, Map<String, Feature>> allFeatures = getFeatureCache();
         for (String featureName : allFeatures.keySet()) {
             Matcher matcher = pattern.matcher(featureName);
             if (matcher.matches()) {
-                Map<String, Feature> versions = allFeatures.get(featureName);
-                Feature matchingFeature = getFeatureMatching(versions, version);
+                Feature matchingFeature = getFeatureMatching(featureName, featureReq.getVersionRange());
                 if (matchingFeature != null) {
                     features.add(matchingFeature);
                 }
@@ -543,35 +542,26 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         return features.toArray(new Feature[features.size()]);
     }
 
-    private Feature getFeatureMatching(Map<String, Feature> versions, String version) {
-        if (version != null) {
-            version = version.trim();
-            if (version.equals(org.apache.karaf.features.internal.model.Feature.DEFAULT_VERSION)) {
-                version = "";
-            }
-        } else {
-            version = "";
-        }
+    private Feature getFeatureMatching(String featureName, VersionRange version) throws Exception {
+        Map<String, Map<String, Feature>> allFeatures = getFeatureCache();
+        Map<String, Feature> versions = allFeatures.get(featureName);
         if (versions == null || versions.isEmpty()) {
             return null;
-        } else {
-            Feature feature = version.isEmpty() ? null : versions.get(version);
-            if (feature == null) {
-                // Compute version range. If an version has been given, assume exact range
-                VersionRange versionRange = version.isEmpty()
-                        ? new VersionRange(Version.emptyVersion)
-                        : new VersionRange(version, true, true);
-                Version latest = Version.emptyVersion;
-                for (String available : versions.keySet()) {
-                    Version availableVersion = VersionTable.getVersion(available);
-                    if (availableVersion.compareTo(latest) >= 0 && versionRange.contains(availableVersion)) {
-                        feature = versions.get(available);
-                        latest = availableVersion;
-                    }
-                }
+        }
+        return getLatestFeature(versions, version);
+    }
+
+    private Feature getLatestFeature(Map<String, Feature> versions, VersionRange versionRange) {
+        Version latest = Version.emptyVersion;
+        Feature feature = null;
+        for (String available : versions.keySet()) {
+            Version availableVersion = VersionTable.getVersion(available);
+            if (availableVersion.compareTo(latest) >= 0 && versionRange.includes(availableVersion)) {
+                feature = versions.get(available);
+                latest = availableVersion;
             }
-            return feature;
         }
+        return feature;
     }
 
     @Override
@@ -586,6 +576,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     /**
      * Should not be called while holding a lock.
+     * @return map from feature name to map from feature version to Feature
      */
     protected Map<String, Map<String, Feature>> getFeatureCache() throws Exception {
         Set<String> uris;
@@ -709,7 +700,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     @Override
     public boolean isRequired(Feature f) {
-        String id = FEATURE_OSGI_REQUIREMENT_PREFIX + getFeatureRequirement(f);
+        String id = FEATURE_OSGI_REQUIREMENT_PREFIX + new FeatureReq(f).toString();
         synchronized (lock) {
             Set<String> features = state.requirements.get(ROOT_REGION);
             return features != null && features.contains(id);
@@ -795,31 +786,37 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
     }
 
     @Override
-    public void installFeatures(Set<String> features, String region, EnumSet<Option> options) throws Exception {
+    public void installFeatures(Set<String> featuresIn, String region, EnumSet<Option> options) throws Exception {
+        Set<FeatureReq> featureReqs = new HashSet<>();
+        for (String feature : featuresIn) {
+            featureReqs.add(new FeatureReq(feature));
+        }
         State state = copyState();
-        Map<String, Set<String>> required = copy(state.requirements);
+        Map<String, Set<String>> requires = copy(state.requirements);
         if (region == null || region.isEmpty()) {
             region = ROOT_REGION;
         }
-        Set<String> fl = required.computeIfAbsent(region, k -> new HashSet<>());
+        Set<String> requiredForRegion = requires.computeIfAbsent(region, k -> new HashSet<>());
+        computeRequirements(options, featureReqs, requiredForRegion);
+        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
+        doProvisionInThread(requires, stateChanges, state, getFeaturesById(), options);
+    }
+
+    void computeRequirements(EnumSet<Option> options, Set<FeatureReq> featureReqs,
+                                 Set<String> requirements)
+        throws Exception {
         Map<String, Map<String, Feature>> allFeatures = getFeatureCache();
-        List<String> featuresToAdd = new ArrayList<>();
+        List<FeatureReq> featuresToAdd = new ArrayList<>();
         List<String> featuresToRemove = new ArrayList<>();
-        for (String feature : features) {
-            if (!feature.contains(VERSION_SEPARATOR)) {
-                feature += "/0.0.0";
-            }
-            String name = feature.substring(0, feature.indexOf(VERSION_SEPARATOR));
-            String version = feature.substring(feature.indexOf(VERSION_SEPARATOR) + 1);
-            Pattern pattern = Pattern.compile(name);
+        for (FeatureReq feature : featureReqs) {
+            Pattern pattern = Pattern.compile(feature.getName());
             boolean matched = false;
             for (String fKey : allFeatures.keySet()) {
                 Matcher matcher = pattern.matcher(fKey);
                 if (matcher.matches()) {
-                    Feature f = getFeatureMatching(allFeatures.get(fKey), version);
+                    Feature f = getFeatureMatching(fKey, feature.getVersionRange());
                     if (f != null) {
-                        String req = getFeatureRequirement(f);
-                        featuresToAdd.add(req);
+                        featuresToAdd.add(new FeatureReq(f));
                         Feature[] installedFeatures = listInstalledFeatures();
                         for (Feature installedFeature : installedFeatures) {
                             if (installedFeature.getName().equals(f.getName()) && installedFeature.getVersion().equals(f.getVersion())) {
@@ -834,12 +831,11 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
                 throw new IllegalArgumentException("No matching features for " + feature);
             }
             if (options.contains(Option.Upgrade)) {
-                for (String existentFeatureReq : fl) {
-                    //remove requirement prefix feature:
-                    String existentFeature = existentFeatureReq.substring(FEATURE_OSGI_REQUIREMENT_PREFIX.length());
-                    if (existentFeature.startsWith(name + VERSION_SEPARATOR)
+                for (String existentFeatureReq : requirements) {
+                    FeatureReq existentFeature = getFeatureRefFromRequired(existentFeatureReq);
+                    if (existentFeature.getName().equals(feature.getName())
                             && !featuresToAdd.contains(existentFeature)) {
-                        featuresToRemove.add(existentFeature);
+                        featuresToRemove.add(existentFeature.toString());
                         //do not break cycle to remove all old versions of feature
                     }
                 }
@@ -848,78 +844,64 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         if (!featuresToRemove.isEmpty()) {
             print("Removing features: " + join(featuresToRemove), options.contains(Option.Verbose));
             for (String featureReq : featuresToRemove) {
-                fl.remove(FEATURE_OSGI_REQUIREMENT_PREFIX + featureReq);
+                requirements.remove(FEATURE_OSGI_REQUIREMENT_PREFIX + featureReq);
             }
         }
-        featuresToAdd = new ArrayList<>(new LinkedHashSet<>(featuresToAdd));
         List<String> featuresToDisplay = new ArrayList<>();
-        for (String feature : featuresToAdd) {
-            fl.add(FEATURE_OSGI_REQUIREMENT_PREFIX + feature);
-            String v = feature.substring(feature.indexOf(VERSION_SEPARATOR) + VERSION_SEPARATOR.length());
-            VersionRange vr = new VersionRange(v, true);
-            if (vr.isPointVersion()) {
-                v = feature.substring(0, feature.indexOf(VERSION_SEPARATOR) + VERSION_SEPARATOR.length())
-                        + vr.getCeiling().toString();
-            }
-            featuresToDisplay.add(v);
+        for (FeatureReq feature : featuresToAdd) {
+            requirements.add(FEATURE_OSGI_REQUIREMENT_PREFIX + feature.toString());
+            featuresToDisplay.add(feature.toString());
         }
         print("Adding features: " + join(featuresToDisplay), options.contains(Option.Verbose));
-        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
-        doProvisionInThread(required, stateChanges, state, getFeaturesById(), options);
     }
 
     @Override
-    public void uninstallFeatures(Set<String> features, String region, EnumSet<Option> options) throws Exception {
+    public void uninstallFeatures(Set<String> featuresIn, String region, EnumSet<Option> options) throws Exception {
+        Set<FeatureReq> featureReqs = new HashSet<>();
+        for (String feature : featuresIn) {
+            featureReqs.add(new FeatureReq(feature));
+        }
         State state = copyState();
         Map<String, Set<String>> required = copy(state.requirements);
         if (region == null || region.isEmpty()) {
             region = ROOT_REGION;
         }
-        Set<String> fl = required.computeIfAbsent(region, k -> new HashSet<>());
-        List<String> featuresToRemove = new ArrayList<>();
-        for (String feature : new HashSet<>(features)) {
+        Set<String> existingFeatures = required.computeIfAbsent(region, k -> new HashSet<>());
+        Set<String> featuresToRemove = new HashSet<>();
+        for (FeatureReq feature : featureReqs) {
+            Pattern pattern = Pattern.compile(feature.getName());
             List<String> toRemove = new ArrayList<>();
-            feature = normalize(feature);
-            if (feature.endsWith("/0.0.0")) {
-                // Match only on name
-                String nameSep = FEATURE_OSGI_REQUIREMENT_PREFIX + feature.substring(0, feature.indexOf(VERSION_SEPARATOR) + 1);
-                for (String f : fl) {
-                    Pattern pattern = Pattern.compile(nameSep.substring(0, nameSep.length() - 1));
-                    Matcher matcher = pattern.matcher(f);
-                    if (matcher.matches() || normalize(f).startsWith(nameSep)) {
-                        toRemove.add(f);
-                    }
-                }
-            } else {
-                Pattern pattern = getNameAndVersionPattern(feature);
-                for (String f : fl) {
-                    Matcher matcher = pattern.matcher(f);
-                    if (matcher.matches()) {
-                        toRemove.add(f);
-                    }
-                }
+            for (String existingFeature : existingFeatures) {
+               FeatureReq existingFeatureReq = getFeatureRefFromRequired(existingFeature);
+               if (existingFeatureReq != null) {
+                   Matcher matcher = pattern.matcher(existingFeatureReq.getName());
+                   if (matcher.matches() && feature.getVersionRange().includes(existingFeatureReq.getVersionRange().getLeft())) {
+                       toRemove.add(existingFeature);
+                   }
+               }
             }
-            toRemove.retainAll(fl);
+            toRemove.retainAll(existingFeatures);
 
             if (toRemove.isEmpty()) {
                 throw new IllegalArgumentException("Feature named '" + feature + "' is not installed");
             }
             featuresToRemove.addAll(toRemove);
         }
-        featuresToRemove = new ArrayList<>(new LinkedHashSet<>(featuresToRemove));
         print("Removing features: " + join(featuresToRemove), options.contains(Option.Verbose));
-        fl.removeAll(featuresToRemove);
-        if (fl.isEmpty()) {
+        existingFeatures.removeAll(featuresToRemove);
+        if (existingFeatures.isEmpty()) {
             required.remove(region);
         }
         Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
         doProvisionInThread(required, stateChanges, state, getFeaturesById(), options);
     }
 
-    private Pattern getNameAndVersionPattern(String feature) {
-        String name = feature.substring(0, feature.indexOf(VERSION_SEPARATOR));
-        String version = feature.substring(feature.indexOf(VERSION_SEPARATOR) + 1);
-        return getFeaturePattern(name, version);
+    private FeatureReq getFeatureRefFromRequired(String featureReq) {
+        if (!featureReq.startsWith(FEATURE_OSGI_REQUIREMENT_PREFIX)) {
+            return null;
+        }
+        String featureReq1 = featureReq.substring(FEATURE_OSGI_REQUIREMENT_PREFIX.length());
+        return new FeatureReq(featureReq1);
     }
 
     @Override
@@ -1206,31 +1188,9 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         installSupport.installLibraries(feature);
     }
 
-    private Pattern getFeaturePattern(String name, String version) {
-        String req = FEATURE_OSGI_REQUIREMENT_PREFIX + getFeatureRequirement(name, version);
-        req = req.replace("[", "\\[");
-        req = req.replace("(", "\\(");
-        req = req.replace("]", "\\]");
-        req = req.replace(")", "\\)");
-        return Pattern.compile(req);
-    }
 
-    private String getFeatureRequirement(Feature feature) {
-        return getFeatureRequirement(feature.getName(), feature.getVersion());
-    }
 
-    private String getFeatureRequirement(String name, String version) {
-        return name + VERSION_SEPARATOR + new VersionRange(version, true);
-    }
-
-    private String join(List<String> list) {
-        StringBuilder sb = new StringBuilder();
-        for (int i = 0; i < list.size(); i++) {
-            if (i > 0) {
-                sb.append(", ");
-            }
-            sb.append(list.get(i));
-        }
-        return sb.toString();
+    private String join(Collection<String> list) {
+        return String.join(", ", list);
     }
 }

http://git-wip-us.apache.org/repos/asf/karaf/blob/3b900267/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesServiceImplTest.java
----------------------------------------------------------------------
diff --git a/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesServiceImplTest.java b/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesServiceImplTest.java
index a5ec75a..f5363d4 100644
--- a/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesServiceImplTest.java
+++ b/features/core/src/test/java/org/apache/karaf/features/internal/service/FeaturesServiceImplTest.java
@@ -125,7 +125,7 @@ public class FeaturesServiceImplTest extends TestBase {
         impl.addRepository(URI.create("custom:cycle/a-references-b.xml"));
         impl.getFeatureCache();
     }
-
+    
     @Test
     public void testRemoveRepo1() throws Exception {
         final FeaturesService featureService = createTestFeatureService();
@@ -141,6 +141,29 @@ public class FeaturesServiceImplTest extends TestBase {
     }
     
     @Test
+    public void testGetFeatureWithVersion() throws Exception {
+        final FeaturesService featureService = createTestFeatureService();
+        URI repoA = URI.create("custom:f09.xml");
+        featureService.addRepository(repoA);
+        Feature feature = featureService.getFeature("test", "1.0.0");
+        assertEquals("1.0.0", feature.getVersion());
+    }
+
+    @Test
+    public void testInstallAndUpdate() throws Exception {
+        final FeaturesService featureService = createTestFeatureService();
+        URI repoA = URI.create("custom:f09.xml");
+        featureService.addRepository(repoA);
+        Feature test100 = featureService.getFeature("test", "1.0.0");
+        installFeature(featureService, test100);
+        assertInstalled(featureService, test100);
+        Feature test110 = featureService.getFeature("test", "1.1.0");
+        featureService.installFeature(test110, EnumSet.of(Option.Upgrade));
+        waitInstalled(featureService, test110);
+        assertNotInstalled(featureService, test100);
+    }
+    
+    @Test
     public void testRemoveRepo2() throws Exception {
         final FeaturesService featureService = createTestFeatureService();
         URI repoA = URI.create("custom:remove/a.xml");
@@ -175,9 +198,8 @@ public class FeaturesServiceImplTest extends TestBase {
         FrameworkInfo dummyInfo = new FrameworkInfo();
         expect(installSupport.getInfo()).andReturn(dummyInfo).atLeastOnce();
         EasyMock.replay(installSupport);
-        final FeaturesServiceImpl featureService = new FeaturesServiceImpl(new Storage(), null, null, this.resolver,
-                                                                 installSupport, null, cfg);
-        return featureService;
+        return new FeaturesServiceImpl(new Storage(), null, null, this.resolver,
+                                       installSupport, null, cfg);
     }
 
     private void assertNotInstalled(FeaturesService featureService, Feature feature) {
@@ -190,11 +212,21 @@ public class FeaturesServiceImplTest extends TestBase {
                     featureService.isInstalled(feature));
     }
 
-    private void installFeature(final FeaturesService featureService, Feature a1Feature)
+    private void installFeature(final FeaturesService featureService, Feature feature)
         throws Exception {
-        featureService.installFeature(a1Feature, EnumSet.noneOf(Option.class));
-        while (!featureService.isInstalled(a1Feature)) {
+        featureService.installFeature(feature, EnumSet.noneOf(Option.class));
+        waitInstalled(featureService, feature);
+    }
+
+    private void waitInstalled(final FeaturesService featureService, Feature feature)
+        throws InterruptedException {
+        int count = 40;
+        while (!featureService.isInstalled(feature) && count > 0) {
             Thread.sleep(100);
+            count --;
+        }
+        if (count == 0) {
+            throw new RuntimeException("Feature " + feature + " not installed.");
         }
     }
     

http://git-wip-us.apache.org/repos/asf/karaf/blob/3b900267/features/core/src/test/resources/org/apache/karaf/features/internal/service/f09.xml
----------------------------------------------------------------------
diff --git a/features/core/src/test/resources/org/apache/karaf/features/internal/service/f09.xml b/features/core/src/test/resources/org/apache/karaf/features/internal/service/f09.xml
new file mode 100644
index 0000000..8a6c26a
--- /dev/null
+++ b/features/core/src/test/resources/org/apache/karaf/features/internal/service/f09.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one or more
+    contributor license agreements.  See the NOTICE file distributed with
+    this work for additional information regarding copyright ownership.
+    The ASF licenses this file to You under the Apache License, Version 2.0
+    (the "License"); you may not use this file except in compliance with
+    the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+<features name="karaf" xmlns="http://karaf.apache.org/xmlns/features/v1.2.1">
+    <feature name="test" version="1.0.0" >
+    </feature>
+    <feature name="test" version="1.1.0" >
+    </feature>
+</features>
+


[05/27] karaf git commit: [KARAF-5309] Upgrade to directory server 2.0.0-M24

Posted by cs...@apache.org.
[KARAF-5309] Upgrade to directory server 2.0.0-M24


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/8a18da51
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/8a18da51
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/8a18da51

Branch: refs/heads/model_features
Commit: 8a18da5194126831c1962ea08d8419fee5a9a296
Parents: 5b4da2c
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 16:23:19 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 16:23:19 2017 +0200

----------------------------------------------------------------------
 jaas/modules/pom.xml | 5 +++++
 pom.xml              | 2 +-
 2 files changed, 6 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/8a18da51/jaas/modules/pom.xml
----------------------------------------------------------------------
diff --git a/jaas/modules/pom.xml b/jaas/modules/pom.xml
index fa4c264..8313005 100644
--- a/jaas/modules/pom.xml
+++ b/jaas/modules/pom.xml
@@ -91,6 +91,11 @@
             <scope>test</scope>
         </dependency>
         <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
             <groupId>org.apache.directory.server</groupId>
             <artifactId>apacheds-core-integ</artifactId>
             <version>${directory-version}</version>

http://git-wip-us.apache.org/repos/asf/karaf/blob/8a18da51/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 791578a..9ff6755 100644
--- a/pom.xml
+++ b/pom.xml
@@ -294,7 +294,7 @@
 
         <sshd.version>1.6.0</sshd.version>
         <derby-version>10.12.1.1</derby-version>
-        <directory-version>2.0.0-M20</directory-version>
+        <directory-version>2.0.0-M24</directory-version>
         <struts.bundle.version>1.3.10_1</struts.bundle.version>
         <xbean.version>3.18</xbean.version>
         <xerces.version>2.11.0_1</xerces.version>


[21/27] karaf git commit: Extract common code

Posted by cs...@apache.org.
Extract common code


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/db2bf32c
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/db2bf32c
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/db2bf32c

Branch: refs/heads/model_features
Commit: db2bf32c780aadae38136e6ea6adeb8ed38950c4
Parents: c79e2ba
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 18:00:43 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 18:00:43 2017 +0200

----------------------------------------------------------------------
 .../apache/karaf/jaas/modules/syncope/SyncopeLoginModule.java  | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/db2bf32c/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModule.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModule.java b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModule.java
index 3d6eb66..1e194b6 100644
--- a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModule.java
+++ b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModule.java
@@ -101,10 +101,11 @@ public class SyncopeLoginModule extends AbstractKarafLoginModule {
             LOGGER.debug("Populating principals with user");
             principals.add(new UserPrincipal(user));
             LOGGER.debug("Retrieving user {} roles", user);
+            String responseSt = EntityUtils.toString(response.getEntity());
             if (version.equals("2.x") || version.equals("2")) {
-                roles = extractingRolesSyncope2(EntityUtils.toString(response.getEntity()));
+                roles = extractingRolesSyncope2(responseSt);
             } else {
-                roles = extractingRolesSyncope1(EntityUtils.toString(response.getEntity()));
+                roles = extractingRolesSyncope1(responseSt);
             }
         } catch (Exception e) {
             LOGGER.error("User {} authentication failed", user, e);
@@ -162,6 +163,7 @@ public class SyncopeLoginModule extends AbstractKarafLoginModule {
      * @return the list of user roles.
      * @throws Exception in case of extractiong failure.
      */
+    @SuppressWarnings("unchecked")
     protected List<String> extractingRolesSyncope2(String response) throws Exception {
         List<String> roles = new ArrayList<>();
         if (response != null && !response.isEmpty()) {


[24/27] karaf git commit: [KARAF-5300] Add documentation

Posted by cs...@apache.org.
[KARAF-5300] Add documentation


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/99c21882
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/99c21882
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/99c21882

Branch: refs/heads/model_features
Commit: 99c21882335430c2bbcf84973a46afd16e178ee7
Parents: 3b90026
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Thu Aug 10 10:33:22 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Thu Aug 17 16:29:30 2017 +0200

----------------------------------------------------------------------
 .../karaf/features/internal/service/FeatureReq.java   | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/99c21882/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
index 2e1f652..1bac816 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeatureReq.java
@@ -22,6 +22,15 @@ import org.osgi.framework.VersionRange;
 
 /**
  * Requirement for a feature
+ * 
+ * <p>The syntax of a requirement as a String is name[/versionRange].
+ * If no versionRange is given then a range of [0,) is assumeed which matches all versions.
+ * 
+ * <p>
+ * - name: Can be a feature name or a glob like myfeat*
+ * - versionRange: version or range
+ * - version: Will specify a specific version. Like [version,version]. An exemption is 0.0.0 which matches all versions.
+ * - range: Like defined in OSGi VersionRange. Example: [1.0.0, 1.1.0)  
  */
 public class FeatureReq {
     public static final String VERSION_SEPARATOR = "/";
@@ -57,7 +66,10 @@ public class FeatureReq {
     }
 
     private static VersionRange exactVersion(String versionRange) {
-        return new VersionRange(VersionRange.LEFT_CLOSED, new Version(versionRange), new Version(versionRange), VersionRange.RIGHT_CLOSED);
+        return new VersionRange(VersionRange.LEFT_CLOSED, 
+                                new Version(versionRange), 
+                                new Version(versionRange), 
+                                VersionRange.RIGHT_CLOSED);
     }
 
     public FeatureReq(String name, VersionRange versionRange) {


[22/27] karaf git commit: Extract response data. Improve assertions

Posted by cs...@apache.org.
Extract response data. Improve assertions


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/b57bceae
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/b57bceae
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/b57bceae

Branch: refs/heads/model_features
Commit: b57bceae1855e610e3941c73b1b1260bea264c0d
Parents: db2bf32
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 18:01:20 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 18:01:20 2017 +0200

----------------------------------------------------------------------
 .../modules/syncope/SyncopeLoginModuleTest.java | 131 +++----------------
 .../jaas/modules/syncope/syncope1Response.xml   |  70 ++++++++++
 .../jaas/modules/syncope/syncope2Response.json  |  55 ++++++++
 3 files changed, 146 insertions(+), 110 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/b57bceae/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModuleTest.java
index 560879a..1156585 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/syncope/SyncopeLoginModuleTest.java
@@ -16,131 +16,42 @@
  */
 package org.apache.karaf.jaas.modules.syncope;
 
-import org.junit.Test;
-import org.junit.Assert;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.Assert.assertThat;
 
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.Test;
 
 public class SyncopeLoginModuleTest {
 
     @Test
     public void testRolesExtractionSyncope1() throws Exception {
-        String syncopeResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
-                "<user>\n" +
-                "    <attributes>\n" +
-                "        <attribute>\n" +
-                "            <readonly>false</readonly>\n" +
-                "            <schema>cool</schema>\n" +
-                "            <value>false</value>\n" +
-                "        </attribute>\n" +
-                "        <attribute>\n" +
-                "            <readonly>false</readonly>\n" +
-                "            <schema>email</schema>\n" +
-                "            <value>karaf@example.net</value>\n" +
-                "        </attribute>\n" +
-                "        <attribute>\n" +
-                "            <readonly>false</readonly>\n" +
-                "            <schema>fullname</schema>\n" +
-                "            <value>karaf</value>\n" +
-                "        </attribute>\n" +
-                "        <attribute>\n" +
-                "            <readonly>false</readonly>\n" +
-                "            <schema>gender</schema>\n" +
-                "            <value>M</value>\n" +
-                "        </attribute>\n" +
-                "        <attribute>\n" +
-                "            <readonly>false</readonly>\n" +
-                "            <schema>surname</schema>\n" +
-                "            <value>karaf</value>\n" +
-                "        </attribute>\n" +
-                "        <attribute>\n" +
-                "            <readonly>false</readonly>\n" +
-                "            <schema>userId</schema>\n" +
-                "            <value>karaf@example.net</value>\n" +
-                "        </attribute>\n" +
-                "    </attributes>\n" +
-                "    <derivedAttributes/>\n" +
-                "    <id>100</id>\n" +
-                "    <propagationStatuses/>\n" +
-                "    <resources/>\n" +
-                "    <virtualAttributes/>\n" +
-                "    <creationDate>2014-08-12T18:37:09.202+02:00</creationDate>\n" +
-                "    <failedLogins>0</failedLogins>\n" +
-                "    <lastLoginDate>2014-08-13T09:38:02.204+02:00</lastLoginDate>\n" +
-                "    <memberships>\n" +
-                "        <membership>\n" +
-                "            <attributes/>\n" +
-                "            <derivedAttributes/>\n" +
-                "            <id>100</id>\n" +
-                "            <propagationStatuses/>\n" +
-                "            <resources/>\n" +
-                "            <virtualAttributes/>\n" +
-                "            <resources/>\n" +
-                "            <roleId>100</roleId>\n" +
-                "            <roleName>admin</roleName>\n" +
-                "        </membership>\n" +
-                "        <membership>\n" +
-                "            <attributes/>\n" +
-                "            <derivedAttributes/>\n" +
-                "            <id>101</id>\n" +
-                "            <propagationStatuses/>\n" +
-                "            <resources/>\n" +
-                "            <virtualAttributes/>\n" +
-                "            <resources/>\n" +
-                "            <roleId>101</roleId>\n" +
-                "            <roleName>another</roleName>\n" +
-                "        </membership>\n" +
-                "    </memberships>\n" +
-                "    <password>36460D3A3C1E27C0DB2AF23344475EE712DD3C9D</password>\n" +
-                "    <status>active</status>\n" +
-                "    <username>karaf</username>\n" +
-                "</user>\n";
+        String syncopeResponse = read("syncope1Response.xml");
         SyncopeLoginModule syncopeLoginModule = new SyncopeLoginModule();
         List<String> roles = syncopeLoginModule.extractingRolesSyncope1(syncopeResponse);
-        Assert.assertEquals(2, roles.size());
-        Assert.assertEquals("admin", roles.get(0));
-        Assert.assertEquals("another", roles.get(1));
+        assertThat(roles, containsInAnyOrder("admin", "another"));
     }
 
     @Test
     public void testRolesExtractionSyncope2() throws Exception {
-        String syncopeResponse = "{\n" + "\n"
-                + "   \"@class\":\"org.apache.syncope.common.lib.to.UserTO\",\n" + "\n"
-                + "   \"creator\":\"admin\",\n" + "\n"
-                + "   \"creationDate\":\"2017-07-31T08:36:41.000+0000\",\n" + "\n"
-                + "   \"lastModifier\":\"admin\",\n" + "\n"
-                + "   \"lastChangeDate\":\"2017-08-01T08:46:19.236+0000\",\n" + "\n"
-                + "   \"key\":\"e5a131b0-eb66-4115-a131-b0eb66511579\",\n" + "\n"
-                + "   \"type\":\"USER\",\n" + "\n" + "   \"realm\":\"/karaf\",\n" + "\n"
-                + "   \"status\":\"created\",\n" + "\n" + "   \"password\":null,\n" + "\n"
-                + "   \"token\":null,\n" + "\n" + "   \"tokenExpireTime\":null,\n" + "\n"
-                + "   \"username\":\"karaf\",\n" + "\n"
-                + "   \"lastLoginDate\":\"2017-08-01T08:46:19.224+0000\",\n" + "\n"
-                + "   \"changePwdDate\":null,\n" + "\n" + "   \"failedLogins\":0,\n" + "\n"
-                + "   \"securityQuestion\":null,\n" + "\n" + "   \"securityAnswer\":null,\n" + "\n"
-                + "   \"mustChangePassword\":false,\n" + "\n" + "   \"auxClasses\":[\n" + "\n"
-                + " \n" + "\n" + "   ],\n" + "\n" + "   \"plainAttrs\":[\n" + "\n" + " \n" + "\n"
-                + "   ],\n" + "\n" + "   \"derAttrs\":[\n" + "\n" + " \n" + "\n" + "   ],\n" + "\n"
-                + "   \"virAttrs\":[\n" + "\n" + " \n" + "\n" + "   ],\n" + "\n"
-                + "   \"resources\":[\n" + "\n" + " \n" + "\n" + "   ],\n" + "\n"
-                + "   \"roles\":[\n" + "\n" + "      \"admin\", \"another\"\n" + "\n" + "   ],\n" +
-                "\n"
-                + "   \"dynRoles\":[\n" + "\n" + "      \"admin\"\n" + "\n" + "   ],\n" + "\n"
-                + "   \"relationships\":[\n" + "\n" + " \n" + "\n" + "   ],\n" + "\n"
-                + "   \"memberships\":[\n" + "\n" + "      {\n" + "\n"
-                + "         \"type\":\"Membership\",\n" + "\n"
-                + "         \"rightType\":\"GROUP\",\n" + "\n"
-                + "         \"rightKey\":\"3847aa78-3202-4d8f-87aa-7832026d8fba\",\n" + "\n"
-                + "         \"groupName\":\"manager\",\n" + "\n" + "         \"plainAttrs\":[\n"
-                + "\n" + " \n" + "\n" + "         ],\n" + "\n" + "         \"derAttrs\":[\n" + "\n"
-                + " \n" + "\n" + "         ],\n" + "\n" + "         \"virAttrs\":[\n" + "\n" + " \n"
-                + "\n" + "         ]\n" + "\n" + "      }\n" + "\n" + "   ],\n" + "\n"
-                + "   \"dynGroups\":[\n" + "\n" + " \n" + "\n" + "   ]\n" + "\n" + "}";
+        String syncopeResponse = read("syncope2Response.json");
         SyncopeLoginModule syncopeLoginModule = new SyncopeLoginModule();
         List<String> roles = syncopeLoginModule.extractingRolesSyncope2(syncopeResponse);
-        Assert.assertEquals(2, roles.size());
-        Assert.assertEquals("admin", roles.get(0));
-        Assert.assertEquals("another", roles.get(1));
+        assertThat(roles, containsInAnyOrder("admin", "another"));
+    }
+
+    private String read(String resourceName) throws URISyntaxException, IOException {
+        URI response = this.getClass().getResource(resourceName).toURI();
+        return Files.lines(Paths.get(response), Charset.forName("UTF-8"))
+            .collect(Collectors.joining("\n"));
     }
 
 }

http://git-wip-us.apache.org/repos/asf/karaf/blob/b57bceae/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope1Response.xml
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope1Response.xml b/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope1Response.xml
new file mode 100644
index 0000000..105ec10
--- /dev/null
+++ b/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope1Response.xml
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<user>
+    <attributes>
+        <attribute>
+            <readonly>false</readonly>
+            <schema>cool</schema>
+            <value>false</value>
+        </attribute>
+        <attribute>
+            <readonly>false</readonly>
+            <schema>email</schema>
+            <value>karaf@example.net</value>
+        </attribute>
+        <attribute>
+            <readonly>false</readonly>
+            <schema>fullname</schema>
+            <value>karaf</value>
+        </attribute>
+        <attribute>
+            <readonly>false</readonly>
+            <schema>gender</schema>
+            <value>M</value>
+        </attribute>
+        <attribute>
+            <readonly>false</readonly>
+            <schema>surname</schema>
+            <value>karaf</value>
+        </attribute>
+        <attribute>
+            <readonly>false</readonly>
+            <schema>userId</schema>
+            <value>karaf@example.net</value>
+        </attribute>
+    </attributes>
+    <derivedAttributes/>
+    <id>100</id>
+    <propagationStatuses/>
+    <resources/>
+    <virtualAttributes/>
+    <creationDate>2014-08-12T18:37:09.202+02:00</creationDate>
+    <failedLogins>0</failedLogins>
+    <lastLoginDate>2014-08-13T09:38:02.204+02:00</lastLoginDate>
+    <memberships>
+        <membership>
+            <attributes/>
+            <derivedAttributes/>
+            <id>100</id>
+            <propagationStatuses/>
+            <resources/>
+            <virtualAttributes/>
+            <resources/>
+            <roleId>100</roleId>
+            <roleName>admin</roleName>
+        </membership>
+        <membership>
+            <attributes/>
+            <derivedAttributes/>
+            <id>101</id>
+            <propagationStatuses/>
+            <resources/>
+            <virtualAttributes/>
+            <resources/>
+            <roleId>101</roleId>
+            <roleName>another</roleName>
+        </membership>
+    </memberships>
+    <password>36460D3A3C1E27C0DB2AF23344475EE712DD3C9D</password>
+    <status>active</status>
+    <username>karaf</username>
+</user>

http://git-wip-us.apache.org/repos/asf/karaf/blob/b57bceae/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope2Response.json
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope2Response.json b/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope2Response.json
new file mode 100644
index 0000000..8a803f2
--- /dev/null
+++ b/jaas/modules/src/test/resources/org/apache/karaf/jaas/modules/syncope/syncope2Response.json
@@ -0,0 +1,55 @@
+{
+   "@class":"org.apache.syncope.common.lib.to.UserTO",
+   "creator":"admin",
+   "creationDate":"2017-07-31T08:36:41.000+0000",
+   "lastModifier":"admin",
+   "lastChangeDate":"2017-08-01T08:46:19.236+0000",
+   "key":"e5a131b0-eb66-4115-a131-b0eb66511579",
+   "type":"USER",
+   "realm":"/karaf",
+   "status":"created",
+   "password":null,
+   "token":null,
+   "tokenExpireTime":null,
+   "username":"karaf",
+   "lastLoginDate":"2017-08-01T08:46:19.224+0000",
+   "changePwdDate":null,
+   "failedLogins":0,
+   "securityQuestion":null,
+   "securityAnswer":null,
+   "mustChangePassword":false,
+   "auxClasses":[
+   ],
+   "plainAttrs":[
+   ],
+   "derAttrs":[
+   ],
+   "virAttrs":[
+   ],
+   "resources":[
+   ],
+   "roles":[
+      "admin", "another"
+   ],
+   "dynRoles":[
+      "admin"
+   ],
+   "relationships":[
+   ],
+   "memberships":[
+      {
+         "type":"Membership",
+         "rightType":"GROUP",
+         "rightKey":"3847aa78-3202-4d8f-87aa-7832026d8fba",
+         "groupName":"manager",
+         "plainAttrs":[
+         ],
+         "derAttrs":[
+         ],
+         "virAttrs":[
+         ]
+      }
+   ],
+   "dynGroups":[
+   ]
+}


[18/27] karaf git commit: Extract common code in test

Posted by cs...@apache.org.
Extract common code in test


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/0853a353
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/0853a353
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/0853a353

Branch: refs/heads/model_features
Commit: 0853a353afa4c8eabad38327e3943b1543fd4c0a
Parents: 3b72701
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 13:41:17 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 13:41:17 2017 +0200

----------------------------------------------------------------------
 .../jaas/modules/krb5/KarafKerberosITest.java   |  51 ++++++++++
 .../jaas/modules/krb5/Krb5LoginModuleTest.java  | 102 +++----------------
 .../modules/ldap/GSSAPILdapLoginModuleTest.java |  29 +-----
 3 files changed, 66 insertions(+), 116 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/0853a353/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/KarafKerberosITest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/KarafKerberosITest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/KarafKerberosITest.java
new file mode 100644
index 0000000..0b57930
--- /dev/null
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/KarafKerberosITest.java
@@ -0,0 +1,51 @@
+/*
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *  under the License.
+ */
+package org.apache.karaf.jaas.modules.krb5;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import org.apache.directory.api.util.Strings;
+import org.apache.directory.server.kerberos.kdc.AbstractKerberosITest;
+import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
+import org.apache.directory.shared.kerberos.crypto.checksum.ChecksumType;
+
+public class KarafKerberosITest extends AbstractKerberosITest {
+
+    protected String createKrb5Conf(ChecksumType checksumType, EncryptionType encryptionType, boolean isTcp) throws IOException {
+        File file = folder.newFile("krb5.conf");
+        PrintStream out = new PrintStream(file);
+        out.println("[libdefaults]");
+        out.println("default_realm = " + REALM);
+        out.println("default_tkt_enctypes = " + encryptionType.getName());
+        out.println("default_tgs_enctypes = " + encryptionType.getName());
+        out.println("permitted_enctypes = " + encryptionType.getName());
+        out.println("default-checksum_type = " + checksumType.getName());
+        if (isTcp) {
+            out.println("udp_preference_limit = 1");
+        }
+        out.println("[realms]");
+        out.println(REALM + " = {");
+        out.println("kdc = " + HOSTNAME + ":" + kdcServer.getTransports()[0].getPort());
+        out.println("}");
+        out.println("[domain_realm]");
+        out.println("." + Strings.lowerCaseAscii(REALM) + " = " + REALM);
+        out.println(Strings.lowerCaseAscii(REALM) + " = " + REALM);
+        out.close();
+        return file.getAbsolutePath();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/0853a353/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/Krb5LoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/Krb5LoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/Krb5LoginModuleTest.java
index e6caf7b..d88955d 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/Krb5LoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/krb5/Krb5LoginModuleTest.java
@@ -16,13 +16,10 @@
  */
 package org.apache.karaf.jaas.modules.krb5;
 
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.SystemUtils;
 import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
 import org.apache.directory.api.ldap.model.entry.DefaultEntry;
 import org.apache.directory.api.ldap.model.entry.Entry;
 import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.api.util.Strings;
 import org.apache.directory.ldap.client.api.Krb5LoginConfiguration;
 import org.apache.directory.server.annotations.CreateKdcServer;
 import org.apache.directory.server.annotations.CreateLdapServer;
@@ -35,7 +32,6 @@ import org.apache.directory.server.core.annotations.CreateIndex;
 import org.apache.directory.server.core.annotations.CreatePartition;
 import org.apache.directory.server.core.integ.FrameworkRunner;
 import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
-import org.apache.directory.server.kerberos.kdc.AbstractKerberosITest;
 import org.apache.directory.server.kerberos.kdc.KerberosTestUtils;
 import org.apache.directory.server.kerberos.shared.crypto.encryption.KerberosKeyFactory;
 import org.apache.directory.server.kerberos.shared.keytab.Keytab;
@@ -65,8 +61,6 @@ import javax.security.auth.kerberos.KerberosTicket;
 import javax.security.auth.login.Configuration;
 import javax.security.auth.login.LoginException;
 import java.io.File;
-import java.io.IOException;
-import java.security.Principal;
 import java.text.ParseException;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -75,8 +69,10 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
+import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertThat;
 
 @RunWith(FrameworkRunner.class)
 @CreateDS(name = "Krb5LoginModuleTest-class",
@@ -130,8 +126,7 @@ import static org.junit.Assert.assertTrue;
         "objectClass: organizationalUnit",
         "ou: users"
 })
-public class Krb5LoginModuleTest extends AbstractKerberosITest {
-
+public class Krb5LoginModuleTest extends KarafKerberosITest {
 
     @Before
     public void setUp() throws Exception {
@@ -155,7 +150,6 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
 
     @Test
     public void testKeytabSuccess() throws Exception {
-
         Map<String, Object> props = new HashMap<>();
         props.put("debug", "true");
         props.put("useKeyTab", "true");
@@ -164,11 +158,9 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
         props.put("doNotPrompt", "true");
         props.put("storeKey", "true");
         props.put("detailed.login.exception", "true");
-
-
         Subject subject = new Subject();
-
         Krb5LoginModule module = new Krb5LoginModule();
+
         module.initialize(subject, null, null, props);
 
         assertEquals("Precondition", 0, subject.getPrincipals().size());
@@ -177,27 +169,11 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
         Assert.assertTrue(module.commit());
 
         assertEquals(1, subject.getPrincipals().size());
+        assertThat(names(subject.getPrincipals(KerberosPrincipal.class)), containsInAnyOrder("hnelson@EXAMPLE.COM"));
 
-        boolean foundUser = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof KerberosPrincipal) {
-                assertEquals("hnelson@EXAMPLE.COM", pr.getName());
-                foundUser = true;
-                break;
-            }
-        }
-        assertTrue(foundUser);
-
-        boolean foundToken = false;
-        for (Object crd : subject.getPrivateCredentials()) {
-            if (crd instanceof KerberosTicket) {
-                assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
-                assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
-                foundToken = true;
-                break;
-            }
-        }
-        assertTrue(foundToken);
+        KerberosTicket ticket = subject.getPrivateCredentials(KerberosTicket.class).iterator().next();
+        assertEquals("hnelson@EXAMPLE.COM", ticket.getClient().getName());
+        assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ticket.getServer().getName());
 
         Assert.assertTrue(module.logout());
 
@@ -215,9 +191,7 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
         props.put("storeKey", "true");
         props.put("detailed.login.exception", "true");
 
-
         Subject subject = new Subject();
-
         Krb5LoginModule module = new Krb5LoginModule();
         module.initialize(subject, null, null, props);
 
@@ -230,7 +204,6 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
     @Test
     public void testLoginSuccess() throws Exception {
         Subject subject = new Subject();
-
         Krb5LoginModule module = new Krb5LoginModule();
         module.initialize(subject, new NamePasswordCallbackHandler("hnelson", "secret"), null, new HashMap<>());
 
@@ -240,27 +213,11 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
         Assert.assertTrue(module.commit());
 
         assertEquals(1, subject.getPrincipals().size());
+        assertThat(names(subject.getPrincipals(KerberosPrincipal.class)), containsInAnyOrder("hnelson@EXAMPLE.COM"));
 
-        boolean foundUser = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof KerberosPrincipal) {
-                assertEquals("hnelson@EXAMPLE.COM", pr.getName());
-                foundUser = true;
-                break;
-            }
-        }
-        assertTrue(foundUser);
-
-        boolean foundToken = false;
-        for (Object crd : subject.getPrivateCredentials()) {
-            if (crd instanceof KerberosTicket) {
-                assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
-                assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
-                foundToken = true;
-                break;
-            }
-        }
-        assertTrue(foundToken);
+        KerberosTicket ticket = subject.getPrivateCredentials(KerberosTicket.class).iterator().next();
+        assertEquals("hnelson@EXAMPLE.COM", ticket.getClient().getName());
+        assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ticket.getServer().getName());
 
         Assert.assertTrue(module.logout());
 
@@ -328,39 +285,6 @@ public class Krb5LoginModuleTest extends AbstractKerberosITest {
         conn.add(entry);
     }
 
-    private String createKrb5Conf(ChecksumType checksumType, EncryptionType encryptionType, boolean isTcp) throws IOException {
-        File file = folder.newFile("krb5.conf");
-
-        String data = "";
-
-        data += "[libdefaults]" + SystemUtils.LINE_SEPARATOR;
-        data += "default_realm = " + REALM + SystemUtils.LINE_SEPARATOR;
-        data += "default_tkt_enctypes = " + encryptionType.getName() + SystemUtils.LINE_SEPARATOR;
-        data += "default_tgs_enctypes = " + encryptionType.getName() + SystemUtils.LINE_SEPARATOR;
-        data += "permitted_enctypes = " + encryptionType.getName() + SystemUtils.LINE_SEPARATOR;
-        //        data += "default_checksum = " + checksumType.getName() + SystemUtils.LINE_SEPARATOR;
-        //        data += "ap_req_checksum_type = " + checksumType.getName() + SystemUtils.LINE_SEPARATOR;
-        data += "default-checksum_type = " + checksumType.getName() + SystemUtils.LINE_SEPARATOR;
-
-        if (isTcp) {
-            data += "udp_preference_limit = 1" + SystemUtils.LINE_SEPARATOR;
-        }
-
-
-        data += "[realms]" + SystemUtils.LINE_SEPARATOR;
-        data += REALM + " = {" + SystemUtils.LINE_SEPARATOR;
-        data += "kdc = " + HOSTNAME + ":" + kdcServer.getTransports()[0].getPort() + SystemUtils.LINE_SEPARATOR;
-        data += "}" + SystemUtils.LINE_SEPARATOR;
-
-        data += "[domain_realm]" + SystemUtils.LINE_SEPARATOR;
-        data += "." + Strings.lowerCaseAscii(REALM) + " = " + REALM + SystemUtils.LINE_SEPARATOR;
-        data += Strings.lowerCaseAscii(REALM) + " = " + REALM + SystemUtils.LINE_SEPARATOR;
-
-        FileUtils.writeStringToFile(file, data);
-
-        return file.getAbsolutePath();
-    }
-
     private KeytabEntry createKeytabEntry() throws ParseException {
         String principalName = "hnelson@EXAMPLE.COM";
         int principalType = 1;

http://git-wip-us.apache.org/repos/asf/karaf/blob/0853a353/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
index 11daa72..b664bc3 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
@@ -22,7 +22,6 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.PrintStream;
 import java.security.Principal;
 import java.util.Collections;
 
@@ -36,7 +35,6 @@ import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
 import org.apache.directory.api.ldap.model.entry.DefaultEntry;
 import org.apache.directory.api.ldap.model.entry.Entry;
 import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.api.util.Strings;
 import org.apache.directory.server.annotations.CreateKdcServer;
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
@@ -48,7 +46,6 @@ import org.apache.directory.server.core.annotations.CreateIndex;
 import org.apache.directory.server.core.annotations.CreatePartition;
 import org.apache.directory.server.core.integ.FrameworkRunner;
 import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
-import org.apache.directory.server.kerberos.kdc.AbstractKerberosITest;
 import org.apache.directory.server.kerberos.kdc.KerberosTestUtils;
 import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler;
 import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler;
@@ -63,6 +60,7 @@ import org.apache.felix.utils.properties.Properties;
 import org.apache.karaf.jaas.boot.principal.RolePrincipal;
 import org.apache.karaf.jaas.boot.principal.UserPrincipal;
 import org.apache.karaf.jaas.modules.NamePasswordCallbackHandler;
+import org.apache.karaf.jaas.modules.krb5.KarafKerberosITest;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -131,7 +129,7 @@ import org.junit.runner.RunWith;
         "cn: admin",
         "member: uid=hnelson,ou=users,dc=example,dc=com"
 })
-public class GSSAPILdapLoginModuleTest extends AbstractKerberosITest {
+public class GSSAPILdapLoginModuleTest extends KarafKerberosITest {
 
     private static boolean loginConfigUpdated;
 
@@ -314,29 +312,6 @@ public class GSSAPILdapLoginModuleTest extends AbstractKerberosITest {
                 "ldap", "randall", servicePrincipal);
     }
 
-    private String createKrb5Conf(ChecksumType checksumType, EncryptionType encryptionType, boolean isTcp) throws IOException {
-        File file = folder.newFile("krb5.conf");
-        PrintStream out = new PrintStream(file);
-        out.println("[libdefaults]");
-        out.println("default_realm = " + REALM);
-        out.println("default_tkt_enctypes = " + encryptionType.getName());
-        out.println("default_tgs_enctypes = " + encryptionType.getName());
-        out.println("permitted_enctypes = " + encryptionType.getName());
-        out.println("default-checksum_type = " + checksumType.getName());
-        if (isTcp) {
-            out.println("udp_preference_limit = 1");
-        }
-        out.println("[realms]");
-        out.println(REALM + " = {");
-        out.println("kdc = " + HOSTNAME + ":" + kdcServer.getTransports()[0].getPort());
-        out.println("}");
-        out.println("[domain_realm]");
-        out.println("." + Strings.lowerCaseAscii(REALM) + " = " + REALM);
-        out.println(Strings.lowerCaseAscii(REALM) + " = " + REALM);
-        out.close();
-        return file.getAbsolutePath();
-    }
-
     private void createPrincipal(String rdn, String sn, String cn,
                                  String uid, String userPassword, String principalName) throws LdapException {
         Entry entry = new DefaultEntry();


[20/27] karaf git commit: Cleanup jdbc tests

Posted by cs...@apache.org.
Cleanup jdbc tests


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/c79e2ba2
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/c79e2ba2
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/c79e2ba2

Branch: refs/heads/model_features
Commit: c79e2ba2b30349f220d2d2affb1d1aed410042fb
Parents: fd74396
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 15:53:10 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 15:53:10 2017 +0200

----------------------------------------------------------------------
 .../karaf/jaas/modules/jdbc/JDBCUtils.java      |   4 +-
 .../jaas/modules/jdbc/JdbcLoginModuleTest.java  | 116 ++++++++-----------
 2 files changed, 52 insertions(+), 68 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/c79e2ba2/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/jdbc/JDBCUtils.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/jdbc/JDBCUtils.java b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/jdbc/JDBCUtils.java
index 4e1cda8..5be25b0 100644
--- a/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/jdbc/JDBCUtils.java
+++ b/jaas/modules/src/main/java/org/apache/karaf/jaas/modules/jdbc/JDBCUtils.java
@@ -75,9 +75,9 @@ public final class JDBCUtils {
             if (tokens.length > 1) {
                 filter = tokens[1];
             }
-            ServiceReference[] references = bc.getServiceReferences(clazz, filter);
+            ServiceReference<?>[] references = bc.getServiceReferences(clazz, filter);
             if (references != null) {
-                ServiceReference ref = references[0];
+                ServiceReference<?> ref = references[0];
                 Object ds = bc.getService(ref);
                 bc.ungetService(ref);
                 return ds;

http://git-wip-us.apache.org/repos/asf/karaf/blob/c79e2ba2/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/jdbc/JdbcLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/jdbc/JdbcLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/jdbc/JdbcLoginModuleTest.java
index cd960ed..66eebb6 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/jdbc/JdbcLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/jdbc/JdbcLoginModuleTest.java
@@ -24,7 +24,7 @@ import java.util.Map;
 import javax.security.auth.Subject;
 import javax.sql.DataSource;
 
-import org.apache.derby.jdbc.EmbeddedDataSource40;
+import org.apache.derby.jdbc.EmbeddedDataSource;
 import org.apache.karaf.jaas.boot.principal.GroupPrincipal;
 import org.apache.karaf.jaas.boot.principal.RolePrincipal;
 import org.apache.karaf.jaas.boot.principal.UserPrincipal;
@@ -42,54 +42,42 @@ import static org.junit.Assert.assertTrue;
 
 public class JdbcLoginModuleTest {
 
-    private EmbeddedDataSource40 dataSource;
+    private EmbeddedDataSource dataSource;
     private Map<String, Object> options;
 
+    @SuppressWarnings("unchecked")
     @Before
     public void setUp() throws Exception {
         System.setProperty("derby.stream.error.file", "target/derby.log");
 
         // Create datasource
-        dataSource = new EmbeddedDataSource40();
+        dataSource = new EmbeddedDataSource();
         dataSource.setDatabaseName("memory:db");
         dataSource.setCreateDatabase("create");
 
         // Delete tables
         try (Connection connection = dataSource.getConnection()) {
             connection.setAutoCommit(true);
-            try {
-                try (Statement statement = connection.createStatement()) {
+            try (Statement statement = connection.createStatement()) {
                     statement.execute("drop table USERS");
-                }
             } catch (SQLException e) {
                 // Ignore
             }
-            try {
-                try (Statement statement = connection.createStatement()) {
-                    statement.execute("drop table ROLES");
-                }
+            try (Statement statement = connection.createStatement()) {
+                statement.execute("drop table ROLES");
             } catch (SQLException e) {
                 // Ignore
             }
-            connection.commit();
-        }
-
-        // Create tables
-        try (Connection connection = dataSource.getConnection()) {
             try (Statement statement = connection.createStatement()) {
                 statement.execute("create table USERS (USERNAME VARCHAR(32) PRIMARY KEY, PASSWORD VARCHAR(32))");
-            }
-            try (Statement statement = connection.createStatement()) {
                 statement.execute("create table ROLES (USERNAME VARCHAR(32), ROLE VARCHAR(1024))");
             }
             connection.commit();
         }
 
-        // Mocks
         BundleContext context = EasyMock.createMock(BundleContext.class);
-        ServiceReference reference = EasyMock.createMock(ServiceReference.class);
+        ServiceReference<DataSource> reference = EasyMock.createMock(ServiceReference.class);
 
-        // Create options
         options = new HashMap<>();
         options.put(JDBCUtils.DATASOURCE, "osgi:" + DataSource.class.getName());
         options.put(BundleContext.class.getName(), context);
@@ -145,72 +133,68 @@ public class JdbcLoginModuleTest {
 
     @Test
     public void testEngine() throws Exception {
-        JDBCBackingEngine engine = new JDBCBackingEngine(dataSource);
+        UserPrincipal user = new UserPrincipal("abc");
+        GroupPrincipal group1 = new GroupPrincipal("group1");
+        RolePrincipal role1 = new RolePrincipal("role1");
+        RolePrincipal role2 = new RolePrincipal("role2");
+        RolePrincipal role3 = new RolePrincipal("role3");
 
+        JDBCBackingEngine engine = new JDBCBackingEngine(dataSource);
         assertTrue(engine.listUsers().isEmpty());
 
         engine.addUser("abc", "xyz");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).isEmpty());
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).isEmpty());
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).isEmpty());
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).isEmpty());
+        assertTrue(engine.listRoles(group1).isEmpty());
+        assertTrue(engine.listGroups(user).isEmpty());
 
         engine.addRole("abc", "role1");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).contains(new RolePrincipal("role1")));
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).isEmpty());
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).isEmpty());
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).contains(role1));
+        assertTrue(engine.listRoles(group1).isEmpty());
+        assertTrue(engine.listGroups(user).isEmpty());
 
         engine.addGroupRole("group1", "role2");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).contains(new RolePrincipal("role1")));
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).contains(new RolePrincipal("role2")));
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).isEmpty());
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).contains(role1));
+        assertTrue(engine.listRoles(group1).contains(role2));
+        assertTrue(engine.listGroups(user).isEmpty());
 
         engine.addGroup("abc", "group1");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).contains(new RolePrincipal("role1")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).contains(new RolePrincipal("role2")));
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).contains(new RolePrincipal("role2")));
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).contains(new GroupPrincipal("group1")));
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).contains(role1));
+        assertTrue(engine.listRoles(user).contains(role2));
+        assertTrue(engine.listRoles(group1).contains(role2));
+        assertTrue(engine.listGroups(user).contains(group1));
 
         engine.deleteRole("abc", "role1");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).contains(new RolePrincipal("role2")));
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).contains(new RolePrincipal("role2")));
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).contains(new GroupPrincipal("group1")));
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).contains(role2));
+        assertTrue(engine.listRoles(group1).contains(role2));
+        assertTrue(engine.listGroups(user).contains(group1));
 
         engine.deleteGroupRole("group1", "role2");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).isEmpty());
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).isEmpty());
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).contains(new GroupPrincipal("group1")));
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).isEmpty());
+        assertTrue(engine.listRoles(group1).isEmpty());
+        assertTrue(engine.listGroups(user).contains(group1));
 
         engine.addGroupRole("group1", "role3");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).contains(new RolePrincipal("role3")));
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).contains(new RolePrincipal("role3")));
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).contains(new GroupPrincipal("group1")));
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).contains(role3));
+        assertTrue(engine.listRoles(group1).contains(role3));
+        assertTrue(engine.listGroups(user).contains(group1));
 
         engine.deleteGroup("abc", "group1");
-
-        assertTrue(engine.listUsers().contains(new UserPrincipal("abc")));
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).isEmpty());
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).isEmpty());
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).isEmpty());
+        assertTrue(engine.listUsers().contains(user));
+        assertTrue(engine.listRoles(user).isEmpty());
+        assertTrue(engine.listRoles(group1).isEmpty());
+        assertTrue(engine.listGroups(user).isEmpty());
 
         engine.deleteUser("abc");
-
         assertTrue(engine.listUsers().isEmpty());
-        assertTrue(engine.listRoles(new UserPrincipal("abc")).isEmpty());
-        assertTrue(engine.listRoles(new GroupPrincipal("group1")).isEmpty());
-        assertTrue(engine.listGroups(new UserPrincipal("abc")).isEmpty());
+        assertTrue(engine.listRoles(user).isEmpty());
+        assertTrue(engine.listRoles(group1).isEmpty());
+        assertTrue(engine.listGroups(user).isEmpty());
     }
 }


[19/27] karaf git commit: Avoid using commons io. Allow to specify replacement function

Posted by cs...@apache.org.
Avoid using commons io. Allow to specify replacement function


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/fd743966
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/fd743966
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/fd743966

Branch: refs/heads/model_features
Commit: fd74396648a0bb42ba2d01c5bed1c6c7bbef1694
Parents: 0853a35
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 14:16:53 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 14:16:53 2017 +0200

----------------------------------------------------------------------
 jaas/modules/pom.xml                            |  5 ---
 .../modules/ldap/GSSAPILdapLoginModuleTest.java | 35 ++++----------------
 .../karaf/jaas/modules/ldap/LdapCacheTest.java  |  4 ++-
 .../modules/ldap/LdapCaseInsensitiveDNTest.java |  4 ++-
 .../jaas/modules/ldap/LdapLoginModuleTest.java  |  9 +++--
 .../ldap/LdapLoginModuleWithEscapesTest.java    |  5 ++-
 .../jaas/modules/ldap/LdapPropsUpdater.java     | 35 ++++++++------------
 .../ldap/LdapSpecialCharsInPasswordTest.java    |  5 ++-
 8 files changed, 40 insertions(+), 62 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/pom.xml
----------------------------------------------------------------------
diff --git a/jaas/modules/pom.xml b/jaas/modules/pom.xml
index b6be3d8..8038102 100644
--- a/jaas/modules/pom.xml
+++ b/jaas/modules/pom.xml
@@ -91,11 +91,6 @@
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>commons-io</groupId>
-            <artifactId>commons-io</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
             <groupId>org.apache.directory.server</groupId>
             <artifactId>apacheds-core-integ</artifactId>
             <version>${directory-version}</version>

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
index b664bc3..9d049d8 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
@@ -14,13 +14,12 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
+import static org.apache.karaf.jaas.modules.ldap.LdapPropsUpdater.ldapProps;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.security.Principal;
 import java.util.Collections;
@@ -30,7 +29,6 @@ import javax.security.auth.kerberos.KerberosPrincipal;
 import javax.security.auth.kerberos.KerberosTicket;
 import javax.security.auth.login.LoginException;
 
-import org.apache.commons.io.IOUtils;
 import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
 import org.apache.directory.api.ldap.model.entry.DefaultEntry;
 import org.apache.directory.api.ldap.model.entry.Entry;
@@ -131,8 +129,6 @@ import org.junit.runner.RunWith;
 })
 public class GSSAPILdapLoginModuleTest extends KarafKerberosITest {
 
-    private static boolean loginConfigUpdated;
-
     @Before
     public void setUp() throws Exception {
         super.setUp();
@@ -153,32 +149,13 @@ public class GSSAPILdapLoginModuleTest extends KarafKerberosITest {
 
         System.setProperty("java.security.auth.login.config", config.toString());
 
-        updatePort();
+        ldapProps("org/apache/karaf/jaas/modules/ldap/gssapi.ldap.properties",
+                  GSSAPILdapLoginModuleTest::replacePortAndAddress);
     }
 
-    public void updatePort() throws Exception {
-        if (!loginConfigUpdated) {
-            String basedir = System.getProperty("basedir");
-            if (basedir == null) {
-                basedir = new File(".").getCanonicalPath();
-            }
-
-            // Read in ldap.properties and substitute in the correct port
-            File f = new File(basedir + "/src/test/resources/org/apache/karaf/jaas/modules/ldap/gssapi.ldap.properties");
-
-            FileInputStream inputStream = new FileInputStream(f);
-            String content = IOUtils.toString(inputStream, "UTF-8");
-            inputStream.close();
-            content = content.replaceAll("portno", "" + getLdapServer().getPort());
-            content = content.replaceAll("address", KerberosTestUtils.getHostName());
-
-            File f2 = new File(basedir + "/target/test-classes/org/apache/karaf/jaas/modules/ldap/gssapi.ldap.properties");
-            FileOutputStream outputStream = new FileOutputStream(f2);
-            IOUtils.write(content, outputStream, "UTF-8");
-            outputStream.close();
-            loginConfigUpdated = true;
-        }
-
+    public static String replacePortAndAddress(String line) {
+        return line.replaceAll("portno", "" + getLdapServer().getPort())
+            .replaceAll("address", KerberosTestUtils.getHostName());
     }
 
     @After

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
index b9d252d..b018545 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
@@ -16,6 +16,7 @@
 package org.apache.karaf.jaas.modules.ldap;
 
 import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.apache.karaf.jaas.modules.ldap.LdapPropsUpdater.ldapProps;
 import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
@@ -60,7 +61,8 @@ public class LdapCacheTest extends AbstractLdapTestUnit {
 
     @Before
     public void updatePort() throws Exception {
-        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap.properties", getLdapServer().getPort());
+        ldapProps("org/apache/karaf/jaas/modules/ldap/ldap.properties", 
+                  LdapLoginModuleTest::replacePort);
     }
 
     @After

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
index 8e3a56e..85ebb1d 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
@@ -16,6 +16,7 @@
 package org.apache.karaf.jaas.modules.ldap;
 
 import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.apache.karaf.jaas.modules.ldap.LdapPropsUpdater.ldapProps;
 import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
@@ -52,7 +53,8 @@ public class LdapCaseInsensitiveDNTest extends LdapLoginModuleTest {
     @Before
     @Override
     public void updatePort() throws Exception {
-        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldapCaseInsensitiveDN.properties", getLdapServer().getPort());
+        ldapProps("org/apache/karaf/jaas/modules/ldap/ldapCaseInsensitiveDN.properties", 
+                  LdapLoginModuleTest::replacePort);
     }
     
     @Test

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
index 847dcf3..f164672 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
@@ -43,6 +43,7 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.apache.karaf.jaas.modules.ldap.LdapPropsUpdater.ldapProps;
 import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
@@ -58,10 +59,14 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
 
     @Before
     public void updatePort() throws Exception {
-        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap.properties", getLdapServer().getPort());
+        ldapProps("org/apache/karaf/jaas/modules/ldap/ldap.properties",
+                                   LdapLoginModuleTest::replacePort);
     }
 
-            
+    public static String replacePort(String line) {
+        return line.replaceAll("portno", "" + getLdapServer().getPort());
+    }
+    
     @After
     public void tearDown() {
         LDAPCache.clear();

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
index c05a39a..eb6f35a 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
@@ -15,6 +15,8 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
+import static org.apache.karaf.jaas.modules.ldap.LdapPropsUpdater.ldapProps;
+
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
 import org.apache.directory.server.core.annotations.ApplyLdifFiles;
@@ -36,6 +38,7 @@ public class LdapLoginModuleWithEscapesTest extends LdapLoginModuleTest {
     @Before
     @Override
     public void updatePort() throws Exception {
-        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap.properties", getLdapServer().getPort());
+        ldapProps("org/apache/karaf/jaas/modules/ldap/ldap.properties", 
+                  LdapLoginModuleTest::replacePort);
     }
 }

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
index 54c4a90..8bf9059 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
@@ -16,39 +16,30 @@
 package org.apache.karaf.jaas.modules.ldap;
 
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
 import java.io.IOException;
-
-import org.apache.commons.io.IOUtils;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 
 public class LdapPropsUpdater {
 
     private LdapPropsUpdater() {
     }
 
-    public static void updatePort(String propsPath, int port) throws IOException {
+    public static void ldapProps(String propsPath, Function<String, String> mapFunction) throws IOException {
         String basedir = System.getProperty("basedir");
         if (basedir == null) {
             basedir = new File(".").getCanonicalPath();
         }
-
-        // Read in ldap.properties and substitute in the correct port
-        String content = readProperties(basedir + "/src/test/resources/" + propsPath);
-        content = content.replaceAll("portno", "" + port);
-        writeProperties(basedir + "/target/test-classes/" + propsPath, content);
-    }
-    
-    private static String readProperties(String path) throws FileNotFoundException, IOException {
-        try (FileInputStream inputStream = new FileInputStream(new File(path))) {;
-            return IOUtils.toString(inputStream, "UTF-8");
-        }
+        Path inPath = new File(basedir + "/src/test/resources/" + propsPath).toPath();
+        List<String> lines = Files.lines(inPath, Charset.forName("UTF-8"))
+            .map(mapFunction)
+            .collect(Collectors.toList());
+        Path outPath = new File(basedir + "/target/test-classes/" + propsPath).toPath();
+        Files.write(outPath, lines, Charset.forName("UTF-8"));
     }
 
-    private static void writeProperties(String path, String content) throws FileNotFoundException, IOException {
-        try (FileOutputStream outputStream = new FileOutputStream(new File(path))) {
-            IOUtils.write(content, outputStream, "UTF-8");
-        }
-    }
 }

http://git-wip-us.apache.org/repos/asf/karaf/blob/fd743966/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
index f188cc2..38bc391 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
@@ -15,6 +15,8 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
+import static org.apache.karaf.jaas.modules.ldap.LdapPropsUpdater.ldapProps;
+
 import java.io.File;
 import java.io.IOException;
 
@@ -49,7 +51,8 @@ public class LdapSpecialCharsInPasswordTest extends LdapLoginModuleTest {
     @Before
     @Override
     public void updatePort() throws Exception {
-        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap_special_char_in_password.properties", getLdapServer().getPort());
+        ldapProps("org/apache/karaf/jaas/modules/ldap/ldap_special_char_in_password.properties", 
+                  LdapLoginModuleTest::replacePort);
     }
 
     protected Properties ldapLoginModuleOptions() throws IOException {


[23/27] karaf git commit: [KARAF-5312]bin/stop script output some unwanted message on mac

Posted by cs...@apache.org.
[KARAF-5312]bin/stop script output some unwanted message on mac


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/8f94e291
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/8f94e291
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/8f94e291

Branch: refs/heads/model_features
Commit: 8f94e291dc24291e28a1e5eefbdd7ec28ce56ffe
Parents: b57bcea
Author: Freeman Fang <fr...@gmail.com>
Authored: Thu Aug 17 13:10:43 2017 +0800
Committer: Freeman Fang <fr...@gmail.com>
Committed: Thu Aug 17 13:10:43 2017 +0800

----------------------------------------------------------------------
 .../features/base/src/main/filtered-resources/resources/bin/karaf  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/8f94e291/assemblies/features/base/src/main/filtered-resources/resources/bin/karaf
----------------------------------------------------------------------
diff --git a/assemblies/features/base/src/main/filtered-resources/resources/bin/karaf b/assemblies/features/base/src/main/filtered-resources/resources/bin/karaf
index 048b344..674b8d0 100644
--- a/assemblies/features/base/src/main/filtered-resources/resources/bin/karaf
+++ b/assemblies/features/base/src/main/filtered-resources/resources/bin/karaf
@@ -92,7 +92,7 @@ checkRootInstance() {
           if ps -p "${ROOT_INSTANCE_PID}" > /dev/null
           then
               MAIN=org.apache.karaf.main.Main
-              PID_COMMAND=$(ps -p "${ROOT_INSTANCE_PID}" o args | sed 1d)
+              PID_COMMAND=$(ps -p "${ROOT_INSTANCE_PID}" -o args | sed 1d)
               if [ "${PID_COMMAND#*$MAIN}" != "$PID_COMMAND" ]; then
                 ROOT_INSTANCE_RUNNING=true
               fi


[09/27] karaf git commit: Refactor GenerateServiceMetadata

Posted by cs...@apache.org.
Refactor GenerateServiceMetadata


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/011c9b04
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/011c9b04
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/011c9b04

Branch: refs/heads/model_features
Commit: 011c9b048f6ae16271be6154e6d547ad288e70fc
Parents: fcf9b7c
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 17:47:32 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 17:47:32 2017 +0200

----------------------------------------------------------------------
 .../tracker/GenerateServiceMetadata.java        | 74 +++++++++-----------
 1 file changed, 33 insertions(+), 41 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/011c9b04/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
----------------------------------------------------------------------
diff --git a/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java b/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
index ba4fac1..2d44bfd 100644
--- a/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
+++ b/tooling/karaf-services-maven-plugin/src/main/java/org/apache/karaf/tooling/tracker/GenerateServiceMetadata.java
@@ -17,6 +17,7 @@
 package org.apache.karaf.tooling.tracker;
 
 import java.io.File;
+import java.io.IOException;
 import java.io.OutputStream;
 import java.net.URL;
 import java.net.URLClassLoader;
@@ -84,8 +85,8 @@ public class GenerateServiceMetadata extends AbstractMojo {
         try {
             boolean addSourceDirectory = false;
 
-            StringBuilder requirements = new StringBuilder();
-            StringBuilder capabilities = new StringBuilder();
+            List<String> requirements = new ArrayList<>();
+            List<String> capabilities = new ArrayList<>();
 
             ClassFinder finder = createFinder(classLoader);
             List<Class<?>> classes = finder.findAnnotatedClasses(Services.class);
@@ -103,28 +104,18 @@ public class GenerateServiceMetadata extends AbstractMojo {
                     activators.add(clazz);
                 }
 
-                Properties props = new Properties();
+                writeServiceProperties(clazz);
+
                 Services services = clazz.getAnnotation(Services.class);
                 if (services != null) {
                     for (RequireService req : services.requires()) {
-                        String fltWithClass = combine(req.filter(), "(objectClass=" + req.value().getName() + ")");
-                        addServiceReq(requirements, fltWithClass);
-                        props.setProperty(req.value().getName(), req.filter());
+                        requirements.add(getRequirement(req));
                     }
                     for (ProvideService cap : services.provides()) {
-                        addServiceCap(capabilities, cap);
+                        capabilities.add(getCapability(cap));
                     }
                 }
-                Managed managed = clazz.getAnnotation(Managed.class);
-                if (managed != null) {
-                    props.setProperty("pid", managed.value());
-                }
-
-                File file = new File(outputDirectory, "OSGI-INF/karaf-tracker/" + clazz.getName());
-                file.getParentFile().mkdirs();
-                try (OutputStream os = buildContext.newFileOutputStream(file)) {
-                    props.store(os, null);
-                }
+                
                 addSourceDirectory = true;
             }
 
@@ -134,8 +125,8 @@ public class GenerateServiceMetadata extends AbstractMojo {
                 project.addResource(resource);
             }
 
-            project.getProperties().setProperty(requirementsProperty, requirements.toString());
-            project.getProperties().setProperty(capabilitiesProperty, capabilities.toString());
+            project.getProperties().setProperty(requirementsProperty, String.join(",", requirements));
+            project.getProperties().setProperty(capabilitiesProperty, String.join(",", capabilities));
             if (activators.size() == 1) {
                 project.getProperties().setProperty(activatorProperty, activators.get(0).getName());
             }
@@ -148,7 +139,7 @@ public class GenerateServiceMetadata extends AbstractMojo {
                 packages.add(clazz.getPackage().getName());
             }
             if (!packages.isEmpty()) {
-                project.getProperties().setProperty("BNDExtension-Karaf-Commands", join(packages, ","));
+                project.getProperties().setProperty("BNDExtension-Karaf-Commands", String.join(",", packages));
             }
 
         } catch (Exception e) {
@@ -156,32 +147,33 @@ public class GenerateServiceMetadata extends AbstractMojo {
         }
     }
 
-    private String join(Set<String> packages, String separator) {
-        StringBuilder sb = new StringBuilder();
-        for (String pkg : packages) {
-            if (sb.length() > 0) {
-                sb.append(separator);
-            }
-            sb.append(pkg);
-        }
-        return sb.toString();
+    private String getRequirement(RequireService req) {
+        String fltWithClass = combine(req.filter(), "(objectClass=" + req.value().getName() + ")");
+        return "osgi.service;effective:=active;filter:=\"" + fltWithClass + "\"";
+    }
+    
+    private String getCapability(ProvideService cap) {
+        return "osgi.service;effective:=active;objectClass=" + cap.value().getName();
     }
 
-    private void addServiceCap(StringBuilder capabilities, ProvideService cap) {
-        if (capabilities.length() > 0) {
-            capabilities.append(",");
+    private void writeServiceProperties(Class<?> serviceClazz) throws IOException {
+        Properties props = new Properties();
+        Services services = serviceClazz.getAnnotation(Services.class);
+        if (services != null) {
+            for (RequireService req : services.requires()) {
+                props.setProperty(req.value().getName(), req.filter());
+            }
+        }
+        Managed managed = serviceClazz.getAnnotation(Managed.class);
+        if (managed != null) {
+            props.setProperty("pid", managed.value());
         }
-        capabilities.append("osgi.service;effective:=active;objectClass=")
-                    .append(cap.value().getName());
-    }
 
-    private void addServiceReq(StringBuilder requirements, String fltWithClass) {
-        if (requirements.length() > 0) {
-            requirements.append(",");
+        File file = new File(outputDirectory, "OSGI-INF/karaf-tracker/" + serviceClazz.getName());
+        file.getParentFile().mkdirs();
+        try (OutputStream os = buildContext.newFileOutputStream(file)) {
+            props.store(os, null);
         }
-        requirements.append("osgi.service;effective:=active;filter:=\"")
-                    .append(fltWithClass)
-                    .append("\"");
     }
 
     private String combine(String filter1, String filter2) {


[15/27] karaf git commit: Replace deprecated call

Posted by cs...@apache.org.
Replace deprecated call


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/71b136ed
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/71b136ed
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/71b136ed

Branch: refs/heads/model_features
Commit: 71b136ed8307f6470e32874dfed627844c9fc666
Parents: 6aa806d
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 11:44:38 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 11:44:38 2017 +0200

----------------------------------------------------------------------
 .../apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/71b136ed/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
index 47ea240..b0152f1 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/GSSAPILdapLoginModuleTest.java
@@ -61,6 +61,7 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.nio.charset.Charset;
 import java.security.Principal;
 import java.util.Collections;
 
@@ -342,7 +343,7 @@ public class GSSAPILdapLoginModuleTest extends AbstractKerberosITest {
         data += "." + Strings.lowerCaseAscii(REALM) + " = " + REALM + SystemUtils.LINE_SEPARATOR;
         data += Strings.lowerCaseAscii(REALM) + " = " + REALM + SystemUtils.LINE_SEPARATOR;
 
-        FileUtils.writeStringToFile(file, data);
+        FileUtils.writeStringToFile(file, data, Charset.defaultCharset());
 
         return file.getAbsolutePath();
     }


[13/27] karaf git commit: Refactor test

Posted by cs...@apache.org.
Refactor test


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/01d0aae9
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/01d0aae9
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/01d0aae9

Branch: refs/heads/model_features
Commit: 01d0aae9b62531919f00d96eb22119bf59d0209b
Parents: 713d25d
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 11:12:46 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 11:12:46 2017 +0200

----------------------------------------------------------------------
 jaas/modules/pom.xml                            |   6 +
 .../karaf/jaas/modules/PrincipalAssert.java     |  40 +++
 .../properties/PropertiesBackingEngineTest.java | 266 +++++++------------
 .../properties/PropertiesLoginModuleTest.java   |  42 +--
 4 files changed, 146 insertions(+), 208 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/01d0aae9/jaas/modules/pom.xml
----------------------------------------------------------------------
diff --git a/jaas/modules/pom.xml b/jaas/modules/pom.xml
index 8313005..b6be3d8 100644
--- a/jaas/modules/pom.xml
+++ b/jaas/modules/pom.xml
@@ -120,6 +120,12 @@
             <version>${derby-version}</version>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.hamcrest</groupId>
+            <artifactId>hamcrest-all</artifactId>
+            <version>1.3</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>

http://git-wip-us.apache.org/repos/asf/karaf/blob/01d0aae9/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java
new file mode 100644
index 0000000..c19fd2b
--- /dev/null
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/PrincipalAssert.java
@@ -0,0 +1,40 @@
+/*
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *  under the License.
+ */
+package org.apache.karaf.jaas.modules;
+
+import static java.util.stream.Collectors.toList;
+
+import java.security.Principal;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import javax.security.auth.Subject;
+
+import org.junit.Assert;
+
+public class PrincipalAssert {
+    
+    public static List<String> names(List<? extends Principal> principals) {
+        return principals.stream().map(r->r.getName()).collect(toList());
+    }
+    
+    public static void assertPrincipalNamed(Subject subject, Class<? extends Principal> clazz, String expectedName) {
+        Long numMatching = subject.getPrincipals(clazz).stream()
+            .filter(pr -> expectedName.equals(pr.getName()))
+            .collect(Collectors.counting());
+        Assert.assertEquals("Expected " + clazz.getSimpleName() + " principal in subject with name=" + expectedName, 
+                            1l, numMatching.intValue());
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/01d0aae9/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
index b781cd1..0c811da 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesBackingEngineTest.java
@@ -16,188 +16,104 @@
  */
 package org.apache.karaf.jaas.modules.properties;
 
-import junit.framework.TestCase;
+import static org.apache.karaf.jaas.modules.PrincipalAssert.names;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+
 import org.apache.felix.utils.properties.Properties;
 import org.apache.karaf.jaas.boot.principal.GroupPrincipal;
-import org.apache.karaf.jaas.boot.principal.RolePrincipal;
 import org.apache.karaf.jaas.boot.principal.UserPrincipal;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
 
-import java.io.File;
-import java.io.IOException;
+public class PropertiesBackingEngineTest {
+    private File f;
 
-public class PropertiesBackingEngineTest extends TestCase {
+    @Before
+    public void start() throws IOException {
+        f = File.createTempFile(getClass().getName(), ".tmp");
+    }
 
+    @Test
     public void testUserRoles() throws IOException {
-        File f = File.createTempFile(getClass().getName(), ".tmp");
-        try {
-            Properties p = new Properties(f);
-
-            PropertiesBackingEngine engine = new PropertiesBackingEngine(p);
-            engine.addUser("a", "aa");
-            assertEquals(1, engine.listUsers().size());
-            UserPrincipal upa = engine.listUsers().iterator().next();
-            assertEquals("a", upa.getName());
-            engine.addUser("b", "bb");
-
-            engine.addRole("a", "role1");
-            engine.addRole("a", "role2");
-            assertEquals(2, engine.listRoles(upa).size());
-
-            boolean foundR1 = false;
-            boolean foundR2 = false;
-            for (RolePrincipal rp : engine.listRoles(upa)) {
-                if ("role1".equals(rp.getName())) {
-                    foundR1 = true;
-                } else if ("role2".equals(rp.getName())) {
-                    foundR2 = true;
-                }
-            }
-            assertTrue(foundR1);
-            assertTrue(foundR2);
-
-            engine.addGroup("a", "g");
-            engine.addGroupRole("g", "role2");
-            engine.addGroupRole("g", "role3");
-            engine.addGroup("b", "g");
-            engine.addGroup("b", "g2");
-            engine.addGroupRole("g2", "role4");
-
-            assertEquals(2, engine.listUsers().size());
-            UserPrincipal upa_1 = null;
-            UserPrincipal upb_1 = null;
-            for (UserPrincipal u : engine.listUsers()) {
-                if ("a".equals(u.getName())) {
-                    upa_1 = u;
-                } else if ("b".equals(u.getName())) {
-                    upb_1 = u;
-                }
-            }
-            assertNotNull(upa_1);
-            assertNotNull(upb_1);
-
-            assertEquals(3, engine.listRoles(upa).size());
-            boolean foundR1_2 = false;
-            boolean foundR2_2 = false;
-            boolean foundR3_2 = false;
-            for (RolePrincipal rp : engine.listRoles(upa)) {
-                if ("role1".equals(rp.getName())) {
-                    foundR1_2 = true;
-                } else if ("role2".equals(rp.getName())) {
-                    foundR2_2 = true;
-                } else if ("role3".equals(rp.getName())) {
-                    foundR3_2 = true;
-                }
-            }
-            assertTrue(foundR1_2);
-            assertTrue(foundR2_2);
-            assertTrue(foundR3_2);
-
-            // check that the loading works
-            PropertiesBackingEngine engine2 = new PropertiesBackingEngine(new Properties(f));
-            assertEquals(2, engine2.listUsers().size());
-            UserPrincipal upa_2 = null;
-            UserPrincipal upb_2 = null;
-            for (UserPrincipal u : engine2.listUsers()) {
-                if ("a".equals(u.getName())) {
-                    upa_2 = u;
-                } else if ("b".equals(u.getName())) {
-                    upb_2 = u;
-                }
-            }
-            assertNotNull(upa_2);
-            assertNotNull(upb_2);
-
-            assertEquals(3, engine2.listRoles(upa_2).size());
-            boolean foundR1_3 = false;
-            boolean foundR2_3 = false;
-            boolean foundR3_3 = false;
-            for (RolePrincipal rp : engine2.listRoles(upa_2)) {
-                if ("role1".equals(rp.getName())) {
-                    foundR1_3 = true;
-                } else if ("role2".equals(rp.getName())) {
-                    foundR2_3 = true;
-                } else if ("role3".equals(rp.getName())) {
-                    foundR3_3 = true;
-                }
-            }
-            assertTrue(foundR1_3);
-            assertTrue(foundR2_3);
-            assertTrue(foundR3_3);
-
-            assertEquals(3, engine2.listRoles(upb_2).size());
-            boolean foundR2_4 = false;
-            boolean foundR3_4 = false;
-            boolean foundR4_4 = false;
-            for (RolePrincipal rp : engine2.listRoles(upb_2)) {
-                if ("role2".equals(rp.getName())) {
-                    foundR2_4 = true;
-                } else if ("role3".equals(rp.getName())) {
-                    foundR3_4 = true;
-                } else if ("role4".equals(rp.getName())) {
-                    foundR4_4 = true;
-                }
-            }
-            assertTrue(foundR2_4);
-            assertTrue(foundR3_4);
-            assertTrue(foundR4_4);
-
-            // removing some stuff
-            UserPrincipal upb = null;
-            for (UserPrincipal up : engine.listUsers()) {
-                if ("b".equals(up.getName())) {
-                    upb = up;
-                }
-            }
-            assertEquals(1, engine.listGroups(upa).size());
-            assertEquals(2, engine.listGroups(upb).size());
-
-            GroupPrincipal gp = engine.listGroups(upa).iterator().next();
-            engine.deleteGroupRole("g", "role2");
-            assertEquals(1, engine.listRoles(gp).size());
-            assertEquals("role3", engine.listRoles(gp).iterator().next().getName());
-
-            // check that the user roles are reported correctly
-            assertEquals("role2 should still be there as it was added to the user directly too", 3, engine.listRoles(upa).size());
-            boolean foundR1_5 = false;
-            boolean foundR2_5 = false;
-            boolean foundR3_5 = false;
-            for (RolePrincipal rp : engine.listRoles(upa)) {
-                if ("role1".equals(rp.getName())) {
-                    foundR1_5 = true;
-                } else if ("role2".equals(rp.getName())) {
-                    foundR2_5 = true;
-                } else if ("role3".equals(rp.getName())) {
-                    foundR3_5 = true;
-                }
-            }
-            assertTrue(foundR1_5);
-            assertTrue(foundR2_5);
-            assertTrue(foundR3_5);
-
-            assertEquals(2, engine.listRoles(upb).size());
-            boolean foundR3_6 = false;
-            boolean foundR4_6 = false;
-            for (RolePrincipal rp : engine.listRoles(upb)) {
-                if ("role3".equals(rp.getName())) {
-                    foundR3_6 = true;
-                } else if ("role4".equals(rp.getName())) {
-                    foundR4_6 = true;
-                }
-            }
-            assertTrue(foundR3_6);
-            assertTrue(foundR4_6);
-
-            engine.deleteGroup("b", "g");
-            engine.deleteGroup("b", "g2");
-            assertEquals(0, engine.listRoles(upb).size());
-
-            engine.deleteUser("b");
-            engine.deleteUser("a");
-            assertEquals("Properties should be empty now", 0, p.size());
-        } finally {
-            if (!f.delete()) {
-                fail("Could not delete temporary file: " + f);
-            }
+        Properties p = new Properties(f);
+
+        PropertiesBackingEngine engine = new PropertiesBackingEngine(p);
+        engine.addUser("a", "aa");
+        engine.addUser("b", "bb");
+
+        engine.addRole("a", "role1");
+        engine.addRole("a", "role2");
+        
+        UserPrincipal upa = getUser(engine, "a");
+        Assert.assertThat(names(engine.listRoles(upa)), containsInAnyOrder("role1", "role2"));
+
+        engine.addGroup("a", "g");
+        engine.addGroupRole("g", "role2");
+        engine.addGroupRole("g", "role3");
+        engine.addGroup("b", "g");
+        engine.addGroup("b", "g2");
+        engine.addGroupRole("g2", "role4");
+
+        Assert.assertThat(names(engine.listUsers()), containsInAnyOrder("a", "b"));
+        Assert.assertThat(names(engine.listRoles(upa)), containsInAnyOrder("role1", "role2", "role3"));
+
+        checkLoading();
+
+        // removing some stuff
+        UserPrincipal upb = getUser(engine, "b");
+        assertEquals(1, engine.listGroups(upa).size());
+        assertEquals(2, engine.listGroups(upb).size());
+
+        GroupPrincipal gp = engine.listGroups(upa).iterator().next();
+        engine.deleteGroupRole("g", "role2");
+        Assert.assertThat(names(engine.listRoles(gp)), containsInAnyOrder("role3"));
+
+        // role2 should still be there as it was added to the user directly too
+        Assert.assertThat(names(engine.listRoles(upa)), containsInAnyOrder("role1", "role2", "role3"));
+        Assert.assertThat(names(engine.listRoles(upb)), containsInAnyOrder("role3", "role4"));
+
+        engine.deleteGroup("b", "g");
+        engine.deleteGroup("b", "g2");
+        assertEquals(0, engine.listRoles(upb).size());
+
+        engine.deleteUser("b");
+        engine.deleteUser("a");
+        assertEquals("Properties should be empty now", 0, p.size());
+    }
+
+    private void checkLoading() throws IOException {
+        PropertiesBackingEngine engine = new PropertiesBackingEngine(new Properties(f));
+        assertEquals(2, engine.listUsers().size());
+        UserPrincipal upa_2 = getUser(engine, "a");
+        UserPrincipal upb_2 = getUser(engine, "b");
+ 
+        assertEquals(3, engine.listRoles(upa_2).size());
+        Assert.assertThat(names(engine.listRoles(upa_2)), containsInAnyOrder("role1", "role2", "role3"));
+
+        assertEquals(3, engine.listRoles(upb_2).size());
+        Assert.assertThat(names(engine.listRoles(upb_2)), containsInAnyOrder("role2", "role3", "role4"));
+    }
+    
+    private UserPrincipal getUser(PropertiesBackingEngine engine, String name) {
+        List<UserPrincipal> matchingUsers = engine.listUsers().stream()
+            .filter(user->name.equals(user.getName())).collect(Collectors.toList());
+        Assert.assertFalse("User with name " + name + " was not found", matchingUsers.isEmpty());
+        return matchingUsers.iterator().next();
+    }
+
+    @After
+    public void cleanup() {
+        if (!f.delete()) {
+            fail("Could not delete temporary file: " + f);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/karaf/blob/01d0aae9/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
index 5d69d20..26d90a7 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/properties/PropertiesLoginModuleTest.java
@@ -16,14 +16,16 @@
  */
 package org.apache.karaf.jaas.modules.properties;
 
+import static org.apache.karaf.jaas.modules.PrincipalAssert.assertPrincipalNamed;
+
 import java.io.File;
 import java.io.IOException;
-import java.security.Principal;
 import java.util.HashMap;
 import java.util.Map;
 
 import javax.security.auth.Subject;
-import javax.security.auth.callback.*;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
 import javax.security.auth.login.FailedLoginException;
 import javax.security.auth.login.LoginException;
 
@@ -59,19 +61,8 @@ public class PropertiesLoginModuleTest {
 
             Assert.assertEquals(2, subject.getPrincipals().size());
 
-            boolean foundUser = false;
-            boolean foundRole = false;
-            for (Principal pr : subject.getPrincipals()) {
-                if (pr instanceof UserPrincipal) {
-                    Assert.assertEquals("abc", pr.getName());
-                    foundUser = true;
-                } else if (pr instanceof RolePrincipal) {
-                    Assert.assertEquals("myrole", pr.getName());
-                    foundRole = true;
-                }
-            }
-            Assert.assertTrue(foundUser);
-            Assert.assertTrue(foundRole);
+            assertPrincipalNamed(subject, UserPrincipal.class, "abc");
+            assertPrincipalNamed(subject, RolePrincipal.class, "myrole");
 
             Assert.assertTrue(module.logout());
             Assert.assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -131,24 +122,9 @@ public class PropertiesLoginModuleTest {
             Assert.assertTrue(module.commit());
 
             Assert.assertEquals(3, subject.getPrincipals().size());
-            boolean foundUser = false;
-            boolean foundRole = false;
-            boolean foundGroup = false;
-            for (Principal pr : subject.getPrincipals()) {
-                if (pr instanceof UserPrincipal) {
-                    Assert.assertEquals("pqr", pr.getName());
-                    foundUser = true;
-                } else if (pr instanceof GroupPrincipal) {
-                    Assert.assertEquals("group1", pr.getName());
-                    foundGroup = true;
-                } else if (pr instanceof RolePrincipal) {
-                    Assert.assertEquals("r1", pr.getName());
-                    foundRole = true;
-                }
-            }
-            Assert.assertTrue(foundUser);
-            Assert.assertTrue(foundGroup);
-            Assert.assertTrue(foundRole);
+            assertPrincipalNamed(subject, UserPrincipal.class, "pqr");
+            assertPrincipalNamed(subject, GroupPrincipal.class, "group1");
+            assertPrincipalNamed(subject, RolePrincipal.class, "r1");
         } finally {
             if (!f.delete()) {
                 Assert.fail("Could not delete temporary file: " + f);


[04/27] karaf git commit: Extract methods

Posted by cs...@apache.org.
Extract methods


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/5b4da2cd
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/5b4da2cd
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/5b4da2cd

Branch: refs/heads/model_features
Commit: 5b4da2cd85b527b335d59ff4fc2ec686ee913558
Parents: 5497403
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 16:05:13 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 16:05:13 2017 +0200

----------------------------------------------------------------------
 .../jaas/modules/ldap/LdapLoginModuleTest.java  | 24 ++++++++++++--------
 1 file changed, 15 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/5b4da2cd/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
index ea29eef..186bdb2 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
@@ -38,6 +38,7 @@ import javax.security.auth.login.LoginException;
 
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.security.Principal;
@@ -59,6 +60,7 @@ import static org.junit.Assert.fail;
 )
 public class LdapLoginModuleTest extends AbstractLdapTestUnit {
     
+    private static final String PROPS_PATH = "org/apache/karaf/jaas/modules/ldap/ldap.properties";
     private static boolean portUpdated;
 
     @Before
@@ -70,18 +72,22 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
             }
 
             // Read in ldap.properties and substitute in the correct port
-            File f = new File(basedir + "/src/test/resources/org/apache/karaf/jaas/modules/ldap/ldap.properties");
-
-            FileInputStream inputStream = new FileInputStream(f);
-            String content = IOUtils.toString(inputStream, "UTF-8");
-            inputStream.close();
+            String content = readProperties(basedir + "/src/test/resources/" + PROPS_PATH);
             content = content.replaceAll("portno", "" + getLdapServer().getPort());
+            writeProperties(basedir + "/target/test-classes/" + PROPS_PATH, content);
+            portUpdated = true;
+        }
+    }
 
-            File f2 = new File(basedir + "/target/test-classes/org/apache/karaf/jaas/modules/ldap/ldap.properties");
-            FileOutputStream outputStream = new FileOutputStream(f2);
+    private String readProperties(String path) throws FileNotFoundException, IOException {
+        try (FileInputStream inputStream = new FileInputStream(new File(path))) {;
+            return IOUtils.toString(inputStream, "UTF-8");
+        }
+    }
+
+    private void writeProperties(String path, String content) throws FileNotFoundException, IOException {
+        try (FileOutputStream outputStream = new FileOutputStream(new File(path))) {
             IOUtils.write(content, outputStream, "UTF-8");
-            outputStream.close();
-            portUpdated = true;
         }
     }
             


[17/27] karaf git commit: Simplify assertions

Posted by cs...@apache.org.
Simplify assertions


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/3b72701c
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/3b72701c
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/3b72701c

Branch: refs/heads/model_features
Commit: 3b72701cdbf06961d2185348b29cbfd5e1f92763
Parents: e973e3c
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Wed Aug 16 11:52:11 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Wed Aug 16 11:52:11 2017 +0200

----------------------------------------------------------------------
 .../modules/ldap/LdapCaseInsensitiveDNTest.java |  20 +--
 .../jaas/modules/ldap/LdapLoginModuleTest.java  | 131 +++----------------
 2 files changed, 23 insertions(+), 128 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/3b72701c/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
index bcf460d..8e3a56e 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
@@ -15,12 +15,14 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
+import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 
 import java.io.File;
 import java.io.IOException;
-import java.security.Principal;
 
 import javax.security.auth.Subject;
 
@@ -65,20 +67,8 @@ public class LdapCaseInsensitiveDNTest extends LdapLoginModuleTest {
         assertTrue(module.commit());
 
         assertEquals(2, subject.getPrincipals().size());
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof UserPrincipal) {
-                assertEquals("admin", pr.getName());
-                foundUser = true;
-            } else if (pr instanceof RolePrincipal) {
-                assertEquals("admin", pr.getName());
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("admin"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());

http://git-wip-us.apache.org/repos/asf/karaf/blob/3b72701c/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
index 140d5df..847dcf3 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
@@ -27,6 +27,7 @@ import org.apache.karaf.jaas.boot.principal.RolePrincipal;
 import org.apache.karaf.jaas.boot.principal.UserPrincipal;
 import org.apache.karaf.jaas.modules.NamePasswordCallbackHandler;
 import org.apache.log4j.Level;
+import org.hamcrest.Matchers;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -37,13 +38,12 @@ import javax.security.auth.login.LoginException;
 
 import java.io.File;
 import java.io.IOException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
 
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
+import static org.apache.karaf.jaas.modules.PrincipalHelper.names;
+import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
@@ -79,20 +79,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(2, subject.getPrincipals().size());
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof UserPrincipal) {
-                assertEquals("admin", pr.getName());
-                foundUser = true;
-            } else if (pr instanceof RolePrincipal) {
-                assertEquals("admin", pr.getName());
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("admin"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -119,21 +107,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(1, subject.getPrincipals().size());
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof UserPrincipal) {
-                assertEquals("cheese", pr.getName());
-                foundUser = true;
-            } else if (pr instanceof RolePrincipal) {
-                assertEquals("admin", pr.getName());
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        // cheese is not an admin so no roles should be returned
-        assertFalse(foundRole);
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("cheese"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), Matchers.empty());
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -152,21 +127,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(1, subject.getPrincipals().size());
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof UserPrincipal) {
-                assertEquals("cheese", pr.getName());
-                foundUser = true;
-            } else if (pr instanceof RolePrincipal) {
-                assertEquals("admin", pr.getName());
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        // cheese is not an admin so no roles should be returned
-        assertFalse(foundRole);
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("cheese"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), Matchers.empty());
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -234,20 +196,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(2, subject.getPrincipals().size());
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal principal : subject.getPrincipals()) {
-            if (principal instanceof UserPrincipal) {
-                assertEquals("admin", principal.getName());
-                foundUser = true;
-            } else if (principal instanceof RolePrincipal) {
-                assertEquals("karaf", principal.getName());
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("karaf"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -266,23 +216,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(4, subject.getPrincipals().size());
-
-        final List<String> roles = new ArrayList<>(Arrays.asList("karaf", "test", "another"));
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal principal : subject.getPrincipals()) {
-            if (principal instanceof UserPrincipal) {
-                assertEquals("admin", principal.getName());
-                foundUser = true;
-            } else if (principal instanceof RolePrincipal) {
-                assertTrue(roles.remove(principal.getName()));
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
-        assertTrue(roles.isEmpty());
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("karaf", "test", "another"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -301,23 +236,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(4, subject.getPrincipals().size());
-
-        final List<String> roles = new ArrayList<>(Arrays.asList("karaf", "test", "another"));
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal pr : subject.getPrincipals()) {
-            if (pr instanceof UserPrincipal) {
-                assertEquals("admin", pr.getName());
-                foundUser = true;
-            } else if (pr instanceof RolePrincipal) {
-                assertTrue(roles.remove(pr.getName()));
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
-        assertTrue(roles.isEmpty());
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("karaf", "test", "another"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
@@ -340,23 +260,8 @@ public class LdapLoginModuleTest extends AbstractLdapTestUnit {
         assertTrue(module.commit());
 
         assertEquals(2, subject.getPrincipals().size());
-
-        final List<String> roles = new ArrayList<>(Arrays.asList("karaf"));
-
-        boolean foundUser = false;
-        boolean foundRole = false;
-        for (Principal principal : subject.getPrincipals()) {
-            if (principal instanceof UserPrincipal) {
-                assertEquals("admin", principal.getName());
-                foundUser = true;
-            } else if (principal instanceof RolePrincipal) {
-                assertTrue(roles.remove(principal.getName()));
-                foundRole = true;
-            }
-        }
-        assertTrue(foundUser);
-        assertTrue(foundRole);
-        assertTrue(roles.isEmpty());
+        assertThat(names(subject.getPrincipals(UserPrincipal.class)), containsInAnyOrder("admin"));
+        assertThat(names(subject.getPrincipals(RolePrincipal.class)), containsInAnyOrder("karaf"));
 
         assertTrue(module.logout());
         assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());


[26/27] karaf git commit: [KARAF-5300] Split install into add and upgrade

Posted by cs...@apache.org.
[KARAF-5300] Split install into add and upgrade


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/69fcb369
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/69fcb369
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/69fcb369

Branch: refs/heads/model_features
Commit: 69fcb3696b5cc2b2707c40e532d06b7b4308aeca
Parents: 99c2188
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Thu Aug 10 11:23:10 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Thu Aug 17 16:29:30 2017 +0200

----------------------------------------------------------------------
 .../internal/service/FeaturesServiceImpl.java   | 114 +++++++++----------
 1 file changed, 55 insertions(+), 59 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/69fcb369/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
----------------------------------------------------------------------
diff --git a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
index 5562390..2767bc8 100644
--- a/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
+++ b/features/core/src/main/java/org/apache/karaf/features/internal/service/FeaturesServiceImpl.java
@@ -83,6 +83,8 @@ import org.osgi.service.resolver.Resolver;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static java.util.Collections.emptyMap;
+import static java.util.stream.Collectors.toSet;
 import static org.apache.karaf.features.internal.service.StateStorage.toStringStringSetMap;
 import static org.apache.karaf.features.internal.util.MapUtils.add;
 import static org.apache.karaf.features.internal.util.MapUtils.copy;
@@ -787,28 +789,39 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
 
     @Override
     public void installFeatures(Set<String> featuresIn, String region, EnumSet<Option> options) throws Exception {
-        Set<FeatureReq> featureReqs = new HashSet<>();
+        Set<FeatureReq> toInstall = new HashSet<>();
         for (String feature : featuresIn) {
-            featureReqs.add(new FeatureReq(feature));
+            toInstall.add(new FeatureReq(feature));
         }
         State state = copyState();
         Map<String, Set<String>> requires = copy(state.requirements);
         if (region == null || region.isEmpty()) {
             region = ROOT_REGION;
         }
-        Set<String> requiredForRegion = requires.computeIfAbsent(region, k -> new HashSet<>());
-        computeRequirements(options, featureReqs, requiredForRegion);
-        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
-        doProvisionInThread(requires, stateChanges, state, getFeaturesById(), options);
-    }
+        Set<String> requirements = requires.computeIfAbsent(region, k -> new HashSet<>());
+        Set<FeatureReq> existingFeatures = requirements.stream().map(r -> toFeatureReq(r)).collect(toSet());
+
+        Set<FeatureReq> toAdd = computeFeaturesToAdd(options, toInstall);
+        toAdd.stream().forEach(f -> requirements.add(toRequirement(f)));
+        print("Adding features: " + join(toAdd), options.contains(Option.Verbose));
+        
+        if (options.contains(Option.Upgrade)) {
+            Set<FeatureReq> toRemove = computeFeaturesToRemoveOnUpdate(toAdd, existingFeatures);
+            toRemove.stream().forEach(f -> requirements.remove(toRequirement(f)));
+            if (!toRemove.isEmpty()) {
+                print("Removing features: " + join(toRemove), options.contains(Option.Verbose));
+            }
+        }
 
-    void computeRequirements(EnumSet<Option> options, Set<FeatureReq> featureReqs,
-                                 Set<String> requirements)
-        throws Exception {
+        doProvisionInThread(requires, emptyMap(), state, getFeaturesById(), options);
+    }
+    
+    private Set<FeatureReq> computeFeaturesToAdd(EnumSet<Option> options, 
+                                                 Set<FeatureReq> toInstall) throws Exception {
+        Feature[] installedFeatures = listInstalledFeatures();
         Map<String, Map<String, Feature>> allFeatures = getFeatureCache();
-        List<FeatureReq> featuresToAdd = new ArrayList<>();
-        List<String> featuresToRemove = new ArrayList<>();
-        for (FeatureReq feature : featureReqs) {
+        Set<FeatureReq> toAdd = new HashSet<>();
+        for (FeatureReq feature : toInstall) {
             Pattern pattern = Pattern.compile(feature.getName());
             boolean matched = false;
             for (String fKey : allFeatures.keySet()) {
@@ -816,8 +829,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
                 if (matcher.matches()) {
                     Feature f = getFeatureMatching(fKey, feature.getVersionRange());
                     if (f != null) {
-                        featuresToAdd.add(new FeatureReq(f));
-                        Feature[] installedFeatures = listInstalledFeatures();
+                        toAdd.add(new FeatureReq(f));
                         for (Feature installedFeature : installedFeatures) {
                             if (installedFeature.getName().equals(f.getName()) && installedFeature.getVersion().equals(f.getVersion())) {
                                 LOGGER.info("The specified feature: '{}' version '{}' {}",f.getName(),f.getVersion(),f.getVersion().endsWith("SNAPSHOT") ? "has been upgraded": "is already installed");
@@ -830,29 +842,20 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
             if (!matched && !options.contains(Option.NoFailOnFeatureNotFound)) {
                 throw new IllegalArgumentException("No matching features for " + feature);
             }
-            if (options.contains(Option.Upgrade)) {
-                for (String existentFeatureReq : requirements) {
-                    FeatureReq existentFeature = getFeatureRefFromRequired(existentFeatureReq);
-                    if (existentFeature.getName().equals(feature.getName())
-                            && !featuresToAdd.contains(existentFeature)) {
-                        featuresToRemove.add(existentFeature.toString());
-                        //do not break cycle to remove all old versions of feature
-                    }
-                }
-            }
-        }
-        if (!featuresToRemove.isEmpty()) {
-            print("Removing features: " + join(featuresToRemove), options.contains(Option.Verbose));
-            for (String featureReq : featuresToRemove) {
-                requirements.remove(FEATURE_OSGI_REQUIREMENT_PREFIX + featureReq);
-            }
         }
-        List<String> featuresToDisplay = new ArrayList<>();
-        for (FeatureReq feature : featuresToAdd) {
-            requirements.add(FEATURE_OSGI_REQUIREMENT_PREFIX + feature.toString());
-            featuresToDisplay.add(feature.toString());
-        }
-        print("Adding features: " + join(featuresToDisplay), options.contains(Option.Verbose));
+        return toAdd;
+    }
+
+    private Set<FeatureReq> computeFeaturesToRemoveOnUpdate(Set<FeatureReq> featuresToAdd,
+                                             Set<FeatureReq> existingFeatures) throws Exception {
+        Set<String> namesToAdd = featuresToAdd.stream().map(f -> f.getName()).collect(toSet());
+        return existingFeatures.stream()
+            .filter(f -> namesToAdd.contains(f.getName()) && !featuresToAdd.contains(f))
+            .collect(toSet());
+    }
+
+    private String toRequirement(FeatureReq feature) {
+        return FEATURE_OSGI_REQUIREMENT_PREFIX + feature.toString();
     }
 
     @Override
@@ -866,21 +869,20 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         if (region == null || region.isEmpty()) {
             region = ROOT_REGION;
         }
-        Set<String> existingFeatures = required.computeIfAbsent(region, k -> new HashSet<>());
-        Set<String> featuresToRemove = new HashSet<>();
+        Set<String> requiredForRegion = required.computeIfAbsent(region, k -> new HashSet<>());
+        Set<FeatureReq> featuresToRemove = new HashSet<>();
         for (FeatureReq feature : featureReqs) {
             Pattern pattern = Pattern.compile(feature.getName());
-            List<String> toRemove = new ArrayList<>();
-            for (String existingFeature : existingFeatures) {
-               FeatureReq existingFeatureReq = getFeatureRefFromRequired(existingFeature);
+            List<FeatureReq> toRemove = new ArrayList<>();
+            for (String existingFeature : requiredForRegion) {
+               FeatureReq existingFeatureReq = toFeatureReq(existingFeature);
                if (existingFeatureReq != null) {
                    Matcher matcher = pattern.matcher(existingFeatureReq.getName());
                    if (matcher.matches() && feature.getVersionRange().includes(existingFeatureReq.getVersionRange().getLeft())) {
-                       toRemove.add(existingFeature);
+                       toRemove.add(existingFeatureReq);
                    }
                }
             }
-            toRemove.retainAll(existingFeatures);
 
             if (toRemove.isEmpty()) {
                 throw new IllegalArgumentException("Feature named '" + feature + "' is not installed");
@@ -888,15 +890,14 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
             featuresToRemove.addAll(toRemove);
         }
         print("Removing features: " + join(featuresToRemove), options.contains(Option.Verbose));
-        existingFeatures.removeAll(featuresToRemove);
-        if (existingFeatures.isEmpty()) {
+        featuresToRemove.stream().forEach(f->requiredForRegion.remove(toRequirement(f)));
+        if (requiredForRegion.isEmpty()) {
             required.remove(region);
         }
-        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
-        doProvisionInThread(required, stateChanges, state, getFeaturesById(), options);
+        doProvisionInThread(required, emptyMap(), state, getFeaturesById(), options);
     }
 
-    private FeatureReq getFeatureRefFromRequired(String featureReq) {
+    private FeatureReq toFeatureReq(String featureReq) {
         if (!featureReq.startsWith(FEATURE_OSGI_REQUIREMENT_PREFIX)) {
             return null;
         }
@@ -915,8 +916,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         State state = copyState();
         Map<String, Set<String>> required = copy(state.requirements);
         add(required, requirements);
-        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
-        doProvisionInThread(required, stateChanges, state, getFeaturesById(), options);
+        doProvisionInThread(required, emptyMap(), state, getFeaturesById(), options);
     }
 
     @Override
@@ -924,8 +924,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         State state = copyState();
         Map<String, Set<String>> required = copy(state.requirements);
         remove(required, requirements);
-        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
-        doProvisionInThread(required, stateChanges, state, getFeaturesById(), options);
+        doProvisionInThread(required, emptyMap(), state, getFeaturesById(), options);
     }
 
     @Override
@@ -948,8 +947,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
             saveState();
             stateCopy = state.copy();
         }
-        Map<String, Map<String, FeatureState>> stateChanges = Collections.emptyMap();
-        doProvisionInThread(requirements, stateChanges, stateCopy, getFeaturesById(), options);
+        doProvisionInThread(requirements, emptyMap(), stateCopy, getFeaturesById(), options);
     }
 
     private <T> Set<T> diff(Set<T> s1, Set<T> s2) {
@@ -1188,9 +1186,7 @@ public class FeaturesServiceImpl implements FeaturesService, Deployer.DeployCall
         installSupport.installLibraries(feature);
     }
 
-
-
-    private String join(Collection<String> list) {
-        return String.join(", ", list);
+    private String join(Collection<FeatureReq> reqs) {
+        return reqs.stream().map(f->f.toString()).collect(Collectors.joining(","));
     }
 }


[11/27] karaf git commit: Avoid excessive logging

Posted by cs...@apache.org.
Avoid excessive logging


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/767012d2
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/767012d2
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/767012d2

Branch: refs/heads/model_features
Commit: 767012d2544be03ab5818f3288912f1578d0e0c2
Parents: 1bf544b
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 17:57:24 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 17:57:24 2017 +0200

----------------------------------------------------------------------
 jaas/blueprint/jasypt/src/test/resources/log4j.properties | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/767012d2/jaas/blueprint/jasypt/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/jaas/blueprint/jasypt/src/test/resources/log4j.properties b/jaas/blueprint/jasypt/src/test/resources/log4j.properties
index e1cbdd1..3822bad 100644
--- a/jaas/blueprint/jasypt/src/test/resources/log4j.properties
+++ b/jaas/blueprint/jasypt/src/test/resources/log4j.properties
@@ -18,7 +18,7 @@
 #
 # The logging properties used during tests..
 #
-log4j.rootLogger=DEBUG, console, file
+log4j.rootLogger=INFO, console, file
 
 # Console will only display warnnings
 log4j.appender.console=org.apache.log4j.ConsoleAppender


[06/27] karaf git commit: Extract port update into class

Posted by cs...@apache.org.
Extract port update into class


Project: http://git-wip-us.apache.org/repos/asf/karaf/repo
Commit: http://git-wip-us.apache.org/repos/asf/karaf/commit/ecf6a8dc
Tree: http://git-wip-us.apache.org/repos/asf/karaf/tree/ecf6a8dc
Diff: http://git-wip-us.apache.org/repos/asf/karaf/diff/ecf6a8dc

Branch: refs/heads/model_features
Commit: ecf6a8dc79cb6f36054f13376772428d9d58634e
Parents: 8a18da5
Author: Christian Schneider <ch...@die-schneider.net>
Authored: Tue Aug 15 16:41:45 2017 +0200
Committer: Christian Schneider <ch...@die-schneider.net>
Committed: Tue Aug 15 16:41:45 2017 +0200

----------------------------------------------------------------------
 .../karaf/jaas/modules/ldap/LdapCacheTest.java  | 26 +---------
 .../modules/ldap/LdapCaseInsensitiveDNTest.java | 28 +---------
 .../jaas/modules/ldap/LdapLoginModuleTest.java  | 31 +----------
 .../ldap/LdapLoginModuleWithEscapesTest.java    | 32 +-----------
 .../jaas/modules/ldap/LdapPropsUpdater.java     | 54 ++++++++++++++++++++
 .../ldap/LdapSpecialCharsInPasswordTest.java    | 26 +---------
 6 files changed, 61 insertions(+), 136 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/karaf/blob/ecf6a8dc/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
index 87dde8f..1b88a16 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCacheTest.java
@@ -23,12 +23,9 @@ import javax.naming.directory.DirContext;
 import javax.security.auth.Subject;
 import javax.security.auth.callback.CallbackHandler;
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.security.Principal;
 
-import org.apache.commons.io.IOUtils;
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
 import org.apache.directory.server.core.annotations.ApplyLdifFiles;
@@ -57,30 +54,9 @@ import static org.junit.Assert.assertTrue;
 )
 public class LdapCacheTest extends AbstractLdapTestUnit {
 
-    private static boolean portUpdated;
-
     @Before
     public void updatePort() throws Exception {
-        if (!portUpdated) {
-            String basedir = System.getProperty("basedir");
-            if (basedir == null) {
-                basedir = new File(".").getCanonicalPath();
-            }
-
-            // Read in ldap.properties and substitute in the correct port
-            File f = new File(basedir + "/src/test/resources/org/apache/karaf/jaas/modules/ldap/ldap.properties");
-
-            FileInputStream inputStream = new FileInputStream(f);
-            String content = IOUtils.toString(inputStream, "UTF-8");
-            inputStream.close();
-            content = content.replaceAll("portno", "" + getLdapServer().getPort());
-
-            File f2 = new File(basedir + "/target/test-classes/org/apache/karaf/jaas/modules/ldap/ldap.properties");
-            FileOutputStream outputStream = new FileOutputStream(f2);
-            IOUtils.write(content, outputStream, "UTF-8");
-            outputStream.close();
-            portUpdated = true;
-        }
+        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap.properties", getLdapServer().getPort());
     }
 
     @After

http://git-wip-us.apache.org/repos/asf/karaf/blob/ecf6a8dc/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
index e4d2035..bcf460d 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapCaseInsensitiveDNTest.java
@@ -19,20 +19,17 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.security.Principal;
 
 import javax.security.auth.Subject;
 
-import org.apache.commons.io.IOUtils;
-import org.apache.directory.server.core.integ.FrameworkRunner;
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
 import org.apache.directory.server.core.annotations.ApplyLdifFiles;
 import org.apache.directory.server.core.annotations.CreateDS;
 import org.apache.directory.server.core.annotations.CreatePartition;
+import org.apache.directory.server.core.integ.FrameworkRunner;
 import org.apache.felix.utils.properties.Properties;
 import org.apache.karaf.jaas.boot.principal.RolePrincipal;
 import org.apache.karaf.jaas.boot.principal.UserPrincipal;
@@ -50,31 +47,10 @@ import org.junit.runner.RunWith;
 )
 public class LdapCaseInsensitiveDNTest extends LdapLoginModuleTest {
     
-    private static boolean portUpdated;
-    
     @Before
     @Override
     public void updatePort() throws Exception {
-        if (!portUpdated) {
-            String basedir = System.getProperty("basedir");
-            if (basedir == null) {
-                basedir = new File(".").getCanonicalPath();
-            }
-
-            // Read in ldap.properties and substitute in the correct port
-            File f = new File(basedir + "/src/test/resources/org/apache/karaf/jaas/modules/ldap/ldapCaseInsensitiveDN.properties");
-
-            FileInputStream inputStream = new FileInputStream(f);
-            String content = IOUtils.toString(inputStream, "UTF-8");
-            inputStream.close();
-            content = content.replaceAll("portno", "" + getLdapServer().getPort());
-
-            File f2 = new File(basedir + "/target/test-classes/org/apache/karaf/jaas/modules/ldap/ldapCaseInsensitiveDN.properties");
-            FileOutputStream outputStream = new FileOutputStream(f2);
-            IOUtils.write(content, outputStream, "UTF-8");
-            outputStream.close();
-            portUpdated = true;
-        }
+        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldapCaseInsensitiveDN.properties", getLdapServer().getPort());
     }
     
     @Test

http://git-wip-us.apache.org/repos/asf/karaf/blob/ecf6a8dc/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
index 186bdb2..140d5df 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleTest.java
@@ -17,7 +17,6 @@ package org.apache.karaf.jaas.modules.ldap;
 
 import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
 import org.apache.directory.server.core.integ.FrameworkRunner;
-import org.apache.commons.io.IOUtils;
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
 import org.apache.directory.server.core.annotations.ApplyLdifFiles;
@@ -37,9 +36,6 @@ import javax.security.auth.Subject;
 import javax.security.auth.login.LoginException;
 
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.security.Principal;
 import java.util.ArrayList;
@@ -59,37 +55,12 @@ import static org.junit.Assert.fail;
         "org/apache/karaf/jaas/modules/ldap/example.com.ldif"
 )
 public class LdapLoginModuleTest extends AbstractLdapTestUnit {
-    
-    private static final String PROPS_PATH = "org/apache/karaf/jaas/modules/ldap/ldap.properties";
-    private static boolean portUpdated;
 
     @Before
     public void updatePort() throws Exception {
-        if (!portUpdated) {
-            String basedir = System.getProperty("basedir");
-            if (basedir == null) {
-                basedir = new File(".").getCanonicalPath();
-            }
-
-            // Read in ldap.properties and substitute in the correct port
-            String content = readProperties(basedir + "/src/test/resources/" + PROPS_PATH);
-            content = content.replaceAll("portno", "" + getLdapServer().getPort());
-            writeProperties(basedir + "/target/test-classes/" + PROPS_PATH, content);
-            portUpdated = true;
-        }
-    }
-
-    private String readProperties(String path) throws FileNotFoundException, IOException {
-        try (FileInputStream inputStream = new FileInputStream(new File(path))) {;
-            return IOUtils.toString(inputStream, "UTF-8");
-        }
+        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap.properties", getLdapServer().getPort());
     }
 
-    private void writeProperties(String path, String content) throws FileNotFoundException, IOException {
-        try (FileOutputStream outputStream = new FileOutputStream(new File(path))) {
-            IOUtils.write(content, outputStream, "UTF-8");
-        }
-    }
             
     @After
     public void tearDown() {

http://git-wip-us.apache.org/repos/asf/karaf/blob/ecf6a8dc/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
index 9dc2272..c05a39a 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapLoginModuleWithEscapesTest.java
@@ -15,18 +15,12 @@
  */
 package org.apache.karaf.jaas.modules.ldap;
 
-import org.apache.directory.server.core.integ.FrameworkRunner;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-
-import org.apache.commons.io.IOUtils;
 import org.apache.directory.server.annotations.CreateLdapServer;
 import org.apache.directory.server.annotations.CreateTransport;
 import org.apache.directory.server.core.annotations.ApplyLdifFiles;
 import org.apache.directory.server.core.annotations.CreateDS;
 import org.apache.directory.server.core.annotations.CreatePartition;
+import org.apache.directory.server.core.integ.FrameworkRunner;
 import org.junit.Before;
 import org.junit.runner.RunWith;
 
@@ -39,31 +33,9 @@ import org.junit.runner.RunWith;
 )
 public class LdapLoginModuleWithEscapesTest extends LdapLoginModuleTest {
     
-    private static boolean portUpdated;
-
     @Before
     @Override
     public void updatePort() throws Exception {
-        if (!portUpdated) {
-            String basedir = System.getProperty("basedir");
-            if (basedir == null) {
-                basedir = new File(".").getCanonicalPath();
-            }
-
-            // Read in ldap.properties and substitute in the correct port
-            File f = new File(basedir + "/src/test/resources/org/apache/karaf/jaas/modules/ldap/ldap.properties");
-
-            FileInputStream inputStream = new FileInputStream(f);
-            String content = IOUtils.toString(inputStream, "UTF-8");
-            inputStream.close();
-            content = content.replaceAll("portno", "" + getLdapServer().getPort());
-
-            File f2 = new File(basedir + "/target/test-classes/org/apache/karaf/jaas/modules/ldap/ldap.properties");
-            FileOutputStream outputStream = new FileOutputStream(f2);
-            IOUtils.write(content, outputStream, "UTF-8");
-            outputStream.close();
-            portUpdated = true;
-        }
+        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap.properties", getLdapServer().getPort());
     }
 }
-            
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/karaf/blob/ecf6a8dc/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
new file mode 100644
index 0000000..54c4a90
--- /dev/null
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapPropsUpdater.java
@@ -0,0 +1,54 @@
+/*
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *  under the License.
+ */
+package org.apache.karaf.jaas.modules.ldap;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.commons.io.IOUtils;
+
+public class LdapPropsUpdater {
+
+    private LdapPropsUpdater() {
+    }
+
+    public static void updatePort(String propsPath, int port) throws IOException {
+        String basedir = System.getProperty("basedir");
+        if (basedir == null) {
+            basedir = new File(".").getCanonicalPath();
+        }
+
+        // Read in ldap.properties and substitute in the correct port
+        String content = readProperties(basedir + "/src/test/resources/" + propsPath);
+        content = content.replaceAll("portno", "" + port);
+        writeProperties(basedir + "/target/test-classes/" + propsPath, content);
+    }
+    
+    private static String readProperties(String path) throws FileNotFoundException, IOException {
+        try (FileInputStream inputStream = new FileInputStream(new File(path))) {;
+            return IOUtils.toString(inputStream, "UTF-8");
+        }
+    }
+
+    private static void writeProperties(String path, String content) throws FileNotFoundException, IOException {
+        try (FileOutputStream outputStream = new FileOutputStream(new File(path))) {
+            IOUtils.write(content, outputStream, "UTF-8");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/ecf6a8dc/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
----------------------------------------------------------------------
diff --git a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
index 7f5a90a..f188cc2 100644
--- a/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
+++ b/jaas/modules/src/test/java/org/apache/karaf/jaas/modules/ldap/LdapSpecialCharsInPasswordTest.java
@@ -16,11 +16,8 @@
 package org.apache.karaf.jaas.modules.ldap;
 
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 
-import org.apache.commons.io.IOUtils;
 import org.apache.directory.api.ldap.model.constants.SchemaConstants;
 import org.apache.directory.api.ldap.model.message.ModifyRequest;
 import org.apache.directory.api.ldap.model.message.ModifyRequestImpl;
@@ -47,32 +44,12 @@ import org.junit.runner.RunWith;
 )
 public class LdapSpecialCharsInPasswordTest extends LdapLoginModuleTest {
     
-    private static boolean portUpdated;
     private static final String NEW_CONNECTION_PASSWORD = "#a&b{>c=<12~d%";
     
     @Before
     @Override
     public void updatePort() throws Exception {
-        if (!portUpdated) {
-            String basedir = System.getProperty("basedir");
-            if (basedir == null) {
-                basedir = new File(".").getCanonicalPath();
-            }
-
-            // Read in ldap.properties and substitute in the correct port
-            File f = new File(basedir + "/src/test/resources/org/apache/karaf/jaas/modules/ldap/ldap_special_char_in_password.properties");
-
-            FileInputStream inputStream = new FileInputStream(f);
-            String content = IOUtils.toString(inputStream, "UTF-8");
-            inputStream.close();
-            content = content.replaceAll("portno", "" + getLdapServer().getPort());
-
-            File f2 = new File(basedir + "/target/test-classes/org/apache/karaf/jaas/modules/ldap/ldap_special_char_in_password.properties");
-            FileOutputStream outputStream = new FileOutputStream(f2);
-            IOUtils.write(content, outputStream, "UTF-8");
-            outputStream.close();
-            portUpdated = true;
-        }
+        LdapPropsUpdater.updatePort("org/apache/karaf/jaas/modules/ldap/ldap_special_char_in_password.properties", getLdapServer().getPort());
     }
 
     protected Properties ldapLoginModuleOptions() throws IOException {
@@ -101,4 +78,3 @@ public class LdapSpecialCharsInPasswordTest extends LdapLoginModuleTest {
         connection.close();
     }
 }
-            
\ No newline at end of file