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.namenode.AvatarNode.java

/**
 * Returns the hostname:port for the AvatarNode. The default
 * port for the AvatarNode is (the client RPC port 
 * of the underlying namenode + 1)/*  w  ww.  ja v  a2  s.c om*/
 */
public static InetSocketAddress getAddress(Configuration conf) {
    InetSocketAddress u = NameNode.getClientProtocolAddress(conf);
    int port = conf.getInt(AvatarNode.DFS_AVATARNODE_PORT_KEY, u.getPort() + 1);
    return new InetSocketAddress(u.getAddress(), port);
}

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

/**
 * Return a HttpServer.Builder that the journalnode / namenode / secondary
 * namenode can use to initialize their HTTP / HTTPS server.
 * <p>/*from   w  w w  . ja v a  2  s . c  o m*/
 */
public static HttpServer3.Builder httpServerTemplateForNNAndJN(Configuration conf,
        final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name,
        String spnegoUserNameKey, String spnegoKeytabFileKey) throws IOException {
    HttpConfig.Policy policy = getHttpPolicy(conf);

    HttpServer3.Builder builder = new HttpServer3.Builder().setName(name).setConf(conf)
            .setACL(new AccessControlList(conf.get(DFS_ADMIN, " ")))
            .setSecurityEnabled(UserGroupInformation.isSecurityEnabled()).setUsernameConfKey(spnegoUserNameKey)
            .setKeytabConfKey(getSpnegoKeytabKey(conf, spnegoKeytabFileKey));

    // initialize the webserver for uploading/downloading files.
    if (UserGroupInformation.isSecurityEnabled()) {
        LOG.info("Starting web server as: "
                + SecurityUtil.getServerPrincipal(conf.get(spnegoUserNameKey), httpAddr.getHostName()));
    }

    if (policy.isHttpEnabled()) {
        if (httpAddr.getPort() == 0) {
            builder.setFindPort(true);
        }

        URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr));
        builder.addEndpoint(uri);
        LOG.info("Starting Web-server for " + name + " at: " + uri);
    }

    if (policy.isHttpsEnabled() && httpsAddr != null) {
        Configuration sslConf = loadSslConfiguration(conf);
        loadSslConfToHttpServerBuilder(builder, sslConf);

        if (httpsAddr.getPort() == 0) {
            builder.setFindPort(true);
        }

        URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr));
        builder.addEndpoint(uri);
        LOG.info("Starting Web-server for " + name + " at: " + uri);
    }
    return builder;
}

From source file:net.pms.network.RequestHandlerV2.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    RequestV2 request = null;//from ww w  . ja  v a2s  .c  o  m
    RendererConfiguration renderer = null;
    String userAgentString = null;
    ArrayList<String> identifiers = new ArrayList<>();

    HttpRequest nettyRequest = this.nettyRequest = (HttpRequest) e.getMessage();

    InetSocketAddress remoteAddress = (InetSocketAddress) e.getChannel().getRemoteAddress();
    InetAddress ia = remoteAddress.getAddress();

    // Is the request from our own Cling service, i.e. self-originating?
    boolean isSelf = ia.getHostAddress().equals(PMS.get().getServer().getHost())
            && nettyRequest.headers().get(HttpHeaders.Names.USER_AGENT) != null
            && nettyRequest.headers().get(HttpHeaders.Names.USER_AGENT).contains("UMS/");

    // Filter if required
    if (isSelf || filterIp(ia)) {
        e.getChannel().close();
        LOGGER.trace(isSelf ? ("Ignoring self-originating request from " + ia + ":" + remoteAddress.getPort())
                : ("Access denied for address " + ia + " based on IP filter"));
        return;
    }

    LOGGER.trace("Opened request handler on socket " + remoteAddress);
    PMS.get().getRegistry().disableGoToSleep();
    request = new RequestV2(nettyRequest.getMethod().getName(), nettyRequest.getUri().substring(1));
    LOGGER.trace("Request: " + nettyRequest.getProtocolVersion().getText() + " : " + request.getMethod() + " : "
            + request.getArgument());

    if (nettyRequest.getProtocolVersion().getMinorVersion() == 0) {
        request.setHttp10(true);
    }

    HttpHeaders headers = nettyRequest.headers();

    // The handler makes a couple of attempts to recognize a renderer from its requests.
    // IP address matches from previous requests are preferred, when that fails request
    // header matches are attempted and if those fail as well we're stuck with the
    // default renderer.

    // Attempt 1: try to recognize the renderer by its socket address from previous requests
    renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);

    // If the renderer exists but isn't marked as loaded it means it's unrecognized
    // by upnp and we still need to attempt http recognition here.
    if (renderer == null || !renderer.loaded) {
        // Attempt 2: try to recognize the renderer by matching headers
        renderer = RendererConfiguration.getRendererConfigurationByHeaders(headers.entries(), ia);
    }

    if (renderer != null) {
        request.setMediaRenderer(renderer);
    }

    Set<String> headerNames = headers.names();
    Iterator<String> iterator = headerNames.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        String headerLine = name + ": " + headers.get(name);
        LOGGER.trace("Received on socket: " + headerLine);

        if (headerLine.toUpperCase().startsWith("USER-AGENT")) {
            userAgentString = headerLine.substring(headerLine.indexOf(':') + 1).trim();
        }

        try {
            StringTokenizer s = new StringTokenizer(headerLine);
            String temp = s.nextToken();
            if (temp.toUpperCase().equals("SOAPACTION:")) {
                request.setSoapaction(s.nextToken());
            } else if (temp.toUpperCase().equals("CALLBACK:")) {
                request.setSoapaction(s.nextToken());
            } else if (headerLine.toUpperCase().contains("RANGE: BYTES=")) {
                String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13)
                        .trim();
                StringTokenizer st = new StringTokenizer(nums, "-");
                if (!nums.startsWith("-")) {
                    request.setLowRange(Long.parseLong(st.nextToken()));
                }
                if (!nums.startsWith("-") && !nums.endsWith("-")) {
                    request.setHighRange(Long.parseLong(st.nextToken()));
                } else {
                    request.setHighRange(-1);
                }
            } else if (headerLine.toLowerCase().contains("transfermode.dlna.org:")) {
                request.setTransferMode(headerLine
                        .substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
            } else if (headerLine.toLowerCase().contains("getcontentfeatures.dlna.org:")) {
                request.setContentFeatures(headerLine
                        .substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28)
                        .trim());
            } else {
                Matcher matcher = TIMERANGE_PATTERN.matcher(headerLine);
                if (matcher.find()) {
                    String first = matcher.group(1);
                    if (first != null) {
                        request.setTimeRangeStartString(first);
                    }
                    String end = matcher.group(2);
                    if (end != null) {
                        request.setTimeRangeEndString(end);
                    }
                } else {
                    /** If we made it to here, none of the previous header checks matched.
                     * Unknown headers make interesting logging info when we cannot recognize
                     * the media renderer, so keep track of the truly unknown ones.
                     */
                    boolean isKnown = false;

                    // Try to match known headers.
                    String lowerCaseHeaderLine = headerLine.toLowerCase();
                    for (String knownHeaderString : KNOWN_HEADERS) {
                        if (lowerCaseHeaderLine.startsWith(knownHeaderString)) {
                            isKnown = true;
                            break;
                        }
                    }

                    // It may be unusual but already known
                    if (!isKnown && renderer != null) {
                        String additionalHeader = renderer.getUserAgentAdditionalHttpHeader();
                        if (StringUtils.isNotBlank(additionalHeader)
                                && lowerCaseHeaderLine.startsWith(additionalHeader)) {
                            isKnown = true;
                        }
                    }

                    if (!isKnown) {
                        // Truly unknown header, therefore interesting. Save for later use.
                        identifiers.add(headerLine);
                    }
                }
            }
        } catch (Exception ee) {
            LOGGER.error("Error parsing HTTP headers", ee);
        }
    }

    // Still no media renderer recognized?
    if (renderer == null) {

        // Attempt 3: Not really an attempt; all other attempts to recognize
        // the renderer have failed. The only option left is to assume the
        // default renderer.
        renderer = RendererConfiguration.resolve(ia, null);
        request.setMediaRenderer(renderer);
        if (renderer != null) {
            LOGGER.trace("Using default media renderer: " + renderer.getConfName());

            if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
                // We have found an unknown renderer
                identifiers.add(0, "User-Agent: " + userAgentString);
                renderer.setIdentifiers(identifiers);
                LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers:"
                        + StringUtils.join(identifiers, ", "));
                PMS.get().setRendererFound(renderer);
            }
        } else {
            // If RendererConfiguration.resolve() didn't return the default renderer
            // it means we know via upnp that it's not really a renderer.
            return;
        }
    } else {
        if (userAgentString != null) {
            LOGGER.trace("HTTP User-Agent: " + userAgentString);
        }

        LOGGER.trace("Recognized media renderer: " + renderer.getRendererName());
    }

    if (nettyRequest.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) {
        byte data[] = new byte[(int) HttpHeaders.getContentLength(nettyRequest)];
        ChannelBuffer content = nettyRequest.getContent();
        content.readBytes(data);
        request.setTextContent(new String(data, "UTF-8"));
    }

    LOGGER.trace(
            "HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-" + request.getHighRange());

    writeResponse(ctx, e, request, ia);
}

From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java

public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);// w  ww .  j a  v a 2 s  .c  o  m
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);//from   w ww.j  av a2s.c o  m
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName(), context);
        return sock;
    } else
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
}

From source file:edu.umass.cs.msocket.gns.GnsIntegration.java

/**
 * Register any globally unique Human Readable Name in the GNS and create a
 * field with the same name in that GUID to store the InetSocketAddress
 * information.//from ww  w .  j  a  v a  2s  . co  m
 * 
 * @param name Human readable name of the service (needs to be unique
 *          GNS-wide)
 * @param saddr The IP address to store for this service
 * @param credentials The GNS credentials to use, usually the account GUID and
 *          default GNS (if null default GNS credentials are used)
 * @throws IOException
 */
public static void registerWithGNS(String name, InetSocketAddress saddr, GnsCredentials credentials)
        throws IOException {
    try {
        if (credentials == null)
            credentials = GnsCredentials.getDefaultCredentials();

        log.trace("Looking for entity " + name + " GUID and certificates...");

        GuidEntry myGuid = KeyPairUtils
                .getGuidEntryFromPreferences(credentials.getGnsHost() + ":" + credentials.getGnsPort(), name);
        final UniversalGnsClient gnsClient = credentials.getGnsClient();

        /*
         * Take a lock on the GNS connection object to prevent concurrent queries to
         * the GNS on the same connection as the library is not thread-safe from
         * that standpoint.
         */
        synchronized (gnsClient) {
            if (myGuid == null) {
                System.out.println("No keys found for service " + name + ". Generating new GUID and keys");
                // Create a new GUID
                myGuid = gnsClient.guidCreate(credentials.getGuidEntry(), name);

                // save keys in the preference
                System.out.println("saving keys to local");
                KeyPairUtils.saveKeyPairToPreferences(KeyPairUtils.getDefaultGnsFromPreferences(),
                        myGuid.getEntityName(), myGuid.getGuid(),
                        new KeyPair(myGuid.getPublicKey(), myGuid.getPrivateKey()));

                // storing alias in gns record, need it to find it when we have GUID
                // from group members
                gnsClient.fieldCreate(myGuid.getGuid(), GnsConstants.ALIAS_FIELD, new JSONArray().put(name),
                        myGuid);
            }

            // Put the IP address in the GNS
            String ipPort = saddr.getAddress().getHostAddress() + ":" + saddr.getPort();
            log.trace("Updating " + GnsConstants.SERVER_REG_ADDR + " GNSValue " + ipPort);
            gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVER_REG_ADDR,
                    new JSONArray().put(ipPort), myGuid);
        }
    } catch (Exception ex) {
        throw new IOException(ex);
    }
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

private void updateStatusView() {
    OperandoProxyStatus proxyStatus = OperandoProxyStatus.STOPPED;
    OperandoProxyLink proxyLink = OperandoProxyLink.INVALID;
    boolean isProxyRunning = MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class);
    boolean isProxyPaused = MainUtil.isProxyPaused(mainContext);
    if (isProxyRunning) {
        if (isProxyPaused) {
            proxyStatus = OperandoProxyStatus.PAUSED;
        } else {/*w w  w .j  a va 2 s.c o m*/
            proxyStatus = OperandoProxyStatus.ACTIVE;
        }
    }
    try {
        Proxy proxy = APL.getCurrentHttpProxyConfiguration();
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        if (proxyAddress != null) {
            //TODO: THIS SHOULD BE DYNAMIC
            String proxyHost = proxyAddress.getHostName();
            int proxyPort = proxyAddress.getPort();

            if (proxyHost.equals("127.0.0.1") && proxyPort == 8899) {
                proxyLink = OperandoProxyLink.VALID;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    String info = "";
    try {
        InputStream is = getResources().openRawResource(R.raw.info_template);
        info = IOUtils.toString(is);
        IOUtils.closeQuietly(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    info = info.replace("@@status@@", proxyStatus.name());
    info = info.replace("@@link@@", proxyLink.name());
    webView.loadDataWithBaseURL("", info, "text/html", "UTF-8", "");
    webView.setBackgroundColor(Color.TRANSPARENT); //TRANSPARENT
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

protected Server createServer(int port, boolean serverSsl, boolean clientSsl) {
    Server server = new Server();
    if (!serverSsl) {
        InetSocketAddress addr = new InetSocketAddress("localhost", port);
        ServerConnector connector = new ServerConnector(server);
        connector.setHost(addr.getHostName());
        connector.setPort(addr.getPort());
        server.setConnectors(new Connector[] { connector });
    } else {//  w  w w .j av a 2s . c o m
        SslContextFactory sslContextFactory = createSslContextFactory(clientSsl);
        ServerConnector httpsConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory());
        httpsConnector.setPort(port);
        httpsConnector.setHost("localhost");
        server.setConnectors(new Connector[] { httpsConnector });
    }
    return server;
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;//w ww . j ava  2  s. com
    }

    final Proxy proxy;

    if (proxyConfig != null) {
        URI hostURI = URI.create(host);
        proxy = proxyConfig.createProxy(hostURI.getHost());
    } else {
        proxy = Proxy.NO_PROXY;
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.log(Level.FINE, "Jenkins proxy: {0}", proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}

From source file:org.apache.hadoop.ipc.TestSaslRPC.java

public void testDigestAuthMethod(boolean useIp) throws Exception {
    setTokenServiceUseIp(useIp);/* w  w  w .  j  a  va2 s . c om*/

    TestTokenSecretManager sm = new TestTokenSecretManager();
    Server server = RPC.getServer(new TestSaslImpl(), ADDRESS, 0, 5, true, conf, sm);
    server.start();

    final UserGroupInformation current = UserGroupInformation.getCurrentUser();
    final InetSocketAddress addr = NetUtils.getConnectAddress(server);
    TestTokenIdentifier tokenId = new TestTokenIdentifier(new Text(current.getUserName()));
    Token<TestTokenIdentifier> token = new Token<TestTokenIdentifier>(tokenId, sm);
    SecurityUtil.setTokenService(token, addr);
    LOG.info("Service IP address for token is " + token.getService());

    InetSocketAddress tokenAddr = SecurityUtil.getTokenServiceAddr(token);
    String expectedHost, gotHost;
    if (useIp) {
        expectedHost = addr.getAddress().getHostAddress();
        gotHost = tokenAddr.getAddress().getHostAddress();
    } else {
        gotHost = tokenAddr.getHostName();
        expectedHost = ADDRESS;
    }
    Assert.assertEquals(expectedHost, gotHost);
    Assert.assertEquals(expectedHost + ":" + addr.getPort(), token.getService().toString());

    current.addToken(token);

    current.doAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws IOException {
            TestSaslProtocol proxy = null;
            try {
                proxy = (TestSaslProtocol) RPC.getProxy(TestSaslProtocol.class, TestSaslProtocol.versionID,
                        addr, conf);
                Assert.assertEquals(AuthenticationMethod.TOKEN, proxy.getAuthMethod());
            } finally {
                if (proxy != null) {
                    RPC.stopProxy(proxy);
                }
            }
            return null;
        }
    });
    server.stop();
}