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:net.java.sip.communicator.service.httputil.SSLSocketFactoryEx.java

/**
 * @since 4.1/*from   w w w. j a  va 2  s . co  m*/
 */
@Override
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket != null ? socket : this.context.getSocketFactory().createSocket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }

    String hostname;
    if (remoteAddress instanceof HttpInetSocketAddress) {
        hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
    } else {
        hostname = remoteAddress.getHostName();
    }

    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        int port = remoteAddress.getPort();
        sslsock = (SSLSocket) this.context.getSocketFactory().createSocket(sock, hostname, port, true);
    }

    return sslsock;
}

From source file:edu.umass.cs.reconfiguration.ActiveReplica.java

@SuppressWarnings("unchecked")
private AddressMessenger<?> initClientMessenger(boolean ssl) {
    AbstractPacketDemultiplexer<JSONObject> pd = null;
    Messenger<InetSocketAddress, JSONObject> cMsgr = null;
    Set<IntegerPacketType> appTypes = null;
    if ((appTypes = this.appCoordinator.getAppRequestTypes()) == null || appTypes.isEmpty())
        // return null
        ;/*from   ww w.  j a  v  a 2 s .c  o m*/
    try {
        int myPort = (this.nodeConfig.getNodePort(getMyID()));
        if ((ssl ? getClientFacingSSLPort(myPort) : getClientFacingClearPort(myPort)) != myPort) {
            log.log(Level.INFO, "{0} creating {1} client messenger at {2}:{3}",
                    new Object[] { this, ssl ? "SSL" : "", this.nodeConfig.getBindAddress(getMyID()),
                            "" + (ssl ? getClientFacingSSLPort(myPort) : getClientFacingClearPort(myPort)) });

            AddressMessenger<?> existing = (ssl ? this.messenger.getSSLClientMessenger()
                    : this.messenger.getClientMessenger());
            if (existing == null || existing == this.messenger) {
                MessageNIOTransport<InetSocketAddress, JSONObject> niot = null;
                InetSocketAddress isa = new InetSocketAddress(this.nodeConfig.getBindAddress(getMyID()),
                        ssl ? getClientFacingSSLPort(myPort) : getClientFacingClearPort(myPort));
                cMsgr = new JSONMessenger<InetSocketAddress>(
                        (niot = new MessageNIOTransport<InetSocketAddress, JSONObject>(isa.getAddress(),
                                isa.getPort(),
                                /* Client facing demultiplexer is single
                                 * threaded to keep clients from
                                 * overwhelming the system with request
                                 * load. */
                                (pd = new ReconfigurationPacketDemultiplexer()),
                                ssl ? ReconfigurationConfig.getClientSSLMode() : SSL_MODES.CLEAR))
                                        .setName(this.appCoordinator.app.toString() + ":" + (ssl ? "SSL" : "")
                                                + "ClientMessenger"));
                if (!niot.getListeningSocketAddress().equals(isa))
                    throw new IOException("Unable to listen on specified client facing socket address " + isa
                            + "; created messenger listening instead on " + niot.getListeningSocketAddress());
            } else if (!ssl) {
                log.log(Level.INFO, "{0} adding self as demultiplexer to existing {1} client messenger",
                        new Object[] { this, ssl ? "SSL" : "" });
                if (this.messenger.getClientMessenger() instanceof Messenger)
                    ((Messenger<NodeIDType, ?>) existing)
                            .addPacketDemultiplexer(pd = new ReconfigurationPacketDemultiplexer());
            } else {
                log.log(Level.INFO, "{0} adding self as demultiplexer to existing {1} client messenger",
                        new Object[] { this, ssl ? "SSL" : "" });
                if (this.messenger.getSSLClientMessenger() instanceof Messenger)
                    ((Messenger<NodeIDType, ?>) existing)
                            .addPacketDemultiplexer(pd = new ReconfigurationPacketDemultiplexer());
            }
            if (appTypes != null && !appTypes.isEmpty())
                pd.register(appTypes
                //this.appCoordinator.getRequestTypes()
                        , this);
            pd.register(PacketType.ECHO_REQUEST, this);
            pd.register(PacketType.REPLICABLE_CLIENT_REQUEST, this);
        }
    } catch (IOException e) {
        e.printStackTrace();
        log.severe(this + ":" + e.getMessage());
        System.exit(1);
    }

    if (cMsgr != null)
        if (ssl && this.messenger.getSSLClientMessenger() == null)
            this.messenger.setSSLClientMessenger(cMsgr);
        else if (!ssl && this.messenger.getClientMessenger() == null)
            this.messenger.setClientMessenger(cMsgr);

    return cMsgr != null ? cMsgr : (AddressMessenger<?>) this.messenger;
}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

/**
 * @since 4.1//from   w w w  . j ava2  s.com
 */
@Override
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket != null ? socket : new Socket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException(
                "Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out");
    }
    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        sslsock = (SSLSocket) getSocketFactory().createSocket(sock, remoteAddress.getHostName(),
                remoteAddress.getPort(), true);
        sslsock = enableSocket(sslsock);
    }
    // do we need it? trust all hosts
    //      if( getHostnameVerifier() != null )
    //      {
    //         try
    //         {
    //            getHostnameVerifier().verify( remoteAddress.getHostName(), sslsock );
    //            // verifyHostName() didn't blowup - good!
    //         }
    //         catch( IOException iox )
    //         {
    //            // close the socket before re-throwing the exception
    //            try
    //            {
    //               sslsock.close();
    //            }
    //            catch( Exception x )
    //            { /* ignore */
    //            }
    //            throw iox;
    //         }
    //      }
    return sslsock;
}

From source file:org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl.java

@SuppressWarnings("unchecked")
@Override/*ww  w.j a  v a 2s  .  co  m*/
public long renewDelegationToken(final Token<TimelineDelegationTokenIdentifier> timelineDT)
        throws IOException, YarnException {
    final boolean isTokenServiceAddrEmpty = timelineDT.getService().toString().isEmpty();
    final String scheme = isTokenServiceAddrEmpty ? null
            : (YarnConfiguration.useHttps(this.getConfig()) ? "https" : "http");
    final InetSocketAddress address = isTokenServiceAddrEmpty ? null
            : SecurityUtil.getTokenServiceAddr(timelineDT);
    PrivilegedExceptionAction<Long> renewDTAction = new PrivilegedExceptionAction<Long>() {

        @Override
        public Long run() throws Exception {
            // If the timeline DT to renew is different than cached, replace it.
            // Token to set every time for retry, because when exception happens,
            // DelegationTokenAuthenticatedURL will reset it to null;
            if (!timelineDT.equals(token.getDelegationToken())) {
                token.setDelegationToken((Token) timelineDT);
            }
            DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(authenticator,
                    connConfigurator);
            // If the token service address is not available, fall back to use
            // the configured service address.
            final URI serviceURI = isTokenServiceAddrEmpty ? resURI
                    : new URI(scheme, null, address.getHostName(), address.getPort(), RESOURCE_URI_STR, null,
                            null);
            return authUrl.renewDelegationToken(serviceURI.toURL(), token, doAsUser);
        }
    };
    return (Long) operateDelegationToken(renewDTAction);
}

From source file:org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl.java

@SuppressWarnings("unchecked")
@Override// w ww.  j  av a 2  s . co m
public void cancelDelegationToken(final Token<TimelineDelegationTokenIdentifier> timelineDT)
        throws IOException, YarnException {
    final boolean isTokenServiceAddrEmpty = timelineDT.getService().toString().isEmpty();
    final String scheme = isTokenServiceAddrEmpty ? null
            : (YarnConfiguration.useHttps(this.getConfig()) ? "https" : "http");
    final InetSocketAddress address = isTokenServiceAddrEmpty ? null
            : SecurityUtil.getTokenServiceAddr(timelineDT);
    PrivilegedExceptionAction<Void> cancelDTAction = new PrivilegedExceptionAction<Void>() {

        @Override
        public Void run() throws Exception {
            // If the timeline DT to cancel is different than cached, replace it.
            // Token to set every time for retry, because when exception happens,
            // DelegationTokenAuthenticatedURL will reset it to null;
            if (!timelineDT.equals(token.getDelegationToken())) {
                token.setDelegationToken((Token) timelineDT);
            }
            DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(authenticator,
                    connConfigurator);
            // If the token service address is not available, fall back to use
            // the configured service address.
            final URI serviceURI = isTokenServiceAddrEmpty ? resURI
                    : new URI(scheme, null, address.getHostName(), address.getPort(), RESOURCE_URI_STR, null,
                            null);
            authUrl.cancelDelegationToken(serviceURI.toURL(), token, doAsUser);
            return null;
        }
    };
    operateDelegationToken(cancelDTAction);
}

From source file:org.apache.hadoop.hdfs.server.datanode.BPOfferService.java

BPOfferService(List<InetSocketAddress> nnAddrs, DataNode dn) {
    Preconditions.checkArgument(!nnAddrs.isEmpty(), "Must pass at least one NN.");
    this.dn = dn;

    for (InetSocketAddress addr : nnAddrs) {
        this.bpServices.add(new BPServiceActor(addr, this));
        nnList.add(new ActiveNodePBImpl(0, "", addr.getAddress().getHostAddress(), addr.getPort(), "",
                addr.getAddress().getHostAddress(), addr.getPort()));
    }//from  ww  w . j  a v  a  2  s  . co  m

    dnConf = dn.getDnConf();
    prevBlockReportId = DFSUtil.getRandom().nextLong();
}

From source file:edu.umass.cs.reconfiguration.Reconfigurator.java

private static Set<InetSocketAddress> modifyPortsForSSL(Set<InetSocketAddress> replicas, Boolean ssl) {
    if (ssl == null)
        return replicas;
    else if ((ssl && ReconfigurationConfig.getClientPortSSLOffset() == 0)
            || (!ssl && ReconfigurationConfig.getClientPortOffset() == 0))
        return replicas;
    Set<InetSocketAddress> modified = new HashSet<InetSocketAddress>();
    for (InetSocketAddress sockAddr : replicas)
        modified.add(new InetSocketAddress(sockAddr.getAddress(),
                ssl ? ReconfigurationConfig.getClientFacingSSLPort(sockAddr.getPort())
                        : ReconfigurationConfig.getClientFacingClearPort(sockAddr.getPort())));
    return modified;
}

From source file:common.NameNode.java

/**
 * Initialize name-node.//from   www  .j a  v a2s . c  om
 * 
 * @param conf the configuration
 */
protected void initialize(Configuration conf) throws IOException {
    InetSocketAddress socAddr = getRpcServerAddress(conf);
    int handlerCount = conf.getInt("dfs.namenode.handler.count", 10);

    // set service-level authorization security policy
    if (serviceAuthEnabled = conf.getBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
        ServiceAuthorizationManager.refresh(conf, new HDFSPolicyProvider());
    }

    NameNode.initMetrics(conf, this.getRole());
    loadNamesystem(conf);
    // create rpc server 
    this.server = RPC.getServer(NamenodeProtocols.class, this, socAddr.getHostName(), socAddr.getPort(),
            handlerCount, false, conf, namesystem.getDelegationTokenSecretManager());
    // The rpc-server port can be ephemeral... ensure we have the correct info
    this.rpcAddress = this.server.getListenerAddress();
    setRpcServerAddress(conf);

    activate(conf);
    LOG.info(getRole() + " up at: " + rpcAddress);
}

From source file:com.linkedin.databus2.core.container.netty.ServerContainer.java

protected void doStart() {
    _controlLock.lock();/*from w  ww.j av  a2 s  .c  o  m*/
    try {
        // Bind and start to accept incoming connections.
        int portNum = getContainerStaticConfig().getHttpPort();
        _tcpChannelGroup = new DefaultChannelGroup();
        _httpChannelGroup = new DefaultChannelGroup();

        _httpServerChannel = _httpBootstrap.bind(new InetSocketAddress(portNum));
        InetSocketAddress actualAddress = (InetSocketAddress) _httpServerChannel.getLocalAddress();
        _containerPort = actualAddress.getPort();

        // persist the port number (file name should be unique for the container)
        File portNumFile = new File(getHttpPortFileName());
        portNumFile.deleteOnExit();
        try {
            FileWriter portNumFileW = new FileWriter(portNumFile);
            portNumFileW.write(Integer.toString(_containerPort));
            portNumFileW.close();
            LOG.info("Saving port number in " + portNumFile.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        _httpChannelGroup.add(_httpServerChannel);
        LOG.info("Serving container " + getContainerStaticConfig().getId() + " HTTP listener on port "
                + _containerPort);

        if (_containerStaticConfig.getTcp().isEnabled()) {
            int tcpPortNum = _containerStaticConfig.getTcp().getPort();
            _tcpServerChannel = _tcpBootstrap.bind(new InetSocketAddress(tcpPortNum));
            _tcpChannelGroup.add(_tcpServerChannel);

            LOG.info("Serving container " + getContainerStaticConfig().getId() + " TCP listener on port "
                    + tcpPortNum);
        }

        _nettyShutdownThread = new NettyShutdownThread();
        Runtime.getRuntime().addShutdownHook(_nettyShutdownThread);

        // Start the producer thread after 5 seconds
        if (null != _jmxConnServer && _containerStaticConfig.getJmx().isRmiEnabled()) {
            try {
                _jmxShutdownThread = new JmxShutdownThread(_jmxConnServer);
                Runtime.getRuntime().addShutdownHook(_jmxShutdownThread);

                _jmxConnServer.start();
                LOG.info("JMX server listening on port " + _containerStaticConfig.getJmx().getJmxServicePort());
            } catch (IOException ioe) {
                if (ioe.getCause() != null && ioe.getCause() instanceof NameAlreadyBoundException) {
                    LOG.warn(
                            "Unable to bind JMX server connector. Likely cause is that the previous instance was not cleanly shutdown: killed in Eclipse?");
                    if (_jmxConnServer.isActive()) {
                        LOG.warn("JMX server connector seems to be running anyway. ");
                    } else {
                        LOG.warn("Unable to determine if JMX server connector is running");
                    }
                } else {
                    LOG.error("Unable to start JMX server connector", ioe);
                }
            }
        }

        _globalStatsThread.start();
    } catch (RuntimeException ex) {
        LOG.error("Got runtime exception :" + ex, ex);
        throw ex;
    } finally {
        _controlLock.unlock();
    }
}