You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by lb...@apache.org on 2017/06/16 15:39:02 UTC

[01/13] camel git commit: CAMEL-11362: create a LeaderElectionservice

Repository: camel
Updated Branches:
  refs/heads/master 04191e541 -> 08d2b0fe8


CAMEL-11362: create a LeaderElectionservice


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

Branch: refs/heads/master
Commit: 54052a327b6a077f037b4ff0e061c4bf0c3d9b4d
Parents: 04191e5
Author: lburgazzoli <lb...@gmail.com>
Authored: Mon May 29 16:34:11 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:52 2017 +0200

----------------------------------------------------------------------
 .../camel/ha/AbstractCamelClusterView.java      | 121 +++++++++++
 .../java/org/apache/camel/ha/CamelCluster.java  |  30 +++
 .../org/apache/camel/ha/CamelClusterMember.java |  26 +++
 .../org/apache/camel/ha/CamelClusterView.java   |  85 ++++++++
 .../org/apache/camel/ha/LeaderRoutePolicy.java  | 169 +++++++++++++++
 .../org/apache/camel/model/RouteDefinition.java |  13 ++
 .../policy/InfinispanRoutePolicy.java           | 207 +++++++------------
 .../policy/InfinispanRoutePolicyTestBase.java   | 115 ++++-------
 8 files changed, 564 insertions(+), 202 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java b/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java
new file mode 100644
index 0000000..64cee58
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java
@@ -0,0 +1,121 @@
+/**
+ * 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.camel.ha;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.locks.StampedLock;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+
+public abstract class AbstractCamelClusterView implements CamelClusterView {
+    private final CamelCluster cluster;
+    private final String namespace;
+    private final List<FilteringConsumer> consumers;
+    private final StampedLock lock;
+
+    protected AbstractCamelClusterView(CamelCluster cluster, String namespace) {
+        this.cluster = cluster;
+        this.namespace = namespace;
+        this.consumers = new ArrayList<>();
+        this.lock = new StampedLock();
+    }
+
+    @Override
+    public CamelCluster getCluster() {
+        return  this.cluster;
+    }
+
+    @Override
+    public String getNamespace() {
+        return this.namespace;
+    }
+
+    @Override
+    public void addEventListener(BiConsumer<Event, Object> consumer) {
+        long stamp = lock.writeLock();
+
+        try {
+            consumers.add(new FilteringConsumer(e -> true, consumer));
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    @Override
+    public void addEventListener(Predicate<Event> predicate, BiConsumer<Event, Object> consumer) {
+        long stamp = lock.writeLock();
+
+        try {
+            this.consumers.add(new FilteringConsumer(predicate, consumer));
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    @Override
+    public void removeEventListener(BiConsumer<Event, Object> consumer) {
+        long stamp = lock.writeLock();
+
+        try {
+            consumers.removeIf(c -> c.getConsumer().equals(consumer));
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    // **************************************
+    // Events
+    // **************************************
+
+    protected void fireEvent(CamelClusterView.Event event, Object payload) {
+        long stamp = lock.readLock();
+
+        try {
+            for (int i = 0; i < consumers.size(); i++) {
+                consumers.get(0).accept(event, payload);
+            }
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
+    // **************************************
+    // Helpers
+    // **************************************
+
+    private final class FilteringConsumer implements BiConsumer<Event, Object> {
+        private final Predicate<Event> predicate;
+        private final BiConsumer<Event, Object> consumer;
+
+        FilteringConsumer(Predicate<Event> predicate,  BiConsumer<Event, Object> consumer) {
+            this.predicate = predicate;
+            this.consumer = consumer;
+        }
+
+        @Override
+        public void accept(CamelClusterView.Event event, Object payload) {
+            if (predicate.test(event)) {
+                consumer.accept(event, payload);
+            }
+        }
+
+        public BiConsumer<Event, Object> getConsumer() {
+            return this.consumer;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
new file mode 100644
index 0000000..5da1e8c
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
@@ -0,0 +1,30 @@
+/**
+ * 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.camel.ha;
+
+import org.apache.camel.spi.HasId;
+
+public interface CamelCluster extends HasId {
+    /**
+     * Creates a view of the cluster bound to a namespace.
+     *
+     * @param namespace the namespace the view refer to.
+     * @return the cluster view.
+     * @throws Exception if the view can't be created.
+     */
+    CamelClusterView createView(String namespace) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/camel-core/src/main/java/org/apache/camel/ha/CamelClusterMember.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterMember.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterMember.java
new file mode 100644
index 0000000..cfe0a79
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterMember.java
@@ -0,0 +1,26 @@
+/**
+ * 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.camel.ha;
+
+import org.apache.camel.spi.HasId;
+
+public interface CamelClusterMember extends HasId {
+    /**
+     * @return true if this member is the master.
+     */
+    boolean isMaster();
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
new file mode 100644
index 0000000..7af5a21
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
@@ -0,0 +1,85 @@
+/**
+ * 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.camel.ha;
+
+import java.util.List;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+
+/**
+ * Represents the View of the cluster at some given period of time.
+ */
+public interface CamelClusterView {
+
+    enum Event {
+        KEEP_ALIVE,
+        LEADERSHIP_CHANGED;
+    }
+
+    /**
+     * @return the cluster.
+     */
+    CamelCluster getCluster();
+
+    /**
+     * @return the namespace for this view.
+     */
+    String getNamespace();
+
+    /**
+     * Provides the master member.
+     *
+     * @return the master member.
+     */
+    CamelClusterMember getMaster();
+
+    /**
+     * Provides the local member.
+     *
+     * @return the local member.
+     */
+    CamelClusterMember getLocalMember();
+
+    /**
+     * Provides the list of members of the cluster.
+     *
+     * @return the list of members.
+     */
+    List<CamelClusterMember> getMembers();
+
+    /**
+     * Add an event consumer.
+     *
+     * @param consumer the event consumer.
+     */
+    void addEventListener(BiConsumer<Event, Object> consumer);
+
+    /**
+     * Add an event consumer for events matching the given predicate.
+     *
+     * @param predicate the predicate to filter events.
+     * @param consumer the event consumer.
+     */
+    void addEventListener(Predicate<Event> predicate, BiConsumer<Event, Object> consumer);
+
+    /**
+     * Remove the event consumer.
+     *
+     * @param event the event consumer.
+     */
+    void removeEventListener(BiConsumer<Event, Object> event);
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java b/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java
new file mode 100644
index 0000000..40ae1e8
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java
@@ -0,0 +1,169 @@
+/**
+ * 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.camel.ha;
+
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.Route;
+import org.apache.camel.api.management.ManagedAttribute;
+import org.apache.camel.api.management.ManagedResource;
+import org.apache.camel.support.RoutePolicySupport;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.ReferenceCount;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ManagedResource(description = "Route policy using ...")
+public class LeaderRoutePolicy extends RoutePolicySupport implements CamelContextAware {
+    private static final Logger LOGGER = LoggerFactory.getLogger(LeaderRoutePolicy.class);
+
+    private final AtomicBoolean leader;
+    private final Set<Route> startedRoutes;
+    private final Set<Route> stoppedRoutes;
+    private final ReferenceCount refCount;
+    private final CamelClusterView clusterView;
+    private final CamelClusterMember clusterMember;
+    private final BiConsumer<CamelClusterView.Event, Object> clusterEventConsumer;
+    private CamelContext camelContext;
+
+    public LeaderRoutePolicy(CamelClusterView clusterView, CamelClusterMember clusterMember) {
+        this.clusterMember = clusterMember;
+        this.clusterView = clusterView;
+        this.clusterEventConsumer = this::onClusterEvent;
+        this.stoppedRoutes = new HashSet<>();
+        this.startedRoutes = new HashSet<>();
+        this.leader = new AtomicBoolean(false);
+
+        this.refCount = ReferenceCount.on(
+            () -> clusterView.addEventListener(clusterEventConsumer),
+            () -> clusterView.removeEventListener(clusterEventConsumer)
+        );
+    }
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    @Override
+    public synchronized void onInit(Route route) {
+        super.onInit(route);
+
+        LOGGER.info("Route managed by {}. Setting route {} AutoStartup flag to false.", getClass(), route.getId());
+        route.getRouteContext().getRoute().setAutoStartup("false");
+
+        stoppedRoutes.add(route);
+
+        this.refCount.retain();
+
+        startManagedRoutes();
+    }
+
+    @Override
+    public synchronized void doShutdown() {
+        this.refCount.release();
+    }
+
+    // ****************************************************
+    // Management
+    // ****************************************************
+
+    @ManagedAttribute(description = "Is this route the master or a slave")
+    public boolean isLeader() {
+        return leader.get();
+    }
+
+    // ****************************************************
+    // Route managements
+    // ****************************************************
+
+    private void onClusterEvent(CamelClusterView.Event event, Object payload) {
+        if (event == CamelClusterView.Event.KEEP_ALIVE) {
+            LOGGER.debug("Got KEEP_ALIVE from cluster '{}' with payload '{}'", clusterView.getCluster().getId(), Objects.toString(payload));
+        }
+        if (event == CamelClusterView.Event.LEADERSHIP_CHANGED) {
+            boolean isLeader = ObjectHelper.equal(clusterMember.getId(), clusterView.getMaster().getId());
+
+            if (isLeader && leader.compareAndSet(false, isLeader)) {
+                LOGGER.info("Leadership taken");
+                startManagedRoutes();
+            } else if (!isLeader && leader.getAndSet(isLeader)) {
+                LOGGER.info("Leadership lost");
+                stopManagedRoutes();
+            }
+        }
+    }
+
+    private synchronized void startManagedRoutes() {
+        if (isLeader()) {
+            doStartManagedRoutes();
+        } else {
+            // If the leadership has been lost in the meanwhile, stop any
+            // eventually started route
+            doStopManagedRoutes();
+        }
+    }
+
+    private synchronized void doStartManagedRoutes() {
+        try {
+            for (Route route : stoppedRoutes) {
+                LOGGER.debug("Starting route {}", route.getId());
+                startRoute(route);
+                startedRoutes.add(route);
+            }
+
+            stoppedRoutes.removeAll(startedRoutes);
+        } catch (Exception e) {
+            handleException(e);
+        }
+    }
+
+    private synchronized void stopManagedRoutes() {
+        if (isLeader()) {
+            // If became a leader in the meanwhile, start any eventually stopped
+            // route
+            doStartManagedRoutes();
+        } else {
+            doStopManagedRoutes();
+        }
+    }
+
+    private synchronized void doStopManagedRoutes() {
+        try {
+            for (Route route : startedRoutes) {
+                LOGGER.debug("Stopping route {}", route.getId());
+                stopRoute(route);
+                stoppedRoutes.add(route);
+            }
+
+            startedRoutes.removeAll(stoppedRoutes);
+        } catch (Exception e) {
+            handleException(e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java b/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java
index 5196da8..28df5ac 100644
--- a/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java
+++ b/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java
@@ -1303,4 +1303,17 @@ public class RouteDefinition extends ProcessorDefinition<RouteDefinition> {
         return routeContext;
     }
 
+
+    // ****************************
+    // Static helpers
+    // ****************************
+
+    public static RouteDefinition fromUri(String uri) {
+        return new RouteDefinition().from(uri);
+    }
+
+    public static RouteDefinition fromEndpoint(Endpoint endpoint) {
+        return new RouteDefinition().from(endpoint);
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicy.java
----------------------------------------------------------------------
diff --git a/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicy.java b/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicy.java
index 7afc26a..3f91f14 100644
--- a/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicy.java
+++ b/components/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicy.java
@@ -36,6 +36,7 @@ import org.apache.camel.component.infinispan.InfinispanUtil;
 import org.apache.camel.support.RoutePolicySupport;
 import org.apache.camel.support.ServiceSupport;
 import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.ReferenceCount;
 import org.apache.camel.util.StringHelper;
 import org.infinispan.Cache;
 import org.infinispan.client.hotrod.RemoteCache;
@@ -58,13 +59,14 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
     private static final Logger LOGGER = LoggerFactory.getLogger(InfinispanRoutePolicy.class);
 
     private final AtomicBoolean leader;
-    private final Set<Route> suspendedRoutes;
+    private final Set<Route> startedRoutes;
+    private final Set<Route> stoppeddRoutes;
     private final InfinispanManager manager;
+    private final ReferenceCount refCount;
 
-    private Route route;
     private CamelContext camelContext;
     private ScheduledExecutorService executorService;
-    private boolean shouldStopConsumer;
+    private boolean shouldStopRoute;
     private String lockMapName;
     private String lockKey;
     private String lockValue;
@@ -83,14 +85,16 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
 
     public InfinispanRoutePolicy(InfinispanManager manager, String lockKey, String lockValue) {
         this.manager = manager;
-        this.suspendedRoutes =  new HashSet<>();
+        this.stoppeddRoutes = new HashSet<>();
+        this.startedRoutes = new HashSet<>();
         this.leader = new AtomicBoolean(false);
-        this.shouldStopConsumer = true;
+        this.shouldStopRoute = true;
         this.lockKey = lockKey;
         this.lockValue = lockValue;
         this.lifespan = 30;
         this.lifespanTimeUnit = TimeUnit.SECONDS;
         this.service = null;
+        this.refCount = ReferenceCount.on(this::startService, this::stopService);
     }
 
     @Override
@@ -104,48 +108,29 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
     }
 
     @Override
-    public void onInit(Route route) {
+    public synchronized void onInit(Route route) {
         super.onInit(route);
-        this.route = route;
-    }
 
-    @Override
-    public void onStart(Route route) {
-        try {
-            startService();
-        } catch (Exception e) {
-            throw new RuntimeCamelException(e);
-        }
+        LOGGER.info("Route managed by {}. Setting route {} AutoStartup flag to false.", getClass(), route.getId());
+        route.getRouteContext().getRoute().setAutoStartup("false");
 
-        if (!leader.get() && shouldStopConsumer) {
-            stopConsumer(route);
-        }
-    }
+        stoppeddRoutes.add(route);
 
-    @Override
-    public synchronized void onStop(Route route) {
-        try {
-            stopService();
-        } catch (Exception e) {
-            throw new RuntimeCamelException(e);
-        }
+        this.refCount.retain();
 
-        suspendedRoutes.remove(route);
+        startManagedRoutes();
     }
 
     @Override
-    public synchronized void onSuspend(Route route) {
-        try {
-            stopService();
-        } catch (Exception e) {
-            throw new RuntimeCamelException(e);
-        }
-
-        suspendedRoutes.remove(route);
+    public synchronized void doShutdown() {
+        this.refCount.release();
     }
 
-    @Override
-    protected void doStart() throws Exception {
+    // ****************************************
+    // Helpers
+    // ****************************************
+
+    private void startService() {
         // validate
         StringHelper.notEmpty(lockMapName, "lockMapName", this);
         StringHelper.notEmpty(lockKey, "lockKey", this);
@@ -156,107 +141,89 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
             this.lockValue = camelContext.getUuidGenerator().generateUuid();
         }
 
-        this.manager.start();
-        this.executorService = getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "InfinispanRoutePolicy");
-
-        if (lifespanTimeUnit.convert(lifespan, TimeUnit.SECONDS) < 2) {
-            throw new IllegalArgumentException("Lock lifespan can not be less that 2 seconds");
-        }
-
-        BasicCache<String, String> cache = manager.getCache(lockMapName);
-        if (manager.isCacheContainerEmbedded()) {
-            this.service = new EmbeddedCacheService(InfinispanUtil.asEmbedded(cache));
-        } else {
-            this.service = new RemoteCacheService(InfinispanUtil.asRemote(cache));
-        }
+        try {
+            this.manager.start();
+            this.executorService = getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "InfinispanRoutePolicy");
 
-        super.doStart();
-    }
+            if (lifespanTimeUnit.convert(lifespan, TimeUnit.SECONDS) < 2) {
+                throw new IllegalArgumentException("Lock lifespan can not be less that 2 seconds");
+            }
 
-    @Override
-    protected void doStop() throws Exception {
-        if (future != null) {
-            future.cancel(true);
-            future = null;
-        }
+            BasicCache<String, String> cache = manager.getCache(lockMapName);
+            if (manager.isCacheContainerEmbedded()) {
+                this.service = new EmbeddedCacheService(InfinispanUtil.asEmbedded(cache));
+            } else {
+                this.service = new RemoteCacheService(InfinispanUtil.asRemote(cache));
+            }
 
-        if (this.service != null) {
-            this.service.stop();
+            service.start();
+        } catch (Exception e) {
+            throw new RuntimeCamelException(e);
         }
+    }
 
-        getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService);
-
+    private void stopService() {
         leader.set(false);
-        manager.stop();
 
-        super.doStop();
-    }
+        try {
+            if (future != null) {
+                future.cancel(true);
+                future = null;
+            }
 
-    private void startService() throws Exception {
-        if (service == null) {
-            throw new IllegalStateException("An Infinispan CacheService should be configured");
-        }
+            manager.stop();
 
-        service.start();
-    }
-
-    private void stopService() throws Exception {
-        leader.set(false);
+            if (this.service != null) {
+                this.service.stop();
+            }
 
-        if (this.service != null) {
-            this.service.stop();
+            getCamelContext().getExecutorServiceManager().shutdownGraceful(executorService);
+        } catch (Exception e) {
+            throw new RuntimeCamelException(e);
         }
     }
 
-    // *************************************************************************
-    //
-    // *************************************************************************
-
-    protected void setLeader(boolean isLeader) {
+    private void setLeader(boolean isLeader) {
         if (isLeader && leader.compareAndSet(false, isLeader)) {
             LOGGER.info("Leadership taken (map={}, key={}, val={})", lockMapName, lockKey, lockValue);
-
-            startAllStoppedConsumers();
+            startManagedRoutes();
         } else if (!isLeader && leader.getAndSet(isLeader)) {
             LOGGER.info("Leadership lost (map={}, key={} val={})", lockMapName, lockKey, lockValue);
+            stopManagedRoutes();
         }
+    }
 
-        if (!isLeader && this.route != null) {
-            stopConsumer(route);
+    private synchronized void startManagedRoutes() {
+        if (!isLeader()) {
+            return;
         }
-    }
 
-    private synchronized void startConsumer(Route route) {
         try {
-            if (suspendedRoutes.contains(route)) {
-                startConsumer(route.getConsumer());
-                suspendedRoutes.remove(route);
+            for (Route route : stoppeddRoutes) {
+                LOGGER.debug("Starting route {}", route.getId());
+                startRoute(route);
+                startedRoutes.add(route);
             }
+
+            stoppeddRoutes.removeAll(startedRoutes);
         } catch (Exception e) {
             handleException(e);
         }
     }
 
-    private synchronized void stopConsumer(Route route) {
-        try {
-            if (!suspendedRoutes.contains(route)) {
-                LOGGER.debug("Stopping consumer for {} ({})", route.getId(), route.getConsumer());
-                stopConsumer(route.getConsumer());
-                suspendedRoutes.add(route);
-            }
-        } catch (Exception e) {
-            handleException(e);
+    private synchronized void stopManagedRoutes() {
+        if (isLeader()) {
+            return;
         }
-    }
 
-    private synchronized void startAllStoppedConsumers() {
         try {
-            for (Route route : suspendedRoutes) {
-                LOGGER.debug("Starting consumer for {} ({})", route.getId(), route.getConsumer());
-                startConsumer(route.getConsumer());
+            for (Route route : startedRoutes) {
+                LOGGER.debug("Stopping route {}", route.getId());
+                stopRoute(route);
+                stoppeddRoutes.add(route);
             }
 
-            suspendedRoutes.clear();
+            startedRoutes.removeAll(stoppeddRoutes);
         } catch (Exception e) {
             handleException(e);
         }
@@ -266,29 +233,13 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
     // Getter/Setters
     // *************************************************************************
 
-    @ManagedAttribute(description = "The route id")
-    public String getRouteId() {
-        if (route != null) {
-            return route.getId();
-        }
-        return null;
-    }
-
-    @ManagedAttribute(description = "The consumer endpoint", mask = true)
-    public String getEndpointUrl() {
-        if (route != null && route.getConsumer() != null && route.getConsumer().getEndpoint() != null) {
-            return route.getConsumer().getEndpoint().toString();
-        }
-        return null;
-    }
-
-    @ManagedAttribute(description = "Whether to stop consumer when starting up and failed to become master")
-    public boolean isShouldStopConsumer() {
-        return shouldStopConsumer;
+    @ManagedAttribute(description = "Whether to stop route when starting up and failed to become master")
+    public boolean isShouldStopRoute() {
+        return shouldStopRoute;
     }
 
-    public void setShouldStopConsumer(boolean shouldStopConsumer) {
-        this.shouldStopConsumer = shouldStopConsumer;
+    public void setShouldStopRoute(boolean shouldStopRoute) {
+        this.shouldStopRoute = shouldStopRoute;
     }
 
     @ManagedAttribute(description = "The lock map name")
@@ -380,7 +331,7 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
 
         @Override
         public void run() {
-            if (!isRunAllowed() || !InfinispanRoutePolicy.this.isRunAllowed()) {
+            if (!isRunAllowed()) {
                 return;
             }
 
@@ -455,7 +406,7 @@ public class InfinispanRoutePolicy extends RoutePolicySupport implements CamelCo
 
         @Override
         public void run() {
-            if (!isRunAllowed() || !InfinispanRoutePolicy.this.isRunAllowed()) {
+            if (!isRunAllowed()) {
                 return;
             }
 

http://git-wip-us.apache.org/repos/asf/camel/blob/54052a32/components/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicyTestBase.java
----------------------------------------------------------------------
diff --git a/components/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicyTestBase.java b/components/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicyTestBase.java
index cad44c1..43abf8f 100644
--- a/components/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicyTestBase.java
+++ b/components/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/policy/InfinispanRoutePolicyTestBase.java
@@ -16,40 +16,17 @@
  */
 package org.apache.camel.component.infinispan.policy;
 
-import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.test.junit4.CamelTestSupport;
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.model.RouteDefinition;
+import org.apache.camel.util.ServiceHelper;
 import org.infinispan.commons.api.BasicCacheContainer;
 import org.junit.Assert;
 import org.junit.Test;
 
-abstract class InfinispanRoutePolicyTestBase extends CamelTestSupport {
-    protected BasicCacheContainer cacheManager;
-    protected InfinispanRoutePolicy policy1;
-    protected InfinispanRoutePolicy policy2;
-
-    @Override
-    protected void doPreSetup() throws Exception {
-        this.cacheManager = createCacheManager();
-
-        this.policy1 = InfinispanRoutePolicy.withManager(cacheManager);
-        this.policy1.setLockMapName("camel-route-policy");
-        this.policy1.setLockKey("route-policy");
-        this.policy1.setLockValue("route1");
-
-        this.policy2 = InfinispanRoutePolicy.withManager(cacheManager);
-        this.policy2.setLockMapName("camel-route-policy");
-        this.policy2.setLockKey("route-policy");
-        this.policy2.setLockValue("route2");
-    }
-
-    @Override
-    public void tearDown() throws Exception {
-        super.tearDown();
-
-        if (this.cacheManager != null) {
-            this.cacheManager.stop();
-        }
-    }
+abstract class InfinispanRoutePolicyTestBase {
+    private final static String CACHE_NAME = "camel-route-policy";
+    private final static String CACHE_KEY = "route-policy";
 
     protected abstract BasicCacheContainer createCacheManager() throws Exception;
 
@@ -59,60 +36,50 @@ abstract class InfinispanRoutePolicyTestBase extends CamelTestSupport {
 
     @Test
     public void testLeadership()throws Exception {
-        context.startRoute("route1");
-        while (!policy1.isLeader()) {
-            Thread.sleep(250);
-        }
+        BasicCacheContainer cacheManager = createCacheManager();
 
-        context.startRoute("route2");
-        Thread.sleep(500);
+        InfinispanRoutePolicy policy1 = InfinispanRoutePolicy.withManager(cacheManager);
+        policy1.setLockMapName(CACHE_NAME);
+        policy1.setLockKey(CACHE_KEY);
+        policy1.setLockValue("route1");
 
-        Assert.assertTrue(policy1.isLeader());
-        Assert.assertFalse(policy2.isLeader());
+        InfinispanRoutePolicy policy2 = InfinispanRoutePolicy.withManager(cacheManager);
+        policy2.setLockMapName(CACHE_NAME);
+        policy2.setLockKey(CACHE_KEY);
+        policy2.setLockValue("route2");
 
-        context.stopRoute("route1");
-        while (!policy2.isLeader()) {
-            Thread.sleep(250);
-        }
+        CamelContext context = new DefaultCamelContext();
 
-        Assert.assertFalse(policy1.isLeader());
-        Assert.assertTrue(policy2.isLeader());
+        try {
+            context = new DefaultCamelContext();
+            context.start();
 
-        context.startRoute("route1");
-        Thread.sleep(500);
+            context.addRouteDefinition(RouteDefinition.fromUri("direct:r1").routePolicy(policy1).to("mock:p1"));
 
-        Assert.assertFalse(policy1.isLeader());
-        Assert.assertTrue(policy2.isLeader());
+            for (int i=0; i < 10 && !policy1.isLeader(); i++) {
+                Thread.sleep(250);
+            }
 
-        context.stopRoute("route2");
-        while (!policy1.isLeader()) {
-            Thread.sleep(250);
-        }
+            context.addRouteDefinition(RouteDefinition.fromUri("direct:r2").routePolicy(policy2).to("mock:p2"));
 
-        Assert.assertTrue(policy1.isLeader());
-        Assert.assertFalse(policy2.isLeader());
-    }
+            Assert.assertTrue(policy1.isLeader());
+            Assert.assertFalse(policy2.isLeader());
 
-    // *******************************************
-    //
-    // *******************************************
+            policy1.shutdown();
 
-    @Override
-    protected RouteBuilder createRouteBuilder() throws Exception {
-        return new RouteBuilder() {
-            @Override
-            public void configure() {
-                from("direct:route1")
-                    .routeId("route1")
-                    .autoStartup(false)
-                    .routePolicy(policy1)
-                    .to("log:org.apache.camel.component.infinispan.policy.1?level=INFO&showAll=true");
-                from("direct:route2")
-                    .routeId("route2")
-                    .autoStartup(false)
-                    .routePolicy(policy2)
-                    .to("log:org.apache.camel.component.infinispan.policy.2?level=INFO&showAll=true");
+            for (int i = 0; i < 10 && !policy2.isLeader(); i++) {
+                Thread.sleep(250);
             }
-        };
+
+            Assert.assertFalse(policy1.isLeader());
+            Assert.assertTrue(policy2.isLeader());
+
+        } finally {
+            ServiceHelper.stopService(context);
+
+            if (cacheManager != null) {
+                cacheManager.stop();
+            }
+        }
     }
 }


[05/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
CAMEL-10054: Create camel-atomix component


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

Branch: refs/heads/master
Commit: 9ddff22c1dad485f76fba820de7a12d2f4a1687e
Parents: 54052a3
Author: lburgazzoli <lb...@gmail.com>
Authored: Tue May 30 17:55:10 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:53 2017 +0200

----------------------------------------------------------------------
 apache-camel/pom.xml                            |   9 +
 .../src/main/descriptors/common-bin.xml         |   2 +
 components/camel-atomix/pom.xml                 |  89 ++++++++
 .../src/main/docs/atomix-component.adoc         |   6 +
 .../component/atomix/ha/AtomixCluster.java      |  47 +++++
 .../atomix/ha/AtomixClusterFactory.java         |  28 +++
 .../atomix/ha/AtomixClusterMember.java          |  45 ++++
 .../component/atomix/ha/AtomixClusterView.java  | 162 +++++++++++++++
 .../src/main/resources/META-INF/LICENSE.txt     | 203 +++++++++++++++++++
 .../src/main/resources/META-INF/NOTICE.txt      |  11 +
 .../services/org/apache/camel/component/atomix  |  18 ++
 .../services/org/apache/camel/ha/atomix         |  18 ++
 .../atomix/ha/AtomixRoutePolicyMain.java        | 119 +++++++++++
 .../src/test/resources/log4j2.properties        |  41 ++++
 components/pom.xml                              |   1 +
 parent/pom.xml                                  |  11 +
 .../camel-spring-boot-dependencies/pom.xml      |  10 +
 17 files changed, 820 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/apache-camel/pom.xml
----------------------------------------------------------------------
diff --git a/apache-camel/pom.xml b/apache-camel/pom.xml
index 27a1907..a61cdcc 100644
--- a/apache-camel/pom.xml
+++ b/apache-camel/pom.xml
@@ -88,6 +88,10 @@
     </dependency>
     <dependency>
       <groupId>org.apache.camel</groupId>
+      <artifactId>camel-atomix</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.camel</groupId>
       <artifactId>camel-aws</artifactId>
     </dependency>
     <dependency>
@@ -1168,6 +1172,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.camel</groupId>
+      <artifactId>camel-atomix-starter</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.camel</groupId>
       <artifactId>camel-avro-starter</artifactId>
       <version>${project.version}</version>
     </dependency>

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/apache-camel/src/main/descriptors/common-bin.xml
----------------------------------------------------------------------
diff --git a/apache-camel/src/main/descriptors/common-bin.xml b/apache-camel/src/main/descriptors/common-bin.xml
index ebf8f07..8f91230 100644
--- a/apache-camel/src/main/descriptors/common-bin.xml
+++ b/apache-camel/src/main/descriptors/common-bin.xml
@@ -33,6 +33,7 @@
         <include>org.apache.camel:camel-atmos</include>
         <include>org.apache.camel:camel-atmosphere-websocket</include>
         <include>org.apache.camel:camel-atom</include>
+        <include>org.apache.camel:camel-atomix</include>
         <include>org.apache.camel:camel-aws</include>
         <include>org.apache.camel:camel-azure</include>
         <include>org.apache.camel:camel-avro</include>
@@ -327,6 +328,7 @@
         <include>org.apache.camel:camel-atmosphere-websocket-starter</include>
         <include>org.apache.camel:camel-atmos-starter</include>
         <include>org.apache.camel:camel-atom-starter</include>
+        <include>org.apache.camel:camel-atomix-starter</include>
         <include>org.apache.camel:camel-avro-starter</include>
         <include>org.apache.camel:camel-aws-starter</include>
         <include>org.apache.camel:camel-bam-starter</include>

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/pom.xml
----------------------------------------------------------------------
diff --git a/components/camel-atomix/pom.xml b/components/camel-atomix/pom.xml
new file mode 100644
index 0000000..3afb62e
--- /dev/null
+++ b/components/camel-atomix/pom.xml
@@ -0,0 +1,89 @@
+<?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.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+
+  <parent>
+    <groupId>org.apache.camel</groupId>
+    <artifactId>components</artifactId>
+    <version>2.20.0-SNAPSHOT</version>
+  </parent>
+
+  <artifactId>camel-atomix</artifactId>
+  <packaging>jar</packaging>
+  <name>Camel :: Atomix</name>
+  <description>Camel Atomix support</description>
+
+  <properties>
+    <camel.osgi.export.pkg>org.apache.camel.component.atomix.*</camel.osgi.export.pkg>
+    <camel.osgi.export.service>
+      org.apache.camel.spi.ComponentResolver;component=atomix
+    </camel.osgi.export.service>
+  </properties>
+
+  <dependencies>
+
+    <dependency>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-core</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+
+    <!-- atomix -->
+    <dependency>
+      <groupId>io.atomix</groupId>
+      <artifactId>atomix-all</artifactId>
+      <version>${atomix-version}</version>
+    </dependency>
+
+    <!-- logging -->       
+    <dependency>
+      <groupId>org.apache.logging.log4j</groupId>
+      <artifactId>log4j-api</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.logging.log4j</groupId>
+      <artifactId>log4j-core</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.logging.log4j</groupId>
+      <artifactId>log4j-slf4j-impl</artifactId>
+      <scope>test</scope>
+    </dependency>
+
+    <!-- testing -->
+    <dependency>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-test</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-test-spring</artifactId>
+      <scope>test</scope>
+    </dependency>
+
+  </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/docs/atomix-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-component.adoc b/components/camel-atomix/src/main/docs/atomix-component.adoc
new file mode 100644
index 0000000..e499f1b
--- /dev/null
+++ b/components/camel-atomix/src/main/docs/atomix-component.adoc
@@ -0,0 +1,6 @@
+## Atomix Component
+
+*Available as of Camel version 2.20*
+
+The camel atomix component allows you to work with Atomix, a fault-tolerant distributed coordination framework.
+

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
new file mode 100644
index 0000000..56f9084
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
@@ -0,0 +1,47 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import io.atomix.Atomix;
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.ha.AbstractCamelCluster;
+
+/**
+ * TODO: Dummy implementation for testing purpose
+ */
+public class AtomixCluster extends AbstractCamelCluster<AtomixClusterView> {
+    private final Atomix atomix;
+
+    public AtomixCluster(Atomix atomix) {
+       this(null, atomix);
+    }
+
+    public AtomixCluster(CamelContext camelContext, Atomix atomix) {
+        super("camel-atomix", camelContext);
+
+        this.atomix = atomix;
+    }
+
+    @Override
+    public AtomixClusterView doCreateView(String namespace) throws Exception {
+        return new AtomixClusterView(
+            this,
+            namespace,
+            atomix.getGroup(namespace).join()
+        );
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java
new file mode 100644
index 0000000..a0f6835
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java
@@ -0,0 +1,28 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterFactory;
+
+public class AtomixClusterFactory implements CamelClusterFactory {
+    @Override
+    public CamelCluster newInstance(CamelContext camelContext) throws Exception {
+        throw new UnsupportedOperationException("Not yet implemented");
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java
new file mode 100644
index 0000000..6268931
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java
@@ -0,0 +1,45 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import io.atomix.group.DistributedGroup;
+import io.atomix.group.GroupMember;
+import org.apache.camel.ha.CamelClusterMember;
+
+class AtomixClusterMember<M extends GroupMember> implements CamelClusterMember {
+    private final DistributedGroup group;
+    private final M member;
+
+    AtomixClusterMember(DistributedGroup group, M member) {
+        this.group = group;
+        this.member = member;
+    }
+
+    @Override
+    public String getId() {
+        return member.id();
+    }
+
+    @Override
+    public boolean isMaster() {
+        return group.election().term().leader().equals(member);
+    }
+
+    M getGroupMember() {
+      return member;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
new file mode 100644
index 0000000..6c8f9e5
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
@@ -0,0 +1,162 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+
+import io.atomix.group.DistributedGroup;
+import io.atomix.group.GroupMember;
+import io.atomix.group.LocalMember;
+import org.apache.camel.ha.CamelClusterMember;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.impl.ha.AbstractCamelClusterView;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class AtomixClusterView extends AbstractCamelClusterView {
+    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixClusterView.class);
+
+    private final DistributedGroup group;
+    private final AtomixLocalMember localMember;
+
+    AtomixClusterView(AtomixCluster cluster, String namespace, DistributedGroup group) {
+        super(cluster, namespace);
+
+        this.group = group;
+        this.localMember = new AtomixLocalMember(group);
+    }
+
+    @Override
+    public CamelClusterMember getMaster() {
+        return asCamelClusterMember(this.group.election().term().leader());
+    }
+
+    @Override
+    public CamelClusterMember getLocalMember() {
+        return this.localMember;
+    }
+
+    @Override
+    public List<CamelClusterMember> getMembers() {
+        // TODO: Dummy implementation for testing purpose
+        return this.group.members().stream()
+            .map(this::asCamelClusterMember)
+            .collect(Collectors.toList());
+    }
+
+    private AtomixClusterMember asCamelClusterMember(GroupMember member) {
+        return new AtomixClusterMember(group, member);
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        if (!this.localMember.hasJoined()) {
+            this.localMember.join();
+            this.group.election().onElection(
+                t -> fireEvent(CamelClusterView.Event.LEADERSHIP_CHANGED, asCamelClusterMember(t.leader()))
+            );
+        }
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        localMember.leave();
+    }
+
+    // ***********************************************
+    //
+    // ***********************************************
+
+    class AtomixLocalMember implements CamelClusterMember {
+        private final DistributedGroup group;
+        private LocalMember member;
+
+        AtomixLocalMember(DistributedGroup group) {
+            this.group = group;
+        }
+
+        @Override
+        public String getId() {
+            if (member == null) {
+                throw new IllegalStateException("Cluster not yet joined");
+            }
+
+            return member.id();
+        }
+
+        @Override
+        public boolean isMaster() {
+            if (member == null) {
+                return false;
+            }
+
+            return group.election().term().leader().equals(member);
+        }
+
+        boolean hasJoined() {
+            return member != null;
+        }
+
+        AtomixLocalMember join() throws ExecutionException, InterruptedException {
+            if (member == null) {
+                LOGGER.debug("Joining group {}", group);
+                member = this.group.join().get();
+            }
+
+            return this;
+        }
+
+        AtomixLocalMember leave() {
+            if (member != null) {
+                LOGGER.debug("Leaving group {}", group);
+                member.leave();
+            }
+
+            return this;
+        }
+
+        LocalMember get() {
+            return member;
+        }
+    }
+
+    class AtomixClusterMember implements CamelClusterMember {
+        private final DistributedGroup group;
+        private final GroupMember member;
+
+        AtomixClusterMember(DistributedGroup group, GroupMember member) {
+            this.group = group;
+            this.member = member;
+        }
+
+        @Override
+        public String getId() {
+            return member.id();
+        }
+
+        @Override
+        public boolean isMaster() {
+            return group.election().term().leader().equals(member);
+        }
+
+        GroupMember get() {
+            return member;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/resources/META-INF/LICENSE.txt
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/LICENSE.txt b/components/camel-atomix/src/main/resources/META-INF/LICENSE.txt
new file mode 100644
index 0000000..6b0b127
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/LICENSE.txt
@@ -0,0 +1,203 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
+

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/resources/META-INF/NOTICE.txt
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/NOTICE.txt b/components/camel-atomix/src/main/resources/META-INF/NOTICE.txt
new file mode 100644
index 0000000..2e215bf
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/NOTICE.txt
@@ -0,0 +1,11 @@
+   =========================================================================
+   ==  NOTICE file corresponding to the section 4 d of                    ==
+   ==  the Apache License, Version 2.0,                                   ==
+   ==  in this case for the Apache Camel distribution.                    ==
+   =========================================================================
+
+   This product includes software developed by
+   The Apache Software Foundation (http://www.apache.org/).
+
+   Please read the different LICENSE files present in the licenses directory of
+   this distribution.

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix
new file mode 100644
index 0000000..d4f1673
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix
@@ -0,0 +1,18 @@
+#
+# 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.
+#
+
+#class=org.apache.camel.component.atomix.AtomixComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
new file mode 100644
index 0000000..2330253
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
@@ -0,0 +1,18 @@
+#
+# 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.
+#
+
+class=org.apache.camel.component.atomix.ha.AtomixClusterFactory

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
new file mode 100644
index 0000000..78ef149
--- /dev/null
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
@@ -0,0 +1,119 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import io.atomix.Atomix;
+import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Address;
+import io.atomix.catalyst.transport.netty.NettyTransport;
+import io.atomix.copycat.server.storage.Storage;
+import io.atomix.copycat.server.storage.StorageLevel;
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.impl.ha.ClusteredRoutePolicy;
+import org.apache.camel.test.AvailablePortFinder;
+import org.apache.camel.util.FileUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class AtomixRoutePolicyMain {
+    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixRoutePolicyMain.class);
+
+    private static final List<Address> ADDRESSES =  Arrays.asList(
+        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
+        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
+        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable())
+    );
+
+    private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(ADDRESSES.size() * 3);
+
+    public static void main(final String[] args) throws Exception {
+        for (Address address :  ADDRESSES) {
+            EXECUTOR.submit(() -> setupContext(address));
+        }
+
+        EXECUTOR.awaitTermination(5, TimeUnit.MINUTES);
+    }
+
+    static void setupContext(Address address) {
+        try {
+            final String id = String.format("atomix-%d", address.port());
+            final File path = new File("target", id);
+
+            // Cleanup
+            FileUtil.removeDir(path);
+
+            Atomix atomix = AtomixReplica.builder(address)
+                .withTransport(new NettyTransport())
+                .withStorage(
+                    Storage.builder()
+                        .withDirectory(path)
+                        .withStorageLevel(StorageLevel.DISK)
+                        .build())
+                .build()
+                .bootstrap(ADDRESSES)
+                .join();
+
+            CountDownLatch latch = new CountDownLatch(1);
+            CamelContext context = new DefaultCamelContext();
+            CamelCluster cluster = new AtomixCluster(atomix);
+            CamelClusterView view = cluster.createView("my-view");
+
+            view.addEventListener((e, p) -> {
+                if (view.getLocalMember().isMaster()) {
+                    LOGGER.info("{}, is now master", address);
+                    try {
+                        EXECUTOR.schedule(latch::countDown, 10, TimeUnit.SECONDS);
+                    } catch (Exception ex) {
+                        throw new RuntimeException(ex);
+                    }
+                }
+            });
+
+            context.disableJMX();
+            context.addService(cluster, true, true);
+            context.addRoutes(new RouteBuilder() {
+                @Override
+                public void configure() throws Exception {
+                    fromF("timer:%s?period=1s", id)
+                        .routeId(id)
+                        .routePolicy(new ClusteredRoutePolicy(view))
+                        .setHeader("ClusterMaster")
+                            .body(b -> view.getMaster().getId())
+                        .log("${routeId} - master is: ${header.ClusterMaster}");
+                }
+            });
+
+            context.start();
+            latch.await();
+            context.stop();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/camel-atomix/src/test/resources/log4j2.properties
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/resources/log4j2.properties b/components/camel-atomix/src/test/resources/log4j2.properties
new file mode 100644
index 0000000..1e650b1
--- /dev/null
+++ b/components/camel-atomix/src/test/resources/log4j2.properties
@@ -0,0 +1,41 @@
+## ---------------------------------------------------------------------------
+## 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.
+## ---------------------------------------------------------------------------
+
+appender.file.type = File
+appender.file.name = file
+appender.file.fileName = target/camel-atomix-test.log
+appender.file.layout.type = PatternLayout
+appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
+appender.out.type = Console
+appender.out.name = out
+appender.out.layout.type = PatternLayout
+appender.out.layout.pattern = [%30.30t] %-30.30c{1} %-5p %m%n
+
+logger.atomix.name = io.atomix
+logger.atomix.level = WARN
+
+logger.camel.name = org.apache.camel
+logger.camel.level = INFO
+logger.camel-atomix.name = org.apache.camel.component.atomix
+logger.camel-atomix.level = DEBUG
+logger.camel-ha.name = org.apache.camel.ha
+logger.camel-ha.level = DEBUG
+logger.camel-impl-ha.name = org.apache.camel.impl.ha
+logger.camel-impl-ha.level = DEBUG
+
+rootLogger.level = INFO
+rootLogger.appenderRef.file.ref = out

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/components/pom.xml
----------------------------------------------------------------------
diff --git a/components/pom.xml b/components/pom.xml
index ae40921..497ec84 100644
--- a/components/pom.xml
+++ b/components/pom.xml
@@ -73,6 +73,7 @@
     <module>camel-atmos</module>
     <module>camel-atmosphere-websocket</module>
     <module>camel-atom</module>
+    <module>camel-atomix</module>
     <module>camel-avro</module>
     <module>camel-aws</module>
     <module>camel-azure</module>

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 3fe3f74..29a8069 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -71,6 +71,7 @@
     <atmos-client-version>2.2.2</atmos-client-version>
     <atmosphere-version>2.4.10</atmosphere-version>
     <atmosphere-version-range>[2.4,3.0)</atmosphere-version-range>
+    <atomix-version>1.0.8</atomix-version>
     <automaton-bundle-version>1.11-8_1</automaton-bundle-version>
     <avalon-bundle-version>4.3.1_1</avalon-bundle-version>
     <avalon-version>4.3.1</avalon-version>
@@ -835,6 +836,11 @@
       </dependency>
       <dependency>
         <groupId>org.apache.camel</groupId>
+        <artifactId>camel-atomix</artifactId>
+        <version>${project.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.apache.camel</groupId>
         <artifactId>camel-avro</artifactId>
         <version>${project.version}</version>
       </dependency>
@@ -2280,6 +2286,11 @@
       </dependency>
       <dependency>
         <groupId>org.apache.camel</groupId>
+        <artifactId>camel-atomix-starter</artifactId>
+        <version>${project.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.apache.camel</groupId>
         <artifactId>camel-avro-starter</artifactId>
         <version>${project.version}</version>
       </dependency>

http://git-wip-us.apache.org/repos/asf/camel/blob/9ddff22c/platforms/spring-boot/spring-boot-dm/camel-spring-boot-dependencies/pom.xml
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/spring-boot-dm/camel-spring-boot-dependencies/pom.xml b/platforms/spring-boot/spring-boot-dm/camel-spring-boot-dependencies/pom.xml
index bbbfa7f..4e21a2a 100644
--- a/platforms/spring-boot/spring-boot-dm/camel-spring-boot-dependencies/pom.xml
+++ b/platforms/spring-boot/spring-boot-dm/camel-spring-boot-dependencies/pom.xml
@@ -299,6 +299,16 @@
       </dependency>
       <dependency>
         <groupId>org.apache.camel</groupId>
+        <artifactId>camel-atomx</artifactId>
+        <version>${project.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.apache.camel</groupId>
+        <artifactId>camel-atomix-starter</artifactId>
+        <version>${project.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.apache.camel</groupId>
         <artifactId>camel-avro</artifactId>
         <version>${project.version}</version>
       </dependency>


[11/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
CAMEL-10054: Create camel-atomix component


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

Branch: refs/heads/master
Commit: 4d7fbb545710a1b9918e92c1f7b3c4dae5f1d72e
Parents: 2573fe6
Author: lburgazzoli <lb...@gmail.com>
Authored: Wed Jun 14 10:33:30 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:55 2017 +0200

----------------------------------------------------------------------
 .../component/atomix/AtomixConfiguration.java   |   1 +
 .../atomix/client/AtomixClientComponent.java    |   1 +
 .../client/AtomixClientConfiguration.java       |   1 +
 .../atomix/cluster/AtomixClusterComponent.java  |   1 +
 .../cluster/AtomixClusterConfiguration.java     |   1 +
 .../atomix/cluster/AtomixClusterHelper.java     |   1 +
 .../component/atomix/ha/AtomixCluster.java      | 191 -------------------
 .../atomix/ha/AtomixClusterService.java         | 180 +++++++++++++++++
 .../component/atomix/ha/AtomixClusterView.java  |  29 +--
 .../services/org/apache/camel/ha/atomix         |   2 +-
 .../atomix/ha/AtomixRoutePolicyMain.java        |  75 --------
 .../atomix/ha/AtomixRoutePolicyTest.java        | 116 +++++++++++
 .../src/test/resources/log4j2.properties        |   2 +-
 13 files changed, 322 insertions(+), 279 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
index 4504488..d0e3203 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
@@ -12,6 +12,7 @@
  * 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.camel.component.atomix;
 

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
index c4348c4..775315b 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
@@ -12,6 +12,7 @@
  * 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.camel.component.atomix.client;
 

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
index 628f88b..d3134c4 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
@@ -12,6 +12,7 @@
  * 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.camel.component.atomix.client;
 

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
index fa1cace..8db6487 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
@@ -12,6 +12,7 @@
  * 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.camel.component.atomix.cluster;
 

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
index 6a61eb9..8a732e1 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
@@ -12,6 +12,7 @@
  * 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.camel.component.atomix.cluster;
 

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
index 4e03627..777a4f6 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
@@ -12,6 +12,7 @@
  * 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.camel.component.atomix.cluster;
 

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
deleted file mode 100644
index ac8dbc7..0000000
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * 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.camel.component.atomix.ha;
-
-import java.util.List;
-
-import io.atomix.Atomix;
-import io.atomix.AtomixReplica;
-import io.atomix.catalyst.transport.Address;
-import io.atomix.catalyst.transport.Transport;
-import io.atomix.copycat.server.storage.StorageLevel;
-import org.apache.camel.CamelContext;
-import org.apache.camel.component.atomix.cluster.AtomixClusterConfiguration;
-import org.apache.camel.component.atomix.cluster.AtomixClusterHelper;
-import org.apache.camel.impl.ha.AbstractCamelCluster;
-import org.apache.camel.util.ObjectHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class AtomixCluster extends AbstractCamelCluster<AtomixClusterView> {
-    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixCluster.class);
-
-    private CamelContext camelContext;
-    private Address address;
-    private AtomixClusterConfiguration configuration;
-    private AtomixReplica atomix;
-
-    public AtomixCluster() {
-        super("atomix");
-
-        this.configuration = new AtomixClusterConfiguration();
-    }
-
-    public AtomixCluster(CamelContext camelContext, Address address, AtomixClusterConfiguration configuration) {
-        super("atomix");
-
-        this.camelContext = camelContext;
-        this.address = address;
-        this.configuration = configuration.copy();
-    }
-
-    // **********************************
-    // Properties
-    // **********************************
-
-    @Override
-    public CamelContext getCamelContext() {
-        return camelContext;
-    }
-
-    @Override
-    public void setCamelContext(CamelContext camelContext) {
-        this.camelContext = camelContext;
-    }
-
-    public Address getAddress() {
-        return address;
-    }
-
-    public void setAddress(String address) {
-        this.address = new Address(address);
-    }
-
-    public void setAddress(Address address) {
-        this.address = address;
-    }
-
-    public AtomixClusterConfiguration getConfiguration() {
-        return configuration;
-    }
-
-    public void setConfiguration(AtomixClusterConfiguration configuration) {
-        this.configuration = configuration.copy();
-    }
-
-    public String getStoragePath() {
-        return configuration.getStoragePath();
-    }
-
-    public void setStoragePath(String storagePath) {
-        configuration.setStoragePath(storagePath);
-    }
-
-    public List<Address> getNodes() {
-        return configuration.getNodes();
-    }
-
-    public StorageLevel getStorageLevel() {
-        return configuration.getStorageLevel();
-    }
-
-    public void setNodes(List<Address> nodes) {
-        configuration.setNodes(nodes);
-    }
-
-    public void setStorageLevel(StorageLevel storageLevel) {
-        configuration.setStorageLevel(storageLevel);
-    }
-
-    public void setNodes(String nodes) {
-        configuration.setNodes(nodes);
-    }
-
-    public Class<? extends Transport> getTransport() {
-        return configuration.getTransport();
-    }
-
-    public void setTransport(Class<? extends Transport> transport) {
-        configuration.setTransport(transport);
-    }
-
-    public String getReplicaRef() {
-        return configuration.getReplicaRef();
-    }
-
-    public void setReplicaRef(String clusterref) {
-        configuration.setReplicaRef(clusterref);
-    }
-
-    public Atomix getReplica() {
-        return configuration.getReplica();
-    }
-
-    public void setReplica(AtomixReplica replica) {
-        configuration.setReplica(replica);
-    }
-
-    public String getConfigurationUri() {
-        return configuration.getConfigurationUri();
-    }
-
-    public void setConfigurationUri(String configurationUri) {
-        configuration.setConfigurationUri(configurationUri);
-    }
-
-    // *********************************************
-    // Lifecycle
-    // *********************************************
-
-    @Override
-    protected void doStart() throws Exception {
-        // Assume that if addresses are provided the cluster needs be bootstrapped.
-        if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
-            LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
-            getOrCreateAtomix().bootstrap(configuration.getNodes()).join();
-            LOGGER.debug("Bootstrap cluster done");
-        }
-
-        super.doStart();
-    }
-
-    @Override
-    protected AtomixClusterView createView(String namespace) throws Exception {
-        return new AtomixClusterView(this, namespace, getOrCreateAtomix());
-    }
-
-
-    private AtomixReplica getOrCreateAtomix() throws Exception {
-        if (atomix == null) {
-            // Validate parameters
-            ObjectHelper.notNull(camelContext, "Camel Context");
-            ObjectHelper.notNull(address, "Atomix Node Address");
-            ObjectHelper.notNull(configuration, "Atomix Node Configuration");
-
-            atomix = AtomixClusterHelper.createReplica(camelContext, address, configuration);
-
-            // Assume that if addresses are provided the cluster needs be bootstrapped.
-            if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
-                LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
-                this.atomix.bootstrap(configuration.getNodes()).join();
-                LOGGER.debug("Bootstrap cluster done");
-            }
-        }
-
-        return this.atomix;
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
new file mode 100644
index 0000000..6a6a750
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
@@ -0,0 +1,180 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import java.util.List;
+
+import io.atomix.Atomix;
+import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Address;
+import io.atomix.catalyst.transport.Transport;
+import io.atomix.copycat.server.storage.StorageLevel;
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.atomix.cluster.AtomixClusterConfiguration;
+import org.apache.camel.component.atomix.cluster.AtomixClusterHelper;
+import org.apache.camel.impl.ha.AbstractCamelClusterService;
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class AtomixClusterService extends AbstractCamelClusterService<AtomixClusterView> {
+    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixClusterService.class);
+
+    private Address address;
+    private AtomixClusterConfiguration configuration;
+    private AtomixReplica atomix;
+
+    public AtomixClusterService() {
+        this.configuration = new AtomixClusterConfiguration();
+    }
+
+    public AtomixClusterService(CamelContext camelContext, Address address, AtomixClusterConfiguration configuration) {
+        super(null, camelContext);
+
+        this.address = address;
+        this.configuration = configuration.copy();
+    }
+
+    // **********************************
+    // Properties
+    // **********************************
+
+    public Address getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = new Address(address);
+    }
+
+    public void setAddress(Address address) {
+        this.address = address;
+    }
+
+    public AtomixClusterConfiguration getConfiguration() {
+        return configuration;
+    }
+
+    public void setConfiguration(AtomixClusterConfiguration configuration) {
+        this.configuration = configuration.copy();
+    }
+
+    public String getStoragePath() {
+        return configuration.getStoragePath();
+    }
+
+    public void setStoragePath(String storagePath) {
+        configuration.setStoragePath(storagePath);
+    }
+
+    public List<Address> getNodes() {
+        return configuration.getNodes();
+    }
+
+    public StorageLevel getStorageLevel() {
+        return configuration.getStorageLevel();
+    }
+
+    public void setNodes(List<Address> nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public void setStorageLevel(StorageLevel storageLevel) {
+        configuration.setStorageLevel(storageLevel);
+    }
+
+    public void setNodes(String nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public Class<? extends Transport> getTransport() {
+        return configuration.getTransport();
+    }
+
+    public void setTransport(Class<? extends Transport> transport) {
+        configuration.setTransport(transport);
+    }
+
+    public String getReplicaRef() {
+        return configuration.getReplicaRef();
+    }
+
+    public void setReplicaRef(String clusterref) {
+        configuration.setReplicaRef(clusterref);
+    }
+
+    public Atomix getReplica() {
+        return configuration.getReplica();
+    }
+
+    public void setReplica(AtomixReplica replica) {
+        configuration.setReplica(replica);
+    }
+
+    public String getConfigurationUri() {
+        return configuration.getConfigurationUri();
+    }
+
+    public void setConfigurationUri(String configurationUri) {
+        configuration.setConfigurationUri(configurationUri);
+    }
+
+    // *********************************************
+    // Lifecycle
+    // *********************************************
+
+    @Override
+    protected void doStart() throws Exception {
+        // Assume that if addresses are provided the cluster needs be bootstrapped.
+        if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
+            LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
+            getOrCreateAtomix().bootstrap(configuration.getNodes()).join();
+            LOGGER.debug("Bootstrap cluster done");
+        }
+
+        super.doStart();
+    }
+
+    @Override
+    protected AtomixClusterView createView(String namespace) throws Exception {
+        return new AtomixClusterView(this, namespace, getOrCreateAtomix());
+    }
+
+
+    private AtomixReplica getOrCreateAtomix() throws Exception {
+        if (atomix == null) {
+            // Validate parameters
+            ObjectHelper.notNull(getCamelContext(), "Camel Context");
+            ObjectHelper.notNull(address, "Atomix Node Address");
+            ObjectHelper.notNull(configuration, "Atomix Node Configuration");
+
+            atomix = AtomixClusterHelper.createReplica(getCamelContext(), address, configuration);
+
+            if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
+                LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
+                this.atomix.bootstrap(configuration.getNodes()).join();
+                LOGGER.debug("Bootstrap cluster done");
+            } else {
+                LOGGER.debug("Bootstrap cluster on address {}", address, configuration.getNodes());
+                this.atomix.bootstrap().join();
+                LOGGER.debug("Bootstrap cluster done");
+            }
+        }
+
+        return this.atomix;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
index bf1c4d1..5078508 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
@@ -24,10 +24,9 @@ import io.atomix.Atomix;
 import io.atomix.group.DistributedGroup;
 import io.atomix.group.GroupMember;
 import io.atomix.group.LocalMember;
-import io.atomix.group.election.Term;
 import org.apache.camel.ha.CamelClusterMember;
-import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.impl.ha.AbstractCamelClusterView;
+import org.apache.camel.util.ObjectHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,7 +37,7 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
     private final AtomixLocalMember localMember;
     private DistributedGroup group;
 
-    AtomixClusterView(AtomixCluster cluster, String namespace, Atomix atomix) {
+    AtomixClusterView(AtomixClusterService cluster, String namespace, Atomix atomix) {
         super(cluster, namespace);
 
         this.atomix = atomix;
@@ -84,7 +83,13 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
             localMember.join();
 
             LOGGER.debug("Listen election events");
-            group.election().onElection(this::onElection);
+            group.election().onElection(term -> fireLeadershipChangedEvent(asCamelClusterMember(term.leader())));
+
+            LOGGER.debug("Listen join events");
+            group.onJoin(member -> fireMemberAddedEvent(asCamelClusterMember(member)));
+
+            LOGGER.debug("Listen leave events");
+            group.onLeave(member -> fireMemberRemovedEvent(asCamelClusterMember(member)));
         }
     }
 
@@ -93,10 +98,6 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
         localMember.leave();
     }
 
-    private void onElection(Term term) {
-        fireEvent(CamelClusterView.Event.LEADERSHIP_CHANGED, asCamelClusterMember(term.leader()));
-    }
-
     // ***********************************************
     //
     // ***********************************************
@@ -122,7 +123,7 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
                 return false;
             }
 
-            return group.election().term().leader().equals(member);
+            return member.equals(group.election().term().leader());
         }
 
         boolean hasJoined() {
@@ -131,8 +132,14 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
 
         AtomixLocalMember join() throws ExecutionException, InterruptedException {
             if (member == null && group != null) {
-                LOGGER.debug("Joining group {}", group);
-                member = group.join().join();
+                String id = getClusterService().getId();
+                if (ObjectHelper.isNotEmpty(id)) {
+                    LOGGER.debug("Joining group: {}, with id: {}", group, id);
+                    member = group.join(id).join();
+                } else {
+                    LOGGER.debug("Joining group: {} ", group);
+                    member = group.join().join();
+                }
             }
 
             return this;

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
index 2330253..a80d8bf 100644
--- a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
+++ b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/ha/atomix
@@ -15,4 +15,4 @@
 # limitations under the License.
 #
 
-class=org.apache.camel.component.atomix.ha.AtomixClusterFactory
+class=org.apache.camel.component.atomix.ha.AtomixClusterService

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
deleted file mode 100644
index e0e253f..0000000
--- a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * 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.camel.component.atomix.ha;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import io.atomix.catalyst.transport.Address;
-import io.atomix.copycat.server.storage.StorageLevel;
-import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.impl.DefaultCamelContext;
-import org.apache.camel.impl.ha.ClusteredRoutePolicyFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class AtomixRoutePolicyMain {
-    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixRoutePolicyMain.class);
-
-    public static void main(final String[] args) throws Exception {
-        final Integer index = Integer.getInteger("atomix.index");
-        final String[] addresses = System.getProperty("atomix.cluster").split(",");
-
-        List<Address> nodes = new ArrayList<>();
-        for (int i = 0; i < addresses.length; i++) {
-            String[] parts = addresses[i].split(":");
-            nodes.add(new Address(parts[0], Integer.valueOf(parts[1])));
-        }
-
-        AtomixCluster cluster = new AtomixCluster();
-        cluster.setStorageLevel(StorageLevel.MEMORY);
-        cluster.setAddress(nodes.get(index));
-        cluster.setNodes(nodes);
-
-        DefaultCamelContext context = new DefaultCamelContext();
-        context.addService(cluster);
-        context.addRoutePolicyFactory(ClusteredRoutePolicyFactory.forNamespace("my-ns"));
-        context.addRoutes(new RouteBuilder() {
-            @Override
-            public void configure() throws Exception {
-                fromF("timer:atomix-%d-1?period=2s", nodes.get(index).port())
-                    .log("${routeId} (1)");
-                fromF("timer:atomix-%d-2?period=5s", nodes.get(index).port())
-                    .log("${routeId} (2)");
-            }
-        });
-
-        context.start();
-
-        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
-            try {
-                context.stop();
-            } catch (Exception e) {
-                LOGGER.warn("", e);
-            }
-        }));
-
-        for (int i = 0; i < Integer.MAX_VALUE; i++) {
-            Thread.sleep(1000);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyTest.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyTest.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyTest.java
new file mode 100644
index 0000000..c70372a
--- /dev/null
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyTest.java
@@ -0,0 +1,116 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+
+import io.atomix.catalyst.transport.Address;
+import io.atomix.copycat.server.storage.StorageLevel;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.impl.ha.ClusteredRoutePolicyFactory;
+import org.apache.camel.test.AvailablePortFinder;
+import org.junit.Assert;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class AtomixRoutePolicyTest {
+    private static final List<Address> ADDRESSES = Arrays.asList(
+        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
+        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
+        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable())
+    );
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixRoutePolicyTest.class);
+    private static final Set<Address> RESULTS = new HashSet<>();
+    private static final ScheduledExecutorService SCHEDULER = Executors.newScheduledThreadPool(ADDRESSES.size() * 2);
+    private static final CountDownLatch LATCH = new CountDownLatch(ADDRESSES.size());
+
+    // ************************************
+    // Test
+    // ************************************
+
+    @Test
+    public void test() throws Exception {
+        for (Address address: ADDRESSES) {
+            SCHEDULER.submit(() -> run(address));
+        }
+
+        LATCH.await(1, TimeUnit.MINUTES);
+        SCHEDULER.shutdownNow();
+
+        Assert.assertEquals(ADDRESSES.size(), RESULTS.size());
+        Assert.assertTrue(RESULTS.containsAll(ADDRESSES));
+    }
+
+    // ************************************
+    // Run a Camel node
+    // ************************************
+
+    private static void run(Address address) {
+        try {
+            CountDownLatch contextLatch = new CountDownLatch(1);
+
+            AtomixClusterService service = new AtomixClusterService();
+            service.setId("node-" + address.port());
+            service.setStorageLevel(StorageLevel.MEMORY);
+            service.setAddress(address);
+            service.setNodes(ADDRESSES);
+
+            DefaultCamelContext context = new DefaultCamelContext();
+            context.disableJMX();
+            context.setName("context-" + address.port());
+            context.addService(service);
+            context.addRoutePolicyFactory(ClusteredRoutePolicyFactory.forNamespace("my-ns"));
+            context.addRoutes(new RouteBuilder() {
+                @Override
+                public void configure() throws Exception {
+                    from("timer:atomix?delay=1s&period=1s&repeatCount=1")
+                        .routeId("route-" + address.port())
+                        .process(e -> {
+                            LOGGER.debug("Node {} done", address);
+                            RESULTS.add(address);
+                            // Shutdown the context later on to give a chance to
+                            // other members to catch-up
+                            SCHEDULER.schedule(contextLatch::countDown, 2 + ThreadLocalRandom.current().nextInt(3), TimeUnit.SECONDS);
+                        });
+                }
+            });
+
+            // Start the context after some random time so the startup order
+            // changes for each test.
+            Thread.sleep(ThreadLocalRandom.current().nextInt(500));
+            context.start();
+
+            contextLatch.await();
+            context.stop();
+
+            LATCH.countDown();
+        } catch (Exception e) {
+            LOGGER.warn("", e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/4d7fbb54/components/camel-atomix/src/test/resources/log4j2.properties
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/resources/log4j2.properties b/components/camel-atomix/src/test/resources/log4j2.properties
index 1e650b1..d70cd9d 100644
--- a/components/camel-atomix/src/test/resources/log4j2.properties
+++ b/components/camel-atomix/src/test/resources/log4j2.properties
@@ -38,4 +38,4 @@ logger.camel-impl-ha.name = org.apache.camel.impl.ha
 logger.camel-impl-ha.level = DEBUG
 
 rootLogger.level = INFO
-rootLogger.appenderRef.file.ref = out
+rootLogger.appenderRef.file.ref = file


[12/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
index 5078508..f7e3be1d 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
@@ -16,7 +16,9 @@
  */
 package org.apache.camel.component.atomix.ha;
 
+import java.util.Collections;
 import java.util.List;
+import java.util.Optional;
 import java.util.concurrent.ExecutionException;
 import java.util.stream.Collectors;
 
@@ -30,7 +32,7 @@ import org.apache.camel.util.ObjectHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public final class AtomixClusterView extends AbstractCamelClusterView {
+final class AtomixClusterView extends AbstractCamelClusterView {
     private static final Logger LOGGER = LoggerFactory.getLogger(AtomixClusterView.class);
 
     private final Atomix atomix;
@@ -45,12 +47,17 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
     }
 
     @Override
-    public CamelClusterMember getMaster() {
+    public Optional<CamelClusterMember> getMaster() {
         if (group == null) {
-            throw new IllegalStateException("The view has not yet joined the cluster");
+            return Optional.empty();
         }
 
-        return asCamelClusterMember(group.election().term().leader());
+        GroupMember leader = group.election().term().leader();
+        if (leader == null) {
+            return Optional.empty();
+        }
+
+        return Optional.of(asCamelClusterMember(leader));
     }
 
     @Override
@@ -61,7 +68,7 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
     @Override
     public List<CamelClusterMember> getMembers() {
         if (group == null) {
-            throw new IllegalStateException("The view has not yet joined the cluster");
+            return Collections.emptyList();
         }
 
         return this.group.members().stream()
@@ -105,11 +112,13 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
     class AtomixLocalMember implements CamelClusterMember {
         private LocalMember member;
 
-        AtomixLocalMember() {
-        }
-
         @Override
         public String getId() {
+            String id = getClusterService().getId();
+            if (ObjectHelper.isNotEmpty(id)) {
+                return id;
+            }
+
             if (member == null) {
                 throw new IllegalStateException("The view has not yet joined the cluster");
             }
@@ -153,10 +162,6 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
 
             return this;
         }
-
-        LocalMember get() {
-            return member;
-        }
     }
 
     class AtomixClusterMember implements CamelClusterMember {
@@ -175,11 +180,7 @@ public final class AtomixClusterView extends AbstractCamelClusterView {
 
         @Override
         public boolean isMaster() {
-            return group.election().term().leader().equals(member);
-        }
-
-        GroupMember get() {
-            return member;
+            return member.equals(group.election().term().leader());
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client
deleted file mode 100644
index 5e7a620..0000000
--- a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client
+++ /dev/null
@@ -1,18 +0,0 @@
-#
-# 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.
-#
-
-class=org.apache.camel.component.atomix.AtomixClientComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-map
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-map b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-map
new file mode 100644
index 0000000..268c354
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-map
@@ -0,0 +1,18 @@
+#
+# 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.
+#
+
+class=org.apache.camel.component.atomix.client.map.AtomixClientMapComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/AtomixClientTestSupport.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/AtomixClientTestSupport.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/AtomixClientTestSupport.java
new file mode 100644
index 0000000..5251627
--- /dev/null
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/AtomixClientTestSupport.java
@@ -0,0 +1,72 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import io.atomix.AtomixClient;
+import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Address;
+import org.apache.camel.component.atomix.AtomixHelper;
+import org.apache.camel.test.AvailablePortFinder;
+import org.apache.camel.test.junit4.CamelTestSupport;
+
+public abstract class AtomixClientTestSupport extends CamelTestSupport {
+    private Address replicaAddress;
+    private AtomixReplica replica;
+    private AtomixClient client;
+
+    @Override
+    protected void doPreSetup() throws Exception {
+        replicaAddress = new Address("127.0.0.1", AvailablePortFinder.getNextAvailable());
+
+        replica = AtomixReplica.builder(replicaAddress).withStorage(AtomixHelper.inMemoryStorage()).build();
+        replica.bootstrap().join();
+
+        client = AtomixClient.builder().build();
+        client.connect(replicaAddress).join();
+
+        super.doPreSetup();
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        if (client != null) {
+            client.close().join();
+        }
+        if (replica != null) {
+            replica.shutdown().join();
+            replica.leave().join();
+        }
+
+        super.tearDown();
+    }
+
+    // *************************************
+    // properties
+    // *************************************
+
+    protected Address getReplicaAddress() {
+        return replicaAddress;
+    }
+
+    protected AtomixReplica getReplica() {
+        return replica;
+    }
+
+    protected AtomixClient getClient() {
+        return client;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumerTest.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumerTest.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumerTest.java
new file mode 100644
index 0000000..8a7728a
--- /dev/null
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumerTest.java
@@ -0,0 +1,115 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import java.util.Collections;
+import java.util.UUID;
+
+import io.atomix.collections.DistributedMap;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.atomix.client.AtomixClientConstants;
+import org.apache.camel.component.atomix.client.AtomixClientTestSupport;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.JndiRegistry;
+import org.junit.Ignore;
+import org.junit.Test;
+
+@Ignore
+public class AtomixClientMapConsumerTest extends AtomixClientTestSupport {
+    private static final String MAP_NAME = UUID.randomUUID().toString();
+    private DistributedMap<Object, Object> map;
+
+    // ************************************
+    // Setup
+    // ************************************
+
+    @Override
+    protected JndiRegistry createRegistry() throws Exception {
+        JndiRegistry registry = super.createRegistry();
+
+        AtomixClientMapComponent component = new AtomixClientMapComponent();
+        component.setNodes(Collections.singletonList(getReplicaAddress()));
+
+        registry.bind("atomix-map", component);
+
+        return registry;
+    }
+
+    @Override
+    protected void doPreSetup() throws Exception {
+        super.doPreSetup();
+
+        map = getClient().getMap(MAP_NAME).join();
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        map.close();
+
+        super.tearDown();
+    }
+
+    // ************************************
+    // Test
+    // ************************************
+
+    @Test
+    public void test() throws Exception {
+        String key = context().getUuidGenerator().generateUuid();
+        String put = context().getUuidGenerator().generateUuid();
+        String upd = context().getUuidGenerator().generateUuid();
+
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.assertExchangeReceived(3);
+        mock.expectedBodiesReceived(put, upd, upd);
+        mock.expectedHeaderReceived(AtomixClientConstants.RESOURCE_KEY, key);
+
+        map.put(key, put).join();
+        map.replace(key, upd).join();
+        map.remove(key).join();
+
+        mock.assertIsSatisfied();
+
+        assertEquals(
+            DistributedMap.Events.ADD,
+            mock.getExchanges().get(0).getIn().getHeader(AtomixClientConstants.EVENT_TYPE)
+        );
+        assertEquals(
+            DistributedMap.Events.UPDATE,
+            mock.getExchanges().get(1).getIn().getHeader(AtomixClientConstants.EVENT_TYPE)
+        );
+        assertEquals(
+            DistributedMap.Events.REMOVE,
+            mock.getExchanges().get(2).getIn().getHeader(AtomixClientConstants.EVENT_TYPE)
+        );
+    }
+
+    // ************************************
+    // Routes
+    // ************************************
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            public void configure() {
+                fromF("atomix-map:%s", MAP_NAME)
+                    .to("mock:result");
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducerTest.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducerTest.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducerTest.java
new file mode 100644
index 0000000..f46d628
--- /dev/null
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducerTest.java
@@ -0,0 +1,398 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+
+import io.atomix.collections.DistributedMap;
+import org.apache.camel.EndpointInject;
+import org.apache.camel.FluentProducerTemplate;
+import org.apache.camel.Message;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.atomix.client.AtomixClientAction;
+import org.apache.camel.component.atomix.client.AtomixClientConstants;
+import org.apache.camel.component.atomix.client.AtomixClientTestSupport;
+import org.apache.camel.impl.JndiRegistry;
+import org.junit.Test;
+
+import static org.hamcrest.core.Is.is;
+
+public class AtomixClientMapProducerTest extends AtomixClientTestSupport {
+    private static final String MAP_NAME = UUID.randomUUID().toString();
+    private DistributedMap<Object, Object> map;
+
+    @EndpointInject(uri = "direct:start")
+    private FluentProducerTemplate fluent;
+
+    // ************************************
+    // Setup
+    // ************************************
+
+    @Override
+    protected JndiRegistry createRegistry() throws Exception {
+        JndiRegistry registry = super.createRegistry();
+
+        AtomixClientMapComponent component = new AtomixClientMapComponent();
+        component.setNodes(Collections.singletonList(getReplicaAddress()));
+
+        registry.bind("atomix-map", component);
+
+        return registry;
+    }
+
+    @Override
+    protected void doPreSetup() throws Exception {
+        super.doPreSetup();
+
+        map = getClient().getMap(MAP_NAME).join();
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        map.close();
+
+        super.tearDown();
+    }
+
+    // ************************************
+    // Test
+    // ************************************
+
+    @Test
+    public void testPut() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val = context().getUuidGenerator().generateUuid();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.PUT)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withHeader(AtomixClientConstants.RESOURCE_TTL, Duration.ofMillis(250))
+            .withBody(val)
+            .request(Message.class);
+
+        assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(val, result.getBody());
+        assertEquals(val, map.get(key).join());
+
+        CountDownLatch latch = new CountDownLatch(1);
+        map.onRemove(e -> latch.countDown());
+
+        latch.await();
+
+        assertFalse(val, map.containsKey(key).join());
+    }
+
+    @Test
+    public void testPutIfAbsent() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val1 = context().getUuidGenerator().generateUuid();
+        final String val2 = context().getUuidGenerator().generateUuid();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.PUT_IF_ABSENT)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withBody(val1)
+            .request(Message.class);
+
+        assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(val1, result.getBody());
+        assertEquals(val1, map.get(key).join());
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.PUT_IF_ABSENT)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withBody(val2)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(val1, result.getBody());
+        assertEquals(val1, map.get(key).join());
+    }
+
+    @Test
+    public void testGet() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val = context().getUuidGenerator().generateUuid();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.GET)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .request(Message.class);
+
+        assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertFalse(map.containsKey(key).join());
+
+        map.put(key, val).join();
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.GET)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(val, result.getBody(String.class));
+        assertTrue(map.containsKey(key).join());
+    }
+
+    @Test
+    public void testSizeClearIsEmpty() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val = context().getUuidGenerator().generateUuid();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.SIZE)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(0, result.getBody(Integer.class).intValue());
+        assertEquals(map.size().join(), result.getBody(Integer.class));
+
+        map.put(key, val).join();
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.SIZE)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(1, result.getBody(Integer.class).intValue());
+        assertEquals(map.size().join(), result.getBody(Integer.class));
+
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.IS_EMPTY)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertFalse(result.getBody(Boolean.class));
+        assertFalse(map.isEmpty().join());
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.CLEAR)
+            .request(Message.class);
+
+        assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(0, map.size().join().intValue());
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.IS_EMPTY)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertTrue(result.getBody(Boolean.class));
+        assertTrue(map.isEmpty().join());
+    }
+
+    @Test
+    public void testContainsKey() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val = context().getUuidGenerator().generateUuid();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.CONTAINS_KEY)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withBody(val)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertFalse(result.getBody(Boolean.class));
+        assertFalse(map.containsKey(key).join());
+
+        map.put(key, val).join();
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.CONTAINS_KEY)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withBody(val)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertTrue(result.getBody(Boolean.class));
+        assertTrue(map.containsKey(key).join());
+    }
+
+    @Test
+    public void testContainsValue() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val = context().getUuidGenerator().generateUuid();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.CONTAINS_VALUE)
+            .withHeader(AtomixClientConstants.RESOURCE_VALUE, val)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertFalse(result.getBody(Boolean.class));
+        assertFalse(map.containsKey(key).join());
+
+        map.put(key, val).join();
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.CONTAINS_VALUE)
+            .withHeader(AtomixClientConstants.RESOURCE_VALUE, val)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertTrue(result.getBody(Boolean.class));
+        assertTrue(map.containsValue(val).join());
+    }
+
+    @Test
+    public void testRemove() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String val = context().getUuidGenerator().generateUuid();
+
+        map.put(key, val).join();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.REMOVE)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withHeader(AtomixClientConstants.RESOURCE_VALUE, context().getUuidGenerator().generateUuid())
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertFalse(result.getBody(Boolean.class));
+        assertTrue(map.containsKey(key).join());
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.REMOVE)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withHeader(AtomixClientConstants.RESOURCE_VALUE, val)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertTrue(result.getBody(Boolean.class));
+        assertFalse(map.containsKey(key).join());
+
+        map.put(key, val).join();
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.REMOVE)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(val, result.getBody(String.class));
+        assertFalse(map.containsKey(key).join());
+    }
+
+    @Test
+    public void testReplace() throws Exception {
+        final String key = context().getUuidGenerator().generateUuid();
+        final String oldVal = context().getUuidGenerator().generateUuid();
+        final String newVal = context().getUuidGenerator().generateUuid();
+
+        map.put(key, oldVal).join();
+
+        Message result;
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.REPLACE)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withHeader(AtomixClientConstants.RESOURCE_OLD_VALUE, context().getUuidGenerator().generateUuid())
+            .withBody(newVal)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertFalse(result.getBody(Boolean.class));
+        assertEquals(oldVal, map.get(key).join());
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.REPLACE)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withHeader(AtomixClientConstants.RESOURCE_OLD_VALUE, oldVal)
+            .withBody(newVal)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertTrue(result.getBody(Boolean.class));
+        assertEquals(newVal, map.get(key).join());
+
+        map.put(key, oldVal).join();
+
+        result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.REPLACE)
+            .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
+            .withBody(newVal)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(oldVal, result.getBody(String.class));
+        assertEquals(newVal, map.get(key).join());
+    }
+
+    @Test
+    public void testValues() throws Exception {
+        map.put(context().getUuidGenerator().generateUuid(), context().getUuidGenerator().generateUuid()).join();
+        map.put(context().getUuidGenerator().generateUuid(), context().getUuidGenerator().generateUuid()).join();
+        map.put(context().getUuidGenerator().generateUuid(), context().getUuidGenerator().generateUuid()).join();
+
+        Message result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.VALUES)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertThat(map.values().join(), is(result.getBody(Collection.class)));
+    }
+
+    @Test
+    public void testEntrySet() throws Exception {
+        map.put(context().getUuidGenerator().generateUuid(), context().getUuidGenerator().generateUuid()).join();
+        map.put(context().getUuidGenerator().generateUuid(), context().getUuidGenerator().generateUuid()).join();
+        map.put(context().getUuidGenerator().generateUuid(), context().getUuidGenerator().generateUuid()).join();
+
+        Message result = fluent.clearAll()
+            .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixClientAction.ENTRY_SET)
+            .request(Message.class);
+
+        assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
+        assertEquals(map.entrySet().join().size(), result.getBody(Set.class).size());
+    }
+
+    // ************************************
+    // Routes
+    // ************************************
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            public void configure() {
+                from("direct:start")
+                    .toF("atomix-map:%s", MAP_NAME);
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 29a8069..7ea2d9a 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -72,6 +72,7 @@
     <atmosphere-version>2.4.10</atmosphere-version>
     <atmosphere-version-range>[2.4,3.0)</atmosphere-version-range>
     <atomix-version>1.0.8</atomix-version>
+    <atomix-catalyst-version>1.2.1</atomix-catalyst-version>
     <automaton-bundle-version>1.11-8_1</automaton-bundle-version>
     <avalon-bundle-version>4.3.1_1</avalon-bundle-version>
     <avalon-version>4.3.1</avalon-version>

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentAutoConfiguration.java
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentAutoConfiguration.java b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentAutoConfiguration.java
new file mode 100644
index 0000000..f6e8b5a
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentAutoConfiguration.java
@@ -0,0 +1,129 @@
+/**
+ * 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.camel.component.atomix.client.map.springboot;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Generated;
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.atomix.client.map.AtomixClientMapComponent;
+import org.apache.camel.spi.ComponentCustomizer;
+import org.apache.camel.spi.HasId;
+import org.apache.camel.spring.boot.CamelAutoConfiguration;
+import org.apache.camel.spring.boot.ComponentConfigurationProperties;
+import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans;
+import org.apache.camel.spring.boot.util.GroupCondition;
+import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator;
+import org.apache.camel.util.IntrospectionSupport;
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Lazy;
+
+/**
+ * Generated by camel-package-maven-plugin - do not edit this file!
+ */
+@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
+@Configuration
+@Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class,
+        AtomixClientMapComponentAutoConfiguration.GroupConditions.class})
+@AutoConfigureAfter(CamelAutoConfiguration.class)
+@EnableConfigurationProperties({ComponentConfigurationProperties.class,
+        AtomixClientMapComponentConfiguration.class})
+public class AtomixClientMapComponentAutoConfiguration {
+
+    private static final Logger LOGGER = LoggerFactory
+            .getLogger(AtomixClientMapComponentAutoConfiguration.class);
+    @Autowired
+    private ApplicationContext applicationContext;
+    @Autowired
+    private CamelContext camelContext;
+    @Autowired
+    private AtomixClientMapComponentConfiguration configuration;
+    @Autowired(required = false)
+    private List<ComponentCustomizer<AtomixClientMapComponent>> customizers;
+
+    static class GroupConditions extends GroupCondition {
+        public GroupConditions() {
+            super("camel.component", "camel.component.atomix-map");
+        }
+    }
+
+    @Lazy
+    @Bean(name = "atomix-map-component")
+    @ConditionalOnMissingBean(AtomixClientMapComponent.class)
+    public AtomixClientMapComponent configureAtomixClientMapComponent()
+            throws Exception {
+        AtomixClientMapComponent component = new AtomixClientMapComponent();
+        component.setCamelContext(camelContext);
+        Map<String, Object> parameters = new HashMap<>();
+        IntrospectionSupport.getProperties(configuration, parameters, null,
+                false);
+        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
+            Object value = entry.getValue();
+            Class<?> paramClass = value.getClass();
+            if (paramClass.getName().endsWith("NestedConfiguration")) {
+                Class nestedClass = null;
+                try {
+                    nestedClass = (Class) paramClass.getDeclaredField(
+                            "CAMEL_NESTED_CLASS").get(null);
+                    HashMap<String, Object> nestedParameters = new HashMap<>();
+                    IntrospectionSupport.getProperties(value, nestedParameters,
+                            null, false);
+                    Object nestedProperty = nestedClass.newInstance();
+                    IntrospectionSupport.setProperties(camelContext,
+                            camelContext.getTypeConverter(), nestedProperty,
+                            nestedParameters);
+                    entry.setValue(nestedProperty);
+                } catch (NoSuchFieldException e) {
+                }
+            }
+        }
+        IntrospectionSupport.setProperties(camelContext,
+                camelContext.getTypeConverter(), component, parameters);
+        if (ObjectHelper.isNotEmpty(customizers)) {
+            for (ComponentCustomizer<AtomixClientMapComponent> customizer : customizers) {
+                boolean useCustomizer = (customizer instanceof HasId)
+                        ? HierarchicalPropertiesEvaluator.evaluate(
+                                applicationContext.getEnvironment(),
+                                "camel.component.customizer",
+                                "camel.component.atomix-map.customizer",
+                                ((HasId) customizer).getId())
+                        : HierarchicalPropertiesEvaluator.evaluate(
+                                applicationContext.getEnvironment(),
+                                "camel.component.customizer",
+                                "camel.component.atomix-map.customizer");
+                if (useCustomizer) {
+                    LOGGER.debug("Configure component {}, with customizer {}",
+                            component, customizer);
+                    customizer.customize(component);
+                }
+            }
+        }
+        return component;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentConfiguration.java
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentConfiguration.java b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentConfiguration.java
new file mode 100644
index 0000000..867d74f
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/java/org/apache/camel/component/atomix/client/map/springboot/AtomixClientMapComponentConfiguration.java
@@ -0,0 +1,103 @@
+/**
+ * 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.camel.component.atomix.client.map.springboot;
+
+import java.util.List;
+import javax.annotation.Generated;
+import io.atomix.AtomixClient;
+import io.atomix.catalyst.transport.Address;
+import org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.boot.context.properties.NestedConfigurationProperty;
+
+/**
+ * Camel Atomix support
+ * 
+ * Generated by camel-package-maven-plugin - do not edit this file!
+ */
+@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
+@ConfigurationProperties(prefix = "camel.component.atomix-map")
+public class AtomixClientMapComponentConfiguration
+        extends
+            ComponentConfigurationPropertiesCommon {
+
+    /**
+     * The shared component configuration
+     */
+    @NestedConfigurationProperty
+    private C configuration;
+    /**
+     * The shared AtomixClient instance
+     */
+    @NestedConfigurationProperty
+    private AtomixClient atomix;
+    /**
+     * The nodes the AtomixClient should connect to
+     */
+    private List<Address> nodes;
+    /**
+     * The path to the AtomixClient configuration
+     */
+    private String configurationUri;
+    /**
+     * Whether the component should resolve property placeholders on itself when
+     * starting. Only properties which are of String type can use property
+     * placeholders.
+     */
+    private Boolean resolvePropertyPlaceholders = true;
+
+    public C getConfiguration() {
+        return configuration;
+    }
+
+    public void setConfiguration(C configuration) {
+        this.configuration = configuration;
+    }
+
+    public AtomixClient getAtomix() {
+        return atomix;
+    }
+
+    public void setAtomix(AtomixClient atomix) {
+        this.atomix = atomix;
+    }
+
+    public List<Address> getNodes() {
+        return nodes;
+    }
+
+    public void setNodes(List<Address> nodes) {
+        this.nodes = nodes;
+    }
+
+    public String getConfigurationUri() {
+        return configurationUri;
+    }
+
+    public void setConfigurationUri(String configurationUri) {
+        this.configurationUri = configurationUri;
+    }
+
+    public Boolean getResolvePropertyPlaceholders() {
+        return resolvePropertyPlaceholders;
+    }
+
+    public void setResolvePropertyPlaceholders(
+            Boolean resolvePropertyPlaceholders) {
+        this.resolvePropertyPlaceholders = resolvePropertyPlaceholders;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.factories
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.factories b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.factories
new file mode 100644
index 0000000..a0f99a3
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.factories
@@ -0,0 +1,19 @@
+## ---------------------------------------------------------------------------
+## 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.
+## ---------------------------------------------------------------------------
+
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+org.apache.camel.component.atomix.client.map.springboot.AtomixClientMapComponentAutoConfiguration


[03/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
CAMEL-10054: Create camel-atomix component


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

Branch: refs/heads/master
Commit: 490766539527f823a32cb4aaffa46005956835c7
Parents: b6f1bdd
Author: lburgazzoli <lb...@gmail.com>
Authored: Thu Jun 1 12:27:37 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:53 2017 +0200

----------------------------------------------------------------------
 .../atomix/ha/AtomixRoutePolicyMain.java        | 49 +++++++++++++-------
 1 file changed, 32 insertions(+), 17 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/49076653/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
index 78ef149..0a126d3 100644
--- a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
@@ -36,6 +36,7 @@ import org.apache.camel.ha.CamelCluster;
 import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.camel.impl.ha.ClusteredRoutePolicy;
+import org.apache.camel.spi.RoutePolicy;
 import org.apache.camel.test.AvailablePortFinder;
 import org.apache.camel.util.FileUtil;
 import org.slf4j.Logger;
@@ -44,23 +45,27 @@ import org.slf4j.LoggerFactory;
 public final class AtomixRoutePolicyMain {
     private static final Logger LOGGER = LoggerFactory.getLogger(AtomixRoutePolicyMain.class);
 
+
     private static final List<Address> ADDRESSES =  Arrays.asList(
         new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
         new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
         new Address("127.0.0.1", AvailablePortFinder.getNextAvailable())
     );
 
-    private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(ADDRESSES.size() * 3);
+    private static final CountDownLatch LATCH = new CountDownLatch(ADDRESSES.size());
+    private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(ADDRESSES.size() * 2);
 
     public static void main(final String[] args) throws Exception {
         for (Address address :  ADDRESSES) {
-            EXECUTOR.submit(() -> setupContext(address));
+            EXECUTOR.submit(() -> run(address));
         }
 
-        EXECUTOR.awaitTermination(5, TimeUnit.MINUTES);
+        LATCH.await();
+
+        System.exit(0);
     }
 
-    static void setupContext(Address address) {
+    static void run(Address address) {
         try {
             final String id = String.format("atomix-%d", address.port());
             final File path = new File("target", id);
@@ -73,7 +78,7 @@ public final class AtomixRoutePolicyMain {
                 .withStorage(
                     Storage.builder()
                         .withDirectory(path)
-                        .withStorageLevel(StorageLevel.DISK)
+                        .withStorageLevel(StorageLevel.MEMORY)
                         .build())
                 .build()
                 .bootstrap(ADDRESSES)
@@ -86,34 +91,44 @@ public final class AtomixRoutePolicyMain {
 
             view.addEventListener((e, p) -> {
                 if (view.getLocalMember().isMaster()) {
-                    LOGGER.info("{}, is now master", address);
-                    try {
-                        EXECUTOR.schedule(latch::countDown, 10, TimeUnit.SECONDS);
-                    } catch (Exception ex) {
-                        throw new RuntimeException(ex);
-                    }
+                    LOGGER.info("Member {} ({}), is now master", view.getLocalMember().getId(), address);
+
+                    // Shutdown the context later on so the next one should take
+                    // the leadership
+                    EXECUTOR.schedule(latch::countDown, 10, TimeUnit.SECONDS);
                 }
             });
 
-            context.disableJMX();
-            context.addService(cluster, true, true);
+            context.addService(cluster);
             context.addRoutes(new RouteBuilder() {
                 @Override
                 public void configure() throws Exception {
-                    fromF("timer:%s?period=1s", id)
-                        .routeId(id)
-                        .routePolicy(new ClusteredRoutePolicy(view))
+                    RoutePolicy policy = ClusteredRoutePolicy.forView(view);
+
+                    fromF("timer:%s-1?period=2s", id)
+                        .routeId(id + "-1")
+                        .routePolicy(policy)
                         .setHeader("ClusterMaster")
                             .body(b -> view.getMaster().getId())
-                        .log("${routeId} - master is: ${header.ClusterMaster}");
+                        .log("${routeId} (1) - master is: ${header.ClusterMaster}");
+                    fromF("timer:%s-2?period=5s", id)
+                        .routeId(id + "-2")
+                        .routePolicy(policy)
+                        .setHeader("ClusterMaster")
+                            .body(b -> view.getMaster().getId())
+                        .log("${routeId} (2) - master is: ${header.ClusterMaster}");
                 }
             });
 
             context.start();
             latch.await();
             context.stop();
+
+            LATCH.countDown();
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
+
+        LOGGER.info("Done {}", address);
     }
 }


[08/13] camel git commit: CAMEL-11362: create a LeaderElectionservice

Posted by lb...@apache.org.
CAMEL-11362: create a LeaderElectionservice


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

Branch: refs/heads/master
Commit: 2573fe6d7e5323c8b7bd3c4df962481e56e5cb9b
Parents: a5d4df8
Author: lburgazzoli <lb...@gmail.com>
Authored: Wed Jun 14 10:33:17 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:54 2017 +0200

----------------------------------------------------------------------
 .../camel/ha/CameClusterEventListener.java      |  32 +++++
 .../java/org/apache/camel/ha/CamelCluster.java  |  32 -----
 .../org/apache/camel/ha/CamelClusterHelper.java |  28 ----
 .../apache/camel/ha/CamelClusterService.java    |  32 +++++
 .../org/apache/camel/ha/CamelClusterView.java   |  30 +---
 .../camel/impl/ha/AbstractCamelCluster.java     | 125 -----------------
 .../impl/ha/AbstractCamelClusterService.java    | 137 +++++++++++++++++++
 .../camel/impl/ha/AbstractCamelClusterView.java | 108 ++++++---------
 .../camel/impl/ha/ClusteredRoutePolicy.java     |  28 ++--
 .../impl/ha/ClusteredRoutePolicyFactory.java    |   8 +-
 .../camel/util/concurrent/LockHelper.java       |  66 +++++++++
 .../camel/util/function/ThrowingRunnable.java   |  22 +++
 12 files changed, 356 insertions(+), 292 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/ha/CameClusterEventListener.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CameClusterEventListener.java b/camel-core/src/main/java/org/apache/camel/ha/CameClusterEventListener.java
new file mode 100644
index 0000000..d021dc5
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CameClusterEventListener.java
@@ -0,0 +1,32 @@
+/**
+ * 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.camel.ha;
+
+/**
+ * Marker interface
+ */
+public interface CameClusterEventListener {
+
+    interface Leadership extends CameClusterEventListener {
+        void leadershipChanged(CamelClusterView view, CamelClusterMember leader);
+    }
+
+    interface Membership extends CameClusterEventListener {
+        void memberAdded(CamelClusterView view, CamelClusterMember leader);
+        void memberRemoved(CamelClusterView view, CamelClusterMember leader);
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
deleted file mode 100644
index a0a797f..0000000
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * 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.camel.ha;
-
-import org.apache.camel.CamelContextAware;
-import org.apache.camel.Service;
-import org.apache.camel.spi.HasId;
-
-public interface CamelCluster extends Service, CamelContextAware, HasId {
-    /**
-     * Get a view of the cluster bound to a namespace creating it if needed.
-     *
-     * @param namespace the namespace the view refer to.
-     * @return the view.
-     * @throws Exception if the view can't be created.
-     */
-    CamelClusterView getView(String namespace) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java
deleted file mode 100644
index c6f91ed..0000000
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 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.camel.ha;
-
-import java.util.function.Predicate;
-
-public final class CamelClusterHelper {
-    private CamelClusterHelper() {
-    }
-
-    public static Predicate<CamelClusterView.Event> leadershipEventFilter() {
-        return e -> e == CamelClusterView.Event.LEADERSHIP_CHANGED;
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
new file mode 100644
index 0000000..7dd12f3
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
@@ -0,0 +1,32 @@
+/**
+ * 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.camel.ha;
+
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.Service;
+import org.apache.camel.spi.IdAware;
+
+public interface CamelClusterService extends Service, CamelContextAware, IdAware {
+    /**
+     * Get a view of the cluster bound to a namespace creating it if needed.
+     *
+     * @param namespace the namespace the view refer to.
+     * @return the view.
+     * @throws Exception if the view can't be created.
+     */
+    CamelClusterView getView(String namespace) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
index bda7f8b..b076800 100644
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
@@ -17,8 +17,6 @@
 package org.apache.camel.ha;
 
 import java.util.List;
-import java.util.function.BiConsumer;
-import java.util.function.Predicate;
 
 import org.apache.camel.CamelContextAware;
 import org.apache.camel.Service;
@@ -27,16 +25,10 @@ import org.apache.camel.Service;
  * Represents the View of the cluster at some given period of time.
  */
 public interface CamelClusterView extends Service, CamelContextAware {
-
-    enum Event {
-        KEEP_ALIVE,
-        LEADERSHIP_CHANGED;
-    }
-
     /**
      * @return the cluster.
      */
-    CamelCluster getCluster();
+    CamelClusterService getClusterService();
 
     /**
      * @return the namespace for this view.
@@ -65,24 +57,16 @@ public interface CamelClusterView extends Service, CamelContextAware {
     List<CamelClusterMember> getMembers();
 
     /**
-     * Add an event consumer.
-     *
-     * @param consumer the event consumer.
-     */
-    void addEventListener(BiConsumer<Event, Object> consumer);
-
-    /**
-     * Add an event consumer for events matching the given predicate.
+     * Add an event listener.
      *
-     * @param predicate the predicate to filter events.
-     * @param consumer the event consumer.
+     * @param listener the event listener.
      */
-    void addEventListener(Predicate<Event> predicate, BiConsumer<Event, Object> consumer);
+    void addEventListener(CameClusterEventListener listener);
 
     /**
-     * Remove the event consumer.
+     * Remove the event listener.
      *
-     * @param event the event consumer.
+     * @param listener the event listener.
      */
-    void removeEventListener(BiConsumer<Event, Object> event);
+    void removeEventListener(CameClusterEventListener listener);
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
deleted file mode 100644
index 16a869b..0000000
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/**
- * 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.camel.impl.ha;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.locks.StampedLock;
-
-import org.apache.camel.CamelContext;
-import org.apache.camel.ha.CamelCluster;
-import org.apache.camel.ha.CamelClusterView;
-import org.apache.camel.support.ServiceSupport;
-
-public abstract class AbstractCamelCluster<T extends CamelClusterView> extends ServiceSupport implements CamelCluster {
-    private final String id;
-    private final Map<String, T> views;
-    private final StampedLock lock;
-    private CamelContext camelContext;
-
-    protected AbstractCamelCluster(String id) {
-        this(id, null);
-    }
-
-    protected AbstractCamelCluster(String id, CamelContext camelContext) {
-        this.id = id;
-        this.camelContext = camelContext;
-        this.views = new HashMap<>();
-        this.lock = new StampedLock();
-    }
-
-    @Override
-    public String getId() {
-        return id;
-    }
-
-    @Override
-    public void setCamelContext(CamelContext camelContext) {
-        this.camelContext = camelContext;
-
-        long stamp = lock.writeLock();
-
-        try {
-            for (T view : views.values()) {
-                view.setCamelContext(camelContext);
-            }
-        } finally {
-            lock.unlockWrite(stamp);
-        }
-    }
-
-    @Override
-    public CamelContext getCamelContext() {
-        return camelContext;
-    }
-
-    @Override
-    protected void doStart() throws Exception {
-        long stamp = lock.readLock();
-
-        try {
-            for (T view : views.values()) {
-                view.start();
-            }
-        } finally {
-            lock.unlockRead(stamp);
-        }
-    }
-
-    @Override
-    protected void doStop() throws Exception {
-        long stamp = lock.readLock();
-
-        try {
-            for (T view : views.values()) {
-                view.stop();
-            }
-        } finally {
-            lock.unlockRead(stamp);
-        }
-    }
-
-    @Override
-    public CamelClusterView getView(String namespace) throws Exception {
-        long stamp = lock.writeLock();
-
-        try {
-            T view = views.get(namespace);
-
-            if (view == null) {
-                view = createView(namespace);
-                view.setCamelContext(this.camelContext);
-
-                views.put(namespace, view);
-
-                if (AbstractCamelCluster.this.isRunAllowed()) {
-                    view.start();
-                }
-            }
-
-            return view;
-        } finally {
-            lock.unlockWrite(stamp);
-        }
-    }
-
-    // **********************************
-    // Implementation
-    // **********************************
-
-    protected abstract T createView(String namespace) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
new file mode 100644
index 0000000..2c63890
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
@@ -0,0 +1,137 @@
+/**
+ * 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.camel.impl.ha;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.locks.StampedLock;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ha.CamelClusterService;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.support.ServiceSupport;
+import org.apache.camel.util.concurrent.LockHelper;
+
+public abstract class AbstractCamelClusterService<T extends CamelClusterView> extends ServiceSupport implements CamelClusterService {
+    private final Map<String, T> views;
+    private final StampedLock lock;
+    private String id;
+    private CamelContext camelContext;
+
+    protected AbstractCamelClusterService() {
+        this(null, null);
+    }
+
+    protected AbstractCamelClusterService(String id) {
+        this(id, null);
+    }
+
+    protected AbstractCamelClusterService(String id, CamelContext camelContext) {
+        this.id = id;
+        this.camelContext = camelContext;
+        this.views = new HashMap<>();
+        this.lock = new StampedLock();
+    }
+
+    /**
+     * Sets the id
+     *
+     * @param id the id
+     */
+    @Override
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    @Override
+    public String getId() {
+        return id;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+
+        LockHelper.doWithWriteLock(
+            lock,
+            () -> {
+                for (T view : views.values()) {
+                    view.setCamelContext(camelContext);
+                }
+            }
+        );
+    }
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        LockHelper.doWithReadLockT(
+            lock,
+            () -> {
+                for (T view : views.values()) {
+                    view.start();
+                }
+            }
+        );
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        LockHelper.doWithReadLockT(
+            lock,
+            () -> {
+                for (T view : views.values()) {
+                    view.stop();
+                }
+            }
+        );
+    }
+
+    @Override
+    public CamelClusterView getView(String namespace) throws Exception {
+        long stamp = lock.writeLock();
+
+        try {
+            T view = views.get(namespace);
+
+            if (view == null) {
+                view = createView(namespace);
+                view.setCamelContext(this.camelContext);
+
+                views.put(namespace, view);
+
+                if (AbstractCamelClusterService.this.isRunAllowed()) {
+                    view.start();
+                }
+            }
+
+            return view;
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    // **********************************
+    // Implementation
+    // **********************************
+
+    protected abstract T createView(String namespace) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
index 8fc9c27..4e68124 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
@@ -19,25 +19,27 @@ package org.apache.camel.impl.ha;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.locks.StampedLock;
-import java.util.function.BiConsumer;
-import java.util.function.Predicate;
+import java.util.function.Consumer;
 
 import org.apache.camel.CamelContext;
-import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CameClusterEventListener;
+import org.apache.camel.ha.CamelClusterMember;
+import org.apache.camel.ha.CamelClusterService;
 import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.support.ServiceSupport;
+import org.apache.camel.util.concurrent.LockHelper;
 
 public abstract class AbstractCamelClusterView extends ServiceSupport implements CamelClusterView {
-    private final CamelCluster cluster;
+    private final CamelClusterService cluster;
     private final String namespace;
-    private final List<FilteringConsumer> consumers;
+    private final List<CameClusterEventListener> listeners;
     private final StampedLock lock;
     private CamelContext camelContext;
 
-    protected AbstractCamelClusterView(CamelCluster cluster, String namespace) {
+    protected AbstractCamelClusterView(CamelClusterService cluster, String namespace) {
         this.cluster = cluster;
         this.namespace = namespace;
-        this.consumers = new ArrayList<>();
+        this.listeners = new ArrayList<>();
         this.lock = new StampedLock();
     }
 
@@ -52,7 +54,7 @@ public abstract class AbstractCamelClusterView extends ServiceSupport implements
     }
 
     @Override
-    public CamelCluster getCluster() {
+    public CamelClusterService getClusterService() {
         return this.cluster;
     }
 
@@ -62,76 +64,52 @@ public abstract class AbstractCamelClusterView extends ServiceSupport implements
     }
 
     @Override
-    public void addEventListener(BiConsumer<Event, Object> consumer) {
-        long stamp = lock.writeLock();
-
-        try {
-            consumers.add(new FilteringConsumer(e -> true, consumer));
-        } finally {
-            lock.unlockWrite(stamp);
-        }
+    public void addEventListener(CameClusterEventListener listener) {
+        LockHelper.doWithWriteLock(lock, () -> listeners.add(listener));
     }
 
     @Override
-    public void addEventListener(Predicate<Event> predicate, BiConsumer<Event, Object> consumer) {
-        long stamp = lock.writeLock();
-
-        try {
-            consumers.add(new FilteringConsumer(predicate, consumer));
-        } finally {
-            lock.unlockWrite(stamp);
-        }
-    }
-
-    @Override
-    public void removeEventListener(BiConsumer<Event, Object> consumer) {
-        long stamp = lock.writeLock();
-
-        try {
-            consumers.removeIf(c -> c.getConsumer().equals(consumer));
-        } finally {
-            lock.unlockWrite(stamp);
-        }
+    public void removeEventListener(CameClusterEventListener listener) {
+        LockHelper.doWithWriteLock(lock, () -> listeners.removeIf(l -> l == listener));
     }
 
     // **************************************
     // Events
     // **************************************
 
-    protected void fireEvent(CamelClusterView.Event event, Object payload) {
-        long stamp = lock.readLock();
-
-        try {
-            for (int i = 0; i < consumers.size(); i++) {
-                consumers.get(i).accept(event, payload);
+    private <T extends CameClusterEventListener> void executeWithListener(Class<T> type, Consumer<T> consumer) {
+        LockHelper.doWithReadLock(
+            lock,
+            () -> {
+                for (int i = 0; i < listeners.size(); i++) {
+                    CameClusterEventListener listener = listeners.get(0);
+
+                    if (type.isInstance(listener)) {
+                        consumer.accept(type.cast(listener));
+                    }
+                }
             }
-        } finally {
-            lock.unlockRead(stamp);
-        }
+        );
     }
 
-    // **************************************
-    // Helpers
-    // **************************************
-
-    private final class FilteringConsumer implements BiConsumer<Event, Object> {
-        private final Predicate<Event> predicate;
-        private final BiConsumer<Event, Object> consumer;
-
-        FilteringConsumer(Predicate<Event> predicate,  BiConsumer<Event, Object> consumer) {
-            this.predicate = predicate;
-            this.consumer = consumer;
-        }
+    protected void fireLeadershipChangedEvent(CamelClusterMember leader) {
+        executeWithListener(
+            CameClusterEventListener.Leadership.class,
+            listener -> listener.leadershipChanged(this, leader)
+        );
+    }
 
-        @Override
-        public void accept(CamelClusterView.Event event, Object payload) {
-            if (predicate.test(event)) {
-                consumer.accept(event, payload);
-            }
-        }
+    protected void fireMemberAddedEvent(CamelClusterMember member) {
+        executeWithListener(
+            CameClusterEventListener.Membership.class,
+            listener -> listener.memberAdded(this, member)
+        );
+    }
 
-        public BiConsumer<Event, Object> getConsumer() {
-            return this.consumer;
-        }
+    protected void fireMemberRemovedEvent(CamelClusterMember member) {
+        executeWithListener(
+            CameClusterEventListener.Membership.class,
+            listener -> listener.memberRemoved(this, member)
+        );
     }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
index 74ca781..6d726f6 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
@@ -20,7 +20,6 @@ import java.util.EventObject;
 import java.util.HashSet;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.BiConsumer;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelContextAware;
@@ -28,8 +27,9 @@ import org.apache.camel.Route;
 import org.apache.camel.StartupListener;
 import org.apache.camel.api.management.ManagedAttribute;
 import org.apache.camel.api.management.ManagedResource;
-import org.apache.camel.ha.CamelCluster;
-import org.apache.camel.ha.CamelClusterHelper;
+import org.apache.camel.ha.CameClusterEventListener;
+import org.apache.camel.ha.CamelClusterMember;
+import org.apache.camel.ha.CamelClusterService;
 import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.management.event.CamelContextStartedEvent;
 import org.apache.camel.support.EventNotifierSupport;
@@ -47,14 +47,15 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
     private final Set<Route> stoppedRoutes;
     private final ReferenceCount refCount;
     private final CamelClusterView clusterView;
-    private final BiConsumer<CamelClusterView.Event, Object> leadershipEventConsumer;
+    private final CameClusterEventListener.Leadership leadershipEventListener;
     private final CamelContextStartupListener listener;
     private final AtomicBoolean contextStarted;
+
     private CamelContext camelContext;
 
     public ClusteredRoutePolicy(CamelClusterView clusterView) {
         this.clusterView = clusterView;
-        this.leadershipEventConsumer = this::onLeadershipEvent;
+        this.leadershipEventListener = new CamelClusterLeadershipListener();
 
         this.stoppedRoutes = new HashSet<>();
         this.startedRoutes = new HashSet<>();
@@ -69,13 +70,13 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
         }
 
         // Cleanup the policy when all the routes it manages have been shut down
-        // so it can be shared among routes.
+        // so a single policy instance can be shared among routes.
         this.refCount = ReferenceCount.onRelease(() -> {
             if (camelContext != null) {
                 camelContext.getManagementStrategy().removeEventNotifier(listener);
             }
 
-            clusterView.removeEventListener(leadershipEventConsumer);
+            clusterView.removeEventListener(leadershipEventListener);
             setLeader(false);
         });
     }
@@ -199,8 +200,11 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
     // Event handling
     // ****************************************************
 
-    private void onLeadershipEvent(CamelClusterView.Event event, Object payload) {
-        setLeader(clusterView.getLocalMember().isMaster());
+    private class CamelClusterLeadershipListener implements CameClusterEventListener.Leadership {
+        @Override
+        public void leadershipChanged(CamelClusterView view, CamelClusterMember leader) {
+            setLeader(clusterView.getLocalMember().isMaster());
+        }
     }
 
     private class CamelContextStartupListener extends EventNotifierSupport implements StartupListener {
@@ -236,7 +240,7 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
             // so start/stop of managed routes do not clash with CamelContext
             // startup
             if (contextStarted.compareAndSet(false, true)) {
-                clusterView.addEventListener(CamelClusterHelper.leadershipEventFilter(), leadershipEventConsumer);
+                clusterView.addEventListener(leadershipEventListener);
                 setLeader(clusterView.getLocalMember().isMaster());
             }
         }
@@ -247,7 +251,7 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
     // ****************************************************
 
     public static ClusteredRoutePolicy forNamespace(CamelContext camelContext, String namespace) throws Exception {
-        CamelCluster cluster = camelContext.hasService(CamelCluster.class);
+        CamelClusterService cluster = camelContext.hasService(CamelClusterService.class);
         if (cluster == null) {
             throw new IllegalStateException("CamelCluster service not found");
         }
@@ -255,7 +259,7 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
         return forNamespace(cluster, namespace);
     }
 
-    public static ClusteredRoutePolicy forNamespace(CamelCluster cluster, String namespace) throws Exception {
+    public static ClusteredRoutePolicy forNamespace(CamelClusterService cluster, String namespace) throws Exception {
         return forView(cluster.getView(namespace));
     }
 

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
index da07706..b7ed05a 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
@@ -18,7 +18,6 @@ package org.apache.camel.impl.ha;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.RuntimeCamelException;
-import org.apache.camel.ha.CamelCluster;
 import org.apache.camel.model.RouteDefinition;
 import org.apache.camel.spi.RoutePolicy;
 import org.apache.camel.spi.RoutePolicyFactory;
@@ -34,12 +33,7 @@ public class ClusteredRoutePolicyFactory implements RoutePolicyFactory {
     @Override
     public RoutePolicy createRoutePolicy(CamelContext camelContext, String routeId, RouteDefinition route) {
         try {
-            CamelCluster cluster = camelContext.hasService(CamelCluster.class);
-            if (cluster == null) {
-                throw new IllegalStateException("CamelCluster service not found");
-            }
-
-            return ClusteredRoutePolicy.forNamespace(cluster, namespace);
+            return ClusteredRoutePolicy.forNamespace(camelContext, namespace);
         } catch (Exception e) {
             throw new RuntimeCamelException(e);
         }

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java b/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
new file mode 100644
index 0000000..7825c2c
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
@@ -0,0 +1,66 @@
+/**
+ * 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.camel.util.concurrent;
+
+import java.util.concurrent.locks.StampedLock;
+
+import org.apache.camel.util.function.ThrowingRunnable;
+
+public final class LockHelper {
+    private LockHelper() {
+    }
+
+    public static void doWithReadLock(StampedLock lock, Runnable task) {
+        long stamp = lock.readLock();
+
+        try {
+            task.run();
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
+    public static <T extends Throwable> void doWithReadLockT(StampedLock lock, ThrowingRunnable<T> task) throws T {
+        long stamp = lock.readLock();
+
+        try {
+            task.run();
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
+    public static void doWithWriteLock(StampedLock lock, Runnable task) {
+        long stamp = lock.writeLock();
+
+        try {
+            task.run();
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    public static <T extends Throwable> void doWithWriteLockT(StampedLock lock, ThrowingRunnable<T> task) throws T {
+        long stamp = lock.writeLock();
+
+        try {
+            task.run();
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/2573fe6d/camel-core/src/main/java/org/apache/camel/util/function/ThrowingRunnable.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/util/function/ThrowingRunnable.java b/camel-core/src/main/java/org/apache/camel/util/function/ThrowingRunnable.java
new file mode 100644
index 0000000..5f8b6fa
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/util/function/ThrowingRunnable.java
@@ -0,0 +1,22 @@
+/**
+ * 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.camel.util.function;
+
+@FunctionalInterface
+public interface ThrowingRunnable<T extends Throwable> {
+    void run() throws T;
+}


[10/13] camel git commit: CAMEL-11362: create a LeaderElectionservice

Posted by lb...@apache.org.
CAMEL-11362: create a LeaderElectionservice


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

Branch: refs/heads/master
Commit: b3681ba7870d77f5b5ee3bdf01ca9f0810d5964a
Parents: 4d7fbb5
Author: lburgazzoli <lb...@gmail.com>
Authored: Wed Jun 14 15:12:42 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:55 2017 +0200

----------------------------------------------------------------------
 .../org/apache/camel/ha/CamelClusterView.java   |  5 +--
 .../impl/ha/AbstractCamelClusterService.java    | 34 ++++++++------------
 .../camel/impl/ha/AbstractCamelClusterView.java |  8 ++---
 .../camel/util/concurrent/LockHelper.java       | 21 ++++++++++++
 4 files changed, 42 insertions(+), 26 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/b3681ba7/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
index b076800..893ba4c 100644
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
@@ -17,6 +17,7 @@
 package org.apache.camel.ha;
 
 import java.util.List;
+import java.util.Optional;
 
 import org.apache.camel.CamelContextAware;
 import org.apache.camel.Service;
@@ -36,11 +37,11 @@ public interface CamelClusterView extends Service, CamelContextAware {
     String getNamespace();
 
     /**
-     * Provides the master member.
+     * Provides the master member if elected.
      *
      * @return the master member.
      */
-    CamelClusterMember getMaster();
+    Optional<CamelClusterMember> getMaster();
 
     /**
      * Provides the local member.

http://git-wip-us.apache.org/repos/asf/camel/blob/b3681ba7/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
index 2c63890..7c9f8ea 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterService.java
@@ -47,11 +47,6 @@ public abstract class AbstractCamelClusterService<T extends CamelClusterView> ex
         this.lock = new StampedLock();
     }
 
-    /**
-     * Sets the id
-     *
-     * @param id the id
-     */
     @Override
     public void setId(String id) {
         this.id = id;
@@ -107,26 +102,25 @@ public abstract class AbstractCamelClusterService<T extends CamelClusterView> ex
 
     @Override
     public CamelClusterView getView(String namespace) throws Exception {
-        long stamp = lock.writeLock();
-
-        try {
-            T view = views.get(namespace);
+        return LockHelper.callWithWriteLock(
+            lock,
+            () -> {
+                T view = views.get(namespace);
 
-            if (view == null) {
-                view = createView(namespace);
-                view.setCamelContext(this.camelContext);
+                if (view == null) {
+                    view = createView(namespace);
+                    view.setCamelContext(this.camelContext);
 
-                views.put(namespace, view);
+                    views.put(namespace, view);
 
-                if (AbstractCamelClusterService.this.isRunAllowed()) {
-                    view.start();
+                    if (AbstractCamelClusterService.this.isRunAllowed()) {
+                        view.start();
+                    }
                 }
-            }
 
-            return view;
-        } finally {
-            lock.unlockWrite(stamp);
-        }
+                return view;
+            }
+        );
     }
 
     // **********************************

http://git-wip-us.apache.org/repos/asf/camel/blob/b3681ba7/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
index 4e68124..b2cbe11 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
@@ -77,7 +77,7 @@ public abstract class AbstractCamelClusterView extends ServiceSupport implements
     // Events
     // **************************************
 
-    private <T extends CameClusterEventListener> void executeWithListener(Class<T> type, Consumer<T> consumer) {
+    private <T extends CameClusterEventListener> void doWithListener(Class<T> type, Consumer<T> consumer) {
         LockHelper.doWithReadLock(
             lock,
             () -> {
@@ -93,21 +93,21 @@ public abstract class AbstractCamelClusterView extends ServiceSupport implements
     }
 
     protected void fireLeadershipChangedEvent(CamelClusterMember leader) {
-        executeWithListener(
+        doWithListener(
             CameClusterEventListener.Leadership.class,
             listener -> listener.leadershipChanged(this, leader)
         );
     }
 
     protected void fireMemberAddedEvent(CamelClusterMember member) {
-        executeWithListener(
+        doWithListener(
             CameClusterEventListener.Membership.class,
             listener -> listener.memberAdded(this, member)
         );
     }
 
     protected void fireMemberRemovedEvent(CamelClusterMember member) {
-        executeWithListener(
+        doWithListener(
             CameClusterEventListener.Membership.class,
             listener -> listener.memberRemoved(this, member)
         );

http://git-wip-us.apache.org/repos/asf/camel/blob/b3681ba7/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java b/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
index 7825c2c..1ba0165 100644
--- a/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
+++ b/camel-core/src/main/java/org/apache/camel/util/concurrent/LockHelper.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.util.concurrent;
 
+import java.util.concurrent.Callable;
 import java.util.concurrent.locks.StampedLock;
 
 import org.apache.camel.util.function.ThrowingRunnable;
@@ -34,6 +35,16 @@ public final class LockHelper {
         }
     }
 
+    public static <R> R callWithReadLock(StampedLock lock, Callable<R> task) throws Exception {
+        long stamp = lock.readLock();
+
+        try {
+            return task.call();
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
     public static <T extends Throwable> void doWithReadLockT(StampedLock lock, ThrowingRunnable<T> task) throws T {
         long stamp = lock.readLock();
 
@@ -54,6 +65,16 @@ public final class LockHelper {
         }
     }
 
+    public static <R> R  callWithWriteLock(StampedLock lock, Callable<R> task) throws Exception {
+        long stamp = lock.writeLock();
+
+        try {
+            return task.call();
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
     public static <T extends Throwable> void doWithWriteLockT(StampedLock lock, ThrowingRunnable<T> task) throws T {
         long stamp = lock.writeLock();
 


[04/13] camel git commit: CAMEL-11362: create a LeaderElectionservice

Posted by lb...@apache.org.
CAMEL-11362: create a LeaderElectionservice


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

Branch: refs/heads/master
Commit: b6f1bdd8807efaa3e085d410affd4497e24aeab3
Parents: 9ddff22
Author: lburgazzoli <lb...@gmail.com>
Authored: Wed May 31 18:12:47 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:53 2017 +0200

----------------------------------------------------------------------
 .../camel/ha/AbstractCamelClusterView.java      | 121 ---------
 .../java/org/apache/camel/ha/CamelCluster.java  |   4 +-
 .../apache/camel/ha/CamelClusterFactory.java    |  27 ++
 .../org/apache/camel/ha/CamelClusterHelper.java |  28 ++
 .../org/apache/camel/ha/CamelClusterView.java   |   5 +-
 .../org/apache/camel/ha/LeaderRoutePolicy.java  | 169 ------------
 .../camel/impl/ha/AbstractCamelCluster.java     | 115 +++++++++
 .../camel/impl/ha/AbstractCamelClusterView.java | 137 ++++++++++
 .../camel/impl/ha/ClusteredRoutePolicy.java     | 256 +++++++++++++++++++
 .../atomix/ha/AtomixClusterMember.java          |  45 ----
 10 files changed, 570 insertions(+), 337 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java b/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java
deleted file mode 100644
index 64cee58..0000000
--- a/camel-core/src/main/java/org/apache/camel/ha/AbstractCamelClusterView.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * 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.camel.ha;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.locks.StampedLock;
-import java.util.function.BiConsumer;
-import java.util.function.Predicate;
-
-public abstract class AbstractCamelClusterView implements CamelClusterView {
-    private final CamelCluster cluster;
-    private final String namespace;
-    private final List<FilteringConsumer> consumers;
-    private final StampedLock lock;
-
-    protected AbstractCamelClusterView(CamelCluster cluster, String namespace) {
-        this.cluster = cluster;
-        this.namespace = namespace;
-        this.consumers = new ArrayList<>();
-        this.lock = new StampedLock();
-    }
-
-    @Override
-    public CamelCluster getCluster() {
-        return  this.cluster;
-    }
-
-    @Override
-    public String getNamespace() {
-        return this.namespace;
-    }
-
-    @Override
-    public void addEventListener(BiConsumer<Event, Object> consumer) {
-        long stamp = lock.writeLock();
-
-        try {
-            consumers.add(new FilteringConsumer(e -> true, consumer));
-        } finally {
-            lock.unlockWrite(stamp);
-        }
-    }
-
-    @Override
-    public void addEventListener(Predicate<Event> predicate, BiConsumer<Event, Object> consumer) {
-        long stamp = lock.writeLock();
-
-        try {
-            this.consumers.add(new FilteringConsumer(predicate, consumer));
-        } finally {
-            lock.unlockWrite(stamp);
-        }
-    }
-
-    @Override
-    public void removeEventListener(BiConsumer<Event, Object> consumer) {
-        long stamp = lock.writeLock();
-
-        try {
-            consumers.removeIf(c -> c.getConsumer().equals(consumer));
-        } finally {
-            lock.unlockWrite(stamp);
-        }
-    }
-
-    // **************************************
-    // Events
-    // **************************************
-
-    protected void fireEvent(CamelClusterView.Event event, Object payload) {
-        long stamp = lock.readLock();
-
-        try {
-            for (int i = 0; i < consumers.size(); i++) {
-                consumers.get(0).accept(event, payload);
-            }
-        } finally {
-            lock.unlockRead(stamp);
-        }
-    }
-
-    // **************************************
-    // Helpers
-    // **************************************
-
-    private final class FilteringConsumer implements BiConsumer<Event, Object> {
-        private final Predicate<Event> predicate;
-        private final BiConsumer<Event, Object> consumer;
-
-        FilteringConsumer(Predicate<Event> predicate,  BiConsumer<Event, Object> consumer) {
-            this.predicate = predicate;
-            this.consumer = consumer;
-        }
-
-        @Override
-        public void accept(CamelClusterView.Event event, Object payload) {
-            if (predicate.test(event)) {
-                consumer.accept(event, payload);
-            }
-        }
-
-        public BiConsumer<Event, Object> getConsumer() {
-            return this.consumer;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
index 5da1e8c..d6c151c 100644
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
@@ -16,9 +16,11 @@
  */
 package org.apache.camel.ha;
 
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.Service;
 import org.apache.camel.spi.HasId;
 
-public interface CamelCluster extends HasId {
+public interface CamelCluster extends Service, CamelContextAware, HasId {
     /**
      * Creates a view of the cluster bound to a namespace.
      *

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java
new file mode 100644
index 0000000..be332b4
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java
@@ -0,0 +1,27 @@
+/**
+ * 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.camel.ha;
+
+import org.apache.camel.CamelContext;
+
+@FunctionalInterface
+public interface CamelClusterFactory {
+    /**
+     * Creates an instance of a cluster.
+     */
+    CamelCluster newInstance(CamelContext camelContext) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java
new file mode 100644
index 0000000..c6f91ed
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterHelper.java
@@ -0,0 +1,28 @@
+/**
+ * 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.camel.ha;
+
+import java.util.function.Predicate;
+
+public final class CamelClusterHelper {
+    private CamelClusterHelper() {
+    }
+
+    public static Predicate<CamelClusterView.Event> leadershipEventFilter() {
+        return e -> e == CamelClusterView.Event.LEADERSHIP_CHANGED;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
index 7af5a21..bda7f8b 100644
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterView.java
@@ -20,10 +20,13 @@ import java.util.List;
 import java.util.function.BiConsumer;
 import java.util.function.Predicate;
 
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.Service;
+
 /**
  * Represents the View of the cluster at some given period of time.
  */
-public interface CamelClusterView {
+public interface CamelClusterView extends Service, CamelContextAware {
 
     enum Event {
         KEEP_ALIVE,

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java b/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java
deleted file mode 100644
index 40ae1e8..0000000
--- a/camel-core/src/main/java/org/apache/camel/ha/LeaderRoutePolicy.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * 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.camel.ha;
-
-import java.util.HashSet;
-import java.util.Objects;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.BiConsumer;
-
-import org.apache.camel.CamelContext;
-import org.apache.camel.CamelContextAware;
-import org.apache.camel.Route;
-import org.apache.camel.api.management.ManagedAttribute;
-import org.apache.camel.api.management.ManagedResource;
-import org.apache.camel.support.RoutePolicySupport;
-import org.apache.camel.util.ObjectHelper;
-import org.apache.camel.util.ReferenceCount;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@ManagedResource(description = "Route policy using ...")
-public class LeaderRoutePolicy extends RoutePolicySupport implements CamelContextAware {
-    private static final Logger LOGGER = LoggerFactory.getLogger(LeaderRoutePolicy.class);
-
-    private final AtomicBoolean leader;
-    private final Set<Route> startedRoutes;
-    private final Set<Route> stoppedRoutes;
-    private final ReferenceCount refCount;
-    private final CamelClusterView clusterView;
-    private final CamelClusterMember clusterMember;
-    private final BiConsumer<CamelClusterView.Event, Object> clusterEventConsumer;
-    private CamelContext camelContext;
-
-    public LeaderRoutePolicy(CamelClusterView clusterView, CamelClusterMember clusterMember) {
-        this.clusterMember = clusterMember;
-        this.clusterView = clusterView;
-        this.clusterEventConsumer = this::onClusterEvent;
-        this.stoppedRoutes = new HashSet<>();
-        this.startedRoutes = new HashSet<>();
-        this.leader = new AtomicBoolean(false);
-
-        this.refCount = ReferenceCount.on(
-            () -> clusterView.addEventListener(clusterEventConsumer),
-            () -> clusterView.removeEventListener(clusterEventConsumer)
-        );
-    }
-
-    @Override
-    public CamelContext getCamelContext() {
-        return camelContext;
-    }
-
-    @Override
-    public void setCamelContext(CamelContext camelContext) {
-        this.camelContext = camelContext;
-    }
-
-    @Override
-    public synchronized void onInit(Route route) {
-        super.onInit(route);
-
-        LOGGER.info("Route managed by {}. Setting route {} AutoStartup flag to false.", getClass(), route.getId());
-        route.getRouteContext().getRoute().setAutoStartup("false");
-
-        stoppedRoutes.add(route);
-
-        this.refCount.retain();
-
-        startManagedRoutes();
-    }
-
-    @Override
-    public synchronized void doShutdown() {
-        this.refCount.release();
-    }
-
-    // ****************************************************
-    // Management
-    // ****************************************************
-
-    @ManagedAttribute(description = "Is this route the master or a slave")
-    public boolean isLeader() {
-        return leader.get();
-    }
-
-    // ****************************************************
-    // Route managements
-    // ****************************************************
-
-    private void onClusterEvent(CamelClusterView.Event event, Object payload) {
-        if (event == CamelClusterView.Event.KEEP_ALIVE) {
-            LOGGER.debug("Got KEEP_ALIVE from cluster '{}' with payload '{}'", clusterView.getCluster().getId(), Objects.toString(payload));
-        }
-        if (event == CamelClusterView.Event.LEADERSHIP_CHANGED) {
-            boolean isLeader = ObjectHelper.equal(clusterMember.getId(), clusterView.getMaster().getId());
-
-            if (isLeader && leader.compareAndSet(false, isLeader)) {
-                LOGGER.info("Leadership taken");
-                startManagedRoutes();
-            } else if (!isLeader && leader.getAndSet(isLeader)) {
-                LOGGER.info("Leadership lost");
-                stopManagedRoutes();
-            }
-        }
-    }
-
-    private synchronized void startManagedRoutes() {
-        if (isLeader()) {
-            doStartManagedRoutes();
-        } else {
-            // If the leadership has been lost in the meanwhile, stop any
-            // eventually started route
-            doStopManagedRoutes();
-        }
-    }
-
-    private synchronized void doStartManagedRoutes() {
-        try {
-            for (Route route : stoppedRoutes) {
-                LOGGER.debug("Starting route {}", route.getId());
-                startRoute(route);
-                startedRoutes.add(route);
-            }
-
-            stoppedRoutes.removeAll(startedRoutes);
-        } catch (Exception e) {
-            handleException(e);
-        }
-    }
-
-    private synchronized void stopManagedRoutes() {
-        if (isLeader()) {
-            // If became a leader in the meanwhile, start any eventually stopped
-            // route
-            doStartManagedRoutes();
-        } else {
-            doStopManagedRoutes();
-        }
-    }
-
-    private synchronized void doStopManagedRoutes() {
-        try {
-            for (Route route : startedRoutes) {
-                LOGGER.debug("Stopping route {}", route.getId());
-                stopRoute(route);
-                stoppedRoutes.add(route);
-            }
-
-            startedRoutes.removeAll(stoppedRoutes);
-        } catch (Exception e) {
-            handleException(e);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
new file mode 100644
index 0000000..9c4691e
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
@@ -0,0 +1,115 @@
+/**
+ * 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.camel.impl.ha;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.locks.StampedLock;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.support.ServiceSupport;
+
+public abstract class AbstractCamelCluster<T extends CamelClusterView> extends ServiceSupport implements CamelCluster {
+    private final String id;
+    private final Map<String, T> views;
+    private final StampedLock lock;
+    private CamelContext camelContext;
+
+    protected AbstractCamelCluster(String id) {
+        this(id, null);
+    }
+
+    protected AbstractCamelCluster(String id, CamelContext camelContext) {
+        this.id = id;
+        this.camelContext = camelContext;
+        this.views = new HashMap<>();
+        this.lock = new StampedLock();
+    }
+
+    @Override
+    public String getId() {
+        return id;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        long stamp = lock.readLock();
+
+        try {
+            for (T view : views.values()) {
+                view.start();
+            }
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        long stamp = lock.readLock();
+
+        try {
+            for (T view : views.values()) {
+                view.stop();
+            }
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
+    @Override
+    public CamelClusterView createView(String namespace) throws Exception {
+        long stamp = lock.writeLock();
+
+        try {
+            T view = views.get(namespace);
+
+            if (view == null) {
+                view = doCreateView(namespace);
+                view.setCamelContext(this.camelContext);
+
+                views.put(namespace, view);
+
+                if (AbstractCamelCluster.this.isRunAllowed()) {
+                    view.start();
+                }
+            }
+
+            return view;
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    // **********************************
+    // Implementation
+    // **********************************
+
+    protected abstract T doCreateView(String namespace) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
new file mode 100644
index 0000000..1149a7f
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
@@ -0,0 +1,137 @@
+/**
+ * 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.camel.impl.ha;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.locks.StampedLock;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.support.ServiceSupport;
+
+public abstract class AbstractCamelClusterView extends ServiceSupport implements CamelClusterView {
+    private final CamelCluster cluster;
+    private final String namespace;
+    private final List<FilteringConsumer> consumers;
+    private final StampedLock lock;
+    private CamelContext camelContext;
+
+    protected AbstractCamelClusterView(CamelCluster cluster, String namespace) {
+        this.cluster = cluster;
+        this.namespace = namespace;
+        this.consumers = new ArrayList<>();
+        this.lock = new StampedLock();
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    @Override
+    public CamelContext getCamelContext() {
+        return null;
+    }
+
+    @Override
+    public CamelCluster getCluster() {
+        return  this.cluster;
+    }
+
+    @Override
+    public String getNamespace() {
+        return this.namespace;
+    }
+
+    @Override
+    public void addEventListener(BiConsumer<Event, Object> consumer) {
+        long stamp = lock.writeLock();
+
+        try {
+            consumers.add(new FilteringConsumer(e -> true, consumer));
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    @Override
+    public void addEventListener(Predicate<Event> predicate, BiConsumer<Event, Object> consumer) {
+        long stamp = lock.writeLock();
+
+        try {
+            consumers.add(new FilteringConsumer(predicate, consumer));
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    @Override
+    public void removeEventListener(BiConsumer<Event, Object> consumer) {
+        long stamp = lock.writeLock();
+
+        try {
+            consumers.removeIf(c -> c.getConsumer().equals(consumer));
+        } finally {
+            lock.unlockWrite(stamp);
+        }
+    }
+
+    // **************************************
+    // Events
+    // **************************************
+
+    protected void fireEvent(CamelClusterView.Event event, Object payload) {
+        long stamp = lock.readLock();
+
+        try {
+            for (int i = 0; i < consumers.size(); i++) {
+                consumers.get(i).accept(event, payload);
+            }
+        } finally {
+            lock.unlockRead(stamp);
+        }
+    }
+
+    // **************************************
+    // Helpers
+    // **************************************
+
+    private final class FilteringConsumer implements BiConsumer<Event, Object> {
+        private final Predicate<Event> predicate;
+        private final BiConsumer<Event, Object> consumer;
+
+        FilteringConsumer(Predicate<Event> predicate,  BiConsumer<Event, Object> consumer) {
+            this.predicate = predicate;
+            this.consumer = consumer;
+        }
+
+        @Override
+        public void accept(CamelClusterView.Event event, Object payload) {
+            if (predicate.test(event)) {
+                consumer.accept(event, payload);
+            }
+        }
+
+        public BiConsumer<Event, Object> getConsumer() {
+            return this.consumer;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
new file mode 100644
index 0000000..4aa1fa2
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
@@ -0,0 +1,256 @@
+/**
+ * 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.camel.impl.ha;
+
+import java.util.EventObject;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.Route;
+import org.apache.camel.StartupListener;
+import org.apache.camel.api.management.ManagedAttribute;
+import org.apache.camel.api.management.ManagedResource;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterHelper;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.management.event.CamelContextStartedEvent;
+import org.apache.camel.support.EventNotifierSupport;
+import org.apache.camel.support.RoutePolicySupport;
+import org.apache.camel.util.ReferenceCount;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@ManagedResource(description = "Clustered Route policy using")
+public final class ClusteredRoutePolicy extends RoutePolicySupport implements CamelContextAware {
+    private static final Logger LOGGER = LoggerFactory.getLogger(ClusteredRoutePolicy.class);
+
+    private final AtomicBoolean leader;
+    private final Set<Route> startedRoutes;
+    private final Set<Route> stoppedRoutes;
+    private final ReferenceCount refCount;
+    private final CamelClusterView clusterView;
+    private final BiConsumer<CamelClusterView.Event, Object> leadershipEventConsumer;
+    private final CamelContextStartupListener listener;
+    private final AtomicBoolean contextStarted;
+    private CamelContext camelContext;
+
+    public ClusteredRoutePolicy(CamelClusterView clusterView) {
+        this.clusterView = clusterView;
+        this.leadershipEventConsumer = this::onLeadershipEvent;
+
+        this.stoppedRoutes = new HashSet<>();
+        this.startedRoutes = new HashSet<>();
+        this.leader = new AtomicBoolean(false);
+        this.contextStarted = new AtomicBoolean(false);
+
+        try {
+            this.listener = new CamelContextStartupListener();
+            this.listener.start();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+
+        // Cleanup the policy when all the routes it manages have been shut down
+        // so it can be shared among routes.
+        this.refCount = ReferenceCount.onRelease(() -> {
+            if (camelContext != null) {
+                camelContext.getManagementStrategy().removeEventNotifier(listener);
+            }
+
+            clusterView.removeEventListener(leadershipEventConsumer);
+            setLeader(false);
+        });
+    }
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        if (this.camelContext == camelContext) {
+            return;
+        }
+
+        if (this.camelContext != null && this.camelContext != camelContext) {
+            throw new IllegalStateException(
+                "CamelContext should not be changed: current=" + this.camelContext + ", new=" + camelContext
+            );
+        }
+
+        try {
+            this.camelContext = camelContext;
+            this.camelContext.addStartupListener(this.listener);
+            this.camelContext.getManagementStrategy().addEventNotifier(this.listener);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void onInit(Route route) {
+        super.onInit(route);
+
+        LOGGER.info("Route managed by {}. Setting route {} AutoStartup flag to false.", getClass(), route.getId());
+        route.getRouteContext().getRoute().setAutoStartup("false");
+
+        this.refCount.retain();
+        this.stoppedRoutes.add(route);
+
+        startManagedRoutes();
+    }
+
+    @Override
+    public void doShutdown() {
+        this.refCount.release();
+    }
+
+    // ****************************************************
+    // Management
+    // ****************************************************
+
+    @ManagedAttribute(description = "Is this route the master or a slave")
+    public boolean isLeader() {
+        return leader.get();
+    }
+
+    // ****************************************************
+    // Route managements
+    // ****************************************************
+
+    private synchronized void setLeader(boolean isLeader) {
+        if (isLeader && leader.compareAndSet(false, isLeader)) {
+            LOGGER.debug("Leadership taken");
+            startManagedRoutes();
+        } else if (!isLeader && leader.getAndSet(isLeader)) {
+            LOGGER.debug("Leadership lost");
+            stopManagedRoutes();
+        }
+    }
+
+    private void startManagedRoutes() {
+        if (isLeader()) {
+            doStartManagedRoutes();
+        } else {
+            // If the leadership has been lost in the meanwhile, stop any
+            // eventually started route
+            doStopManagedRoutes();
+        }
+    }
+
+    private void doStartManagedRoutes() {
+        try {
+            for (Route route : stoppedRoutes) {
+                LOGGER.debug("Starting route {}", route.getId());
+                camelContext.startRoute(route.getId());
+                startedRoutes.add(route);
+            }
+
+            stoppedRoutes.removeAll(startedRoutes);
+        } catch (Exception e) {
+            handleException(e);
+        }
+    }
+
+    private void stopManagedRoutes() {
+        if (isLeader()) {
+            // If became a leader in the meanwhile, start any eventually stopped
+            // route
+            doStartManagedRoutes();
+        } else {
+            doStopManagedRoutes();
+        }
+    }
+
+    private void doStopManagedRoutes() {
+        try {
+            for (Route route : startedRoutes) {
+                LOGGER.debug("Stopping route {}", route.getId());
+                stopRoute(route);
+                stoppedRoutes.add(route);
+            }
+
+            startedRoutes.removeAll(stoppedRoutes);
+        } catch (Exception e) {
+            handleException(e);
+        }
+    }
+
+    // ****************************************************
+    // Event handling
+    // ****************************************************
+
+    private void onLeadershipEvent(CamelClusterView.Event event, Object payload) {
+        setLeader(clusterView.getLocalMember().isMaster());
+    }
+
+    private class CamelContextStartupListener extends EventNotifierSupport implements StartupListener {
+        @Override
+        public void notify(EventObject event) throws Exception {
+            onCamelContextStarted();
+        }
+
+        @Override
+        public boolean isEnabled(EventObject event) {
+            return event instanceof CamelContextStartedEvent;
+        }
+
+        @Override
+        public void onCamelContextStarted(CamelContext context, boolean alreadyStarted) throws Exception {
+            if (alreadyStarted) {
+                // Invoke it only if the context was already started as this
+                // method is not invoked at last event as documented but after
+                // routes warm-up so this is useful for routes deployed after
+                // the camel context has been started-up. For standard routes
+                // configuration the notification of the camel context started
+                // is provided by EventNotifier.
+                //
+                // We should check why this callback is not invoked at latest
+                // stage, or maybe rename it as it is misleading and provide a
+                // better alternative for intercept camel events.
+                onCamelContextStarted();
+            }
+        }
+
+        private void onCamelContextStarted() {
+            // Start managing the routes only when the camel context is started
+            // so start/stop of managed routes do not clash with CamelContext
+            // startup
+            if (contextStarted.compareAndSet(false, true)) {
+                clusterView.addEventListener(CamelClusterHelper.leadershipEventFilter(), leadershipEventConsumer);
+                setLeader(clusterView.getLocalMember().isMaster());
+            }
+        }
+    }
+
+    // ****************************************************
+    // Static helpers
+    // ****************************************************
+
+    public static ClusteredRoutePolicy forNamespace(CamelCluster cluster, String namespace) throws Exception {
+        return new ClusteredRoutePolicy(cluster.createView(namespace));
+    }
+
+    public static ClusteredRoutePolicy forView(CamelClusterView view) throws Exception  {
+        return new ClusteredRoutePolicy(view);
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/b6f1bdd8/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java
deleted file mode 100644
index 6268931..0000000
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterMember.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * 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.camel.component.atomix.ha;
-
-import io.atomix.group.DistributedGroup;
-import io.atomix.group.GroupMember;
-import org.apache.camel.ha.CamelClusterMember;
-
-class AtomixClusterMember<M extends GroupMember> implements CamelClusterMember {
-    private final DistributedGroup group;
-    private final M member;
-
-    AtomixClusterMember(DistributedGroup group, M member) {
-        this.group = group;
-        this.member = member;
-    }
-
-    @Override
-    public String getId() {
-        return member.id();
-    }
-
-    @Override
-    public boolean isMaster() {
-        return group.election().term().leader().equals(member);
-    }
-
-    M getGroupMember() {
-      return member;
-    }
-}


[02/13] camel git commit: CAMEL-11362: create a LeaderElectionservice

Posted by lb...@apache.org.
CAMEL-11362: create a LeaderElectionservice


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

Branch: refs/heads/master
Commit: 21b65d965ff8f3eeecaf7aa3fbc599e5e3b23ace
Parents: 4907665
Author: lburgazzoli <lb...@gmail.com>
Authored: Thu Jun 1 19:27:09 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:53 2017 +0200

----------------------------------------------------------------------
 .../apache/camel/ha/CamelClusterFactory.java    | 27 -----------------
 .../apache/camel/ha/CamelClusterService.java    | 31 ++++++++++++++++++++
 .../camel/impl/ha/AbstractCamelClusterView.java |  4 +--
 .../camel/impl/ha/ClusteredRoutePolicy.java     |  7 +++--
 4 files changed, 38 insertions(+), 31 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/21b65d96/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java
deleted file mode 100644
index be332b4..0000000
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterFactory.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * 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.camel.ha;
-
-import org.apache.camel.CamelContext;
-
-@FunctionalInterface
-public interface CamelClusterFactory {
-    /**
-     * Creates an instance of a cluster.
-     */
-    CamelCluster newInstance(CamelContext camelContext) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/21b65d96/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
new file mode 100644
index 0000000..004eab3
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
@@ -0,0 +1,31 @@
+/**
+ * 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.camel.ha;
+
+import org.apache.camel.Service;
+
+public interface CamelClusterService extends Service {
+    /**
+     * Get the {@linke CamelCluster} instance managed by the service
+     */
+    CamelCluster getCluster() throws Exception;
+
+    /**
+     * Create a {@linke CamelClusterView} for the given namespace
+     */
+    CamelClusterView createView(String namespace) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/21b65d96/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
index 1149a7f..8fc9c27 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelClusterView.java
@@ -48,12 +48,12 @@ public abstract class AbstractCamelClusterView extends ServiceSupport implements
 
     @Override
     public CamelContext getCamelContext() {
-        return null;
+        return camelContext;
     }
 
     @Override
     public CamelCluster getCluster() {
-        return  this.cluster;
+        return this.cluster;
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/camel/blob/21b65d96/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
index 4aa1fa2..b08cddb 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
@@ -247,10 +247,13 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
     // ****************************************************
 
     public static ClusteredRoutePolicy forNamespace(CamelCluster cluster, String namespace) throws Exception {
-        return new ClusteredRoutePolicy(cluster.createView(namespace));
+        return forView(cluster.createView(namespace));
     }
 
     public static ClusteredRoutePolicy forView(CamelClusterView view) throws Exception  {
-        return new ClusteredRoutePolicy(view);
+        ClusteredRoutePolicy policy = new ClusteredRoutePolicy(view);
+        policy.setCamelContext(view.getCamelContext());
+
+        return policy;
     }
 }


[13/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
CAMEL-10054: Create camel-atomix component


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

Branch: refs/heads/master
Commit: 08d2b0fe8a91eab8e22e064299eaa74783279f2f
Parents: b3681ba
Author: lburgazzoli <lb...@gmail.com>
Authored: Wed Jun 14 18:02:53 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:55 2017 +0200

----------------------------------------------------------------------
 .../apache/camel/FluentProducerTemplate.java    |   5 +
 .../builder/DefaultFluentProducerTemplate.java  |   8 +
 .../org/apache/camel/util/ExchangeHelper.java   |  18 +
 .../camel/util/function/ThrowingBiFunction.java |  22 +
 components/camel-atomix/pom.xml                 |  21 +-
 .../src/main/docs/atomix-client-component.adoc  |   6 -
 .../src/main/docs/atomix-map-component.adoc     |  45 +++
 .../atomix/AtomixAsyncMessageProcessor.java     |  31 ++
 .../component/atomix/AtomixConfiguration.java   |  36 +-
 .../camel/component/atomix/AtomixHelper.java    |  29 ++
 .../AbstractAsyncAtomixClientProducer.java      | 140 +++++++
 .../client/AbstractAtomixClientComponent.java   |  93 +++++
 .../client/AbstractAtomixClientConsumer.java    |  31 ++
 .../client/AbstractAtomixClientEndpoint.java    |  86 ++++
 .../client/AbstractAtomixClientProducer.java    |  30 ++
 .../atomix/client/AtomixClientAction.java       |  32 ++
 .../atomix/client/AtomixClientComponent.java    |  37 --
 .../client/AtomixClientConfiguration.java       |   7 +-
 .../atomix/client/AtomixClientConstants.java    |  34 ++
 .../atomix/client/AtomixClientHelper.java       |  61 +++
 .../client/map/AtomixClientMapComponent.java    |  41 ++
 .../map/AtomixClientMapConfiguration.java       | 109 +++++
 .../client/map/AtomixClientMapConsumer.java     |  85 ++++
 .../client/map/AtomixClientMapEndpoint.java     |  53 +++
 .../client/map/AtomixClientMapProducer.java     | 364 +++++++++++++++++
 .../cluster/AtomixClusterConfiguration.java     |  60 +--
 .../atomix/cluster/AtomixClusterHelper.java     |  59 +--
 .../atomix/ha/AtomixClusterService.java         |  30 +-
 .../component/atomix/ha/AtomixClusterView.java  |  35 +-
 .../org/apache/camel/component/atomix-client    |  18 -
 .../org/apache/camel/component/atomix-map       |  18 +
 .../atomix/client/AtomixClientTestSupport.java  |  72 ++++
 .../client/map/AtomixClientMapConsumerTest.java | 115 ++++++
 .../client/map/AtomixClientMapProducerTest.java | 398 +++++++++++++++++++
 parent/pom.xml                                  |   1 +
 ...omixClientMapComponentAutoConfiguration.java | 129 ++++++
 .../AtomixClientMapComponentConfiguration.java  | 103 +++++
 .../main/resources/META-INF/spring.factories    |  19 +
 38 files changed, 2319 insertions(+), 162 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/camel-core/src/main/java/org/apache/camel/FluentProducerTemplate.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/FluentProducerTemplate.java b/camel-core/src/main/java/org/apache/camel/FluentProducerTemplate.java
index 688ce19..3a37890 100644
--- a/camel-core/src/main/java/org/apache/camel/FluentProducerTemplate.java
+++ b/camel-core/src/main/java/org/apache/camel/FluentProducerTemplate.java
@@ -137,6 +137,11 @@ public interface FluentProducerTemplate extends Service {
     // -----------------------------------------------------------------------
 
     /**
+     * Remove the body and headers.
+     */
+    FluentProducerTemplate clearAll();
+
+    /**
      * Set the header
      *
      * @param key the key of the header

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/camel-core/src/main/java/org/apache/camel/builder/DefaultFluentProducerTemplate.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/builder/DefaultFluentProducerTemplate.java b/camel-core/src/main/java/org/apache/camel/builder/DefaultFluentProducerTemplate.java
index 965afef..4c6034b 100644
--- a/camel-core/src/main/java/org/apache/camel/builder/DefaultFluentProducerTemplate.java
+++ b/camel-core/src/main/java/org/apache/camel/builder/DefaultFluentProducerTemplate.java
@@ -124,6 +124,14 @@ public class DefaultFluentProducerTemplate extends ServiceSupport implements Flu
     }
 
     @Override
+    public FluentProducerTemplate clearAll() {
+       clearBody();
+       clearHeaders();
+
+       return this;
+    }
+
+    @Override
     public FluentProducerTemplate withHeader(String key, Object value) {
         if (headers == null) {
             headers = new HashMap<>();

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java
index 06fe7bf..11b0dac 100644
--- a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java
+++ b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java
@@ -129,6 +129,24 @@ public final class ExchangeHelper {
     }
 
     /**
+     * Gets the mandatory inbound header of the correct type
+     *
+     * @param message       the message
+     * @param headerName    the header name
+     * @param type          the type
+     * @return the header value
+     * @throws TypeConversionException is thrown if error during type conversion
+     * @throws NoSuchHeaderException is thrown if no headers exists
+     */
+    public static <T> T getMandatoryHeader(Message message, String headerName, Class<T> type) throws TypeConversionException, NoSuchHeaderException {
+        T answer = message.getHeader(headerName, type);
+        if (answer == null) {
+            throw new NoSuchHeaderException(message.getExchange(), headerName, type);
+        }
+        return answer;
+    }
+
+    /**
      * Gets an header or property of the correct type
      *
      * @param exchange      the exchange

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/camel-core/src/main/java/org/apache/camel/util/function/ThrowingBiFunction.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/util/function/ThrowingBiFunction.java b/camel-core/src/main/java/org/apache/camel/util/function/ThrowingBiFunction.java
new file mode 100644
index 0000000..6b8cedc
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/util/function/ThrowingBiFunction.java
@@ -0,0 +1,22 @@
+/**
+ * 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.camel.util.function;
+
+@FunctionalInterface
+public interface ThrowingBiFunction<I1, I2, R, T extends Throwable> {
+    R apply(I1 in1, I2 in2) throws T;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/pom.xml
----------------------------------------------------------------------
diff --git a/components/camel-atomix/pom.xml b/components/camel-atomix/pom.xml
index ca4ad29..0c4a8db 100644
--- a/components/camel-atomix/pom.xml
+++ b/components/camel-atomix/pom.xml
@@ -38,9 +38,10 @@
       org.apache.camel.component.atomix.*,
       org.apache.camel.component.atomix.client.*,
       org.apache.camel.component.atomix.cluster.*
+      org.apache.camel.component.atomix.ha.*
     </camel.osgi.export.pkg>
     <camel.osgi.export.service>
-      org.apache.camel.spi.ComponentResolver;component=atomix-client,
+      org.apache.camel.spi.ComponentResolver;component=atomix-map,
       org.apache.camel.spi.ComponentResolver;component=atomix-cluster,
     </camel.osgi.export.service>
   </properties>
@@ -56,9 +57,19 @@
     <!-- atomix -->
     <dependency>
       <groupId>io.atomix</groupId>
-      <artifactId>atomix-all</artifactId>
+      <artifactId>atomix</artifactId>
       <version>${atomix-version}</version>
     </dependency>
+    <dependency>
+      <groupId>io.atomix</groupId>
+      <artifactId>atomix-groups</artifactId>
+      <version>${atomix-version}</version>
+    </dependency>
+    <dependency>
+      <groupId>io.atomix.catalyst</groupId>
+      <artifactId>catalyst-netty</artifactId>
+      <version>${atomix-catalyst-version}</version>
+    </dependency>
 
     <!-- logging -->       
     <dependency>
@@ -88,6 +99,12 @@
       <artifactId>camel-test-spring</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.hamcrest</groupId>
+      <artifactId>java-hamcrest</artifactId>
+      <version>${hamcrest-version}</version>
+      <scope>test</scope>
+    </dependency>
 
   </dependencies>
 

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/docs/atomix-client-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-client-component.adoc b/components/camel-atomix/src/main/docs/atomix-client-component.adoc
deleted file mode 100644
index 20ece42..0000000
--- a/components/camel-atomix/src/main/docs/atomix-client-component.adoc
+++ /dev/null
@@ -1,6 +0,0 @@
-## Atomix Client Component
-
-*Available as of Camel version 2.20*
-
-The camel atomix component allows you to work with Atomix, a fault-tolerant distributed coordination framework.
-

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/docs/atomix-map-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-map-component.adoc b/components/camel-atomix/src/main/docs/atomix-map-component.adoc
new file mode 100644
index 0000000..653057e
--- /dev/null
+++ b/components/camel-atomix/src/main/docs/atomix-map-component.adoc
@@ -0,0 +1,45 @@
+## atomix-map Component
+
+*Available as of Camel version 2.20*
+
+The camel atomix component allows you to work with Atomix, a fault-tolerant distributed coordination framework.
+
+// component options: START
+The atomix-map component supports 5 options which are listed below.
+
+
+
+[width="100%",cols="2,5,^1,2",options="header"]
+|=======================================================================
+| Name | Description | Default | Type
+| **configuration** (advanced) | The shared component configuration |  | C
+| **atomix** (producer) | The shared AtomixClient instance |  | AtomixClient
+| **nodes** (producer) | The nodes the AtomixClient should connect to |  | List
+| **configurationUri** (producer) | The path to the AtomixClient configuration |  | String
+| **resolveProperty Placeholders** (advanced) | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | boolean
+|=======================================================================
+// component options: END
+
+// endpoint options: START
+The atomix-map endpoint is configured using URI syntax:
+
+    atomix-map:mapName
+
+with the following path and query parameters:
+
+#### Path Parameters (1 parameters):
+
+[width="100%",cols="2,5,^1,2",options="header"]
+|=======================================================================
+| Name | Description | Default | Type
+| **mapName** | *Required* The distributed map name |  | String
+|=======================================================================
+
+#### Query Parameters (1 parameters):
+
+[width="100%",cols="2,5,^1,2",options="header"]
+|=======================================================================
+| Name | Description | Default | Type
+| **synchronous** (advanced) | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | false | boolean
+|=======================================================================
+// endpoint options: END

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixAsyncMessageProcessor.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixAsyncMessageProcessor.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixAsyncMessageProcessor.java
new file mode 100644
index 0000000..bfa5e95
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixAsyncMessageProcessor.java
@@ -0,0 +1,31 @@
+/**
+ * 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.camel.component.atomix;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Message;
+
+@FunctionalInterface
+public interface AtomixAsyncMessageProcessor {
+    /**
+     * @param message
+     * @param callback
+     * @return
+     * @throws Exception
+     */
+    boolean process(Message message, AsyncCallback callback) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
index d0e3203..1ffc06d 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
@@ -21,13 +21,18 @@ import java.util.List;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
+import io.atomix.Atomix;
 import io.atomix.catalyst.transport.Address;
 import io.atomix.catalyst.transport.Transport;
 import io.atomix.catalyst.transport.netty.NettyTransport;
+import io.atomix.resource.ReadConsistency;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.util.ObjectHelper;
 
-public class AtomixConfiguration {
+public class AtomixConfiguration<T extends Atomix> implements Cloneable {
+    @UriParam
+    private T atomix;
+
     @UriParam(javaType = "java.lang.String")
     private List<Address> nodes = Collections.emptyList();
 
@@ -37,9 +42,27 @@ public class AtomixConfiguration {
     @UriParam
     private String configurationUri;
 
+    @UriParam(label = "advanced")
+    private ReadConsistency readConsistency;
+
     protected AtomixConfiguration() {
     }
 
+    // *****************************************
+    // Properties
+    // *****************************************
+
+    public T getAtomix() {
+        return atomix;
+    }
+
+    /**
+     * The Atomix instance to use
+     */
+    public void setAtomix(T client) {
+        this.atomix = client;
+    }
+
     public List<Address> getNodes() {
         return nodes;
     }
@@ -78,4 +101,15 @@ public class AtomixConfiguration {
     public void setConfigurationUri(String configurationUri) {
         this.configurationUri = configurationUri;
     }
+
+    public ReadConsistency getReadConsistency() {
+        return readConsistency;
+    }
+
+    /**
+     * The read consistency level.
+     */
+    public void setReadConsistency(ReadConsistency readConsistency) {
+        this.readConsistency = readConsistency;
+    }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixHelper.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixHelper.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixHelper.java
new file mode 100644
index 0000000..959c894
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixHelper.java
@@ -0,0 +1,29 @@
+/**
+ * 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.camel.component.atomix;
+
+import io.atomix.copycat.server.storage.Storage;
+import io.atomix.copycat.server.storage.StorageLevel;
+
+public final class AtomixHelper {
+    private AtomixHelper() {
+    }
+
+    public static Storage inMemoryStorage() {
+        return Storage.builder().withStorageLevel(StorageLevel.MEMORY).build();
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAsyncAtomixClientProducer.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAsyncAtomixClientProducer.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAsyncAtomixClientProducer.java
new file mode 100644
index 0000000..931e9e4
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAsyncAtomixClientProducer.java
@@ -0,0 +1,140 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Repeatable;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProcessor;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.component.atomix.AtomixAsyncMessageProcessor;
+import org.apache.camel.impl.DefaultProducer;
+import org.apache.camel.util.AsyncProcessorHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class AbstractAsyncAtomixClientProducer<E extends AbstractAtomixClientEndpoint> extends DefaultProducer implements AsyncProcessor {
+    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractAsyncAtomixClientProducer.class);
+    private final Map<AtomixClientAction, AtomixAsyncMessageProcessor> processors;
+
+    protected AbstractAsyncAtomixClientProducer(E endpoint) {
+        super(endpoint);
+
+        this.processors = new HashMap<>();
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        for (final Method method : getClass().getDeclaredMethods()) {
+            AsyncInvokeOnHeaders annotations = method.getAnnotation(AsyncInvokeOnHeaders.class);
+            if (annotations != null) {
+                for (AsyncInvokeOnHeader annotation : annotations.value()) {
+                    bind(annotation, method);
+                }
+            } else {
+                AsyncInvokeOnHeader annotation = method.getAnnotation(AsyncInvokeOnHeader.class);
+                if (annotation != null) {
+                    bind(annotation, method);
+                }
+            }
+        }
+
+        super.doStart();
+    }
+
+    @Override
+    public void process(Exchange exchange) throws Exception {
+        AsyncProcessorHelper.process(this, exchange);
+    }
+
+    @Override
+    public boolean process(Exchange exchange, AsyncCallback callback) {
+        final Message message = exchange.getIn();
+        final AtomixClientAction action = getAction(message);
+
+        AtomixAsyncMessageProcessor processor = this.processors.get(action);
+        if (processor != null) {
+            try {
+                return processor.process(message, callback);
+            } catch (Exception e) {
+                throw new RuntimeCamelException(e);
+            }
+        } else {
+            throw new RuntimeCamelException("No handler for action " + action);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    protected E getAtomixEndpoint() {
+        return (E)super.getEndpoint();
+    }
+
+    protected abstract AtomixClientAction getAction(Message message);
+
+    // ************************************
+    // Binding helpers
+    // ************************************
+
+    private void bind(AsyncInvokeOnHeader annotation, final Method method) {
+        if (method.getParameterCount() == 2) {
+            method.setAccessible(true);
+
+            if (!Message.class.isAssignableFrom(method.getParameterTypes()[0])) {
+                throw new IllegalArgumentException("First argument should be of type Message");
+            }
+            if (!AsyncCallback.class.isAssignableFrom(method.getParameterTypes()[1])) {
+                throw new IllegalArgumentException("Second argument should be of type AsyncCallback");
+            }
+
+            LOGGER.debug("bind key={}, class={}, method={}",
+                annotation.value(), this.getClass(), method.getName());
+
+            this.processors.put(annotation.value(), (m, c) -> (boolean)method.invoke(this, m, c));
+        } else {
+            throw new IllegalArgumentException(
+                "Illegal number of parameters for method: " + method.getName() + ", required: 2, found: " + method.getParameterCount()
+            );
+        }
+    }
+
+    // ************************************
+    // Annotations
+    // ************************************
+
+    @Repeatable(AsyncInvokeOnHeaders.class)
+    @Retention(RetentionPolicy.RUNTIME)
+    @Target(ElementType.METHOD)
+    public @interface AsyncInvokeOnHeader {
+        AtomixClientAction value();
+    }
+
+    @Retention(RetentionPolicy.RUNTIME)
+    @Target(ElementType.METHOD)
+    public @interface AsyncInvokeOnHeaders {
+        AsyncInvokeOnHeader[] value();
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientComponent.java
new file mode 100644
index 0000000..66fd91b
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientComponent.java
@@ -0,0 +1,93 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import java.util.List;
+
+import io.atomix.AtomixClient;
+import io.atomix.catalyst.transport.Address;
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.DefaultComponent;
+import org.apache.camel.spi.Metadata;
+
+public abstract class AbstractAtomixClientComponent<C extends AtomixClientConfiguration> extends DefaultComponent {
+    @Metadata(label = "advanced")
+    private C configuration;
+
+    protected AbstractAtomixClientComponent(C configuration) {
+        this.configuration = configuration;
+    }
+
+    protected AbstractAtomixClientComponent(CamelContext camelContext, C configuration) {
+        super(camelContext);
+
+        this.configuration = configuration;
+    }
+
+    // *****************************************
+    // Properties
+    // *****************************************
+
+    public C getConfiguration() {
+        return configuration;
+    }
+
+    /**
+     * The shared component configuration
+     */
+    public void setConfiguration(C configuration) {
+        this.configuration = configuration;
+    }
+
+    public AtomixClient getAtomix() {
+        return configuration.getAtomix();
+    }
+
+    /**
+     * The shared AtomixClient instance
+     */
+    public void setAtomix(AtomixClient client) {
+        configuration.setAtomix(client);
+    }
+
+    public List<Address> getNodes() {
+        return configuration.getNodes();
+    }
+
+    /**
+     * The nodes the AtomixClient should connect to
+     */
+    public void setNodes(List<Address> nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public void setNodes(String nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public String getConfigurationUri() {
+        return configuration.getConfigurationUri();
+    }
+
+
+    /**
+     * The path to the AtomixClient configuration
+     */
+    public void setConfigurationUri(String configurationUri) {
+        configuration.setConfigurationUri(configurationUri);
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientConsumer.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientConsumer.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientConsumer.java
new file mode 100644
index 0000000..8f800e9
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientConsumer.java
@@ -0,0 +1,31 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import org.apache.camel.Processor;
+import org.apache.camel.impl.DefaultConsumer;
+
+public abstract class AbstractAtomixClientConsumer<E extends AbstractAtomixClientEndpoint> extends DefaultConsumer {
+    protected AbstractAtomixClientConsumer(E endpoint, Processor processor) {
+        super(endpoint, processor);
+    }
+
+    @SuppressWarnings("unchecked")
+    protected E getAtomixEndpoint() {
+        return (E)super.getEndpoint();
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientEndpoint.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientEndpoint.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientEndpoint.java
new file mode 100644
index 0000000..5a83873
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientEndpoint.java
@@ -0,0 +1,86 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import io.atomix.AtomixClient;
+import org.apache.camel.Consumer;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.impl.DefaultEndpoint;
+
+
+public abstract class AbstractAtomixClientEndpoint<T extends AbstractAtomixClientComponent, C extends AtomixClientConfiguration> extends DefaultEndpoint {
+    private final C configuration;
+    private AtomixClient atomix;
+
+    protected AbstractAtomixClientEndpoint(String uri, T component, C configuration) {
+        super(uri, component);
+
+        this.configuration = configuration;
+    }
+
+    @Override
+    public boolean isSingleton() {
+        return true;
+    }
+
+    @Override
+    public Producer createProducer() throws Exception {
+        throw new UnsupportedOperationException("Producer not supported");
+    }
+
+    @Override
+    public Consumer createConsumer(Processor processor) throws Exception {
+        throw new UnsupportedOperationException("Consumer not supported");
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        if (atomix == null) {
+            atomix = AtomixClientHelper.createClient(getCamelContext(), configuration);
+            atomix.connect(configuration.getNodes()).join();
+        }
+
+        super.doStart();
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        super.doStop();
+
+        if (atomix != null) {
+            atomix.close();
+        }
+    }
+
+    // **********************************
+    // Helpers for implementations
+    // *********************************
+
+    @SuppressWarnings("unchecked")
+    public T getAtomixComponent() {
+        return (T)super.getComponent();
+    }
+
+    public C getAtomixConfiguration() {
+        return this.configuration;
+    }
+
+    public AtomixClient getAtomix() {
+        return atomix;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientProducer.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientProducer.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientProducer.java
new file mode 100644
index 0000000..16a7866
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AbstractAtomixClientProducer.java
@@ -0,0 +1,30 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import org.apache.camel.impl.HeaderSelectorProducer;
+
+public abstract class AbstractAtomixClientProducer<E extends AbstractAtomixClientEndpoint> extends HeaderSelectorProducer {
+    protected AbstractAtomixClientProducer(E endpoint, String header) {
+        super(endpoint, header);
+    }
+
+    @SuppressWarnings("unchecked")
+    protected E getAtomixEndpoint() {
+        return (E)super.getEndpoint();
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientAction.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientAction.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientAction.java
new file mode 100644
index 0000000..5bf641f
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientAction.java
@@ -0,0 +1,32 @@
+/**
+ * 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.camel.component.atomix.client;
+
+public enum AtomixClientAction {
+    PUT,
+    PUT_IF_ABSENT,
+    GET,
+    CLEAR,
+    SIZE,
+    CONTAINS_KEY,
+    CONTAINS_VALUE,
+    IS_EMPTY,
+    ENTRY_SET,
+    REMOVE,
+    REPLACE,
+    VALUES
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
deleted file mode 100644
index 775315b..0000000
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 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.camel.component.atomix.client;
-
-import java.util.Map;
-
-import org.apache.camel.CamelContext;
-import org.apache.camel.Endpoint;
-import org.apache.camel.impl.DefaultComponent;
-
-public class AtomixClientComponent extends DefaultComponent {
-    public AtomixClientComponent() {
-    }
-
-    public AtomixClientComponent(CamelContext camelContext) {
-        super(camelContext);
-    }
-
-    @Override
-    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
-        throw new UnsupportedOperationException("Not yet implemented");
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
index d3134c4..0b8a0d8 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
@@ -16,11 +16,8 @@
  */
 package org.apache.camel.component.atomix.client;
 
+import io.atomix.AtomixClient;
 import org.apache.camel.component.atomix.AtomixConfiguration;
-import org.apache.camel.spi.UriParams;
 
-@UriParams
-public class AtomixClientConfiguration extends AtomixConfiguration {
-    public AtomixClientConfiguration() {
-    }
+public class AtomixClientConfiguration extends AtomixConfiguration<AtomixClient> implements Cloneable {
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConstants.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConstants.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConstants.java
new file mode 100644
index 0000000..2fccd8e
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConstants.java
@@ -0,0 +1,34 @@
+/**
+ * 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.camel.component.atomix.client;
+
+public final class AtomixClientConstants {
+    public static final String RESOURCE_NAME = "CamelAtomixResourceName";
+    public static final String RESOURCE_ACTION = "CamelAtomixResourceAction";
+    public static final String RESOURCE_KEY = "CamelAtomixResourceKey";
+    public static final String RESOURCE_VALUE = "CamelAtomixResourceValue";
+    public static final String RESOURCE_DEFAULT_VALUE = "CamelAtomixResourceDefaultValue";
+    public static final String RESOURCE_OLD_VALUE = "CamelAtomixResourceOldValue";
+    public static final String RESOURCE_ACTION_HAS_RESULT = "CamelAtomixResourceActionHasResult";
+    public static final String RESOURCE_TTL = "CamelAtomixResourceTTL";
+    public static final String RESOURCE_READ_CONSISTENCY = "CamelAtomixResourceReadConsistency";
+    public static final String EVENT_TYPE = "CamelAtomixEventType";
+
+    private AtomixClientConstants() {
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientHelper.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientHelper.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientHelper.java
new file mode 100644
index 0000000..bbe9358
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientHelper.java
@@ -0,0 +1,61 @@
+/**
+ * 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.camel.component.atomix.client;
+
+import java.io.InputStream;
+import java.util.Properties;
+
+import io.atomix.AtomixClient;
+import org.apache.camel.CamelContext;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.ResourceHelper;
+
+public final class AtomixClientHelper {
+    private AtomixClientHelper() {
+    }
+
+    public static AtomixClient createClient(CamelContext camelContext, AtomixClientConfiguration configuration) throws Exception {
+        AtomixClient atomix = configuration.getAtomix();
+
+        if (atomix == null) {
+            final AtomixClient.Builder atomixBuilder;
+
+            String uri = configuration.getConfigurationUri();
+            if (ObjectHelper.isNotEmpty(uri)) {
+                uri = camelContext.resolvePropertyPlaceholders(uri);
+                try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
+                    Properties properties = new Properties();
+                    properties.load(is);
+
+                    atomixBuilder = AtomixClient.builder(properties);
+                }
+            } else {
+                atomixBuilder = AtomixClient.builder();
+            }
+
+            if (configuration.getTransport() != null) {
+                atomixBuilder.withTransport(
+                    camelContext.getInjector().newInstance(configuration.getTransport())
+                );
+            }
+
+            atomix = atomixBuilder.build();
+        }
+
+        return atomix;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapComponent.java
new file mode 100644
index 0000000..a853e7d
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapComponent.java
@@ -0,0 +1,41 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Endpoint;
+import org.apache.camel.component.atomix.client.AbstractAtomixClientComponent;
+
+public class AtomixClientMapComponent extends AbstractAtomixClientComponent<AtomixClientMapConfiguration> {
+    public AtomixClientMapComponent() {
+        super(new AtomixClientMapConfiguration());
+    }
+
+    public AtomixClientMapComponent(CamelContext camelContext) {
+        super(camelContext, new AtomixClientMapConfiguration());
+    }
+
+    @Override
+    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
+        AtomixClientMapConfiguration configuration = super.getConfiguration().copy();
+        setProperties(configuration, parameters);
+
+        return new AtomixClientMapEndpoint(uri, this, configuration, remaining);
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConfiguration.java
new file mode 100644
index 0000000..f7f50a2
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConfiguration.java
@@ -0,0 +1,109 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import io.atomix.collections.DistributedMap;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.component.atomix.client.AtomixClientAction;
+import org.apache.camel.component.atomix.client.AtomixClientConfiguration;
+import org.apache.camel.spi.UriParam;
+import org.apache.camel.spi.UriParams;
+
+@UriParams
+public class AtomixClientMapConfiguration extends AtomixClientConfiguration {
+    @UriParam(defaultValue = "PUT")
+    private AtomixClientAction defaultAction = AtomixClientAction.PUT;
+    @UriParam
+    private Long ttl;
+    @UriParam
+    private String resultHeader;
+    @UriParam(label = "advanced")
+    private DistributedMap.Config config = new DistributedMap.Config();
+    @UriParam(label = "advanced")
+    private DistributedMap.Options options = new DistributedMap.Options();
+
+    // ****************************************
+    // Properties
+    // ****************************************
+
+    public AtomixClientAction getDefaultAction() {
+        return defaultAction;
+    }
+
+    /**
+     * The default action.
+     */
+    public void setDefaultAction(AtomixClientAction defaultAction) {
+        this.defaultAction = defaultAction;
+    }
+
+    public Long getTtl() {
+        return ttl;
+    }
+
+    /**
+     * The resource ttl.
+     */
+    public void setTtl(Long ttl) {
+        this.ttl = ttl;
+    }
+
+    public String getResultHeader() {
+        return resultHeader;
+    }
+
+    /**
+     * The header that wil carry the result.
+     */
+    public void setResultHeader(String resultHeader) {
+        this.resultHeader = resultHeader;
+    }
+
+    public DistributedMap.Config getConfig() {
+        return config;
+    }
+
+    /**
+     * The cluster wide map config
+     */
+    public void setConfig(DistributedMap.Config config) {
+        this.config = config;
+    }
+
+    public DistributedMap.Options getOptions() {
+        return options;
+    }
+
+    /**
+     * The local map options
+     */
+    public void setOptions(DistributedMap.Options options) {
+        this.options = options;
+    }
+
+    // ****************************************
+    // Copy
+    // ****************************************
+
+    public AtomixClientMapConfiguration copy() {
+        try {
+            return (AtomixClientMapConfiguration) super.clone();
+        } catch (CloneNotSupportedException e) {
+            throw new RuntimeCamelException(e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumer.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumer.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumer.java
new file mode 100644
index 0000000..6e7b410
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapConsumer.java
@@ -0,0 +1,85 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import io.atomix.catalyst.concurrent.Listener;
+import io.atomix.collections.DistributedMap;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.component.atomix.client.AbstractAtomixClientConsumer;
+import org.apache.camel.component.atomix.client.AtomixClientConstants;
+
+public class AtomixClientMapConsumer extends AbstractAtomixClientConsumer<AtomixClientMapEndpoint> {
+    private final List<Listener<DistributedMap.EntryEvent<Object, Object>>> listeners;
+    private DistributedMap<Object, Object> map;
+
+    public AtomixClientMapConsumer(AtomixClientMapEndpoint endpoint, Processor processor) {
+        super(endpoint, processor);
+        this.listeners = new ArrayList<>();
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        super.doStart();
+
+        this.map = getAtomixEndpoint()
+            .getAtomix()
+            .getMap(
+                getAtomixEndpoint().getMapName(),
+                getAtomixEndpoint().getAtomixConfiguration().getConfig(),
+                getAtomixEndpoint().getAtomixConfiguration().getOptions())
+            .join();
+
+        this.listeners.add(this.map.onAdd(this::onEvent).join());
+        this.listeners.add(this.map.onRemove(this::onEvent).join());
+        this.listeners.add(this.map.onUpdate(this::onEvent).join());
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        // close listeners
+        listeners.forEach(Listener::close);
+
+        // close the map
+        if (this.map == null) {
+            this.map.close().join();
+            this.map = null;
+        }
+
+        super.doStart();
+    }
+
+    // ********************************************
+    // Event handler
+    // ********************************************
+
+    private void onEvent(DistributedMap.EntryEvent<Object, Object> event) {
+        Exchange exchange = getEndpoint().createExchange();
+        exchange.getIn().setHeader(AtomixClientConstants.EVENT_TYPE, event.type());
+        exchange.getIn().setHeader(AtomixClientConstants.RESOURCE_KEY, event.entry().getKey());
+        exchange.getIn().setBody(event.entry().getValue());
+
+        try {
+            getProcessor().process(exchange);
+        } catch (Exception e) {
+            getExceptionHandler().handleException(e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapEndpoint.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapEndpoint.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapEndpoint.java
new file mode 100644
index 0000000..e8525a0
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapEndpoint.java
@@ -0,0 +1,53 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import org.apache.camel.Producer;
+import org.apache.camel.component.atomix.client.AbstractAtomixClientEndpoint;
+import org.apache.camel.spi.Metadata;
+import org.apache.camel.spi.UriEndpoint;
+import org.apache.camel.spi.UriPath;
+
+@UriEndpoint(firstVersion = "2.20.0", scheme = "atomix-map", title = "atomix-map", syntax = "atomix-map:mapName", producerOnly = true, label = "clustering")
+class AtomixClientMapEndpoint extends AbstractAtomixClientEndpoint<AtomixClientMapComponent, AtomixClientMapConfiguration> {
+
+    @UriPath(description = "The distributed map name")
+    @Metadata(required = "true")
+    private final String mapName;
+
+    public AtomixClientMapEndpoint(String uri, AtomixClientMapComponent component, AtomixClientMapConfiguration configuration, String mapName) {
+        super(uri, component, configuration);
+
+        this.mapName = mapName;
+    }
+
+    @Override
+    public Producer createProducer() throws Exception {
+        return new AtomixClientMapProducer(this, mapName);
+    }
+
+    /*
+    @Override
+    public Consumer createConsumer(Processor processor) throws Exception {
+        return new AtomixClientMapConsumer(this, processor);
+    }
+    */
+
+    public String getMapName() {
+        return mapName;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducer.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducer.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducer.java
new file mode 100644
index 0000000..70dc656
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/map/AtomixClientMapProducer.java
@@ -0,0 +1,364 @@
+/**
+ * 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.camel.component.atomix.client.map;
+
+import java.time.Duration;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import io.atomix.collections.DistributedMap;
+import io.atomix.resource.ReadConsistency;
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Message;
+import org.apache.camel.component.atomix.client.AbstractAsyncAtomixClientProducer;
+import org.apache.camel.component.atomix.client.AtomixClientAction;
+import org.apache.camel.util.ExchangeHelper;
+import org.apache.camel.util.ObjectHelper;
+
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_ACTION;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_DEFAULT_VALUE;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_KEY;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_NAME;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_OLD_VALUE;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_READ_CONSISTENCY;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_TTL;
+import static org.apache.camel.component.atomix.client.AtomixClientConstants.RESOURCE_VALUE;
+
+final class AtomixClientMapProducer extends AbstractAsyncAtomixClientProducer<AtomixClientMapEndpoint> {
+    private final String mapName;
+    private final ConcurrentMap<String, DistributedMap<Object, Object>> maps;
+    private final AtomixClientMapConfiguration configuration;
+
+    protected AtomixClientMapProducer(AtomixClientMapEndpoint endpoint, String mapName) {
+        super(endpoint);
+        this.mapName = ObjectHelper.notNull(mapName, "map name");
+        this.configuration = endpoint.getAtomixConfiguration();
+        this.maps = new ConcurrentHashMap<>();
+    }
+
+    @Override
+    protected AtomixClientAction getAction(Message message) {
+        return message.getHeader(RESOURCE_ACTION, configuration::getDefaultAction, AtomixClientAction.class);
+    }
+
+    // *********************************
+    // Handlers
+    // *********************************
+
+    @AsyncInvokeOnHeader(AtomixClientAction.PUT)
+    boolean onPut(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final Object key = ExchangeHelper.getMandatoryHeader(message, RESOURCE_KEY, Object.class);
+        final Duration ttl = message.getHeader(RESOURCE_TTL, configuration::getTtl, Duration.class);
+
+        if (ttl != null) {
+            map.put(
+                key,
+                message.getMandatoryBody(),
+                ttl
+            ).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.put(
+                key,
+                message.getMandatoryBody()
+            ).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.PUT_IF_ABSENT)
+    boolean onPutIfAbsent(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final Object key = ExchangeHelper.getMandatoryHeader(message, RESOURCE_KEY, Object.class);
+        final Duration ttl = message.getHeader(RESOURCE_TTL, configuration::getTtl, Duration.class);
+
+        if (ttl != null) {
+            map.putIfAbsent(
+                key,
+                message.getMandatoryBody(),
+                ttl
+            ).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.putIfAbsent(
+                key,
+                message.getMandatoryBody()
+            ).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.GET)
+    boolean onGet(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final Object key = ExchangeHelper.getMandatoryHeader(message, RESOURCE_KEY, Object.class);
+        final Object defaultValue = message.getHeader(RESOURCE_DEFAULT_VALUE);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY,  configuration::getReadConsistency, ReadConsistency.class);
+
+        if (consistency != null) {
+            if (defaultValue != null) {
+                map.getOrDefault(key, defaultValue, consistency).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            } else {
+                map.get(key, consistency).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            }
+        } else {
+            if (defaultValue != null) {
+                map.getOrDefault(key, defaultValue).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            } else {
+                map.get(key).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            }
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.CLEAR)
+    boolean onClear(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+
+        map.clear().thenAccept(
+            result -> processResult(message, callback, result)
+        );
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.SIZE)
+    boolean onSize(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY,  configuration::getReadConsistency, ReadConsistency.class);
+
+        if (consistency != null) {
+            map.size(consistency).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.size().thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.IS_EMPTY)
+    boolean onIsEmpty(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY,  configuration::getReadConsistency, ReadConsistency.class);
+
+        if (consistency != null) {
+            map.isEmpty(consistency).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.isEmpty().thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.ENTRY_SET)
+    boolean onEntrySet(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY, configuration::getReadConsistency, ReadConsistency.class);
+
+        if (consistency != null) {
+            map.entrySet(consistency).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.entrySet().thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.VALUES)
+    boolean onValues(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY, configuration::getReadConsistency, ReadConsistency.class);
+
+        if (consistency != null) {
+            map.values(consistency).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.values().thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.CONTAINS_KEY)
+    boolean onContainsKey(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY,  configuration::getReadConsistency, ReadConsistency.class);
+        final Object key = message.getHeader(RESOURCE_KEY, message::getBody, Object.class);
+
+        ObjectHelper.notNull(key, RESOURCE_KEY);
+
+        if (consistency != null) {
+            map.containsKey(key, consistency).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.containsKey(key).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.CONTAINS_VALUE)
+    boolean onContainsValue(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final ReadConsistency consistency = message.getHeader(RESOURCE_READ_CONSISTENCY,  configuration::getReadConsistency, ReadConsistency.class);
+        final Object value = message.getHeader(RESOURCE_VALUE, message::getBody, Object.class);
+
+        ObjectHelper.notNull(value, RESOURCE_VALUE);
+
+        if (consistency != null) {
+            map.containsValue(value, consistency).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.containsValue(value).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.REMOVE)
+    boolean onRemove(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final Object key = message.getHeader(RESOURCE_KEY, message::getBody, Object.class);
+        final Object value = message.getHeader(RESOURCE_VALUE, message::getBody, Object.class);
+
+        ObjectHelper.notNull(key, RESOURCE_VALUE);
+
+        if (value != null) {
+            map.remove(key, value).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        } else {
+            map.remove(key).thenAccept(
+                result -> processResult(message, callback, result)
+            );
+        }
+
+        return false;
+    }
+
+    @AsyncInvokeOnHeader(AtomixClientAction.REPLACE)
+    boolean onReplace(Message message, AsyncCallback callback) throws Exception {
+        final DistributedMap<Object, Object> map = getMap(message);
+        final Duration ttl = message.getHeader(RESOURCE_TTL, configuration::getTtl, Duration.class);
+        final Object key = message.getHeader(RESOURCE_KEY, message::getBody, Object.class);
+        final Object newValue = message.getHeader(RESOURCE_VALUE, message::getBody, Object.class);
+        final Object oldValue = message.getHeader(RESOURCE_OLD_VALUE, Object.class);
+
+        ObjectHelper.notNull(key, RESOURCE_VALUE);
+        ObjectHelper.notNull(newValue, RESOURCE_VALUE);
+
+        if (ttl != null) {
+            if (oldValue != null) {
+                map.replace(key, oldValue, newValue, ttl).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            } else {
+                map.replace(key, newValue, ttl).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            }
+        } else {
+            if (oldValue != null) {
+                map.replace(key, oldValue, newValue).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            } else {
+                map.replace(key, newValue).thenAccept(
+                    result -> processResult(message, callback, result)
+                );
+            }
+        }
+
+        return false;
+    }
+
+    // *********************************
+    // Helpers
+    // *********************************
+
+    private void processResult(Message message, AsyncCallback callback, Object result) {
+        if (result != null && !(result instanceof Void)) {
+            message.setHeader(RESOURCE_ACTION_HAS_RESULT, true);
+
+            String resultHeader = configuration.getResultHeader();
+            if (resultHeader != null) {
+                message.setHeader(resultHeader, result);
+            } else {
+                message.setBody(result);
+            }
+        } else {
+            message.setHeader(RESOURCE_ACTION_HAS_RESULT, false);
+        }
+
+        callback.done(false);
+    }
+
+    private DistributedMap<Object, Object> getMap(Message message) {
+        return maps.computeIfAbsent(
+            message.getHeader(RESOURCE_NAME, getAtomixEndpoint().getMapName(), String.class),
+            name -> {
+                return getAtomixEndpoint()
+                    .getAtomix()
+                    .getMap(
+                        name,
+                        getAtomixEndpoint().getAtomixConfiguration().getConfig(),
+                        getAtomixEndpoint().getAtomixConfiguration().getOptions())
+                    .join();
+            }
+        );
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
index 8a732e1..b05230f 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
@@ -17,6 +17,7 @@
 package org.apache.camel.component.atomix.cluster;
 
 import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Transport;
 import io.atomix.copycat.server.storage.StorageLevel;
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.component.atomix.AtomixConfiguration;
@@ -24,65 +25,70 @@ import org.apache.camel.spi.UriParam;
 import org.apache.camel.spi.UriParams;
 
 @UriParams
-public class AtomixClusterConfiguration extends AtomixConfiguration implements Cloneable {
+public class AtomixClusterConfiguration extends AtomixConfiguration<AtomixReplica> implements Cloneable {
 
     @UriParam
-    private String storagePath;
-
-    @UriParam(defaultValue = "MEMORY")
-    private StorageLevel storageLevel = StorageLevel.MEMORY;
+    private Class<? extends Transport> clientTransport;
 
     @UriParam
-    private String replicaRef;
+    private Class<? extends Transport> serverTransport;
 
     @UriParam
-    private AtomixReplica replica;
+    private String storagePath;
+
+    @UriParam(defaultValue = "MEMORY")
+    private StorageLevel storageLevel = StorageLevel.MEMORY;
 
     public AtomixClusterConfiguration() {
     }
 
-    public String getStoragePath() {
-        return storagePath;
+    // ******************************************
+    // Properties
+    // ******************************************
+
+
+    public Class<? extends Transport> getClientTransport() {
+        return clientTransport;
     }
 
     /**
-     * Sets the log directory.
+     * The client transport
      */
-    public void setStoragePath(String storagePath) {
-        this.storagePath = storagePath;
+    public void setClientTransport(Class<? extends Transport> clientTransport) {
+        this.clientTransport = clientTransport;
     }
 
-    public StorageLevel getStorageLevel() {
-        return storageLevel;
+    public Class<? extends Transport> getServerTransport() {
+        return serverTransport;
     }
 
     /**
-     * Sets the log storage level.
+     * The server transport
      */
-    public void setStorageLevel(StorageLevel storageLevel) {
-        this.storageLevel = storageLevel;
+    public void setServerTransport(Class<? extends Transport> serverTransport) {
+        this.serverTransport = serverTransport;
     }
 
-    public String getReplicaRef() {
-        return replicaRef;
+    public String getStoragePath() {
+        return storagePath;
     }
 
     /**
-     * Set the reference of an instance of {@link AtomixReplica}.
+     * Sets the log directory.
      */
-    public void setReplicaRef(String clusterref) {
-        this.replicaRef = clusterref;
+    public void setStoragePath(String storagePath) {
+        this.storagePath = storagePath;
     }
 
-    public AtomixReplica getReplica() {
-        return replica;
+    public StorageLevel getStorageLevel() {
+        return storageLevel;
     }
 
     /**
-     * Set an instance of {@link AtomixReplica}.
+     * Sets the log storage level.
      */
-    public void setReplica(AtomixReplica replica) {
-        this.replica = replica;
+    public void setStorageLevel(StorageLevel storageLevel) {
+        this.storageLevel = storageLevel;
     }
 
     // ****************************************

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
index 777a4f6..0530495 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
@@ -23,7 +23,6 @@ import io.atomix.AtomixReplica;
 import io.atomix.catalyst.transport.Address;
 import io.atomix.copycat.server.storage.Storage;
 import org.apache.camel.CamelContext;
-import org.apache.camel.util.CamelContextHelper;
 import org.apache.camel.util.ObjectHelper;
 import org.apache.camel.util.ResourceHelper;
 
@@ -36,41 +35,47 @@ public final class AtomixClusterHelper {
     }
 
     public static AtomixReplica createReplica(CamelContext camelContext, Address address, AtomixClusterConfiguration configuration) throws Exception {
-        AtomixReplica atomix = configuration.getReplica();
+        AtomixReplica atomix = configuration.getAtomix();
 
         if (atomix == null) {
-            if (configuration.getReplicaRef() != null) {
-                atomix = CamelContextHelper.mandatoryLookup(camelContext, configuration.getReplicaRef(), AtomixReplica.class);
-            } else {
-                final AtomixReplica.Builder atomixBuilder;
+            final AtomixReplica.Builder atomixBuilder;
 
-                String uri = configuration.getConfigurationUri();
-                if (ObjectHelper.isNotEmpty(uri)) {
-                    uri = camelContext.resolvePropertyPlaceholders(uri);
-                    try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
-                        Properties properties = new Properties();
-                        properties.load(is);
+            String uri = configuration.getConfigurationUri();
+            if (ObjectHelper.isNotEmpty(uri)) {
+                uri = camelContext.resolvePropertyPlaceholders(uri);
+                try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
+                    Properties properties = new Properties();
+                    properties.load(is);
 
-                        atomixBuilder = AtomixReplica.builder(address, properties);
-                    }
-                } else {
-                    atomixBuilder = AtomixReplica.builder(address);
+                    atomixBuilder = AtomixReplica.builder(address, properties);
                 }
+            } else {
+                atomixBuilder = AtomixReplica.builder(address);
+            }
 
-                Storage.Builder storageBuilder = Storage.builder();
-                ObjectHelper.ifNotEmpty(configuration.getStorageLevel(), storageBuilder::withStorageLevel);
-                ObjectHelper.ifNotEmpty(configuration.getStoragePath(), storageBuilder::withDirectory);
-
-                atomixBuilder.withStorage(storageBuilder.build());
+            Storage.Builder storageBuilder = Storage.builder();
+            ObjectHelper.ifNotEmpty(configuration.getStorageLevel(), storageBuilder::withStorageLevel);
+            ObjectHelper.ifNotEmpty(configuration.getStoragePath(), storageBuilder::withDirectory);
 
-                if (configuration.getTransport() != null) {
-                    atomixBuilder.withTransport(
-                        camelContext.getInjector().newInstance(configuration.getTransport())
-                    );
-                }
+            atomixBuilder.withStorage(storageBuilder.build());
 
-                atomix = atomixBuilder.build();
+            if (configuration.getTransport() != null) {
+                atomixBuilder.withTransport(
+                    camelContext.getInjector().newInstance(configuration.getTransport())
+                );
+            }
+            if (configuration.getClientTransport() != null) {
+                atomixBuilder.withClientTransport(
+                    camelContext.getInjector().newInstance(configuration.getClientTransport())
+                );
             }
+            if (configuration.getServerTransport() != null) {
+                atomixBuilder.withServerTransport(
+                    camelContext.getInjector().newInstance(configuration.getServerTransport())
+                );
+            }
+
+            atomix = atomixBuilder.build();
         }
 
         return atomix;

http://git-wip-us.apache.org/repos/asf/camel/blob/08d2b0fe/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
index 6a6a750..bf49eab 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
@@ -18,7 +18,6 @@ package org.apache.camel.component.atomix.ha;
 
 import java.util.List;
 
-import io.atomix.Atomix;
 import io.atomix.AtomixReplica;
 import io.atomix.catalyst.transport.Address;
 import io.atomix.catalyst.transport.Transport;
@@ -109,20 +108,12 @@ public final class AtomixClusterService extends AbstractCamelClusterService<Atom
         configuration.setTransport(transport);
     }
 
-    public String getReplicaRef() {
-        return configuration.getReplicaRef();
+    public AtomixReplica getAtomix() {
+        return configuration.getAtomix();
     }
 
-    public void setReplicaRef(String clusterref) {
-        configuration.setReplicaRef(clusterref);
-    }
-
-    public Atomix getReplica() {
-        return configuration.getReplica();
-    }
-
-    public void setReplica(AtomixReplica replica) {
-        configuration.setReplica(replica);
+    public void setAtomix(AtomixReplica atomix) {
+        configuration.setAtomix(atomix);
     }
 
     public String getConfigurationUri() {
@@ -139,23 +130,18 @@ public final class AtomixClusterService extends AbstractCamelClusterService<Atom
 
     @Override
     protected void doStart() throws Exception {
-        // Assume that if addresses are provided the cluster needs be bootstrapped.
-        if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
-            LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
-            getOrCreateAtomix().bootstrap(configuration.getNodes()).join();
-            LOGGER.debug("Bootstrap cluster done");
-        }
+        // instantiate a new atomix replica
+        getOrCreateReplica();
 
         super.doStart();
     }
 
     @Override
     protected AtomixClusterView createView(String namespace) throws Exception {
-        return new AtomixClusterView(this, namespace, getOrCreateAtomix());
+        return new AtomixClusterView(this, namespace, getOrCreateReplica());
     }
 
-
-    private AtomixReplica getOrCreateAtomix() throws Exception {
+    private AtomixReplica getOrCreateReplica() throws Exception {
         if (atomix == null) {
             // Validate parameters
             ObjectHelper.notNull(getCamelContext(), "Camel Context");


[07/13] camel git commit: CAMEL-11362: create a LeaderElectionservice

Posted by lb...@apache.org.
CAMEL-11362: create a LeaderElectionservice


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

Branch: refs/heads/master
Commit: abb0ef47a28f19e808bcb595d4c592661a1f4727
Parents: 14f88f2
Author: lburgazzoli <lb...@gmail.com>
Authored: Fri Jun 2 08:12:58 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:54 2017 +0200

----------------------------------------------------------------------
 .../java/org/apache/camel/ha/CamelCluster.java  |  6 +--
 .../apache/camel/ha/CamelClusterService.java    | 31 -----------
 .../camel/impl/ha/AbstractCamelCluster.java     | 16 ++++--
 .../camel/impl/ha/ClusteredRoutePolicy.java     | 11 +++-
 .../impl/ha/ClusteredRoutePolicyFactory.java    | 55 ++++++++++++++++++++
 5 files changed, 81 insertions(+), 38 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/abb0ef47/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
index d6c151c..a0a797f 100644
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
+++ b/camel-core/src/main/java/org/apache/camel/ha/CamelCluster.java
@@ -22,11 +22,11 @@ import org.apache.camel.spi.HasId;
 
 public interface CamelCluster extends Service, CamelContextAware, HasId {
     /**
-     * Creates a view of the cluster bound to a namespace.
+     * Get a view of the cluster bound to a namespace creating it if needed.
      *
      * @param namespace the namespace the view refer to.
-     * @return the cluster view.
+     * @return the view.
      * @throws Exception if the view can't be created.
      */
-    CamelClusterView createView(String namespace) throws Exception;
+    CamelClusterView getView(String namespace) throws Exception;
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/abb0ef47/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java b/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
deleted file mode 100644
index 004eab3..0000000
--- a/camel-core/src/main/java/org/apache/camel/ha/CamelClusterService.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * 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.camel.ha;
-
-import org.apache.camel.Service;
-
-public interface CamelClusterService extends Service {
-    /**
-     * Get the {@linke CamelCluster} instance managed by the service
-     */
-    CamelCluster getCluster() throws Exception;
-
-    /**
-     * Create a {@linke CamelClusterView} for the given namespace
-     */
-    CamelClusterView createView(String namespace) throws Exception;
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/abb0ef47/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
index 9c4691e..16a869b 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/AbstractCamelCluster.java
@@ -50,6 +50,16 @@ public abstract class AbstractCamelCluster<T extends CamelClusterView> extends S
     @Override
     public void setCamelContext(CamelContext camelContext) {
         this.camelContext = camelContext;
+
+        long stamp = lock.writeLock();
+
+        try {
+            for (T view : views.values()) {
+                view.setCamelContext(camelContext);
+            }
+        } finally {
+            lock.unlockWrite(stamp);
+        }
     }
 
     @Override
@@ -84,14 +94,14 @@ public abstract class AbstractCamelCluster<T extends CamelClusterView> extends S
     }
 
     @Override
-    public CamelClusterView createView(String namespace) throws Exception {
+    public CamelClusterView getView(String namespace) throws Exception {
         long stamp = lock.writeLock();
 
         try {
             T view = views.get(namespace);
 
             if (view == null) {
-                view = doCreateView(namespace);
+                view = createView(namespace);
                 view.setCamelContext(this.camelContext);
 
                 views.put(namespace, view);
@@ -111,5 +121,5 @@ public abstract class AbstractCamelCluster<T extends CamelClusterView> extends S
     // Implementation
     // **********************************
 
-    protected abstract T doCreateView(String namespace) throws Exception;
+    protected abstract T createView(String namespace) throws Exception;
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/abb0ef47/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
index b08cddb..74ca781 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicy.java
@@ -246,8 +246,17 @@ public final class ClusteredRoutePolicy extends RoutePolicySupport implements Ca
     // Static helpers
     // ****************************************************
 
+    public static ClusteredRoutePolicy forNamespace(CamelContext camelContext, String namespace) throws Exception {
+        CamelCluster cluster = camelContext.hasService(CamelCluster.class);
+        if (cluster == null) {
+            throw new IllegalStateException("CamelCluster service not found");
+        }
+
+        return forNamespace(cluster, namespace);
+    }
+
     public static ClusteredRoutePolicy forNamespace(CamelCluster cluster, String namespace) throws Exception {
-        return forView(cluster.createView(namespace));
+        return forView(cluster.getView(namespace));
     }
 
     public static ClusteredRoutePolicy forView(CamelClusterView view) throws Exception  {

http://git-wip-us.apache.org/repos/asf/camel/blob/abb0ef47/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
new file mode 100644
index 0000000..da07706
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/ha/ClusteredRoutePolicyFactory.java
@@ -0,0 +1,55 @@
+/**
+ * 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.camel.impl.ha;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.model.RouteDefinition;
+import org.apache.camel.spi.RoutePolicy;
+import org.apache.camel.spi.RoutePolicyFactory;
+import org.apache.camel.util.ObjectHelper;
+
+public class ClusteredRoutePolicyFactory implements RoutePolicyFactory {
+    private final String namespace;
+
+    public ClusteredRoutePolicyFactory(String viewName) {
+        this.namespace = ObjectHelper.notNull(viewName, "Cluster View Namespace");
+    }
+
+    @Override
+    public RoutePolicy createRoutePolicy(CamelContext camelContext, String routeId, RouteDefinition route) {
+        try {
+            CamelCluster cluster = camelContext.hasService(CamelCluster.class);
+            if (cluster == null) {
+                throw new IllegalStateException("CamelCluster service not found");
+            }
+
+            return ClusteredRoutePolicy.forNamespace(cluster, namespace);
+        } catch (Exception e) {
+            throw new RuntimeCamelException(e);
+        }
+    }
+
+    // ****************************************************
+    // Static helpers
+    // ****************************************************
+
+    public static ClusteredRoutePolicyFactory forNamespace(String namespace) {
+        return new ClusteredRoutePolicyFactory(namespace);
+    }
+}


[06/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
CAMEL-10054: Create camel-atomix component


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

Branch: refs/heads/master
Commit: 14f88f2e6cc0733dc72ff35a05973787c8dfec44
Parents: 21b65d9
Author: lburgazzoli <lb...@gmail.com>
Authored: Thu Jun 1 19:27:31 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:54 2017 +0200

----------------------------------------------------------------------
 components/camel-atomix/pom.xml                 |   9 +-
 .../src/main/docs/atomix-client-component.adoc  |   6 +
 .../src/main/docs/atomix-cluster-component.adoc |  27 +++
 .../src/main/docs/atomix-component.adoc         |   6 -
 .../component/atomix/AtomixConfiguration.java   |  80 +++++++
 .../atomix/client/AtomixClientComponent.java    |  36 +++
 .../client/AtomixClientConfiguration.java       |  25 +++
 .../atomix/cluster/AtomixClusterComponent.java  |  36 +++
 .../cluster/AtomixClusterConfiguration.java     |  85 +++++++
 .../component/atomix/ha/AtomixCluster.java      |  51 +++--
 .../atomix/ha/AtomixClusterFactory.java         |  28 ---
 .../atomix/ha/AtomixClusterService.java         | 224 +++++++++++++++++++
 .../component/atomix/ha/AtomixClusterView.java  |  54 +++--
 .../services/org/apache/camel/component/atomix  |  18 --
 .../org/apache/camel/component/atomix-client    |  18 ++
 .../org/apache/camel/component/atomix-cluster   |  18 ++
 .../atomix/ha/AtomixRoutePolicyMain.java        | 144 +++++-------
 .../camel-atomix-starter/pom.xml                |  53 +++++
 .../src/main/resources/META-INF/LICENSE.txt     | 203 +++++++++++++++++
 .../src/main/resources/META-INF/NOTICE.txt      |  11 +
 .../src/main/resources/META-INF/spring.provides |  17 ++
 .../spring-boot/components-starter/pom.xml      |   1 +
 22 files changed, 971 insertions(+), 179 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/pom.xml
----------------------------------------------------------------------
diff --git a/components/camel-atomix/pom.xml b/components/camel-atomix/pom.xml
index 3afb62e..ca4ad29 100644
--- a/components/camel-atomix/pom.xml
+++ b/components/camel-atomix/pom.xml
@@ -34,9 +34,14 @@
   <description>Camel Atomix support</description>
 
   <properties>
-    <camel.osgi.export.pkg>org.apache.camel.component.atomix.*</camel.osgi.export.pkg>
+    <camel.osgi.export.pkg>
+      org.apache.camel.component.atomix.*,
+      org.apache.camel.component.atomix.client.*,
+      org.apache.camel.component.atomix.cluster.*
+    </camel.osgi.export.pkg>
     <camel.osgi.export.service>
-      org.apache.camel.spi.ComponentResolver;component=atomix
+      org.apache.camel.spi.ComponentResolver;component=atomix-client,
+      org.apache.camel.spi.ComponentResolver;component=atomix-cluster,
     </camel.osgi.export.service>
   </properties>
 

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/docs/atomix-client-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-client-component.adoc b/components/camel-atomix/src/main/docs/atomix-client-component.adoc
new file mode 100644
index 0000000..20ece42
--- /dev/null
+++ b/components/camel-atomix/src/main/docs/atomix-client-component.adoc
@@ -0,0 +1,6 @@
+## Atomix Client Component
+
+*Available as of Camel version 2.20*
+
+The camel atomix component allows you to work with Atomix, a fault-tolerant distributed coordination framework.
+

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc b/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
new file mode 100644
index 0000000..80f2f7e
--- /dev/null
+++ b/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
@@ -0,0 +1,27 @@
+## Atomix Cluster Component
+
+*Available as of Camel version 2.20*
+
+The camel atomix component allows you to work with Atomix, a fault-tolerant distributed coordination framework.
+
+
+mvn \
+    -Datomix.cluster="127.0.0.1:9001,127.0.0.1:9002,127.0.0.1:9003" \
+    -Dexec.mainClass=org.apache.camel.component.atomix.ha.AtomixRoutePolicyMain \
+    -Dexec.classpathScope=test \
+    test-compile \
+    exec:java
+
+mvn \
+    -Datomix.cluster="127.0.0.1:9002,127.0.0.1:9001,127.0.0.1:9003" \
+    -Dexec.mainClass=org.apache.camel.component.atomix.ha.AtomixRoutePolicyMain \
+    -Dexec.classpathScope=test \
+    test-compile \
+    exec:java
+
+mvn \
+    -Datomix.cluster="127.0.0.1:9003,127.0.0.1:9001,127.0.0.1:9002" \
+    -Dexec.mainClass=org.apache.camel.component.atomix.ha.AtomixRoutePolicyMain \
+    -Dexec.classpathScope=test \
+    test-compile \
+    exec:java
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/docs/atomix-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-component.adoc b/components/camel-atomix/src/main/docs/atomix-component.adoc
deleted file mode 100644
index e499f1b..0000000
--- a/components/camel-atomix/src/main/docs/atomix-component.adoc
+++ /dev/null
@@ -1,6 +0,0 @@
-## Atomix Component
-
-*Available as of Camel version 2.20*
-
-The camel atomix component allows you to work with Atomix, a fault-tolerant distributed coordination framework.
-

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
new file mode 100644
index 0000000..4504488
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/AtomixConfiguration.java
@@ -0,0 +1,80 @@
+/**
+ * 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
+ */
+package org.apache.camel.component.atomix;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import io.atomix.catalyst.transport.Address;
+import io.atomix.catalyst.transport.Transport;
+import io.atomix.catalyst.transport.netty.NettyTransport;
+import org.apache.camel.spi.UriParam;
+import org.apache.camel.util.ObjectHelper;
+
+public class AtomixConfiguration {
+    @UriParam(javaType = "java.lang.String")
+    private List<Address> nodes = Collections.emptyList();
+
+    @UriParam(defaultValue = "io.atomix.catalyst.transport.netty.NettyTransport")
+    private Class<? extends Transport> transport = NettyTransport.class;
+
+    @UriParam
+    private String configurationUri;
+
+    protected AtomixConfiguration() {
+    }
+
+    public List<Address> getNodes() {
+        return nodes;
+    }
+
+    /**
+     * The address of the nodes composing the cluster.
+     */
+    public void setNodes(List<Address> nodes) {
+        this.nodes = ObjectHelper.notNull(nodes, "Atomix Nodes");
+    }
+
+    public void setNodes(String nodes) {
+        if (ObjectHelper.isNotEmpty(nodes)) {
+            setNodes(Stream.of(nodes.split(",")).map(Address::new).collect(Collectors.toList()));
+        }
+    }
+
+    public Class<? extends Transport> getTransport() {
+        return transport;
+    }
+
+    /**
+     * Sets the Atomix transport.
+     */
+    public void setTransport(Class<? extends Transport> transport) {
+        this.transport = transport;
+    }
+
+    public String getConfigurationUri() {
+        return configurationUri;
+    }
+
+    /**
+     * The Atomix configuration uri.
+     */
+    public void setConfigurationUri(String configurationUri) {
+        this.configurationUri = configurationUri;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
new file mode 100644
index 0000000..c4348c4
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientComponent.java
@@ -0,0 +1,36 @@
+/**
+ * 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
+ */
+package org.apache.camel.component.atomix.client;
+
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Endpoint;
+import org.apache.camel.impl.DefaultComponent;
+
+public class AtomixClientComponent extends DefaultComponent {
+    public AtomixClientComponent() {
+    }
+
+    public AtomixClientComponent(CamelContext camelContext) {
+        super(camelContext);
+    }
+
+    @Override
+    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
+        throw new UnsupportedOperationException("Not yet implemented");
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
new file mode 100644
index 0000000..628f88b
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/client/AtomixClientConfiguration.java
@@ -0,0 +1,25 @@
+/**
+ * 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
+ */
+package org.apache.camel.component.atomix.client;
+
+import org.apache.camel.component.atomix.AtomixConfiguration;
+import org.apache.camel.spi.UriParams;
+
+@UriParams
+public class AtomixClientConfiguration extends AtomixConfiguration {
+    public AtomixClientConfiguration() {
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
new file mode 100644
index 0000000..fa1cace
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterComponent.java
@@ -0,0 +1,36 @@
+/**
+ * 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
+ */
+package org.apache.camel.component.atomix.cluster;
+
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Endpoint;
+import org.apache.camel.impl.DefaultComponent;
+
+public class AtomixClusterComponent extends DefaultComponent {
+    public AtomixClusterComponent() {
+    }
+
+    public AtomixClusterComponent(CamelContext camelContext) {
+        super(camelContext);
+    }
+
+    @Override
+    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
+        throw new UnsupportedOperationException("Not yet implemented");
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
new file mode 100644
index 0000000..5d1cbb1
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
@@ -0,0 +1,85 @@
+/**
+ * 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
+ */
+package org.apache.camel.component.atomix.cluster;
+
+import io.atomix.AtomixReplica;
+import io.atomix.copycat.server.storage.StorageLevel;
+import org.apache.camel.component.atomix.AtomixConfiguration;
+import org.apache.camel.spi.UriParam;
+import org.apache.camel.spi.UriParams;
+
+@UriParams
+public class AtomixClusterConfiguration extends AtomixConfiguration {
+
+    @UriParam
+    private String storagePath;
+
+    @UriParam(defaultValue = "MEMORY")
+    private StorageLevel storageLevel = StorageLevel.MEMORY;
+
+    @UriParam
+    private String replicaRef;
+
+    @UriParam
+    private AtomixReplica replica;
+
+    public AtomixClusterConfiguration() {
+    }
+
+    public String getStoragePath() {
+        return storagePath;
+    }
+
+    /**
+     * Sets the log directory.
+     */
+    public void setStoragePath(String storagePath) {
+        this.storagePath = storagePath;
+    }
+
+    public StorageLevel getStorageLevel() {
+        return storageLevel;
+    }
+
+    /**
+     * Sets the log storage level.
+     */
+    public void setStorageLevel(StorageLevel storageLevel) {
+        this.storageLevel = storageLevel;
+    }
+
+    public String getReplicaRef() {
+        return replicaRef;
+    }
+
+    /**
+     * Set the reference of an instance of {@link AtomixReplica}.
+     */
+    public void setReplicaRef(String clusterref) {
+        this.replicaRef = clusterref;
+    }
+
+    public AtomixReplica getReplica() {
+        return replica;
+    }
+
+    /**
+     * Set an instance of {@link AtomixReplica}.
+     */
+    public void setReplica(AtomixReplica replica) {
+        this.replica = replica;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
index 56f9084..10d53bc 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
@@ -16,32 +16,53 @@
  */
 package org.apache.camel.component.atomix.ha;
 
-import io.atomix.Atomix;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Address;
 import org.apache.camel.CamelContext;
 import org.apache.camel.impl.ha.AbstractCamelCluster;
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-/**
- * TODO: Dummy implementation for testing purpose
- */
-public class AtomixCluster extends AbstractCamelCluster<AtomixClusterView> {
-    private final Atomix atomix;
+public final class AtomixCluster extends AbstractCamelCluster<AtomixClusterView> {
+    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixCluster.class);
+
+    private final AtomixReplica atomix;
+    private final List<Address> addresses;
+
+    public AtomixCluster(AtomixReplica atomix) {
+        this(null, atomix, Collections.emptyList());
+    }
 
-    public AtomixCluster(Atomix atomix) {
-       this(null, atomix);
+    public AtomixCluster(AtomixReplica atomix, List<Address> addresses) {
+       this(null, atomix, addresses);
     }
 
-    public AtomixCluster(CamelContext camelContext, Atomix atomix) {
+    public AtomixCluster(CamelContext camelContext, AtomixReplica atomix, List<Address> addresses) {
         super("camel-atomix", camelContext);
 
         this.atomix = atomix;
+        this.addresses = new ArrayList<>(addresses);
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        // Assume that if addresses are provided the cluster needs be bootstrapped.
+        if (ObjectHelper.isNotEmpty(addresses)) {
+            LOGGER.debug("Bootstrap cluster for nodes: {}", addresses);
+            this.atomix.bootstrap(addresses).join();
+            LOGGER.debug("Bootstrap cluster done");
+        }
+
+        super.doStart();
     }
 
     @Override
-    public AtomixClusterView doCreateView(String namespace) throws Exception {
-        return new AtomixClusterView(
-            this,
-            namespace,
-            atomix.getGroup(namespace).join()
-        );
+    protected AtomixClusterView doCreateView(String namespace) throws Exception {
+        return new AtomixClusterView(this, namespace, atomix);
     }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java
deleted file mode 100644
index a0f6835..0000000
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterFactory.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 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.camel.component.atomix.ha;
-
-import org.apache.camel.CamelContext;
-import org.apache.camel.ha.CamelCluster;
-import org.apache.camel.ha.CamelClusterFactory;
-
-public class AtomixClusterFactory implements CamelClusterFactory {
-    @Override
-    public CamelCluster newInstance(CamelContext camelContext) throws Exception {
-        throw new UnsupportedOperationException("Not yet implemented");
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
new file mode 100644
index 0000000..61fc817
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
@@ -0,0 +1,224 @@
+/**
+ * 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.camel.component.atomix.ha;
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.Properties;
+
+import io.atomix.Atomix;
+import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Address;
+import io.atomix.catalyst.transport.Transport;
+import io.atomix.copycat.server.storage.Storage;
+import io.atomix.copycat.server.storage.StorageLevel;
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.component.atomix.cluster.AtomixClusterConfiguration;
+import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterService;
+import org.apache.camel.ha.CamelClusterView;
+import org.apache.camel.support.ServiceSupport;
+import org.apache.camel.util.CamelContextHelper;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.ResourceHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class AtomixClusterService extends ServiceSupport implements CamelContextAware, CamelClusterService {
+    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixClusterService.class);
+
+    private final AtomixClusterConfiguration configuration;
+
+    private CamelContext camelContext;
+    private Address address;
+    private AtomixCluster cluster;
+
+    public AtomixClusterService() {
+        this.configuration = new AtomixClusterConfiguration();
+    }
+
+    // **********************************
+    // Properties
+    // **********************************
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    public Address getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = new Address(address);
+    }
+
+    public void setAddress(Address address) {
+        this.address = address;
+    }
+
+    public String getStoragePath() {
+        return configuration.getStoragePath();
+    }
+
+    public void setStoragePath(String storagePath) {
+        configuration.setStoragePath(storagePath);
+    }
+
+    public List<Address> getNodes() {
+        return configuration.getNodes();
+    }
+
+    public StorageLevel getStorageLevel() {
+        return configuration.getStorageLevel();
+    }
+
+    public void setNodes(List<Address> nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public void setStorageLevel(StorageLevel storageLevel) {
+        configuration.setStorageLevel(storageLevel);
+    }
+
+    public void setNodes(String nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public Class<? extends Transport> getTransport() {
+        return configuration.getTransport();
+    }
+
+    public void setTransport(Class<? extends Transport> transport) {
+        configuration.setTransport(transport);
+    }
+
+    public String getReplicaRef() {
+        return configuration.getReplicaRef();
+    }
+
+    /**
+     * Set the reference of an instance of {@link AtomixReplica}.
+     * @param clusterref
+     */
+    public void setReplicaRef(String clusterref) {
+        configuration.setReplicaRef(clusterref);
+    }
+
+    public Atomix getReplica() {
+        return configuration.getReplica();
+    }
+
+    /**
+     * Set an instance of {@link AtomixReplica}.
+     * @param replica
+     */
+    public void setReplica(AtomixReplica replica) {
+        configuration.setReplica(replica);
+    }
+
+    public String getConfigurationUri() {
+        return configuration.getConfigurationUri();
+    }
+
+    public void setConfigurationUri(String configurationUri) {
+        configuration.setConfigurationUri(configurationUri);
+    }
+
+    // **********************************
+    // Cluster
+    // **********************************
+
+    @Override
+    public synchronized CamelCluster getCluster() throws Exception  {
+        if (this.cluster == null) {
+            AtomixReplica atomix = configuration.getReplica();
+
+            if (atomix == null) {
+                if (configuration.getReplicaRef() != null) {
+                    atomix = CamelContextHelper.mandatoryLookup(camelContext, configuration.getReplicaRef(), AtomixReplica.class);
+                } else {
+                    ObjectHelper.notNull(this.address, "Atomix Address");
+
+                    final AtomixReplica.Builder atomixBuilder;
+
+                    String uri = configuration.getConfigurationUri();
+                    if (ObjectHelper.isNotEmpty(uri)) {
+                        uri = camelContext.resolvePropertyPlaceholders(uri);
+                        try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
+                            Properties properties = new Properties();
+                            properties.load(is);
+
+                            atomixBuilder = AtomixReplica.builder(this.address, properties);
+                        }
+                    } else {
+                        atomixBuilder = AtomixReplica.builder(this.address);
+                    }
+
+                    Storage.Builder storageBuilder = Storage.builder();
+                    ObjectHelper.ifNotEmpty(configuration.getStorageLevel(), storageBuilder::withStorageLevel);
+                    ObjectHelper.ifNotEmpty(configuration.getStoragePath(), storageBuilder::withDirectory);
+
+                    atomixBuilder.withStorage(storageBuilder.build());
+
+                    if (configuration.getTransport() != null) {
+                        atomixBuilder.withTransport(
+                            camelContext.getInjector().newInstance(configuration.getTransport())
+                        );
+                    }
+
+                    atomix = atomixBuilder.build();
+                }
+            }
+
+            this.cluster = new AtomixCluster(atomix, configuration.getNodes());
+            this.cluster.setCamelContext(camelContext);
+        }
+
+        return this.cluster;
+    }
+
+    @Override
+    public CamelClusterView createView(String namespace) throws Exception {
+        return getCluster().createView(namespace);
+    }
+
+    // **********************************
+    // Service
+    // **********************************
+
+    @Override
+    protected void doStart() throws Exception {
+        LOGGER.debug("Starting cluster on address {}", address);
+        getCluster().start();
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        if (this.cluster != null) {
+            this.cluster.stop();
+            this.cluster = null;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
index 6c8f9e5..bf1c4d1 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterView.java
@@ -20,41 +20,51 @@ import java.util.List;
 import java.util.concurrent.ExecutionException;
 import java.util.stream.Collectors;
 
+import io.atomix.Atomix;
 import io.atomix.group.DistributedGroup;
 import io.atomix.group.GroupMember;
 import io.atomix.group.LocalMember;
+import io.atomix.group.election.Term;
 import org.apache.camel.ha.CamelClusterMember;
 import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.impl.ha.AbstractCamelClusterView;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class AtomixClusterView extends AbstractCamelClusterView {
+public final class AtomixClusterView extends AbstractCamelClusterView {
     private static final Logger LOGGER = LoggerFactory.getLogger(AtomixClusterView.class);
 
-    private final DistributedGroup group;
+    private final Atomix atomix;
     private final AtomixLocalMember localMember;
+    private DistributedGroup group;
 
-    AtomixClusterView(AtomixCluster cluster, String namespace, DistributedGroup group) {
+    AtomixClusterView(AtomixCluster cluster, String namespace, Atomix atomix) {
         super(cluster, namespace);
 
-        this.group = group;
-        this.localMember = new AtomixLocalMember(group);
+        this.atomix = atomix;
+        this.localMember = new AtomixLocalMember();
     }
 
     @Override
     public CamelClusterMember getMaster() {
-        return asCamelClusterMember(this.group.election().term().leader());
+        if (group == null) {
+            throw new IllegalStateException("The view has not yet joined the cluster");
+        }
+
+        return asCamelClusterMember(group.election().term().leader());
     }
 
     @Override
     public CamelClusterMember getLocalMember() {
-        return this.localMember;
+        return localMember;
     }
 
     @Override
     public List<CamelClusterMember> getMembers() {
-        // TODO: Dummy implementation for testing purpose
+        if (group == null) {
+            throw new IllegalStateException("The view has not yet joined the cluster");
+        }
+
         return this.group.members().stream()
             .map(this::asCamelClusterMember)
             .collect(Collectors.toList());
@@ -66,11 +76,15 @@ public class AtomixClusterView extends AbstractCamelClusterView {
 
     @Override
     protected void doStart() throws Exception {
-        if (!this.localMember.hasJoined()) {
-            this.localMember.join();
-            this.group.election().onElection(
-                t -> fireEvent(CamelClusterView.Event.LEADERSHIP_CHANGED, asCamelClusterMember(t.leader()))
-            );
+        if (!localMember.hasJoined()) {
+            LOGGER.debug("Get group {}", getNamespace());
+            group = this.atomix.getGroup(getNamespace()).get();
+
+            LOGGER.debug("Join group {}", getNamespace());
+            localMember.join();
+
+            LOGGER.debug("Listen election events");
+            group.election().onElection(this::onElection);
         }
     }
 
@@ -79,22 +93,24 @@ public class AtomixClusterView extends AbstractCamelClusterView {
         localMember.leave();
     }
 
+    private void onElection(Term term) {
+        fireEvent(CamelClusterView.Event.LEADERSHIP_CHANGED, asCamelClusterMember(term.leader()));
+    }
+
     // ***********************************************
     //
     // ***********************************************
 
     class AtomixLocalMember implements CamelClusterMember {
-        private final DistributedGroup group;
         private LocalMember member;
 
-        AtomixLocalMember(DistributedGroup group) {
-            this.group = group;
+        AtomixLocalMember() {
         }
 
         @Override
         public String getId() {
             if (member == null) {
-                throw new IllegalStateException("Cluster not yet joined");
+                throw new IllegalStateException("The view has not yet joined the cluster");
             }
 
             return member.id();
@@ -114,9 +130,9 @@ public class AtomixClusterView extends AbstractCamelClusterView {
         }
 
         AtomixLocalMember join() throws ExecutionException, InterruptedException {
-            if (member == null) {
+            if (member == null && group != null) {
                 LOGGER.debug("Joining group {}", group);
-                member = this.group.join().get();
+                member = group.join().join();
             }
 
             return this;

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix
deleted file mode 100644
index d4f1673..0000000
--- a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix
+++ /dev/null
@@ -1,18 +0,0 @@
-#
-# 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.
-#
-
-#class=org.apache.camel.component.atomix.AtomixComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client
new file mode 100644
index 0000000..5e7a620
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-client
@@ -0,0 +1,18 @@
+#
+# 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.
+#
+
+class=org.apache.camel.component.atomix.AtomixClientComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-cluster
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-cluster b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-cluster
new file mode 100644
index 0000000..57df716
--- /dev/null
+++ b/components/camel-atomix/src/main/resources/META-INF/services/org/apache/camel/component/atomix-cluster
@@ -0,0 +1,18 @@
+#
+# 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.
+#
+
+class=org.apache.camel.component.atomix.AtomixClusterComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
index 0a126d3..e622900 100644
--- a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
@@ -17,27 +17,17 @@
 package org.apache.camel.component.atomix.ha;
 
 import java.io.File;
-import java.util.Arrays;
+import java.util.ArrayList;
 import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
 
-import io.atomix.Atomix;
-import io.atomix.AtomixReplica;
 import io.atomix.catalyst.transport.Address;
-import io.atomix.catalyst.transport.netty.NettyTransport;
-import io.atomix.copycat.server.storage.Storage;
 import io.atomix.copycat.server.storage.StorageLevel;
-import org.apache.camel.CamelContext;
 import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.ha.CamelCluster;
+import org.apache.camel.ha.CamelClusterService;
 import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.camel.impl.ha.ClusteredRoutePolicy;
 import org.apache.camel.spi.RoutePolicy;
-import org.apache.camel.test.AvailablePortFinder;
 import org.apache.camel.util.FileUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -45,90 +35,62 @@ import org.slf4j.LoggerFactory;
 public final class AtomixRoutePolicyMain {
     private static final Logger LOGGER = LoggerFactory.getLogger(AtomixRoutePolicyMain.class);
 
-
-    private static final List<Address> ADDRESSES =  Arrays.asList(
-        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
-        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable()),
-        new Address("127.0.0.1", AvailablePortFinder.getNextAvailable())
-    );
-
-    private static final CountDownLatch LATCH = new CountDownLatch(ADDRESSES.size());
-    private static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(ADDRESSES.size() * 2);
-
     public static void main(final String[] args) throws Exception {
-        for (Address address :  ADDRESSES) {
-            EXECUTOR.submit(() -> run(address));
-        }
-
-        LATCH.await();
-
-        System.exit(0);
-    }
-
-    static void run(Address address) {
-        try {
-            final String id = String.format("atomix-%d", address.port());
-            final File path = new File("target", id);
-
-            // Cleanup
-            FileUtil.removeDir(path);
+        String[] addresses = System.getProperty("atomix.cluster").split(",");
 
-            Atomix atomix = AtomixReplica.builder(address)
-                .withTransport(new NettyTransport())
-                .withStorage(
-                    Storage.builder()
-                        .withDirectory(path)
-                        .withStorageLevel(StorageLevel.MEMORY)
-                        .build())
-                .build()
-                .bootstrap(ADDRESSES)
-                .join();
-
-            CountDownLatch latch = new CountDownLatch(1);
-            CamelContext context = new DefaultCamelContext();
-            CamelCluster cluster = new AtomixCluster(atomix);
-            CamelClusterView view = cluster.createView("my-view");
-
-            view.addEventListener((e, p) -> {
-                if (view.getLocalMember().isMaster()) {
-                    LOGGER.info("Member {} ({}), is now master", view.getLocalMember().getId(), address);
-
-                    // Shutdown the context later on so the next one should take
-                    // the leadership
-                    EXECUTOR.schedule(latch::countDown, 10, TimeUnit.SECONDS);
-                }
-            });
-
-            context.addService(cluster);
-            context.addRoutes(new RouteBuilder() {
-                @Override
-                public void configure() throws Exception {
-                    RoutePolicy policy = ClusteredRoutePolicy.forView(view);
+        List<Address> cluster = new ArrayList<>();
+        for (int i = 0; i < addresses.length; i++) {
+            String[] parts = addresses[i].split(":");
+            cluster.add(new Address(parts[0], Integer.valueOf(parts[1])));
+        }
 
-                    fromF("timer:%s-1?period=2s", id)
-                        .routeId(id + "-1")
-                        .routePolicy(policy)
-                        .setHeader("ClusterMaster")
-                            .body(b -> view.getMaster().getId())
-                        .log("${routeId} (1) - master is: ${header.ClusterMaster}");
-                    fromF("timer:%s-2?period=5s", id)
-                        .routeId(id + "-2")
-                        .routePolicy(policy)
-                        .setHeader("ClusterMaster")
-                            .body(b -> view.getMaster().getId())
-                        .log("${routeId} (2) - master is: ${header.ClusterMaster}");
+        final String id = String.format("atomix-%d", cluster.get(0).port());
+        final File path = new File("target", id);
+
+        // Cleanup
+        FileUtil.removeDir(path);
+
+        AtomixClusterService service = new AtomixClusterService();
+        service.setStoragePath(path.getAbsolutePath());
+        service.setStorageLevel(StorageLevel.DISK);
+        service.setAddress(cluster.get(0));
+        service.setNodes(cluster);
+
+        DefaultCamelContext context = new DefaultCamelContext();
+        context.addService(service);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                CamelClusterService cluster = getContext().hasService(AtomixClusterService.class);
+                CamelClusterView view = cluster.createView("my-view");
+                RoutePolicy policy = ClusteredRoutePolicy.forView(view);
+
+                fromF("timer:%s-1?period=2s", id)
+                    .routeId(id + "-1")
+                    .routePolicy(policy)
+                    .log("${routeId} (1)");
+                fromF("timer:%s-2?period=5s", id)
+                    .routeId(id + "-2")
+                    .routePolicy(policy)
+                    .log("${routeId} (2)");
+            }
+        });
+
+        context.start();
+
+        Runtime.getRuntime().addShutdownHook(new Thread() {
+            @Override
+            public void run() {
+                try {
+                    context.stop();
+                } catch (Exception e) {
+                    LOGGER.warn("", e);
                 }
-            });
+            }
+        });
 
-            context.start();
-            latch.await();
-            context.stop();
-
-            LATCH.countDown();
-        } catch (Exception e) {
-            throw new RuntimeException(e);
+        for (int i = 0; i < Integer.MAX_VALUE; i++) {
+            Thread.sleep(1000);
         }
-
-        LOGGER.info("Done {}", address);
     }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/platforms/spring-boot/components-starter/camel-atomix-starter/pom.xml
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/pom.xml b/platforms/spring-boot/components-starter/camel-atomix-starter/pom.xml
new file mode 100644
index 0000000..b3231a5
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/pom.xml
@@ -0,0 +1,53 @@
+<?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.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.apache.camel</groupId>
+    <artifactId>components-starter</artifactId>
+    <version>2.20.0-SNAPSHOT</version>
+  </parent>
+  <artifactId>camel-atomix-starter</artifactId>
+  <packaging>jar</packaging>
+  <name>Spring-Boot Starter :: Camel :: Atomix</name>
+  <description>Spring-Boot Starter for Camel Atomix support</description>
+  <dependencies>
+    <dependency>
+      <groupId>org.springframework.boot</groupId>
+      <artifactId>spring-boot-starter</artifactId>
+      <version>${spring-boot-version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-atomix</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <!--START OF GENERATED CODE-->
+    <dependency>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-core-starter</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.camel</groupId>
+      <artifactId>camel-spring-boot-starter</artifactId>
+    </dependency>
+    <!--END OF GENERATED CODE-->
+  </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/LICENSE.txt
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/LICENSE.txt b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/LICENSE.txt
new file mode 100644
index 0000000..6b0b127
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/LICENSE.txt
@@ -0,0 +1,203 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
+

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/NOTICE.txt
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/NOTICE.txt b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/NOTICE.txt
new file mode 100644
index 0000000..2e215bf
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/NOTICE.txt
@@ -0,0 +1,11 @@
+   =========================================================================
+   ==  NOTICE file corresponding to the section 4 d of                    ==
+   ==  the Apache License, Version 2.0,                                   ==
+   ==  in this case for the Apache Camel distribution.                    ==
+   =========================================================================
+
+   This product includes software developed by
+   The Apache Software Foundation (http://www.apache.org/).
+
+   Please read the different LICENSE files present in the licenses directory of
+   this distribution.

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.provides
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.provides b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.provides
new file mode 100644
index 0000000..26745eb
--- /dev/null
+++ b/platforms/spring-boot/components-starter/camel-atomix-starter/src/main/resources/META-INF/spring.provides
@@ -0,0 +1,17 @@
+## ---------------------------------------------------------------------------
+## 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.
+## ---------------------------------------------------------------------------
+provides: camel-atomix

http://git-wip-us.apache.org/repos/asf/camel/blob/14f88f2e/platforms/spring-boot/components-starter/pom.xml
----------------------------------------------------------------------
diff --git a/platforms/spring-boot/components-starter/pom.xml b/platforms/spring-boot/components-starter/pom.xml
index 4bca7c5..35fc760 100644
--- a/platforms/spring-boot/components-starter/pom.xml
+++ b/platforms/spring-boot/components-starter/pom.xml
@@ -83,6 +83,7 @@
     <module>camel-atmos-starter</module>
     <module>camel-atmosphere-websocket-starter</module>
     <module>camel-atom-starter</module>
+    <module>camel-atomix-starter</module>
     <module>camel-avro-starter</module>
     <module>camel-aws-starter</module>
     <module>camel-azure-starter</module>


[09/13] camel git commit: CAMEL-10054: Create camel-atomix component

Posted by lb...@apache.org.
CAMEL-10054: Create camel-atomix component


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

Branch: refs/heads/master
Commit: a5d4df8fa301e5ba16619eb2176ee4d1a815441c
Parents: abb0ef4
Author: lburgazzoli <lb...@gmail.com>
Authored: Fri Jun 2 08:13:14 2017 +0200
Committer: lburgazzoli <lb...@gmail.com>
Committed: Fri Jun 16 17:37:54 2017 +0200

----------------------------------------------------------------------
 .../src/main/docs/atomix-cluster-component.adoc |  19 +-
 .../cluster/AtomixClusterConfiguration.java     |  15 +-
 .../atomix/cluster/AtomixClusterHelper.java     |  77 +++++++
 .../component/atomix/ha/AtomixCluster.java      | 157 +++++++++++--
 .../atomix/ha/AtomixClusterService.java         | 224 -------------------
 .../atomix/ha/AtomixRoutePolicyMain.java        |  59 ++---
 6 files changed, 253 insertions(+), 298 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/a5d4df8f/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc b/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
index 80f2f7e..5ae5df1 100644
--- a/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
+++ b/components/camel-atomix/src/main/docs/atomix-cluster-component.adoc
@@ -6,22 +6,9 @@ The camel atomix component allows you to work with Atomix, a fault-tolerant dist
 
 
 mvn \
-    -Datomix.cluster="127.0.0.1:9001,127.0.0.1:9002,127.0.0.1:9003" \
-    -Dexec.mainClass=org.apache.camel.component.atomix.ha.AtomixRoutePolicyMain \
-    -Dexec.classpathScope=test \
-    test-compile \
-    exec:java
-
-mvn \
-    -Datomix.cluster="127.0.0.1:9002,127.0.0.1:9001,127.0.0.1:9003" \
     -Dexec.mainClass=org.apache.camel.component.atomix.ha.AtomixRoutePolicyMain \
     -Dexec.classpathScope=test \
     test-compile \
-    exec:java
-
-mvn \
-    -Datomix.cluster="127.0.0.1:9003,127.0.0.1:9001,127.0.0.1:9002" \
-    -Dexec.mainClass=org.apache.camel.component.atomix.ha.AtomixRoutePolicyMain \
-    -Dexec.classpathScope=test \
-    test-compile \
-    exec:java
\ No newline at end of file
+    exec:java \
+    -Datomix.cluster="127.0.0.1:9001,127.0.0.1:9002,127.0.0.1:9003" \
+    -Datomix.index="0"

http://git-wip-us.apache.org/repos/asf/camel/blob/a5d4df8f/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
index 5d1cbb1..6a61eb9 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterConfiguration.java
@@ -17,12 +17,13 @@ package org.apache.camel.component.atomix.cluster;
 
 import io.atomix.AtomixReplica;
 import io.atomix.copycat.server.storage.StorageLevel;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.component.atomix.AtomixConfiguration;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.spi.UriParams;
 
 @UriParams
-public class AtomixClusterConfiguration extends AtomixConfiguration {
+public class AtomixClusterConfiguration extends AtomixConfiguration implements Cloneable {
 
     @UriParam
     private String storagePath;
@@ -82,4 +83,16 @@ public class AtomixClusterConfiguration extends AtomixConfiguration {
     public void setReplica(AtomixReplica replica) {
         this.replica = replica;
     }
+
+    // ****************************************
+    // Copy
+    // ****************************************
+
+    public AtomixClusterConfiguration copy() {
+        try {
+            return (AtomixClusterConfiguration) super.clone();
+        } catch (CloneNotSupportedException e) {
+            throw new RuntimeCamelException(e);
+        }
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/a5d4df8f/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
new file mode 100644
index 0000000..4e03627
--- /dev/null
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/cluster/AtomixClusterHelper.java
@@ -0,0 +1,77 @@
+/**
+ * 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
+ */
+package org.apache.camel.component.atomix.cluster;
+
+import java.io.InputStream;
+import java.util.Properties;
+
+import io.atomix.AtomixReplica;
+import io.atomix.catalyst.transport.Address;
+import io.atomix.copycat.server.storage.Storage;
+import org.apache.camel.CamelContext;
+import org.apache.camel.util.CamelContextHelper;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.ResourceHelper;
+
+public final class AtomixClusterHelper {
+    private AtomixClusterHelper() {
+    }
+
+    public static AtomixReplica createReplica(CamelContext camelContext, String address, AtomixClusterConfiguration configuration) throws Exception {
+        return createReplica(camelContext, new Address(address), configuration);
+    }
+
+    public static AtomixReplica createReplica(CamelContext camelContext, Address address, AtomixClusterConfiguration configuration) throws Exception {
+        AtomixReplica atomix = configuration.getReplica();
+
+        if (atomix == null) {
+            if (configuration.getReplicaRef() != null) {
+                atomix = CamelContextHelper.mandatoryLookup(camelContext, configuration.getReplicaRef(), AtomixReplica.class);
+            } else {
+                final AtomixReplica.Builder atomixBuilder;
+
+                String uri = configuration.getConfigurationUri();
+                if (ObjectHelper.isNotEmpty(uri)) {
+                    uri = camelContext.resolvePropertyPlaceholders(uri);
+                    try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
+                        Properties properties = new Properties();
+                        properties.load(is);
+
+                        atomixBuilder = AtomixReplica.builder(address, properties);
+                    }
+                } else {
+                    atomixBuilder = AtomixReplica.builder(address);
+                }
+
+                Storage.Builder storageBuilder = Storage.builder();
+                ObjectHelper.ifNotEmpty(configuration.getStorageLevel(), storageBuilder::withStorageLevel);
+                ObjectHelper.ifNotEmpty(configuration.getStoragePath(), storageBuilder::withDirectory);
+
+                atomixBuilder.withStorage(storageBuilder.build());
+
+                if (configuration.getTransport() != null) {
+                    atomixBuilder.withTransport(
+                        camelContext.getInjector().newInstance(configuration.getTransport())
+                    );
+                }
+
+                atomix = atomixBuilder.build();
+            }
+        }
+
+        return atomix;
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/a5d4df8f/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
index 10d53bc..ac8dbc7 100644
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
+++ b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixCluster.java
@@ -16,13 +16,16 @@
  */
 package org.apache.camel.component.atomix.ha;
 
-import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
 
+import io.atomix.Atomix;
 import io.atomix.AtomixReplica;
 import io.atomix.catalyst.transport.Address;
+import io.atomix.catalyst.transport.Transport;
+import io.atomix.copycat.server.storage.StorageLevel;
 import org.apache.camel.CamelContext;
+import org.apache.camel.component.atomix.cluster.AtomixClusterConfiguration;
+import org.apache.camel.component.atomix.cluster.AtomixClusterHelper;
 import org.apache.camel.impl.ha.AbstractCamelCluster;
 import org.apache.camel.util.ObjectHelper;
 import org.slf4j.Logger;
@@ -31,30 +34,129 @@ import org.slf4j.LoggerFactory;
 public final class AtomixCluster extends AbstractCamelCluster<AtomixClusterView> {
     private static final Logger LOGGER = LoggerFactory.getLogger(AtomixCluster.class);
 
-    private final AtomixReplica atomix;
-    private final List<Address> addresses;
+    private CamelContext camelContext;
+    private Address address;
+    private AtomixClusterConfiguration configuration;
+    private AtomixReplica atomix;
 
-    public AtomixCluster(AtomixReplica atomix) {
-        this(null, atomix, Collections.emptyList());
+    public AtomixCluster() {
+        super("atomix");
+
+        this.configuration = new AtomixClusterConfiguration();
+    }
+
+    public AtomixCluster(CamelContext camelContext, Address address, AtomixClusterConfiguration configuration) {
+        super("atomix");
+
+        this.camelContext = camelContext;
+        this.address = address;
+        this.configuration = configuration.copy();
+    }
+
+    // **********************************
+    // Properties
+    // **********************************
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    public Address getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = new Address(address);
+    }
+
+    public void setAddress(Address address) {
+        this.address = address;
+    }
+
+    public AtomixClusterConfiguration getConfiguration() {
+        return configuration;
+    }
+
+    public void setConfiguration(AtomixClusterConfiguration configuration) {
+        this.configuration = configuration.copy();
+    }
+
+    public String getStoragePath() {
+        return configuration.getStoragePath();
+    }
+
+    public void setStoragePath(String storagePath) {
+        configuration.setStoragePath(storagePath);
+    }
+
+    public List<Address> getNodes() {
+        return configuration.getNodes();
     }
 
-    public AtomixCluster(AtomixReplica atomix, List<Address> addresses) {
-       this(null, atomix, addresses);
+    public StorageLevel getStorageLevel() {
+        return configuration.getStorageLevel();
     }
 
-    public AtomixCluster(CamelContext camelContext, AtomixReplica atomix, List<Address> addresses) {
-        super("camel-atomix", camelContext);
+    public void setNodes(List<Address> nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public void setStorageLevel(StorageLevel storageLevel) {
+        configuration.setStorageLevel(storageLevel);
+    }
+
+    public void setNodes(String nodes) {
+        configuration.setNodes(nodes);
+    }
+
+    public Class<? extends Transport> getTransport() {
+        return configuration.getTransport();
+    }
 
-        this.atomix = atomix;
-        this.addresses = new ArrayList<>(addresses);
+    public void setTransport(Class<? extends Transport> transport) {
+        configuration.setTransport(transport);
     }
 
+    public String getReplicaRef() {
+        return configuration.getReplicaRef();
+    }
+
+    public void setReplicaRef(String clusterref) {
+        configuration.setReplicaRef(clusterref);
+    }
+
+    public Atomix getReplica() {
+        return configuration.getReplica();
+    }
+
+    public void setReplica(AtomixReplica replica) {
+        configuration.setReplica(replica);
+    }
+
+    public String getConfigurationUri() {
+        return configuration.getConfigurationUri();
+    }
+
+    public void setConfigurationUri(String configurationUri) {
+        configuration.setConfigurationUri(configurationUri);
+    }
+
+    // *********************************************
+    // Lifecycle
+    // *********************************************
+
     @Override
     protected void doStart() throws Exception {
         // Assume that if addresses are provided the cluster needs be bootstrapped.
-        if (ObjectHelper.isNotEmpty(addresses)) {
-            LOGGER.debug("Bootstrap cluster for nodes: {}", addresses);
-            this.atomix.bootstrap(addresses).join();
+        if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
+            LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
+            getOrCreateAtomix().bootstrap(configuration.getNodes()).join();
             LOGGER.debug("Bootstrap cluster done");
         }
 
@@ -62,7 +164,28 @@ public final class AtomixCluster extends AbstractCamelCluster<AtomixClusterView>
     }
 
     @Override
-    protected AtomixClusterView doCreateView(String namespace) throws Exception {
-        return new AtomixClusterView(this, namespace, atomix);
+    protected AtomixClusterView createView(String namespace) throws Exception {
+        return new AtomixClusterView(this, namespace, getOrCreateAtomix());
+    }
+
+
+    private AtomixReplica getOrCreateAtomix() throws Exception {
+        if (atomix == null) {
+            // Validate parameters
+            ObjectHelper.notNull(camelContext, "Camel Context");
+            ObjectHelper.notNull(address, "Atomix Node Address");
+            ObjectHelper.notNull(configuration, "Atomix Node Configuration");
+
+            atomix = AtomixClusterHelper.createReplica(camelContext, address, configuration);
+
+            // Assume that if addresses are provided the cluster needs be bootstrapped.
+            if (ObjectHelper.isNotEmpty(configuration.getNodes())) {
+                LOGGER.debug("Bootstrap cluster on address {} for nodes: {}", address, configuration.getNodes());
+                this.atomix.bootstrap(configuration.getNodes()).join();
+                LOGGER.debug("Bootstrap cluster done");
+            }
+        }
+
+        return this.atomix;
     }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/a5d4df8f/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java b/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
deleted file mode 100644
index 61fc817..0000000
--- a/components/camel-atomix/src/main/java/org/apache/camel/component/atomix/ha/AtomixClusterService.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * 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.camel.component.atomix.ha;
-
-import java.io.InputStream;
-import java.util.List;
-import java.util.Properties;
-
-import io.atomix.Atomix;
-import io.atomix.AtomixReplica;
-import io.atomix.catalyst.transport.Address;
-import io.atomix.catalyst.transport.Transport;
-import io.atomix.copycat.server.storage.Storage;
-import io.atomix.copycat.server.storage.StorageLevel;
-import org.apache.camel.CamelContext;
-import org.apache.camel.CamelContextAware;
-import org.apache.camel.component.atomix.cluster.AtomixClusterConfiguration;
-import org.apache.camel.ha.CamelCluster;
-import org.apache.camel.ha.CamelClusterService;
-import org.apache.camel.ha.CamelClusterView;
-import org.apache.camel.support.ServiceSupport;
-import org.apache.camel.util.CamelContextHelper;
-import org.apache.camel.util.ObjectHelper;
-import org.apache.camel.util.ResourceHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AtomixClusterService extends ServiceSupport implements CamelContextAware, CamelClusterService {
-    private static final Logger LOGGER = LoggerFactory.getLogger(AtomixClusterService.class);
-
-    private final AtomixClusterConfiguration configuration;
-
-    private CamelContext camelContext;
-    private Address address;
-    private AtomixCluster cluster;
-
-    public AtomixClusterService() {
-        this.configuration = new AtomixClusterConfiguration();
-    }
-
-    // **********************************
-    // Properties
-    // **********************************
-
-    @Override
-    public CamelContext getCamelContext() {
-        return camelContext;
-    }
-
-    @Override
-    public void setCamelContext(CamelContext camelContext) {
-        this.camelContext = camelContext;
-    }
-
-    public Address getAddress() {
-        return address;
-    }
-
-    public void setAddress(String address) {
-        this.address = new Address(address);
-    }
-
-    public void setAddress(Address address) {
-        this.address = address;
-    }
-
-    public String getStoragePath() {
-        return configuration.getStoragePath();
-    }
-
-    public void setStoragePath(String storagePath) {
-        configuration.setStoragePath(storagePath);
-    }
-
-    public List<Address> getNodes() {
-        return configuration.getNodes();
-    }
-
-    public StorageLevel getStorageLevel() {
-        return configuration.getStorageLevel();
-    }
-
-    public void setNodes(List<Address> nodes) {
-        configuration.setNodes(nodes);
-    }
-
-    public void setStorageLevel(StorageLevel storageLevel) {
-        configuration.setStorageLevel(storageLevel);
-    }
-
-    public void setNodes(String nodes) {
-        configuration.setNodes(nodes);
-    }
-
-    public Class<? extends Transport> getTransport() {
-        return configuration.getTransport();
-    }
-
-    public void setTransport(Class<? extends Transport> transport) {
-        configuration.setTransport(transport);
-    }
-
-    public String getReplicaRef() {
-        return configuration.getReplicaRef();
-    }
-
-    /**
-     * Set the reference of an instance of {@link AtomixReplica}.
-     * @param clusterref
-     */
-    public void setReplicaRef(String clusterref) {
-        configuration.setReplicaRef(clusterref);
-    }
-
-    public Atomix getReplica() {
-        return configuration.getReplica();
-    }
-
-    /**
-     * Set an instance of {@link AtomixReplica}.
-     * @param replica
-     */
-    public void setReplica(AtomixReplica replica) {
-        configuration.setReplica(replica);
-    }
-
-    public String getConfigurationUri() {
-        return configuration.getConfigurationUri();
-    }
-
-    public void setConfigurationUri(String configurationUri) {
-        configuration.setConfigurationUri(configurationUri);
-    }
-
-    // **********************************
-    // Cluster
-    // **********************************
-
-    @Override
-    public synchronized CamelCluster getCluster() throws Exception  {
-        if (this.cluster == null) {
-            AtomixReplica atomix = configuration.getReplica();
-
-            if (atomix == null) {
-                if (configuration.getReplicaRef() != null) {
-                    atomix = CamelContextHelper.mandatoryLookup(camelContext, configuration.getReplicaRef(), AtomixReplica.class);
-                } else {
-                    ObjectHelper.notNull(this.address, "Atomix Address");
-
-                    final AtomixReplica.Builder atomixBuilder;
-
-                    String uri = configuration.getConfigurationUri();
-                    if (ObjectHelper.isNotEmpty(uri)) {
-                        uri = camelContext.resolvePropertyPlaceholders(uri);
-                        try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri)) {
-                            Properties properties = new Properties();
-                            properties.load(is);
-
-                            atomixBuilder = AtomixReplica.builder(this.address, properties);
-                        }
-                    } else {
-                        atomixBuilder = AtomixReplica.builder(this.address);
-                    }
-
-                    Storage.Builder storageBuilder = Storage.builder();
-                    ObjectHelper.ifNotEmpty(configuration.getStorageLevel(), storageBuilder::withStorageLevel);
-                    ObjectHelper.ifNotEmpty(configuration.getStoragePath(), storageBuilder::withDirectory);
-
-                    atomixBuilder.withStorage(storageBuilder.build());
-
-                    if (configuration.getTransport() != null) {
-                        atomixBuilder.withTransport(
-                            camelContext.getInjector().newInstance(configuration.getTransport())
-                        );
-                    }
-
-                    atomix = atomixBuilder.build();
-                }
-            }
-
-            this.cluster = new AtomixCluster(atomix, configuration.getNodes());
-            this.cluster.setCamelContext(camelContext);
-        }
-
-        return this.cluster;
-    }
-
-    @Override
-    public CamelClusterView createView(String namespace) throws Exception {
-        return getCluster().createView(namespace);
-    }
-
-    // **********************************
-    // Service
-    // **********************************
-
-    @Override
-    protected void doStart() throws Exception {
-        LOGGER.debug("Starting cluster on address {}", address);
-        getCluster().start();
-    }
-
-    @Override
-    protected void doStop() throws Exception {
-        if (this.cluster != null) {
-            this.cluster.stop();
-            this.cluster = null;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/a5d4df8f/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
----------------------------------------------------------------------
diff --git a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
index e622900..e0e253f 100644
--- a/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
+++ b/components/camel-atomix/src/test/java/org/apache/camel/component/atomix/ha/AtomixRoutePolicyMain.java
@@ -16,19 +16,14 @@
  */
 package org.apache.camel.component.atomix.ha;
 
-import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
 
 import io.atomix.catalyst.transport.Address;
 import io.atomix.copycat.server.storage.StorageLevel;
 import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.ha.CamelClusterService;
-import org.apache.camel.ha.CamelClusterView;
 import org.apache.camel.impl.DefaultCamelContext;
-import org.apache.camel.impl.ha.ClusteredRoutePolicy;
-import org.apache.camel.spi.RoutePolicy;
-import org.apache.camel.util.FileUtil;
+import org.apache.camel.impl.ha.ClusteredRoutePolicyFactory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -36,58 +31,42 @@ public final class AtomixRoutePolicyMain {
     private static final Logger LOGGER = LoggerFactory.getLogger(AtomixRoutePolicyMain.class);
 
     public static void main(final String[] args) throws Exception {
-        String[] addresses = System.getProperty("atomix.cluster").split(",");
+        final Integer index = Integer.getInteger("atomix.index");
+        final String[] addresses = System.getProperty("atomix.cluster").split(",");
 
-        List<Address> cluster = new ArrayList<>();
+        List<Address> nodes = new ArrayList<>();
         for (int i = 0; i < addresses.length; i++) {
             String[] parts = addresses[i].split(":");
-            cluster.add(new Address(parts[0], Integer.valueOf(parts[1])));
+            nodes.add(new Address(parts[0], Integer.valueOf(parts[1])));
         }
 
-        final String id = String.format("atomix-%d", cluster.get(0).port());
-        final File path = new File("target", id);
-
-        // Cleanup
-        FileUtil.removeDir(path);
-
-        AtomixClusterService service = new AtomixClusterService();
-        service.setStoragePath(path.getAbsolutePath());
-        service.setStorageLevel(StorageLevel.DISK);
-        service.setAddress(cluster.get(0));
-        service.setNodes(cluster);
+        AtomixCluster cluster = new AtomixCluster();
+        cluster.setStorageLevel(StorageLevel.MEMORY);
+        cluster.setAddress(nodes.get(index));
+        cluster.setNodes(nodes);
 
         DefaultCamelContext context = new DefaultCamelContext();
-        context.addService(service);
+        context.addService(cluster);
+        context.addRoutePolicyFactory(ClusteredRoutePolicyFactory.forNamespace("my-ns"));
         context.addRoutes(new RouteBuilder() {
             @Override
             public void configure() throws Exception {
-                CamelClusterService cluster = getContext().hasService(AtomixClusterService.class);
-                CamelClusterView view = cluster.createView("my-view");
-                RoutePolicy policy = ClusteredRoutePolicy.forView(view);
-
-                fromF("timer:%s-1?period=2s", id)
-                    .routeId(id + "-1")
-                    .routePolicy(policy)
+                fromF("timer:atomix-%d-1?period=2s", nodes.get(index).port())
                     .log("${routeId} (1)");
-                fromF("timer:%s-2?period=5s", id)
-                    .routeId(id + "-2")
-                    .routePolicy(policy)
+                fromF("timer:atomix-%d-2?period=5s", nodes.get(index).port())
                     .log("${routeId} (2)");
             }
         });
 
         context.start();
 
-        Runtime.getRuntime().addShutdownHook(new Thread() {
-            @Override
-            public void run() {
-                try {
-                    context.stop();
-                } catch (Exception e) {
-                    LOGGER.warn("", e);
-                }
+        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+            try {
+                context.stop();
+            } catch (Exception e) {
+                LOGGER.warn("", e);
             }
-        });
+        }));
 
         for (int i = 0; i < Integer.MAX_VALUE; i++) {
             Thread.sleep(1000);