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.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java

@Test
public void testResolveRemoteAddress() throws Exception {
    final InternalAddressResolver addressResolver = new InternalAddressResolver(schemePortResolver,
            dnsResolver);//from   w ww .  j a va2s .  com

    final HttpHost target = new HttpHost("somehost", 80);
    final HttpRoute route = new HttpRoute(target);

    Mockito.when(schemePortResolver.resolve(target)).thenReturn(123);
    final byte[] ip = new byte[] { 10, 0, 0, 10 };
    Mockito.when(dnsResolver.resolve("somehost"))
            .thenReturn(new InetAddress[] { InetAddress.getByAddress(ip) });

    final InetSocketAddress address = (InetSocketAddress) addressResolver.resolveRemoteAddress(route);

    Assert.assertNotNull(address);
    Assert.assertEquals(InetAddress.getByAddress(ip), address.getAddress());
    Assert.assertEquals(123, address.getPort());
}

From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java

@Test
public void testResolveRemoteAddressViaProxy() throws Exception {
    final InternalAddressResolver addressResolver = new InternalAddressResolver(schemePortResolver,
            dnsResolver);/*from w w  w.j ava 2  s . c  o m*/

    final HttpHost target = new HttpHost("somehost", 80);
    final HttpHost proxy = new HttpHost("someproxy");
    final HttpRoute route = new HttpRoute(target, null, proxy, false);

    Mockito.when(schemePortResolver.resolve(proxy)).thenReturn(8888);
    final byte[] ip = new byte[] { 10, 0, 0, 10 };
    Mockito.when(dnsResolver.resolve("someproxy"))
            .thenReturn(new InetAddress[] { InetAddress.getByAddress(ip) });

    final InetSocketAddress address = (InetSocketAddress) addressResolver.resolveRemoteAddress(route);

    Assert.assertNotNull(address);
    Assert.assertEquals(InetAddress.getByAddress(ip), address.getAddress());
    Assert.assertEquals(8888, address.getPort());
}

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

private void basicReorderReadSequenceWithLocalRegionTest(String myRegion, boolean isReadLAC) throws Exception {
    prepareNetworkTopologyForReorderTests(myRegion);

    ArrayList<InetSocketAddress> ensemble = repp.newEnsemble(9, 9, new HashSet<InetSocketAddress>());
    assertEquals(9, getNumCoveredRegionsInWriteQuorum(ensemble, 9));

    DistributionSchedule ds = new RoundRobinDistributionSchedule(9, 9, 9);

    LOG.info("My region is {}, ensemble : {}", repp.myRegion, ensemble);

    int ensembleSize = ensemble.size();
    for (int i = 0; i < ensembleSize; i++) {
        List<Integer> writeSet = ds.getWriteSet(i);
        List<Integer> readSet;
        if (isReadLAC) {
            readSet = repp.reorderReadLACSequence(ensemble, writeSet);
        } else {//from  ww  w  .  java 2 s.  c o m
            readSet = repp.reorderReadSequence(ensemble, writeSet);
        }

        LOG.info("Reorder {} => {}.", writeSet, readSet);

        // first few nodes less than REMOTE_NODE_IN_REORDER_SEQUENCE should be local region
        int k = 0;
        for (; k < RegionAwareEnsemblePlacementPolicy.REMOTE_NODE_IN_REORDER_SEQUENCE; k++) {
            InetSocketAddress address = ensemble.get(readSet.get(k));
            assertEquals(myRegion, StaticDNSResolver.getRegion(address.getAddress().getHostAddress()));
        }
        InetSocketAddress remoteAddress = ensemble.get(readSet.get(k));
        assertFalse(myRegion.equals(StaticDNSResolver.getRegion(remoteAddress.getAddress().getHostAddress())));
        k++;
        InetSocketAddress localAddress = ensemble.get(readSet.get(k));
        assertEquals(myRegion, StaticDNSResolver.getRegion(localAddress.getAddress().getHostAddress()));
        k++;
        for (; k < ensembleSize; k++) {
            InetSocketAddress address = ensemble.get(readSet.get(k));
            assertFalse(myRegion.equals(StaticDNSResolver.getRegion(address.getAddress().getHostAddress())));
        }
    }
}

From source file:org.apache.hadoop.mapred.ProxyJobTracker.java

public void shutdown() throws Exception {
    infoServer.stop();//from   ww w  .  j a  v  a  2 s  .c o m
    rpcServer.stop();
    thriftServer.stop();
    // Do an dummy connect to the thrift server port. This will cause an thrift
    // exception and move the server beyond the blocking accept.
    // Thread.interrupt() does not help.
    String target = conf.getProxyJobTrackerThriftAddress();
    InetSocketAddress addr = NetUtils.createSocketAddr(target);
    try {
        new Socket(addr.getAddress(), addr.getPort()).close();
    } catch (IOException e) {
    }
}

From source file:org.apache.tajo.ha.HdfsServiceTracker.java

/**
 * It will creates the following form string. It includes
 *
 * <pre>/* ww  w .  j  a  v a 2 s.  c o  m*/
 * {CLIENT_RPC_HOST:PORT}_{RESOURCE_TRACKER_HOST:PORT}_{CATALOG_HOST:PORT}_{MASTER_WEB_HOST:PORT}
 * </pre>
 *
 * @throws IOException
 */
@Override
public void register() throws IOException {
    // Check lock file
    boolean lockResult = createLockFile();

    String fileName = masterName.replaceAll(":", "_");
    Path activeFile = new Path(activePath, fileName);
    Path backupFile = new Path(backupPath, fileName);

    // Set TajoMasterInfo object which has several rpc server addresses.
    StringBuilder sb = new StringBuilder();
    InetSocketAddress address = getHostAddress(HAConstants.MASTER_UMBILICAL_RPC_ADDRESS);
    sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_");

    address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS);
    sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_");

    address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS);
    sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_");

    address = getHostAddress(HAConstants.CATALOG_ADDRESS);
    sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_");

    address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS);
    sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort());

    // Phase 1: If there is not another active master, this try to become active master.
    if (lockResult) {
        fs.delete(backupFile, false);
        createMasterFile(activeFile, sb);
        currentActiveMaster = masterName;
        writeSystemConf();
        LOG.info(String.format("This is added to active master (%s)", masterName));
    } else {
        // Phase 2: If there is active master information, we need to check its status.
        FileStatus[] files = fs.listStatus(activePath);
        Path existingActiveFile = null;
        if (files.length > 2) {
            throw new ServiceTrackerException("Three or more than active master entries.");
        }
        for (FileStatus eachFile : files) {
            if (!eachFile.getPath().getName().equals(HAConstants.ACTIVE_LOCK_FILE)) {
                existingActiveFile = eachFile.getPath();
            }
        }
        currentActiveMaster = existingActiveFile.getName().replaceAll("_", ":");

        // Phase 3: If current active master is dead, this master should be active master.
        if (!checkConnection(currentActiveMaster)) {
            fs.delete(existingActiveFile, false);
            fs.delete(backupFile, false);
            createMasterFile(activeFile, sb);
            currentActiveMaster = masterName;
            LOG.info(String.format("This is added to active master (%s)", masterName));
        } else {
            // Phase 4: If current active master is alive, this master need to be backup master.
            if (masterName.equals(currentActiveMaster)) {
                LOG.info(String.format("This has already been added to active master (%s)", masterName));
            } else {
                if (fs.exists(backupFile)) {
                    LOG.info(String.format("This has already been added to backup masters (%s)", masterName));
                } else {
                    createMasterFile(backupFile, sb);
                    LOG.info(String.format("This is added to backup master (%s)", masterName));
                }
            }
        }
    }

    if (!isActiveMaster()) {
        startPingChecker();
    }
}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void serveTCP(InetSocketAddress address) {
    try {// w w  w. j  av a2 s.  co m
        final ServerSocket sock = new ServerSocket(address.getPort(), 128, address.getAddress());
        synchronized (_closeables) {
            _closeables.add(sock);
        }
        while (!currentThread().isInterrupted()) {
            final Socket s = accept(sock);
            final Thread thread;
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    TCPclient(s);
                }
            });
            _threads.add(thread);
            thread.start();
        }
    } catch (final InterruptedIOException ignored) {
        currentThread().interrupt();
    } catch (final IOException e) {
        LOG.warn("serveTCP(" + addrport(address.getAddress(), address.getPort()) + ")", e);
    }
}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void serveUDP(InetSocketAddress address) {
    try {// www .  j av a  2 s. c  o  m
        final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress());
        synchronized (_closeables) {
            _closeables.add(sock);
        }
        final short udpLength = 512;
        final byte[] in = new byte[udpLength];
        final DatagramPacket indp = new DatagramPacket(in, in.length);
        DatagramPacket outdp = null;
        while (!currentThread().isInterrupted()) {
            indp.setLength(in.length);
            receive(sock, indp);
            final Message query;
            byte[] response;
            try {
                query = new Message(in);
                response = generateReply(query, in, indp.getLength(), null);
                if (response == null) {
                    continue;
                }
            } catch (final IOException ignored) {
                response = formerrMessage(in);
            }
            if (outdp == null) {
                outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort());
            } else {
                outdp.setData(response);
                outdp.setLength(response.length);
                outdp.setAddress(indp.getAddress());
                outdp.setPort(indp.getPort());
            }
            sock.send(outdp);
        }
    } catch (final InterruptedIOException ignored) {
        currentThread().interrupt();
    } catch (final IOException e) {
        LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e);
    }
}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uri = request.getRequestURI();

    String port = "";
    String host = "";

    int c = uri.indexOf(':');
    if (c >= 0) {
        port = uri.substring(c + 1);/*from ww  w  . j  a  va2 s  . co  m*/
        host = uri.substring(0, c);
        if (host.indexOf('/') > 0)
            host = host.substring(host.indexOf('/') + 1);
    }

    InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port));

    // if
    // (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
    // {
    // sendForbid(request,response,uri);
    // }
    // else
    {
        InputStream in = request.getInputStream();
        final OutputStream out = response.getOutputStream();

        final Socket socket = new Socket(inetAddress.getAddress(), inetAddress.getPort());

        response.setStatus(200);
        response.setHeader("Connection", "close");
        response.flushBuffer();

        //         try {
        //            Thread copy = new Thread(new Runnable() {
        //               public void run() {
        //                  try {
        IOUtils.copy(socket.getInputStream(), out);
        //                  } catch (IOException e) {
        //                     e.printStackTrace();
        //                  }
        //               }
        //            });
        //            copy.start();
        IOUtils.copy(in, socket.getOutputStream());
        //            copy.join();
        //            copy.join(10000);
        //         }
        //         catch (InterruptedException e) {
        //            e.printStackTrace();
        //         }
    }
}

From source file:org.cloudgraph.hbase.mapreduce.GraphInputFormat.java

@Override
public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException {
    if (scans.isEmpty()) {
        throw new IOException("No scans were provided.");
    }/*from w w w.  j  a v  a 2 s .  c  o m*/

    try {
        RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(regionLocator, admin);
        Pair<byte[][], byte[][]> keys = getStartEndKeys();
        // if potentially a single split (or table is empty?)
        if (keys == null || keys.getFirst() == null || keys.getFirst().length == 0) {
            HRegionLocation regLoc = regionLocator.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());
            Scan scan = scans.get(0);
            if (scans.size() > 1)
                log.warn("single split with multiple scans - ignoring other than first scan");

            TableSplit split = new TableSplit(table.getName(), scan, 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 (Scan scan : scans) {

            for (int i = 0; i < keys.getFirst().length; i++) {
                if (!includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
                    continue;
                }
                HRegionLocation location = regionLocator.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.error("Failed to resolve host: " + isa + " - ignoring entire split for this host!");
                    continue;
                }
                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(), scan, // must
                            // include
                            // the scan
                            // as it
                            // may have
                            // various filters
                            splitStart, splitStop, regionLocation, regionSize);
                    splits.add(split);
                    if (log.isDebugEnabled()) {
                        log.debug("getSplits: split -> " + i + " -> " + split);
                    }
                }
            }
        }
        return splits;
    } finally {
        closeAll();
    }
}

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testInvalidAuth() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/* w w  w  .  j  av a 2  s  .c  o  m*/
    try {
        server = createServer(createProtocol(new TestPassCmdHandler()), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());

        assertThat(client.login("invalid", "invalid")).isFalse();
        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}