Example usage for java.net URI getPort

List of usage examples for java.net URI getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Returns the port number of this URI.

Usage

From source file:Main.java

public static void main(String[] args) throws NullPointerException, URISyntaxException {
    URI uri = new URI("http://www.java2s.com:8080/yourpath/fileName.htm");
    System.out.println("URI      : " + uri);
    System.out.println(uri.getPort());
}

From source file:com.ibm.crail.namenode.NameNode.java

public static void main(String args[]) throws Exception {
    LOG.info("initalizing namenode ");
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);

    URI uri = CrailUtils.getPrimaryNameNode();
    String address = uri.getHost();
    int port = uri.getPort();

    if (args != null) {
        Option addressOption = Option.builder("a").desc("ip address namenode is started on").hasArg().build();
        Option portOption = Option.builder("p").desc("port namenode is started on").hasArg().build();
        Options options = new Options();
        options.addOption(portOption);/*from   w  w  w  . j a  v a 2s .c o m*/
        options.addOption(addressOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length));
            if (line.hasOption(addressOption.getOpt())) {
                address = line.getOptionValue(addressOption.getOpt());
            }
            if (line.hasOption(portOption.getOpt())) {
                port = Integer.parseInt(line.getOptionValue(portOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Namenode", options);
            System.exit(-1);
        }
    }

    String namenode = "crail://" + address + ":" + port;
    long serviceId = CrailUtils.getServiceId(namenode);
    long serviceSize = CrailUtils.getServiceSize();
    if (!CrailUtils.verifyNamenode(namenode)) {
        throw new Exception("Namenode address/port [" + namenode
                + "] has to be listed in crail.namenode.address " + CrailConstants.NAMENODE_ADDRESS);
    }

    CrailConstants.NAMENODE_ADDRESS = namenode + "?id=" + serviceId + "&size=" + serviceSize;
    CrailConstants.printConf();
    CrailConstants.verify();

    RpcNameNodeService service = RpcNameNodeService.createInstance(CrailConstants.NAMENODE_RPC_SERVICE);
    RpcBinding rpcBinding = RpcBinding.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcBinding.init(conf, null);
    rpcBinding.printConf(LOG);
    rpcBinding.run(service);
    System.exit(0);
    ;
}

From source file:inn.eatery.clientTest.Client.java

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from   w w  w . java 2s . c o  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        l.warn("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                //p.addLast(new HttpClientCodec());
                p.addLast("decoder", new HttpResponseDecoder());
                p.addLast("encoder", new HttpRequestEncoder());

                // Remove the following line if you don't want automatic content decompression.
                // p.addLast(new HttpContentDecompressor());

                // Uncomment the following line if you don't want to handle HttpContents.
                //p.addLast(new HttpObjectAggregator(1048576));

                p.addLast(new ClientHandler());
            }
        });

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        ClientHandler.pubEvent(ch, ClientHandler.event);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
        l.info("Closing Client side Connection !!!");
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);/*from  w w w.  j ava  2  s .  c  o m*/

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    URI u = new URI("http://www.java2s.com");
    System.out.println("The URI is " + u);
    if (u.isOpaque()) {
        System.out.println("This is an opaque URI.");
        System.out.println("The scheme is " + u.getScheme());
        System.out.println("The scheme specific part is " + u.getSchemeSpecificPart());
        System.out.println("The fragment ID is " + u.getFragment());
    } else {//from   ww w .j  av  a 2s  .  co m
        System.out.println("This is a hierarchical URI.");
        System.out.println("The scheme is " + u.getScheme());

        u = u.parseServerAuthority();
        System.out.println("The host is " + u.getUserInfo());
        System.out.println("The user info is " + u.getUserInfo());
        System.out.println("The port is " + u.getPort());
        System.out.println("The path is " + u.getPath());
        System.out.println("The query string is " + u.getQuery());
        System.out.println("The fragment ID is " + u.getFragment());
    }

}

From source file:Main.java

/**
 * Get the port from the <code>URI</code> in iRODS form.
 * /*  w  w  w.  jav a2 s . c  o  m*/
 * @param irodsURI
 *            {@link URI} in the <code>irods://</code> format
 * @return <code>int</code> with the iRODS port.
 */
public static int getPortFromURI(final URI irodsURI) {
    return irodsURI.getPort();
}

From source file:Main.java

public static int getEffectivePort(URI uri) {
    return getEffectivePort(uri.getScheme(), uri.getPort());
}

From source file:Main.java

/**
 * Given an endpoint, calculate the corresponding BrowserID audience.
 * <p>//from w  ww .j av  a  2s . com
 * This is the domain, in web parlance.
 *
 * @param serverURI endpoint.
 * @return BrowserID audience.
 * @throws URISyntaxException
 */
public static String getAudienceForURL(String serverURI) throws URISyntaxException {
    URI uri = new URI(serverURI);
    return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), null, null, null).toString();
}

From source file:cf.service.integration.FunctionalTest.java

private static String localIp(String cloudControllerUri) {
    final URI uri = URI.create(cloudControllerUri);
    final int port = uri.getPort() == -1 ? 80 : uri.getPort();
    try (Socket socket = new Socket(uri.getHost(), port)) {
        return socket.getLocalAddress().getHostAddress();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }//from  w ww.  j  a  v a  2  s .com
}

From source file:org.brutusin.rpc.RpcUtils.java

private static int getPort(URI uri) {
    if (uri.getPort() >= 0) {
        return uri.getPort();
    }//from  ww w .ja  v a2s.com
    if ("http".equals(uri.getScheme())) {
        return 80;
    }
    if ("https".equals(uri.getScheme())) {
        return 443;
    }
    return uri.getPort();
}