Example usage for java.net InetSocketAddress getAddress

List of usage examples for java.net InetSocketAddress getAddress

Introduction

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

Prototype

public final InetAddress getAddress() 

Source Link

Document

Gets the InetAddress .

Usage

From source file:org.apache.hadoop.yarn.conf.HAUtil.java

/**
 * @param conf Configuration. Please use verifyAndSetRMHAId to check.
 * @return RM Id on success/*from  w w w.  j  a va2s .  co  m*/
 */
public static String getRMHAId(Configuration conf) {
    int found = 0;
    String currentRMId = conf.getTrimmed(YarnConfiguration.RM_HA_ID);
    if (currentRMId == null) {
        for (String rmId : getRMHAIds(conf)) {
            String key = addSuffix(YarnConfiguration.RM_ADDRESS, rmId);
            String addr = conf.get(key);
            if (addr == null) {
                continue;
            }
            InetSocketAddress s;
            try {
                s = NetUtils.createSocketAddr(addr);
            } catch (Exception e) {
                LOG.warn("Exception in creating socket address " + addr, e);
                continue;
            }
            if (!s.isUnresolved() && NetUtils.isLocalAddress(s.getAddress())) {
                currentRMId = rmId.trim();
                found++;
            }
        }
    }
    if (found > 1) { // Only one address must match the local address
        String msg = "The HA Configuration has multiple addresses that match " + "local node's address.";
        throw new HadoopIllegalArgumentException(msg);
    }
    return currentRMId;
}

From source file:org.apache.hadoop.hbase.mob.mapreduce.SweepJob.java

static ServerName getCurrentServerName(Configuration conf) throws IOException {
    String hostname = conf.get("hbase.regionserver.ipc.address",
            Strings.domainNamePointerToHostName(
                    DNS.getDefaultHost(conf.get("hbase.regionserver.dns.interface", "default"),
                            conf.get("hbase.regionserver.dns.nameserver", "default"))));
    int port = conf.getInt(HConstants.REGIONSERVER_PORT, HConstants.DEFAULT_REGIONSERVER_PORT);
    // Creation of a HSA will force a resolve.
    InetSocketAddress initialIsa = new InetSocketAddress(hostname, port);
    if (initialIsa.getAddress() == null) {
        throw new IllegalArgumentException("Failed resolve of " + initialIsa);
    }//from w  w  w. ja va2 s  .  co m
    return ServerName.valueOf(initialIsa.getHostName(), initialIsa.getPort(),
            EnvironmentEdgeManager.currentTime());
}

From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {/*  w w  w. ja v  a 2  s .c  om*/
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                new ExternalAddressNatPmpResponse(packet); // should error out if not valid

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(16);
        ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest();
        eanpr.dump(outBuf);

        outBuf.flip();

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:edu.umass.cs.nio.MessageExtractor.java

/**
 * @param sndrAddress/*from w  w  w.j  av a 2  s .com*/
 * @param rcvrAddress
 * @param json
 * @return JSONObject with addresses stamped.
 */
@SuppressWarnings("deprecation")
// for backwards compatibility
public static JSONObject stampAddressIntoJSONObject(InetSocketAddress sndrAddress,
        InetSocketAddress rcvrAddress, JSONObject json) {
    // only put the IP field in if it doesn't exist already
    try {
        // put sender address
        if (!json.has(MessageNIOTransport.SNDR_ADDRESS_FIELD))
            json.put(MessageNIOTransport.SNDR_ADDRESS_FIELD,
                    sndrAddress.getAddress().getHostAddress() + ":" + sndrAddress.getPort());

        // TODO: remove the deprecated lines bel
        if (!json.has(JSONNIOTransport.SNDR_IP_FIELD))
            json.put(JSONNIOTransport.SNDR_IP_FIELD, sndrAddress.getAddress().getHostAddress());
        if (!json.has(JSONNIOTransport.SNDR_PORT_FIELD))
            json.put(JSONNIOTransport.SNDR_PORT_FIELD, sndrAddress.getPort());

        // put receiver address
        if (!json.has(MessageNIOTransport.RCVR_ADDRESS_FIELD))
            json.put(MessageNIOTransport.RCVR_ADDRESS_FIELD,
                    rcvrAddress.getAddress().getHostAddress() + ":" + rcvrAddress.getPort());

    } catch (JSONException e) {
        log.severe("Encountered JSONException while stamping sender address and port at receiver: ");
        e.printStackTrace();
    }
    return json;
}

From source file:edu.umass.cs.nio.MessageNIOTransport.java

/**
 * @param json/*from w  w w.  j av  a 2 s  .  c  o  m*/
 * @return Sender InetAddress read from json.
 * @throws JSONException
 */
public static final InetAddress getSenderInetAddress(JSONObject json) throws JSONException {
    InetSocketAddress isa = getSenderAddress(json);
    return isa != null ? isa.getAddress() : null;
}

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

public static ByteBuffer getTokens(StramDelegationTokenManager delegationTokenManager,
        InetSocketAddress heartbeatAddress) throws IOException {
    if (UserGroupInformation.isSecurityEnabled()) {
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        StramDelegationTokenIdentifier identifier = new StramDelegationTokenIdentifier(
                new Text(ugi.getUserName()), new Text(""), new Text(""));
        String service = heartbeatAddress.getAddress().getHostAddress() + ":" + heartbeatAddress.getPort();
        Token<StramDelegationTokenIdentifier> stramToken = new Token<StramDelegationTokenIdentifier>(identifier,
                delegationTokenManager);
        stramToken.setService(new Text(service));
        return getTokens(ugi, stramToken);
    }/*from   w  ww .ja va 2s.  c  o  m*/
    return null;
}

From source file:org.apache.bookkeeper.client.TestRegionAwareEnsemblePlacementPolicy.java

static Set<InetSocketAddress> getBookiesForRegion(ArrayList<InetSocketAddress> ensemble, String region) {
    Set<InetSocketAddress> regionBookies = new HashSet<InetSocketAddress>();
    for (InetSocketAddress address : ensemble) {
        String r = StaticDNSResolver.getRegion(address.getAddress().getHostAddress());
        if (r.equals(region)) {
            regionBookies.add(address);//w w  w .  j  a  va  2  s.c om
        }
    }
    return regionBookies;
}

From source file:edu.umass.cs.utils.Util.java

public static InetSocketAddress offsetPort(InetSocketAddress isa, int offset) {
    return new InetSocketAddress(isa.getAddress(), isa.getPort() + offset);
}

From source file:org.owasp.proxy.Main.java

private static HttpRequestHandler configureAJP(HttpRequestHandler rh, Configuration config) {
    if (config.ajpServer != null) {
        final DefaultAJPRequestHandler arh = new DefaultAJPRequestHandler();
        arh.setTarget(config.ajpServer);
        AJPProperties ajpProperties = new AJPProperties();
        ajpProperties.setRemoteAddress(config.ajpClientAddress);
        if (config.ajpClientCert != null && config.ajpClientCert.endsWith(".pem")) {
            try {
                BufferedReader in = new BufferedReader(new FileReader(config.ajpClientCert));
                StringBuffer buff = new StringBuffer();
                String line;/*ww  w.  j  a  v a 2  s .co  m*/
                while ((line = in.readLine()) != null) {
                    buff.append(line);
                }
                in.close();
                ajpProperties.setSslCert(buff.toString());
                ajpProperties.setSslCipher("ECDHE-RSA-AES256-SHA");
                ajpProperties.setSslSession("RANDOMID");
                ajpProperties.setSslKeySize("256");
            } catch (IOException ioe) {
                ioe.printStackTrace();
                System.exit(1);
            }
        }
        ajpProperties.setRemoteUser(config.ajpUser);
        ajpProperties.setAuthType("BASIC");
        ajpProperties.setContext("/manager");
        arh.setProperties(ajpProperties);
        final Set<String> ajpHosts = new HashSet<String>();
        if (config.ajpHosts != null)
            ajpHosts.addAll(Arrays.asList(config.ajpHosts));
        final HttpRequestHandler hrh = rh;
        return new HttpRequestHandler() {

            @Override
            public StreamingResponse handleRequest(InetAddress source, StreamingRequest request,
                    boolean isContinue) throws IOException, MessageFormatException {
                InetSocketAddress target = request.getTarget();
                if (ajpHosts.isEmpty() || ajpHosts.contains(target.getHostName())
                        || ajpHosts.contains(target.getAddress().getHostAddress())) {
                    return arh.handleRequest(source, request, isContinue);
                } else {
                    return hrh.handleRequest(source, request, isContinue);
                }
            }

            @Override
            public void dispose() throws IOException {
                arh.dispose();
                hrh.dispose();
            }

        };
    } else {
        return rh;
    }
}

From source file:edu.umass.cs.utils.Util.java

private static String sockAddrToEncodedString(InetSocketAddress isa) throws UnsupportedEncodingException {
    byte[] address = isa.getAddress().getAddress();
    byte[] buf = new byte[address.length + 2];
    for (int i = 0; i < address.length; i++)
        buf[i] = address[i];/*from   ww  w . j  a v  a  2  s.  c o  m*/
    buf[address.length] = (byte) (isa.getPort() >> 8);
    buf[address.length + 1] = (byte) (isa.getPort() & 255);
    return new String(buf, CHARSET);

}