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:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

private ProxyHost getProxyHost() {
    ProxyHost theProxyHost = null;//w w w. j  ava 2s . c  om
    ProxySelector ps = ProxySelector.getDefault();
    List<Proxy> p = null;
    // select the proxy for the URI of this repository
    try {
        if (ps != null) {
            // log.info( "Getting Proxy List." );
            p = ps.select(new java.net.URI(this.servletURL));
        }
    } catch (Exception e) {
        // log.warn( "Exception getting proxy: " + e.toString() );
    }
    if (p == null) {
        // log.warn( "No proxy information available." );
    } else {
        // log.info( "Received proxy list: " + p.toString() );
        Iterator<Proxy> proxies = p.iterator();
        // just take the first for now
        if (proxies != null && proxies.hasNext()) {
            Proxy theProxy = (Proxy) proxies.next();
            // log.info( "Proxy set to: " + theProxy.toString() );
            if (!Proxy.NO_PROXY.equals(theProxy)) {
                InetSocketAddress theSock = (InetSocketAddress) theProxy.address();
                theProxyHost = new ProxyHost(theSock.getHostName(), theSock.getPort());
            }
        } else {
            // log.warn( "Proxy list has zero members." );
        }
    }
    return theProxyHost;
}

From source file:org.apache.hama.bsp.TaskRunner.java

private List<String> buildJvmArgs(BSPJob jobConf, String classPath, Class<?> child) {
    // Build exec child jmv args.
    List<String> vargs = new ArrayList<String>();
    File jvm = // use same jvm as parent
            new File(new File(System.getProperty("java.home"), "bin"), "java");
    vargs.add(jvm.toString());//  w  w w .ja v a  2 s .c  o m

    // bsp.child.java.opts
    String javaOpts = jobConf.getConfiguration().get("bsp.child.java.opts", "-Xmx200m");
    javaOpts = javaOpts.replace("@taskid@", task.getTaskID().toString());

    String[] javaOptsSplit = javaOpts.split(" ");
    Collections.addAll(vargs, javaOptsSplit);

    // Add classpath.
    vargs.add("-classpath");
    vargs.add(classPath);
    // Add main class and its arguments
    LOG.debug("Executing child Process " + child.getName());
    vargs.add(child.getName()); // bsp class name

    if (GroomServer.BSPPeerChild.class.equals(child)) {
        InetSocketAddress addr = groomServer.getTaskTrackerReportAddress();
        vargs.add(addr.getHostName());
        vargs.add(Integer.toString(addr.getPort()));
        vargs.add(task.getTaskID().toString());
        vargs.add(groomServer.groomHostName);
        vargs.add(Long.toString(groomServer.getStartSuperstep(task.getTaskID())));
        TaskStatus status = groomServer.getTaskStatus(task.getTaskID());

        if (status != null && TaskStatus.State.RECOVERING.equals(status.getRunState())) {
            vargs.add(TaskStatus.State.RECOVERING.name());
        } else {
            vargs.add(TaskStatus.State.RUNNING.name());
        }

    }
    return vargs;
}

From source file:com.joyent.manta.http.MantaConnectionFactory.java

/**
 * Finds the host of the proxy server that was configured as part of the
 * JVM settings.//  w w w.j av a2s.  com
 *
 * @return proxy server as {@link HttpHost}, if no proxy then null
 */
protected HttpHost findProxyServer() {
    final ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> proxies = proxySelector.select(URI.create(config.getMantaURL()));

    if (!proxies.isEmpty()) {
        /* The Apache HTTP Client doesn't understand the concept of multiple
         * proxies, so we use only the first one returned. */
        final Proxy proxy = proxies.get(0);

        switch (proxy.type()) {
        case DIRECT:
            return null;
        case SOCKS:
            throw new ConfigurationException("SOCKS proxies are unsupported");
        default:
            // do nothing and fall through
        }

        if (proxy.address() instanceof InetSocketAddress) {
            InetSocketAddress sa = (InetSocketAddress) proxy.address();

            return new HttpHost(sa.getHostName(), sa.getPort());
        } else {
            String msg = String.format(
                    "Expecting proxy to be instance of InetSocketAddress. " + " Actually: %s", proxy.address());
            throw new ConfigurationException(msg);
        }
    } else {
        return null;
    }
}

From source file:co.elastic.tealess.SSLChecker.java

private void checkHandshake(SSLReport sslReport, SocketChannel socket) {
    final InetSocketAddress address = sslReport.getAddress();
    final String name = sslReport.getHostname();
    IOObserver ioObserver = new IOObserver();
    ObservingSSLEngine sslEngine = new ObservingSSLEngine(ctx.createSSLEngine(name, address.getPort()),
            ioObserver);//ww w.j av  a  2s .  co m
    sslReport.setIOObserver(ioObserver);
    sslEngine.setUseClientMode(true);

    try {
        sslEngine.beginHandshake();
    } catch (SSLException e) {
        sslReport.setFailed(e);
        Throwable cause = Blame.get(e);
        logger.warn("beginHandshake failed: [{}] {}", cause.getClass(), cause.getMessage());
    }

    // TODO: Is this enough bytes?
    int size = sslEngine.getSession().getApplicationBufferSize() * 2;
    ByteBuffer localText = ByteBuffer.allocate(size);
    ByteBuffer localWire = ByteBuffer.allocate(size);
    ByteBuffer peerText = ByteBuffer.allocate(size);
    ByteBuffer peerWire = ByteBuffer.allocate(size);

    // TODO: I wonder... do we need to send any data at all?
    localText.put("SSL TEST. HELLO.".getBytes());
    localText.flip();

    SSLEngineResult result;
    logger.info("Starting SSL handshake [{}] ", address);
    try {
        SSLEngineResult.HandshakeStatus state;
        state = sslEngine.getHandshakeStatus();
        while (state != FINISHED) {
            // XXX: Use a Selector to wait for data.
            //logger.trace("State: {} [{}]", state, address);
            switch (state) {
            case NEED_TASK:
                sslEngine.getDelegatedTask().run();
                state = sslEngine.getHandshakeStatus();
                break;
            case NEED_WRAP:
                localWire.clear();
                result = sslEngine.wrap(localText, localWire);
                state = result.getHandshakeStatus();
                localWire.flip();
                while (localWire.hasRemaining()) {
                    socket.write(localWire);
                    //logger.trace("Sent {} bytes [{}]", bytes, address);
                }
                localWire.compact();
                break;
            case NEED_UNWRAP:
                // Try reading until we get data.
                Selector selector = Selector.open();
                while (peerWire.position() == 0) {
                    socket.read(peerWire);
                    try {
                        Thread.currentThread().sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Read " + peerWire.position() + " bytes");
                peerWire.flip();
                result = sslEngine.unwrap(peerWire, peerText);
                state = result.getHandshakeStatus();
                peerWire.compact();
                break;
            }
        }
    } catch (IOException e) {
        sslReport.setFailed(e);
        sslReport.setSSLSession(sslEngine.getHandshakeSession());
        sslReport.setPeerCertificateDetails(peerCertificateDetails);
        logger.warn("beginHandshake failed", e);
        return;
    }

    logger.info("handshake completed [{}]", address);

    // Handshake OK!
    sslReport.setSSLSession(sslEngine.getSession());
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.SNIHttpClientConnection.java

private HttpClient getClient() {
    if (client == null)
        client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        isUsingProxy = true;/* ww w.j a v  a2 s .c o m*/
        InetSocketAddress adr = (InetSocketAddress) proxy.address();
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(adr.getHostName(), adr.getPort()));
    }
    if (timeout != null)
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout.intValue());
    if (readTimeout != null)
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout.intValue());
    if (followRedirects != null)
        params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects.booleanValue());
    SSLSocketFactory sf = hostnameverifier != null ? new SNISSLSocketFactory(getSSLContext(), hostnameverifier)
            : new SNISSLSocketFactory(getSSLContext());
    Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
    client.getConnectionManager().getSchemeRegistry().register(https);
    return client;
}

From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;//from  w ww  . j  a v a2 s  . c o  m
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}

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

@Override
public void init(DaemonContext context) throws Exception {
    System.err.println("Initializing secure datanode resources");
    // We should only start up a secure datanode in a Kerberos-secured cluster
    Configuration conf = new Configuration(); // Skip UGI method to not log in
    if (!conf.get(HADOOP_SECURITY_AUTHENTICATION).equals("kerberos"))
        throw new RuntimeException("Cannot start secure datanode in unsecure cluster");

    // Stash command-line arguments for regular datanode
    args = context.getArguments();//from w w w  .j a v a 2 s  .co m

    // Obtain secure port for data streaming to datanode
    InetSocketAddress socAddr = DataNode.getStreamingAddr(conf);
    int socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT);

    ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
    ss.bind(socAddr, 0);

    // Check that we got the port we need
    if (ss.getLocalPort() != socAddr.getPort())
        throw new RuntimeException("Unable to bind on specified streaming port in secure " + "context. Needed "
                + socAddr.getPort() + ", got " + ss.getLocalPort());

    // Obtain secure listener for web server
    SelectChannelConnector listener = (SelectChannelConnector) HttpServer.createDefaultChannelConnector();
    InetSocketAddress infoSocAddr = DataNode.getInfoAddr(conf);
    listener.setHost(infoSocAddr.getHostName());
    listener.setPort(infoSocAddr.getPort());
    // Open listener here in order to bind to port as root
    listener.open();
    if (listener.getPort() != infoSocAddr.getPort())
        throw new RuntimeException("Unable to bind on specified info port in secure " + "context. Needed "
                + socAddr.getPort() + ", got " + ss.getLocalPort());

    if (ss.getLocalPort() >= 1023 || listener.getPort() >= 1023)
        throw new RuntimeException(
                "Cannot start secure datanode on non-privileged " + " ports. (streaming port = " + ss
                        + " ) (http listener port = " + listener.getConnection() + "). Exiting.");

    System.err.println("Successfully obtained privileged resources (streaming port = " + ss
            + " ) (http listener port = " + listener.getConnection() + ")");

    resources = new SecureResources(ss, listener);
}

From source file:org.apache.hadoop.hdfs.tools.TestGetConf.java

/**
 * Using {@link GetConf} methods get the list of given {@code type} of
 * addresses// ww  w . j  ava  2s.c om
 * 
 * @param type, TestType
 * @param conf, configuration
 * @param checkPort, If checkPort is true, verify NNPRCADDRESSES whose 
 *      expected value is hostname:rpc-port.  If checkPort is false, the 
 *      expected is hostname only.
 * @param expected, expected addresses
 */
private void getAddressListFromTool(TestType type, HdfsConfiguration conf, boolean checkPort,
        List<InetSocketAddress> expected) throws Exception {
    String out = getAddressListFromTool(type, conf, expected.size() != 0);
    List<String> values = new ArrayList<String>();

    // Convert list of addresses returned to an array of string
    StringTokenizer tokenizer = new StringTokenizer(out);
    while (tokenizer.hasMoreTokens()) {
        String s = tokenizer.nextToken().trim();
        values.add(s);
    }
    String[] actual = values.toArray(new String[values.size()]);

    // Convert expected list to String[] of hosts
    int i = 0;
    String[] expectedHosts = new String[expected.size()];
    for (InetSocketAddress addr : expected) {
        if (!checkPort) {
            expectedHosts[i++] = addr.getHostName();
        } else {
            expectedHosts[i++] = addr.getHostName() + ":" + addr.getPort();
        }
    }

    // Compare two arrays
    assertTrue(Arrays.equals(expectedHosts, actual));
}

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

/**
 * This test makes sure that we have a valid
 * Node ID after the checkNodeUUID is done.
 *//*from  w  ww .  j av  a 2  s  .c  om*/
@Test
public void testDatanodeUuid() throws Exception {

    final InetSocketAddress NN_ADDR = new InetSocketAddress("localhost", 5020);
    Configuration conf = new HdfsConfiguration();
    conf.set(DFSConfigKeys.DFS_DATANODE_ADDRESS_KEY, "0.0.0.0:0");
    conf.set(DFSConfigKeys.DFS_DATANODE_HTTP_ADDRESS_KEY, "0.0.0.0:0");
    conf.set(DFSConfigKeys.DFS_DATANODE_IPC_ADDRESS_KEY, "0.0.0.0:0");
    FileSystem.setDefaultUri(conf, "hdfs://" + NN_ADDR.getHostName() + ":" + NN_ADDR.getPort());
    ArrayList<StorageLocation> locations = new ArrayList<>();

    DataNode dn = new DataNode(conf, locations, null);

    //Assert that Node iD is null
    String nullString = null;
    assertEquals(dn.getDatanodeUuid(), nullString);

    // CheckDataNodeUUID will create an UUID if UUID is null
    dn.checkDatanodeUuid();

    // Make sure that we have a valid DataNodeUUID at that point of time.
    assertNotEquals(dn.getDatanodeUuid(), nullString);
}

From source file:org.apache.hadoop.hdfs.server.namenode.StandbyNew.java

/**
 * Initialize the webserver so that the primary namenode can fetch
 * transaction logs from standby via http.
 *//*  ww  w.j a  v  a  2  s . c  o m*/
void initSecondary(Configuration conf) throws IOException {

    nameNodeAddr = AvatarNode.getRemoteNamenodeAddress(conf);
    this.primaryNamenode = (NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
            NamenodeProtocol.versionID, nameNodeAddr, conf);

    fsName = AvatarNode.getRemoteNamenodeHttpName(conf);

    // 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 HttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf);
    infoServer.setAttribute("name.system.image", fsImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addInternalServlet("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)");
}