001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.hazelcast.instance;
018
019 import com.hazelcast.core.Hazelcast;
020 import com.hazelcast.core.MembershipEvent;
021 import com.hazelcast.core.MembershipListener;
022
023 import org.apache.camel.Exchange;
024 import org.apache.camel.Processor;
025 import org.apache.camel.component.hazelcast.HazelcastComponentHelper;
026 import org.apache.camel.component.hazelcast.HazelcastConstants;
027 import org.apache.camel.impl.DefaultConsumer;
028 import org.apache.camel.impl.DefaultEndpoint;
029
030 public class HazelcastInstanceConsumer extends DefaultConsumer {
031
032 public HazelcastInstanceConsumer(DefaultEndpoint endpoint, Processor processor) {
033 super(endpoint, processor);
034
035 Hazelcast.getCluster().addMembershipListener(new HazelcastMembershipListener());
036 }
037
038 class HazelcastMembershipListener implements MembershipListener {
039
040 public void memberAdded(MembershipEvent event) {
041 this.sendExchange(event, HazelcastConstants.ADDED);
042 }
043
044 public void memberRemoved(MembershipEvent event) {
045 this.sendExchange(event, HazelcastConstants.REMOVED);
046 }
047
048 private void sendExchange(MembershipEvent event, String action) {
049 Exchange exchange = getEndpoint().createExchange();
050
051 HazelcastComponentHelper.setListenerHeaders(exchange, HazelcastConstants.INSTANCE_LISTENER, action);
052
053 // instance listener header values
054 exchange.getOut().setHeader(HazelcastConstants.INSTANCE_HOST, event.getMember().getInetSocketAddress().getHostName());
055 exchange.getOut().setHeader(HazelcastConstants.INSTANCE_PORT, event.getMember().getInetSocketAddress().getPort());
056
057 try {
058 getProcessor().process(exchange);
059 } catch (Exception e) {
060 if (exchange.getException() != null) {
061 getExceptionHandler().handleException("Error processing exchange for hazelcast consumer on your Hazelcast cluster.", exchange, exchange.getException());
062 }
063 }
064 }
065
066 }
067
068 }