Example usage for java.net InetSocketAddress getPort

List of usage examples for java.net InetSocketAddress getPort

Introduction

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

Prototype

public final int getPort() 

Source Link

Document

Gets the port number.

Usage

From source file:org.apache.hadoop.hbase.ipc.TestAsyncIPC.java

@Test
public void testAsyncConnectionSetup() throws Exception {
    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = createRpcClient(CONF);
    try {//from ww w .  j  ava2s  .c o  m
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        channel.callMethod(md, new PayloadCarryingRpcController(), param, md.getOutputType().toProto(),
                new RpcCallback<Message>() {
                    @Override
                    public void run(Message parameter) {
                        done.set(true);
                    }
                });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestClientRMTokens.java

@Test
public void testShortCircuitRenewCancelDifferentHostSamePort() throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(rmAddr, new InetSocketAddress("1.1.1.1", rmAddr.getPort()), false);
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestClientRMTokens.java

@Test
public void testShortCircuitRenewCancelDifferentHostDifferentPort() throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(rmAddr, new InetSocketAddress("1.1.1.1", rmAddr.getPort() + 1), false);
}

From source file:edu.umass.cs.reconfiguration.deprecated.ReconfigurableClient.java

private InetSocketAddress getRandomRCReplica(boolean offset) {
    int index = (int) (this.getReconfigurators().size() * Math.random());
    InetSocketAddress address = (InetSocketAddress) (this.getReconfigurators().toArray()[index]);
    return offset
            ? new InetSocketAddress(address.getAddress(), ActiveReplica.getClientFacingPort(address.getPort()))
            : address;/*  ww  w .  ja  va 2 s .  c  om*/
}

From source file:org.apache.hadoop.hbase.ipc.TestAsyncIPC.java

@Test
public void testRTEDuringAsyncConnectionSetup() throws Exception {
    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = createRpcClientRTEDuringConnectionSetup(CONF);
    try {//w  ww  .  java2  s. com
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        PayloadCarryingRpcController controller = new PayloadCarryingRpcController();
        controller.notifyOnFail(new RpcCallback<IOException>() {
            @Override
            public void run(IOException e) {
                done.set(true);
                LOG.info("Caught expected exception: " + e.toString());
                assertTrue(StringUtils.stringifyException(e).contains("Injected fault"));
            }
        });

        channel.callMethod(md, controller, param, md.getOutputType().toProto(), new RpcCallback<Message>() {
            @Override
            public void run(Message parameter) {
                done.set(true);
                fail("Expected an exception to have been thrown!");
            }
        });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestClientRMTokens.java

@Test
public void testShortCircuitRenewCancelSameHostDifferentPort() throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(rmAddr, new InetSocketAddress(rmAddr.getAddress(), rmAddr.getPort() + 1),
            false);//from w w w  .  j  ava 2s .c  o  m
}

From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClientTest.java

/**
 * Initializes the test.//from   w  w w  . jav a2  s .  c o  m
 * @throws Exception if some errors were occurred
 */
@Before
public void setUp() throws Exception {
    BasicHttpProcessor proc = new BasicHttpProcessor();
    proc.addInterceptor(new ResponseDate());
    proc.addInterceptor(new ResponseServer());
    proc.addInterceptor(new ResponseContent());
    proc.addInterceptor(new ResponseConnControl());
    proc.addInterceptor(new RequestBasicAuth());
    proc.addInterceptor(new ResponseBasicUnauthorized());
    server = new LocalTestServer(proc, null);
    server.start();
    InetSocketAddress address = server.getServiceAddress();
    baseUrl = new URL("http", address.getHostName(), address.getPort(), "/").toExternalForm();
}

From source file:org.apache.hadoop.hbase.security.AbstractTestSecureIPC.java

/**
 * Sets up a RPC Server and a Client. Does a RPC checks the result. If an exception is thrown
 * from the stub, this function will throw root cause of that exception.
 *///from   w  w w. j ava 2s . c  o m
private void callRpcService(User clientUser) throws Exception {
    SecurityInfo securityInfoMock = Mockito.mock(SecurityInfo.class);
    Mockito.when(securityInfoMock.getServerPrincipal()).thenReturn(HBaseKerberosUtils.KRB_PRINCIPAL);
    SecurityInfo.addInfo("TestProtobufRpcProto", securityInfoMock);

    InetSocketAddress isa = new InetSocketAddress(HOST, 0);

    RpcServerInterface rpcServer = new RpcServer(null, "AbstractTestSecureIPC",
            Lists.newArrayList(new RpcServer.BlockingServiceAndInterface(SERVICE, null)), isa, serverConf,
            new FifoRpcScheduler(serverConf, 1));
    rpcServer.start();
    try (RpcClient rpcClient = RpcClientFactory.createClient(clientConf,
            HConstants.DEFAULT_CLUSTER_ID.toString())) {
        InetSocketAddress address = rpcServer.getListenerAddress();
        if (address == null) {
            throw new IOException("Listener channel is closed");
        }
        BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                clientUser, 0);
        TestRpcServiceProtos.TestProtobufRpcProto.BlockingInterface stub = TestRpcServiceProtos.TestProtobufRpcProto
                .newBlockingStub(channel);
        List<String> results = new ArrayList<>();
        TestThread th1 = new TestThread(stub, results);
        final Throwable exception[] = new Throwable[1];
        Collections.synchronizedList(new ArrayList<Throwable>());
        Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                exception[0] = ex;
            }
        };
        th1.setUncaughtExceptionHandler(exceptionHandler);
        th1.start();
        th1.join();
        if (exception[0] != null) {
            // throw root cause.
            while (exception[0].getCause() != null) {
                exception[0] = exception[0].getCause();
            }
            throw (Exception) exception[0];
        }
    } finally {
        rpcServer.stop();
    }
}

From source file:org.apache.hadoop.dfs.SecondaryNameNode.java

/**
 * Initialize SecondaryNameNode.//w w  w. j a v  a2  s.co  m
 */
private void initialize(Configuration conf) throws IOException {
    // initiate Java VM metrics
    JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));

    // Create connection to the namenode.
    shouldRun = true;
    nameNodeAddr = NameNode.getAddress(conf);

    this.conf = conf;
    this.namenode = (ClientProtocol) RPC.waitForProxy(ClientProtocol.class, ClientProtocol.versionID,
            nameNodeAddr, conf);

    // initialize checkpoint directories
    fsName = getInfoServer();
    checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary");
    checkpointImage = new CheckpointStorage();
    checkpointImage.recoverCreate(checkpointDirs);

    // Initialize other scheduling parameters from the configuration
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);

    // initialize the webserver for uploading files.
    String infoAddr = NetUtils.getServerAddress(conf, "dfs.secondary.info.bindAddress",
            "dfs.secondary.info.port", "dfs.secondary.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    infoBindAddress = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new StatusHttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0);
    infoServer.setAttribute("name.system.image", checkpointImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort);
    LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort);
    LOG.warn("Checkpoint Period   :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)");
    LOG.warn("Log Size Trigger    :" + checkpointSize + " bytes " + "(" + checkpointSize / 1024 + " KB)");
}

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

/** Test that timeout occurs when DN does not respond to RPC.
 * Start up a server and ask it to sleep for n seconds. Make an
 * RPC to the server and set rpcTimeout to less than n and ensure
 * that socketTimeoutException is obtained
 */// w w  w.  ja v  a 2 s .c om
public void testClientDNProtocolTimeout() throws IOException {
    final Server server = new TestServer(1, true);
    server.start();

    final InetSocketAddress addr = NetUtils.getConnectAddress(server);
    DatanodeID fakeDnId = new DatanodeID("localhost:" + addr.getPort(), "fake-storage", 0, addr.getPort());
    DatanodeInfo dnInfo = new DatanodeInfo(fakeDnId);

    LocatedBlock fakeBlock = new LocatedBlock(new Block(12345L), new DatanodeInfo[0]);

    ClientDatanodeProtocol proxy = null;

    try {
        proxy = DFSClient.createClientDatanodeProtocolProxy(dnInfo, conf, fakeBlock.getBlock(),
                fakeBlock.getBlockToken(), 500);

        fail("Did not get expected exception: SocketTimeoutException");
    } catch (SocketTimeoutException e) {
        LOG.info("Got the expected Exception: SocketTimeoutException");
    } finally {
        if (proxy != null) {
            RPC.stopProxy(proxy);
        }
        server.stop();
    }
}