/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2011, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.as.ejb3.remote;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jboss.as.clustering.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.network.ClientMapping;
import org.jboss.as.remoting.RemotingConnectorBindingInfoService;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.as.server.ServerEnvironmentService;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.ValueService;
import org.jboss.msc.value.InjectedValue;
import org.jboss.msc.value.Value;
import org.wildfly.clustering.ejb.BeanManagerFactoryBuilderConfiguration;
import org.wildfly.clustering.service.Builder;
import org.wildfly.clustering.spi.ClusteringCacheRequirement;

/**
 * @author Jaikiran Pai
 */
public class EJBRemotingConnectorClientMappingsEntryProviderService implements CapabilityServiceBuilder<Map.Entry<String, List<ClientMapping>>>, Value<Map.Entry<String, List<ClientMapping>>> {

    private final InjectedValue<ServerEnvironment> serverEnvironment = new InjectedValue<>();
    private final InjectedValue<RemotingConnectorBindingInfoService.RemotingConnectorInfo> remotingConnectorInfo = new InjectedValue<>();
    private final ServiceName remotingServerInfoServiceName;

    private volatile String clientMappingsClusterName;
    private volatile ServiceName name;

    public EJBRemotingConnectorClientMappingsEntryProviderService(String clientMappingsClusterName, ServiceName remotingServerInfoServiceName) {
        this.clientMappingsClusterName = clientMappingsClusterName;
        this.remotingServerInfoServiceName = remotingServerInfoServiceName;
    }

    @Override
    public ServiceName getServiceName() {
        return this.name;
    }

    @Override
    public Builder<Map.Entry<String, List<ClientMapping>>> configure(OperationContext context) {
        this.name = ClusteringCacheRequirement.REGISTRY_ENTRY.getServiceName(context, this.clientMappingsClusterName, BeanManagerFactoryBuilderConfiguration.CLIENT_MAPPINGS_CACHE_NAME);
        return this;
    }

    @Override
    public ServiceBuilder<Map.Entry<String, List<ClientMapping>>> build(ServiceTarget target) {
        return target.addService(this.name, new ValueService<>(this))
                .addDependency(ServerEnvironmentService.SERVICE_NAME, ServerEnvironment.class, this.serverEnvironment)
                .addDependency(this.remotingServerInfoServiceName, RemotingConnectorBindingInfoService.RemotingConnectorInfo.class, this.remotingConnectorInfo)
        ;
    }

    @Override
    public Map.Entry<String, List<ClientMapping>> getValue() {
        return new AbstractMap.SimpleImmutableEntry<>(this.serverEnvironment.getValue().getNodeName(), this.getClientMappings());
    }

    List<ClientMapping> getClientMappings() {
        final List<ClientMapping> ret = new ArrayList<>();
        RemotingConnectorBindingInfoService.RemotingConnectorInfo info = this.remotingConnectorInfo.getValue();
        if (info.getSocketBinding().getClientMappings() != null && !info.getSocketBinding().getClientMappings().isEmpty()) {
            ret.addAll(info.getSocketBinding().getClientMappings());
        } else {
            // TODO: We use the textual form of IP address as the destination address for now.
            // This needs to be configurable (i.e. send either host name or the IP address). But
            // since this is a corner case (i.e. absence of any client-mappings for a socket binding),
            // this should be OK for now
            final String destinationAddress = info.getSocketBinding().getAddress().getHostAddress();
            final InetAddress clientNetworkAddress;
            try {
                clientNetworkAddress = InetAddress.getByName("::");
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
            final ClientMapping defaultClientMapping = new ClientMapping(clientNetworkAddress, 0, destinationAddress, info.getSocketBinding().getAbsolutePort());
            ret.add(defaultClientMapping);
        }
        return ret;
    }
}

@@ -1453,107 +1453,8 @@
 ce;%0A
-import org.jboss.as.server.ServerEnvironment;%0Aimport org.jboss.as.server.ServerEnvironmentService;%0A
 impo
@@ -1769,24 +1769,67 @@
 figuration;%0A
+import org.wildfly.clustering.group.Group;%0A
 import org.w
@@ -1855,32 +1855,150 @@
 ervice.Builder;%0A
+import org.wildfly.clustering.service.InjectedValueDependency;%0Aimport org.wildfly.clustering.service.ValueDependency;%0A
 import org.wildf
@@ -2042,16 +2042,73 @@
 irement;
+%0Aimport org.wildfly.clustering.spi.ClusteringRequirement;
 %0A%0A/**%0A *
@@ -2331,102 +2331,8 @@
  %7B%0A%0A
-    private final InjectedValue%3CServerEnvironment%3E serverEnvironment = new InjectedValue%3C%3E();%0A
     
@@ -2523,24 +2523,75 @@
 rviceName;%0A%0A
+    private volatile ValueDependency%3CGroup%3E group;%0A
     private 
@@ -3367,325 +3367,414 @@
     
-return this;%0A    %7D%0A%0A    @Override%0A    public ServiceBuilder%3CMap.Entry%3CString, List%3CClientMapping%3E%3E%3E build(ServiceTarget target) %7B%0A        return target.addService(this.name, new ValueService%3C%3E(this))%0A                .addDependency(ServerEnvironmentService.SERVICE_NAME, ServerEnvironment.class, this.serverEnvironment
+this.group = new InjectedValueDependency%3C%3E(ClusteringRequirement.GROUP.getServiceName(context, this.clientMappingsClusterName), Group.class);%0A        return this;%0A    %7D%0A%0A    @Override%0A    public ServiceBuilder%3CMap.Entry%3CString, List%3CClientMapping%3E%3E%3E build(ServiceTarget target) %7B%0A        ServiceBuilder%3CMap.Entry%3CString, List%3CClientMapping%3E%3E%3E builder = target.addService(this.name, new ValueService%3C%3E(this)
 )%0A  
@@ -3939,16 +3939,69 @@
         
+        ;%0A        return this.group.register(builder)
 ;%0A    %7D%0A
@@ -4141,44 +4141,43 @@
 his.
-serverEnvironment.getValue().getNode
+group.getValue().getLocalNode().get
 Name

Determine node name from Group, not ServerEnvironment.