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.hdfs.server.datanode.TestInterDatanodeProtocol.java

/** Test to verify that InterDatanode RPC timesout as expected when
 *  the server DN does not respond.//  w  w w  .j a v a 2 s  .c om
 */
@Test
public void testInterDNProtocolTimeout() throws Exception {
    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 dInfo = new DatanodeInfo(fakeDnId);
    InterDatanodeProtocol proxy = null;

    try {
        proxy = DataNode.createInterDataNodeProtocolProxy(dInfo, conf, 500);
        proxy.initReplicaRecovery(null);
        fail("Expected SocketTimeoutException exception, but did not get.");
    } catch (SocketTimeoutException e) {
        DataNode.LOG.info("Got expected Exception: SocketTimeoutException" + e);
    } finally {
        if (proxy != null) {
            RPC.stopProxy(proxy);
        }
        server.stop();
    }
}

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

private InetSocketAddress getRandomRCReplica() {
    int index = (int) (this.getReconfigurators().size() * Math.random());
    InetSocketAddress address = (InetSocketAddress) (this.getReconfigurators().toArray()[index]);
    return new InetSocketAddress(address.getAddress(), ActiveReplica.getClientFacingPort(address.getPort()));
}

From source file:org.opcfoundation.ua.transport.https.HttpsClientPendingRequest.java

@Override
public void run() {
    try {//from  w ww  .  j av  a 2 s  . c o  m
        // Abort exit branch
        if (abortCode != null) {
            result.setError(new ServiceResultException(abortCode));
            return;
        }

        // Http Post
        InetSocketAddress inetAddress = UriUtil.getSocketAddress(httpsClient.connectUrl);
        String host = inetAddress.getHostName();
        int port = inetAddress.getPort();
        String scheme = UriUtil.getTransportProtocol(httpsClient.connectUrl);
        HttpHost httpHost = new HttpHost(host, port, scheme);
        String url = httpsClient.transportChannelSettings.getDescription().getEndpointUrl();
        String endpointId = url == null ? "" : url; //UriUtil.getEndpointName(url);
        httpPost = new HttpPost(endpointId);
        httpPost.addHeader("OPCUA-SecurityPolicy", httpsClient.securityPolicyUri);
        httpPost.addHeader("Content-Type", "application/octet-stream");

        // Calculate message length
        EncoderCalc calc = new EncoderCalc();
        calc.setEncoderContext(httpsClient.encoderCtx);
        calc.putMessage(requestMessage);
        int len = calc.getLength();

        // Assert max size is not exceeded
        int maxLen = httpsClient.encoderCtx.getMaxMessageSize();
        if (maxLen != 0 && len > maxLen) {
            final EncodingException encodingException = new EncodingException(
                    StatusCodes.Bad_EncodingLimitsExceeded, "MaxStringLength " + maxLen + " < " + len);
            logger.warn("run: failed", encodingException);
            throw encodingException;
        }

        // Encode message
        byte[] data = new byte[len];
        BinaryEncoder enc = new BinaryEncoder(data);
        enc.setEncoderContext(httpsClient.encoderCtx);
        enc.setEncoderMode(EncoderMode.NonStrict);
        enc.putMessage(requestMessage);
        httpPost.setEntity(new NByteArrayEntity(data));

        // Abort exit branch
        if (abortCode != null) {
            result.setError(new ServiceResultException(abortCode));
            return;
        }

        // Execute Post

        HttpResponse httpResponse;
        try {
            httpResponse = httpsClient.httpclient.execute(httpHost, httpPost);
        } catch (SSLPeerUnverifiedException e) {
            // Currently, TLS_1_2 is not supported by JSSE implementations, for some odd reason
            // and it will give this exception when used.
            // Also, if the server certificate is rejected, we will get this error
            result.setError(new ServiceResultException(StatusCodes.Bad_SecurityPolicyRejected, e,
                    "Could not negotiate a TLS security cipher or the server did not provide a valid certificate."));
            return;
        }
        HttpEntity entity = httpResponse.getEntity();

        // Error response
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            UnsignedInteger uacode = StatusCodes.Bad_UnknownResponse;
            if (statusCode == 501)
                uacode = StatusCodes.Bad_ServiceUnsupported;
            String msg = EntityUtils.toString(entity);
            result.setError(new ServiceResultException(uacode, statusCode + ": " + msg));
            return;
        }

        // Abort exit branch
        if (abortCode != null) {
            result.setError(new ServiceResultException(abortCode));
            return;
        }

        // Decode Message
        data = EntityUtils.toByteArray(entity);

        BinaryDecoder dec = new BinaryDecoder(data);
        dec.setEncoderContext(httpsClient.encoderCtx);
        IEncodeable response = dec.getMessage();

        // Client sent an error
        if (response instanceof ErrorMessage) {
            ErrorMessage error = (ErrorMessage) response;
            ServiceResultException errorResult = new ServiceResultException(new StatusCode(error.getError()),
                    error.getReason());
            result.setError(errorResult);
            return;
        }

        try {
            // Client sent a valid message
            result.setResult((ServiceResponse) response);
        } catch (ClassCastException e) {
            result.setError(new ServiceResultException(e));
            logger.error("Cannot cast response to ServiceResponse, response=" + response.getClass(), e);
        }
    } catch (EncodingException e) {
        // Internal Error
        result.setError(new ServiceResultException(StatusCodes.Bad_EncodingError, e));
    } catch (ClientProtocolException e) {
        result.setError(new ServiceResultException(StatusCodes.Bad_CommunicationError, e));
    } catch (IOException e) {
        if (abortCode != null) {
            result.setError(new ServiceResultException(abortCode, e));
        } else {
            result.setError(new ServiceResultException(StatusCodes.Bad_CommunicationError, e));
        }
    } catch (DecodingException e) {
        result.setError(new ServiceResultException(StatusCodes.Bad_DecodingError, e));
    } catch (ServiceResultException e) {
        result.setError(e);
    } catch (RuntimeException rte) {
        // http-client seems to be throwing these, IllegalArgumentException for one
        result.setError(new ServiceResultException(rte));
    } finally {
        httpsClient.requests.remove(requestId);
    }
}

From source file:com.liferay.nativity.control.findersync.FSNativityControlImpl.java

@Override
public boolean connect() {
    if (_connected) {
        return true;
    }/*from   www .  j  a v a 2 s  . c  o  m*/

    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);

        serverBootstrap.channel(NioServerSocketChannel.class);

        ChannelInitializer channelInitializer = new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {

                DelimiterBasedFrameDecoder messageDecoder = new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                        Delimiters.lineDelimiter());

                FinderSyncChannelHandler finderSyncChannelHandler = new FinderSyncChannelHandler();

                socketChannel.pipeline().addLast(messageDecoder, finderSyncChannelHandler);
            }
        };

        serverBootstrap.childHandler(channelInitializer);

        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture channelFuture = serverBootstrap.bind(0).sync();

        InetSocketAddress inetSocketAddress = (InetSocketAddress) channelFuture.channel().localAddress();

        _writePortToFile(inetSocketAddress.getPort());
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);

        _connected = false;

        return false;
    }

    _connected = true;

    return true;
}

From source file:co.rsk.net.discovery.PeerExplorer.java

public PingPeerMessage sendPing(InetSocketAddress nodeAddress, int attempt, Node node) {
    PingPeerMessage nodeMessage = checkPendingPeerToAddress(nodeAddress);
    if (nodeMessage != null) {
        return nodeMessage;
    }/*from  w  w  w .  jav  a 2s  .c o m*/
    InetSocketAddress localAddress = this.localNode.getAddress();
    String id = UUID.randomUUID().toString();
    nodeMessage = PingPeerMessage.create(localAddress.getHostName(), localAddress.getPort(), id, this.key);
    udpChannel.write(new DiscoveryEvent(nodeMessage, nodeAddress));

    PeerDiscoveryRequest request = PeerDiscoveryRequestBuilder.builder().messageId(id).message(nodeMessage)
            .address(nodeAddress).expectedResponse(DiscoveryMessageType.PONG).relatedNode(node)
            .expirationPeriod(requestTimeout).attemptNumber(attempt).build();

    pendingPingRequests.put(nodeMessage.getMessageId(), request);
    return nodeMessage;
}

From source file:com.amazonaws.http.conn.ssl.SdkTLSSocketFactory.java

@Override
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (log.isDebugEnabled())
        log.debug("connecting to " + remoteAddress.getAddress() + ":" + remoteAddress.getPort());
    try {//from   w w w  .j a v a  2s  . co m
        verifyMasterSecret(super.connectSocket(socket, remoteAddress, localAddress, params));
    } catch (final SSLException sslEx) {
        // clear any related sessions from our cache
        if (log.isDebugEnabled()) {
            log.debug("connection failed due to SSL error, clearing TLS session cache", sslEx);
        }
        clearSessionCache(sslContext.getClientSessionContext(), remoteAddress);
        throw sslEx;
    }
    if (socket instanceof SSLSocket)
        return new SdkSSLSocket((SSLSocket) socket);
    return new SdkSocket(socket);
}

From source file:com.all.networking.PeerNetworkingService.java

@Override
public void sessionClosed(IoSession session) throws Exception {
    log.info("Session to " + session.getRemoteAddress() + " was closed.");
    InetSocketAddress remoteSocketAddress = (InetSocketAddress) session.getRemoteAddress();
    String remoteAddress = remoteSocketAddress.getAddress().getHostAddress();
    int remotePort = remoteSocketAddress.getPort();
    IoSession removed = currentSessions.remove(createSessionKey(remoteAddress, remotePort));
    if (removed != null) {
        log.info("Removing " + remoteAddress + " from current sessions.");
    }//from  w  w w .  ja v  a 2 s  . c o m
}

From source file:com.sharneng.net.portforward.Listener.java

/**
 * Constructs a new instance of Listener.
 * /*from w  w  w  . j a  v a2 s .  c om*/
 * @param from
 *            the address to listen for connections
 * @param to
 *            the address to forward connections to
 * @throws IOException
 *             when something is not going write when network operation
 */
public Listener(InetSocketAddress from, InetSocketAddress to) throws IOException {
    this.from = from;
    this.to = to;
    serverSocket = new ServerSocket();
    serverSocket.setReuseAddress(true);
    serverSocket.bind(from);
    String hostname = from.getHostName();
    if (hostname == null)
        hostname = "*";
    log.info("Ready to accept client connection on " + hostname + ":" + from.getPort());
}

From source file:oz.hadoop.yarn.api.core.AbstractApplicationMasterLauncher.java

/**
 * /*from   ww  w .  ja  v a2 s  .  com*/
 */
private void initApplicationContainerServer(int applicationContainerCount, boolean finite) {
    this.clientServer = this.buildClientServer(applicationContainerCount, finite);
    InetSocketAddress address = clientServer.start();
    this.applicationSpecification.put(YayaConstants.CLIENT_HOST, address.getHostName());
    this.applicationSpecification.put(YayaConstants.CLIENT_PORT, address.getPort());
}