Example usage for java.net InetSocketAddress isUnresolved

List of usage examples for java.net InetSocketAddress isUnresolved

Introduction

In this page you can find the example usage for java.net InetSocketAddress isUnresolved.

Prototype

public final boolean isUnresolved() 

Source Link

Document

Checks whether the address has been resolved or not.

Usage

From source file:edu.tsinghua.lumaqq.qq.net.Socks5Proxy.java

@Override
public void setRemoteAddress(InetSocketAddress serverAddress) {
    super.setRemoteAddress(serverAddress);
    // ???//w  ww  . ja  v  a 2s. co  m
    if (serverAddress.isUnresolved()) {
        /* ??? */
        isIp = false;
        byte[] b = serverAddress.getHostName().getBytes();
        remoteAddress = new byte[b.length + 1];
        remoteAddress[0] = (byte) (b.length & 0xFF);
        System.arraycopy(b, 0, remoteAddress, 1, b.length);
    } else {
        /* ???IPSocks5??????ipip */
        isIp = true;
        remoteAddress = serverAddress.getAddress().getAddress();
    }
    remotePort = serverAddress.getPort();
}

From source file:org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java

private ListenerEndpoint startEndpoint(InetSocketAddress inetSocketAddress,
        ListeningIOReactor defaultListeningIOReactor, String endPointName) throws Exception {
    ListenerEndpoint endpoint = defaultListeningIOReactor.listen(inetSocketAddress);
    try {/*from w  w  w .  j  ava  2  s. com*/
        endpoint.waitFor();
        InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
        if (!address.isUnresolved()) {
            log.info((endPointName != null ? "Pass-through " + endPointName : " Pass-through Http ")
                    + " Listener started on " + address.getHostName() + ":" + address.getPort());
        } else {
            log.info((endPointName != null ? "Pass-through " + endPointName : " Pass-through Http ")
                    + " Listener started on " + address);
        }
    } catch (Exception e) {
        throw new Exception("Endpoint does not start for port " + inetSocketAddress.getPort()
                + "May be IO Reactor not started or endpoint binding exception ", e);

    }
    return endpoint;
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java

/**
 * Start specific end points given by InetSockeAddress list
 *
 * @param endpointsClosed InetSocketAddresses of endpoints to be started
 * @throws AxisFault//from  w  w w. j a va2 s  .  c  o  m
 */
private void startSpecificEndpoints(List<InetSocketAddress> endpointsClosed) throws AxisFault {
    Queue<ListenerEndpoint> endpoints = new LinkedList<ListenerEndpoint>();

    // Ensure simple but stable order
    List<InetSocketAddress> addressList = endpointsClosed;
    Collections.sort(addressList, new Comparator<InetSocketAddress>() {

        public int compare(InetSocketAddress a1, InetSocketAddress a2) {
            String s1 = a1.toString();
            String s2 = a2.toString();
            return s1.compareTo(s2);
        }

    });

    for (InetSocketAddress address : addressList) {
        endpoints.add(ioReactor.listen(address));
    }

    // Wait for the endpoint to become ready, i.e. for the listener to start accepting
    // requests.
    while (!endpoints.isEmpty()) {
        ListenerEndpoint endpoint = endpoints.remove();
        try {
            endpoint.waitFor();
            if (log.isInfoEnabled()) {
                InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
                if (!address.isUnresolved()) {
                    log.info(name + " started on " + address.getHostName() + ":" + address.getPort());
                } else {
                    log.info(name + " started on " + address);
                }
            }
        } catch (InterruptedException e) {
            log.warn("Listener startup was interrupted");
            break;
        }
    }
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java

private void startEndpoints() throws AxisFault {
    Queue<ListenerEndpoint> endpoints = new LinkedList<ListenerEndpoint>();

    Set<InetSocketAddress> addressSet = new HashSet<InetSocketAddress>();
    addressSet.addAll(connFactory.getBindAddresses());
    if (NHttpConfiguration.getInstance().getMaxActiveConnections() != -1) {
        addMaxConnectionCountController(NHttpConfiguration.getInstance().getMaxActiveConnections());
    }//w w w. j av a2 s .c o m
    if (listenerContext.getBindAddress() != null) {
        addressSet.add(new InetSocketAddress(listenerContext.getBindAddress(), listenerContext.getPort()));
    }
    if (addressSet.isEmpty()) {
        addressSet.add(new InetSocketAddress(listenerContext.getPort()));
    }

    // Ensure simple but stable order
    List<InetSocketAddress> addressList = new ArrayList<InetSocketAddress>(addressSet);
    Collections.sort(addressList, new Comparator<InetSocketAddress>() {

        public int compare(InetSocketAddress a1, InetSocketAddress a2) {
            String s1 = a1.toString();
            String s2 = a2.toString();
            return s1.compareTo(s2);
        }

    });
    for (InetSocketAddress address : addressList) {
        endpoints.add(ioReactor.listen(address));
    }

    // Wait for the endpoint to become ready, i.e. for the listener to start accepting
    // requests.
    while (!endpoints.isEmpty()) {
        ListenerEndpoint endpoint = endpoints.remove();
        try {
            endpoint.waitFor();
            if (log.isInfoEnabled()) {
                InetSocketAddress address = (InetSocketAddress) endpoint.getAddress();
                if (!address.isUnresolved()) {
                    log.info(name + " started on " + address.getHostName() + ":" + address.getPort());
                } else {
                    log.info(name + " started on " + address);
                }
            }
        } catch (InterruptedException e) {
            log.warn("Listener startup was interrupted");
            break;
        }
    }
}

From source file:io.bitsquare.btc.WalletService.java

public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler,
        ExceptionHandler exceptionHandler) {
    Log.traceCall();/*from   www.  j a  v  a  2  s  .  co m*/
    // Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.

    Threading.USER_THREAD = UserThread.getExecutor();

    Timer timeoutTimer = UserThread.runAfter(
            () -> exceptionHandler.handleException(
                    new TimeoutException("Wallet did not initialize in " + STARTUP_TIMEOUT_SEC + " seconds.")),
            STARTUP_TIMEOUT_SEC);

    backupWallet();

    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy()
            : null;
    log.debug("Use socks5Proxy for bitcoinj: " + socks5Proxy);

    // If seed is non-null it means we are restoring from backup.
    walletAppKit = new WalletAppKitBitSquare(params, socks5Proxy, walletDir, "Bitsquare") {
        @Override
        protected void onSetupCompleted() {
            // Don't make the user wait for confirmations for now, as the intention is they're sending it
            // their own money!
            walletAppKit.wallet().allowSpendingUnconfirmedTransactions();
            final PeerGroup peerGroup = walletAppKit.peerGroup();

            if (params != RegTestParams.get())
                peerGroup.setMaxConnections(11);

            // We don't want to get our node white list polluted with nodes from AddressMessage calls.
            if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
                peerGroup.setAddPeersFromAddressMessage(false);

            wallet = walletAppKit.wallet();
            wallet.addEventListener(walletEventListener);

            addressEntryList.onWalletReady(wallet);

            peerGroup.addEventListener(new PeerEventListener() {
                @Override
                public void onPeersDiscovered(Set<PeerAddress> peerAddresses) {
                }

                @Override
                public void onBlocksDownloaded(Peer peer, Block block, FilteredBlock filteredBlock,
                        int blocksLeft) {
                }

                @Override
                public void onChainDownloadStarted(Peer peer, int blocksLeft) {
                }

                @Override
                public void onPeerConnected(Peer peer, int peerCount) {
                    numPeers.set(peerCount);
                    connectedPeers.set(peerGroup.getConnectedPeers());
                }

                @Override
                public void onPeerDisconnected(Peer peer, int peerCount) {
                    numPeers.set(peerCount);
                    connectedPeers.set(peerGroup.getConnectedPeers());
                }

                @Override
                public Message onPreMessageReceived(Peer peer, Message m) {
                    return null;
                }

                @Override
                public void onTransaction(Peer peer, Transaction t) {
                }

                @Nullable
                @Override
                public List<Message> getData(Peer peer, GetDataMessage m) {
                    return null;
                }
            });

            // set after wallet is ready
            tradeWalletService.setWalletAppKit(walletAppKit);
            tradeWalletService.setAddressEntryList(addressEntryList);
            timeoutTimer.stop();

            // onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
            UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
        }
    };

    // Bloom filters in BitcoinJ are completely broken
    // See: https://jonasnick.github.io/blog/2015/02/12/privacy-in-bitcoinj/
    // Here are a few improvements to fix a few vulnerabilities.

    // Bitsquare's BitcoinJ fork has added a bloomFilterTweak (nonce) setter to reuse the same seed avoiding the trivial vulnerability
    // by getting the real pub keys by intersections of several filters sent at each startup.
    walletAppKit.setBloomFilterTweak(bloomFilterTweak);

    // Avoid the simple attack (see: https://jonasnick.github.io/blog/2015/02/12/privacy-in-bitcoinj/) due to the 
    // default implementation using both pubkey and hash of pubkey. We have set a insertPubKey flag in BasicKeyChain to default false.

    // Default only 266 keys are generated (2 * 100+33). That would trigger new bloom filters when we are reaching 
    // the threshold. To avoid reaching the threshold we create much more keys which are unlikely to cause update of the
    // filter for most users. With lookaheadSize of 500 we get 1333 keys which should be enough for most users to 
    // never need to update a bloom filter, which would weaken privacy.
    walletAppKit.setLookaheadSize(500);

    // Calculation is derived from: https://www.reddit.com/r/Bitcoin/comments/2vrx6n/privacy_in_bitcoinj_android_wallet_multibit_hive/coknjuz
    // No. of false positives (56M keys in the blockchain): 
    // First attempt for FP rate:
    // FP rate = 0,0001;  No. of false positives: 0,0001 * 56 000 000  = 5600
    // We have 1333keys: 1333 / (5600 + 1333) = 0.19 -> 19 % probability that a pub key is in our wallet
    // After tests I found out that the bandwidth consumption varies widely related to the generated filter.
    // About 20- 40 MB for upload and 30-130 MB for download at first start up (spv chain).
    // Afterwards its about 1 MB for upload and 20-80 MB for download.
    // Probably better then a high FP rate would be to include foreign pubKeyHashes which are tested to not be used 
    // in many transactions. If we had a pool of 100 000 such keys (2 MB data dump) to random select 4000 we could mix it with our
    // 1000 own keys and get a similar probability rate as with the current setup but less variation in bandwidth 
    // consumption.

    // For now to reduce risks with high bandwidth consumption we reduce the FP rate by half.
    // FP rate = 0,00005;  No. of false positives: 0,00005 * 56 000 000  = 2800
    // 1333 / (2800 + 1333) = 0.32 -> 32 % probability that a pub key is in our wallet
    walletAppKit.setBloomFilterFalsePositiveRate(0.00005);

    String btcNodes = preferences.getBitcoinNodes();
    log.debug("btcNodes: " + btcNodes);
    boolean usePeerNodes = false;

    // Pass custom seed nodes if set in options
    if (!btcNodes.isEmpty()) {
        String[] nodes = StringUtils.deleteWhitespace(btcNodes).split(",");
        List<PeerAddress> peerAddressList = new ArrayList<>();
        for (String node : nodes) {
            String[] parts = node.split(":");
            if (parts.length == 1) {
                // port not specified.  Use default port for network.
                parts = new String[] { parts[0], Integer.toString(params.getPort()) };
            }
            if (parts.length == 2) {
                // note: this will cause a DNS request if hostname used.
                // note: DNS requests are routed over socks5 proxy, if used.
                // note: .onion hostnames will be unresolved.
                InetSocketAddress addr;
                if (socks5Proxy != null) {
                    try {
                        // proxy remote DNS request happens here.  blocking.
                        addr = new InetSocketAddress(DnsLookupTor.lookup(socks5Proxy, parts[0]),
                                Integer.parseInt(parts[1]));
                    } catch (Exception e) {
                        log.warn("Dns lookup failed for host: {}", parts[0]);
                        addr = null;
                    }
                } else {
                    // DNS request happens here. if it fails, addr.isUnresolved() == true.
                    addr = new InetSocketAddress(parts[0], Integer.parseInt(parts[1]));
                }
                if (addr != null && !addr.isUnresolved()) {
                    peerAddressList.add(new PeerAddress(addr.getAddress(), addr.getPort()));
                }
            }
        }
        if (peerAddressList.size() > 0) {
            PeerAddress peerAddressListFixed[] = new PeerAddress[peerAddressList.size()];
            log.debug("btcNodes parsed: " + Arrays.toString(peerAddressListFixed));

            walletAppKit.setPeerNodes(peerAddressList.toArray(peerAddressListFixed));
            usePeerNodes = true;
        }
    }

    // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
    // or progress widget to keep the user engaged whilst we initialise, but we don't.
    if (params == RegTestParams.get()) {
        if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            try {
                walletAppKit.setPeerNodes(
                        new PeerAddress(InetAddress.getByName(RegTestHost.SERVER_IP), params.getPort()));
                usePeerNodes = true;
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }
        } else if (regTestHost == RegTestHost.LOCALHOST) {
            walletAppKit.connectToLocalHost(); // You should run a regtest mode bitcoind locally.}
        }
    } else if (params == MainNetParams.get()) {
        // Checkpoints are block headers that ship inside our app: for a new user, we pick the last header
        // in the checkpoints file and then download the rest from the network. It makes things much faster.
        // Checkpoint files are made using the BuildCheckpoints tool and usually we have to download the
        // last months worth or more (takes a few seconds).
        try {
            walletAppKit.setCheckpoints(getClass().getResourceAsStream("/wallet/checkpoints"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    } else if (params == TestNet3Params.get()) {
        walletAppKit.setCheckpoints(getClass().getResourceAsStream("/wallet/checkpoints.testnet"));
    }

    // If operating over a proxy and we haven't set any peer nodes, then
    // we want to use SeedPeers for discovery instead of the default DnsDiscovery.
    // This is only because we do not yet have a Dns discovery class that works
    // reliably over proxy/tor.
    //
    // todo: There should be a user pref called "Use Local DNS for Proxy/Tor"
    // that disables this.  In that case, the default DnsDiscovery class will
    // be used which should work, but is less private.  The aim here is to
    // be private by default when using proxy/tor.  However, the seedpeers
    // could become outdated, so it is important that the user be able to
    // disable it, but should be made aware of the reduced privacy.
    if (socks5Proxy != null && !usePeerNodes) {
        // SeedPeers uses hard coded stable addresses (from MainNetParams). It should be updated from time to time.
        walletAppKit.setDiscovery(new Socks5MultiDiscovery(socks5Proxy, params, socks5DiscoverMode));
    }

    walletAppKit.setDownloadListener(downloadListener).setBlockingStartup(false)
            .setUserAgent(userAgent.getName(), userAgent.getVersion()).restoreWalletFromSeed(seed);

    walletAppKit.addListener(new Service.Listener() {
        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletAppKit = null;
            log.error("walletAppKit failed");
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);
    walletAppKit.startAsync();
}

From source file:com.datatorrent.stram.StreamingContainerManager.java

private BufferServerController getBufferServerClient(PTOperator operator) {
    BufferServerController bsc = new BufferServerController(operator.getLogicalId());
    bsc.setToken(operator.getContainer().getBufferServerToken());
    InetSocketAddress address = operator.getContainer().bufferServerAddress;
    StreamingContainer.eventloop.connect(
            address.isUnresolved() ? new InetSocketAddress(address.getHostName(), address.getPort()) : address,
            bsc);/*ww  w .j  av a2 s .  c  om*/
    return bsc;
}

From source file:org.apache.atlas.ha.AtlasServerIdSelector.java

/**
 * Return the ID corresponding to this Atlas instance.
 *
 * The match is done by looking for an ID configured in {@link HAConfiguration#ATLAS_SERVER_IDS} key
 * that has a host:port entry for the key {@link HAConfiguration#ATLAS_SERVER_ADDRESS_PREFIX}+ID where
 * the host is a local IP address and port is set in the system property
 * {@link AtlasConstants#SYSTEM_PROPERTY_APP_PORT}.
 *
 * @param configuration/*from   w w w.  j a  v a  2s  .  co  m*/
 * @return
 * @throws AtlasException if no ID is found that maps to a local IP Address or port
 */
public static String selectServerId(Configuration configuration) throws AtlasException {
    // ids are already trimmed by this method
    String[] ids = configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS);
    String matchingServerId = null;
    int appPort = Integer.parseInt(System.getProperty(AtlasConstants.SYSTEM_PROPERTY_APP_PORT));
    for (String id : ids) {
        String hostPort = configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX + id);
        if (!StringUtils.isEmpty(hostPort)) {
            InetSocketAddress socketAddress;
            try {
                socketAddress = NetUtils.createSocketAddr(hostPort);
            } catch (Exception e) {
                LOG.warn("Exception while trying to get socket address for {}", hostPort, e);
                continue;
            }
            if (!socketAddress.isUnresolved() && NetUtils.isLocalAddress(socketAddress.getAddress())
                    && appPort == socketAddress.getPort()) {
                LOG.info("Found matched server id {} with host port: {}", id, hostPort);
                matchingServerId = id;
                break;
            }
        } else {
            LOG.info("Could not find matching address entry for id: {}", id);
        }
    }
    if (matchingServerId == null) {
        String msg = String.format(
                "Could not find server id for this instance. "
                        + "Unable to find IDs matching any local host and port binding among %s",
                StringUtils.join(ids, ","));
        throw new AtlasException(msg);
    }
    return matchingServerId;
}

From source file:org.apache.hadoop.hbase.mapreduce.TableInputFormatBase.java

/**
 * Calculates the splits that will serve as input for the map tasks. The
 * number of splits matches the number of regions in a table.
 *
 * @param context  The current job context.
 * @return The list of input splits.//from  ww w.j a  v a  2 s  .  c o  m
 * @throws IOException When creating the list of splits fails.
 * @see org.apache.hadoop.mapreduce.InputFormat#getSplits(
 *   org.apache.hadoop.mapreduce.JobContext)
 */
@Override
public List<InputSplit> getSplits(JobContext context) throws IOException {
    if (table == null) {
        throw new IOException("No table was provided.");
    }
    // Get the name server address and the default value is null.
    this.nameServer = context.getConfiguration().get("hbase.nameserver.address", null);

    RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(table);

    Pair<byte[][], byte[][]> keys = table.getStartEndKeys();
    if (keys == null || keys.getFirst() == null || keys.getFirst().length == 0) {
        HRegionLocation regLoc = table.getRegionLocation(HConstants.EMPTY_BYTE_ARRAY, false);
        if (null == regLoc) {
            throw new IOException("Expecting at least one region.");
        }
        List<InputSplit> splits = new ArrayList<InputSplit>(1);
        long regionSize = sizeCalculator.getRegionSize(regLoc.getRegionInfo().getRegionName());
        TableSplit split = new TableSplit(table.getName(), HConstants.EMPTY_BYTE_ARRAY,
                HConstants.EMPTY_BYTE_ARRAY,
                regLoc.getHostnamePort().split(Addressing.HOSTNAME_PORT_SEPARATOR)[0], regionSize);
        splits.add(split);
        return splits;
    }
    List<InputSplit> splits = new ArrayList<InputSplit>(keys.getFirst().length);
    for (int i = 0; i < keys.getFirst().length; i++) {
        if (!includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
            continue;
        }
        HRegionLocation location = table.getRegionLocation(keys.getFirst()[i], false);
        // The below InetSocketAddress creation does a name resolution.
        InetSocketAddress isa = new InetSocketAddress(location.getHostname(), location.getPort());
        if (isa.isUnresolved()) {
            LOG.warn("Failed resolve " + isa);
        }
        InetAddress regionAddress = isa.getAddress();
        String regionLocation;
        try {
            regionLocation = reverseDNS(regionAddress);
        } catch (NamingException e) {
            LOG.warn("Cannot resolve the host name for " + regionAddress + " because of " + e);
            regionLocation = location.getHostname();
        }

        byte[] startRow = scan.getStartRow();
        byte[] stopRow = scan.getStopRow();
        // determine if the given start an stop key fall into the region
        if ((startRow.length == 0 || keys.getSecond()[i].length == 0
                || Bytes.compareTo(startRow, keys.getSecond()[i]) < 0)
                && (stopRow.length == 0 || Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) {
            byte[] splitStart = startRow.length == 0 || Bytes.compareTo(keys.getFirst()[i], startRow) >= 0
                    ? keys.getFirst()[i]
                    : startRow;
            byte[] splitStop = (stopRow.length == 0 || Bytes.compareTo(keys.getSecond()[i], stopRow) <= 0)
                    && keys.getSecond()[i].length > 0 ? keys.getSecond()[i] : stopRow;

            byte[] regionName = location.getRegionInfo().getRegionName();
            long regionSize = sizeCalculator.getRegionSize(regionName);
            TableSplit split = new TableSplit(table.getName(), splitStart, splitStop, regionLocation,
                    regionSize);
            splits.add(split);
            if (LOG.isDebugEnabled()) {
                LOG.debug("getSplits: split -> " + i + " -> " + split);
            }
        }
    }
    return splits;
}

From source file:org.apache.hadoop.hdfs.DFSUtil.java

/**
 * Returns nameservice Id and namenode Id when the local host matches the
 * configuration parameter {@code addressKey}.<nameservice Id>.<namenode Id>
 * /*from   w  w  w.  j av a 2 s  .  c om*/
 * @param conf Configuration
 * @param addressKey configuration key corresponding to the address.
 * @param knownNsId only look at configs for the given nameservice, if not-null
 * @param knownNNId only look at configs for the given namenode, if not null
 * @param matcher matching criteria for matching the address
 * @return Array with nameservice Id and namenode Id on success. First element
 *         in the array is nameservice Id and second element is namenode Id.
 *         Null value indicates that the configuration does not have the the
 *         Id.
 * @throws HadoopIllegalArgumentException on error
 */
static String[] getSuffixIDs(final Configuration conf, final String addressKey, String knownNsId,
        String knownNNId, final AddressMatcher matcher) {
    String nameserviceId = null;
    String namenodeId = null;
    int found = 0;

    Collection<String> nsIds = getNameServiceIds(conf);
    for (String nsId : emptyAsSingletonNull(nsIds)) {
        if (knownNsId != null && !knownNsId.equals(nsId)) {
            continue;
        }

        Collection<String> nnIds = getNameNodeIds(conf, nsId);
        for (String nnId : emptyAsSingletonNull(nnIds)) {
            if (LOG.isTraceEnabled()) {
                LOG.trace(String.format("addressKey: %s nsId: %s nnId: %s", addressKey, nsId, nnId));
            }
            if (knownNNId != null && !knownNNId.equals(nnId)) {
                continue;
            }
            String key = addKeySuffixes(addressKey, nsId, nnId);
            String addr = conf.get(key);
            if (addr == null) {
                continue;
            }
            InetSocketAddress s = null;
            try {
                s = NetUtils.createSocketAddr(addr);
            } catch (Exception e) {
                LOG.warn("Exception in creating socket address " + addr, e);
                continue;
            }
            if (!s.isUnresolved() && matcher.match(s)) {
                nameserviceId = nsId;
                namenodeId = nnId;
                found++;
            }
        }
    }
    if (found > 1) { // Only one address must match the local address
        String msg = "Configuration has multiple addresses that match "
                + "local node's address. Please configure the system with " + DFS_NAMESERVICE_ID;
        throw new HadoopIllegalArgumentException(msg);
    }
    return new String[] { nameserviceId, namenodeId };
}

From source file:org.apache.hadoop.hdfs.DFSUtilClient.java

static Map<String, InetSocketAddress> getAddressesForNameserviceId(Configuration conf, String nsId,
        String defaultValue, String... keys) {
    Collection<String> nnIds = getNameNodeIds(conf, nsId);
    Map<String, InetSocketAddress> ret = Maps.newHashMap();
    for (String nnId : emptyAsSingletonNull(nnIds)) {
        String suffix = concatSuffixes(nsId, nnId);
        String address = getConfValue(defaultValue, suffix, conf, keys);
        if (address != null) {
            InetSocketAddress isa = NetUtils.createSocketAddr(address);
            if (isa.isUnresolved()) {
                LOG.warn(/*from  www .j  a v  a 2s. c  om*/
                        "Namenode for {} remains unresolved for ID {}. Check your "
                                + "hdfs-site.xml file to ensure namenodes are configured " + "properly.",
                        nsId, nnId);
            }
            ret.put(nnId, isa);
        }
    }
    return ret;
}