Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Returns the host component 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.getHost());
}

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);// ww  w. j  av  a2 s  .  co 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 .  j  a va  2  s .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:dataflow.examples.TransferFiles.java

public static void main(String[] args) throws IOException, URISyntaxException {
    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    List<FilePair> filePairs = new ArrayList<FilePair>();

    URI ftpInput = new URI(options.getInput());

    FTPClient ftp = new FTPClient();
    ftp.connect(ftpInput.getHost());

    // After connection attempt, you should check the reply code to verify
    // success./*from   ww  w . ja v  a2  s  . co m*/
    int reply = ftp.getReplyCode();

    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        logger.error("FTP server refused connection.");
        throw new RuntimeException("FTP server refused connection.");
    }

    ftp.login("anonymous", "someemail@gmail.com");

    String ftpPath = ftpInput.getPath();
    FTPFile[] files = ftp.listFiles(ftpPath);

    URI gcsUri = null;
    if (options.getOutput().endsWith("/")) {
        gcsUri = new URI(options.getOutput());
    } else {
        gcsUri = new URI(options.getOutput() + "/");
    }

    for (FTPFile f : files) {
        logger.info("File: " + f.getName());
        FilePair p = new FilePair();
        p.server = ftpInput.getHost();
        p.ftpPath = f.getName();

        // URI ftpURI = new URI("ftp", p.server, f.getName(), "");
        p.gcsPath = gcsUri.resolve(FilenameUtils.getName(f.getName())).toString();

        filePairs.add(p);
    }

    ftp.logout();

    Pipeline p = Pipeline.create(options);
    PCollection<FilePair> inputs = p.apply(Create.of(filePairs));
    inputs.apply(ParDo.of(new FTPToGCS()).named("CopyToGCS"))
            .apply(AvroIO.Write.withSchema(FilePair.class).to(options.getOutput()));
    p.run();
}

From source file:edu.usc.goffish.gopher.impl.Main.java

public static void main(String[] args) {

    Properties properties = new Properties();
    try {/* w w  w .  ja v  a2 s . c o  m*/
        properties.load(new FileInputStream(CONFIG_FILE));
    } catch (IOException e) {
        String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -"
                + e.getCause();
        log.warning(message);
    }

    if (args.length == 4) {

        PropertiesConfiguration propertiesConfiguration;
        String url = null;

        URI uri = URI.create(args[3]);

        String dataDir = uri.getPath();

        String currentHost = uri.getHost();
        try {

            propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config");
            propertiesConfiguration.load();
            url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY);

        } catch (ConfigurationException e) {

            String message = " Error while reading gofs-config cause -" + e.getCause();
            handleException(message);
        }

        URI nameNodeUri = URI.create(url);

        INameNode nameNode = new RemoteNameNode(nameNodeUri);
        int partition = -1;
        try {
            for (URI u : nameNode.getDataNodes()) {
                if (URIHelper.isLocalURI(u)) {
                    IDataNode dataNode = DataNode.create(u);
                    IntCollection partitions = dataNode.getLocalPartitions(args[2]);
                    partition = partitions.iterator().nextInt();
                    break;
                }
            }

            if (partition == -1) {
                String message = "Partition not loaded from uri : " + nameNodeUri;
                handleException(message);
            }

            properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition));

        } catch (Exception e) {
            String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage();
            e.printStackTrace();
            handleException(message);
        }

        properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1));
        FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment();
        environment.setSystemConfig(properties);
        properties.setProperty(Constants.CURRET_HOST, currentHost);
        String managerHost = args[0];
        int managerPort = Integer.parseInt(args[1]);

        Container container = environment.getContainer();
        container.setManager(managerHost, managerPort);

        DefaultClientConfig config = new DefaultClientConfig();
        config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);
        config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);

        Client c = Client.create(config);

        if (managerHost == null || managerPort == 0) {
            handleException("Manager Host / Port have to be configured in " + args[0]);
        }

        WebResource r = c.resource("http://" + managerHost + ":" + managerPort
                + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId()
                + "/Host=" + container.getContainerInfo().getContainerHost());
        c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
        r.post();
        log.log(Level.INFO, "Container started  ");

    } else {

        String message = "Invalid arguments , arg[0]=Manager host, "
                + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri";

        message += "\n Current Arguments...." + args.length + "\n";
        for (int i = 0; i < args.length; i++) {
            message += "arg " + i + " : " + args[i] + "\n";
        }

        handleException(message);

    }

}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *///  w w  w.j a  v  a  2 s.  c  o m
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:edu.usc.goffish.gofs.tools.GoFSFormat.java

public static void main(String[] args) throws IOException {
    if (args.length < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);/*ww  w .  j  a  v a2  s.  c  o m*/
    }

    if (args.length == 1 && args[0].equals("-help")) {
        PrintUsageAndQuit(null);
    }

    Path executableDirectory;
    try {
        executableDirectory = Paths
                .get(GoFSFormat.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unexpected error retrieving executable location", e);
    }
    Path configPath = executableDirectory.resolve(DEFAULT_CONFIG).normalize();

    boolean copyBinaries = false;

    // parse optional arguments
    int i = 0;
    OptArgLoop: for (i = 0; i < args.length - REQUIRED_ARGS; i++) {
        switch (args[i]) {
        case "-config":
            i++;

            try {
                configPath = Paths.get(args[i]);
            } catch (InvalidPathException e) {
                PrintUsageAndQuit("Config file - " + e.getMessage());
            }

            break;
        case "-copyBinaries":
            copyBinaries = true;
            break;
        default:
            break OptArgLoop;
        }
    }

    if (args.length - i < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);
    }

    // finished parsing args
    if (i < args.length) {
        PrintUsageAndQuit("Unrecognized argument \"" + args[i] + "\"");
    }

    // parse config

    System.out.println("Parsing config...");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setDelimiterParsingDisabled(true);
    try {
        config.load(Files.newInputStream(configPath));
    } catch (ConfigurationException e) {
        throw new IOException(e);
    }

    // retrieve data nodes
    ArrayList<URI> dataNodes;
    {
        String[] dataNodesArray = config.getStringArray(GOFS_DATANODES_KEY);
        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config must contain key " + GOFS_DATANODES_KEY);
        }

        dataNodes = new ArrayList<>(dataNodesArray.length);

        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config key " + GOFS_DATANODES_KEY
                    + " has invalid format - must define at least one data node");
        }

        try {
            for (String node : dataNodesArray) {
                URI dataNodeURI = new URI(node);

                if (!"file".equalsIgnoreCase(dataNodeURI.getScheme())) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have 'file' scheme");
                } else if (dataNodeURI.getPath() == null || dataNodeURI.getPath().isEmpty()) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have an absolute path specified");
                }

                // ensure uri ends with a slash, so we know it is a directory
                if (!dataNodeURI.getPath().endsWith("/")) {
                    dataNodeURI = dataNodeURI.resolve(dataNodeURI.getPath() + "/");
                }

                dataNodes.add(dataNodeURI);
            }
        } catch (URISyntaxException e) {
            throw new ConversionException(
                    "Config key " + GOFS_DATANODES_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // validate serializer type
    Class<? extends ISliceSerializer> serializerType;
    {
        String serializerTypeName = config.getString(GOFS_SERIALIZER_KEY);
        if (serializerTypeName == null) {
            throw new ConversionException("Config must contain key " + GOFS_SERIALIZER_KEY);
        }

        try {
            serializerType = SliceSerializerProvider.loadSliceSerializerType(serializerTypeName);
        } catch (ReflectiveOperationException e) {
            throw new ConversionException(
                    "Config key " + GOFS_SERIALIZER_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // retrieve name node
    IInternalNameNode nameNode;
    try {
        nameNode = NameNodeProvider.loadNameNodeFromConfig(config, GOFS_NAMENODE_TYPE_KEY,
                GOFS_NAMENODE_LOCATION_KEY);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to load name node", e);
    }

    System.out.println("Contacting name node...");

    // validate name node
    if (!nameNode.isAvailable()) {
        throw new IOException("Name node at " + nameNode.getURI() + " is not available");
    }

    System.out.println("Contacting data nodes...");

    // validate data nodes
    for (URI dataNode : dataNodes) {
        // only attempt ssh if host exists
        if (dataNode.getHost() != null) {
            try {
                SSHHelper.SSH(dataNode, "true");
            } catch (IOException e) {
                throw new IOException("Data node at " + dataNode + " is not available", e);
            }
        }
    }

    // create temporary directory
    Path workingDir = Files.createTempDirectory("gofs_format");
    try {
        // create deploy directory
        Path deployDirectory = Files.createDirectory(workingDir.resolve(DATANODE_DIR_NAME));

        // create empty slice directory
        Files.createDirectory(deployDirectory.resolve(DataNode.DATANODE_SLICE_DIR));

        // copy binaries
        if (copyBinaries) {
            System.out.println("Copying binaries...");
            FileUtils.copyDirectory(executableDirectory.toFile(),
                    deployDirectory.resolve(executableDirectory.getFileName()).toFile());
        }

        // write config file
        Path dataNodeConfigFile = deployDirectory.resolve(DataNode.DATANODE_CONFIG);
        try {
            // create config for every data node and scp deploy folder into place
            for (URI dataNodeParent : dataNodes) {
                URI dataNode = dataNodeParent.resolve(DATANODE_DIR_NAME);

                PropertiesConfiguration datanode_config = new PropertiesConfiguration();
                datanode_config.setDelimiterParsingDisabled(true);
                datanode_config.setProperty(DataNode.DATANODE_INSTALLED_KEY, true);
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_TYPE_KEY,
                        config.getString(GOFS_NAMENODE_TYPE_KEY));
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_LOCATION_KEY,
                        config.getString(GOFS_NAMENODE_LOCATION_KEY));
                datanode_config.setProperty(DataNode.DATANODE_LOCALHOSTURI_KEY, dataNode.toString());

                try {
                    datanode_config.save(Files.newOutputStream(dataNodeConfigFile));
                } catch (ConfigurationException e) {
                    throw new IOException(e);
                }

                System.out.println("Formatting data node " + dataNode.toString() + "...");

                // scp everything into place on the data node
                SCPHelper.SCP(deployDirectory, dataNodeParent);

                // update name node
                nameNode.addDataNode(dataNode);
            }

            // update name node
            nameNode.setSerializer(serializerType);
        } catch (Exception e) {
            System.out.println(
                    "ERROR: data node formatting interrupted - name node and data nodes are in an inconsistent state and require clean up");
            throw e;
        }

        System.out.println("GoFS format complete");

    } finally {
        FileUtils.deleteQuietly(workingDir.toFile());
    }
}

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 www.  j a v  a2 s  . co  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:Main.java

/**
 * Get the host (if available) from the <code>URI</code> in iRODS form.
 * //from w  ww. j  av  a 2 s  .  c  o m
 * @param irodsURI
 *            {@link URI} in the <code>irods://</code> format
 * @return <code>String</code> with the iRODS host, or <code>null</code> if
 *         not available.
 */
public static String getHostFromURI(final URI irodsURI) {
    return irodsURI.getHost();
}

From source file:Main.java

public static String urlFromRequest(URI paramURI) {
    return paramURI.getScheme() + "://" + paramURI.getHost() + paramURI.getPath();
}