Example usage for java.net URI getScheme

List of usage examples for java.net URI getScheme

Introduction

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

Prototype

public String getScheme() 

Source Link

Document

Returns the scheme 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.getScheme());
}

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 av  a 2  s.  com*/
        } 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: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 {//w  w w . j  av  a 2s.c o 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: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 ww.ja  v  a  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:com.github.pierods.ramltoapidocconverter.RAMLToApidocConverter.java

public static void main(String[] args) throws IOException, URISyntaxException {

    OptionParser optionParser = new OptionParser("h");

    optionParser.accepts("raml").withRequiredArg();
    optionParser.accepts("apidoc").withRequiredArg();
    optionParser.accepts("version");
    optionParser.accepts("help");

    OptionSet optionSet = optionParser.parse(args);

    if (optionSet.has("help") || optionSet.has("h")) {
        System.out.println("Usage: -raml uri of raml " + "-apidoc name of apidoc file /n" + "or /"
                + "-raml uri of raml -version");
        System.exit(0);//from ww w . j ava  2 s  .  c  o m
    }

    if (!optionSet.has("raml")) {
        System.out.println("Missing raml option");
        System.exit(-1);
    }

    URI uri = new URI((String) optionSet.valueOf("raml"));

    if (uri.getScheme() == null) {
        System.out.println("Bad raml uri - should be file:// or http:// ");
        System.exit(-1);
    }

    RAMLToApidocConverter instance = new RAMLToApidocConverter();

    if (optionSet.has("version")) {
        System.out.print(instance.getVersion((String) optionSet.valueOf("raml")));
        return;
    }

    String data = instance.convert((String) optionSet.valueOf("raml"));
    if (optionSet.has("apidoc")) {
        Files.write(Paths.get((String) optionSet.valueOf("apidoc")), data.getBytes());
    } else {
        System.out.print(data);
    }

}

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);//from  w  ww .j  av a 2 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:fr.cls.atoll.motu.processor.wps.StringList.java

/**
 * .//  www. jav a2s.com
 * 
 * @param args
 */
public static void main(String[] args) {

    try {
        Organizer.initProxyLogin();
    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        URI uri = new URI("sftp://C:/home/data");
        System.out.println(uri.getScheme());
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // String serverURL = "http://localhost:8080/atoll-motuservlet/services";
    //
    // try {
    // WPSInfo wpsInfo = WPSFactory.getWpsInfo(serverURL);
    // } catch (MotuException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }

    // StatusModeType test = StatusModeType.DONE;
    // test.toString();
    // StatusModeType.valueOf("DONE");
    // Enum.valueOf(StatusModeType.class, "DONE");
    // boolean b = StatusModeType.class.isEnum();

    // testCreateObject();

    // testComplexOutputWPSResponse();

    // AnnotatedElement annotatedElement = StatusType.class;
    // System.out.println(annotatedElement.getAnnotations().toString());
    // for (Annotation annotation : annotatedElement.getAnnotations()) {
    // System.out.println(annotation.toString());
    // System.out.println(annotation.annotationType().toString());
    //            
    // }
    //        
    // XmlType xmlType = annotatedElement.getAnnotation(XmlType.class);
    // System.out.println(xmlType.propOrder().toString());
    // for (String annotation : xmlType.propOrder()) {
    // System.out.println(annotation);
    //            
    // }
    //        
    //        
    // testArrayToEnum(xmlType.propOrder());

    // Collection<String> tt = new ArrayList<String>();
    // tt.add("qsdfsdf");
    //        
    // System.out.println(tt.getClass());
    // System.out.println(tt.getClass().getGenericSuperclass());
    // ParameterizedType pt = (ParameterizedType) tt.getClass().getGenericSuperclass();
    // System.out.println(pt.getActualTypeArguments()[0]);
    // System.out.println(pt.getOwnerType());
    // System.out.println(pt.getRawType());
    // System.out.println(tt.getClass().getTypeParameters()[0].getName());
    // System.out.println(tt.getClass().getTypeParameters()[0].getGenericDeclaration());
    // System.out.println(tt.getClass().getComponentType());
    //        
    //        
    // Object o = tt.iterator().next();
    // System.out.println(o.getClass());

    // Type type = StringList.class.getGenericSuperclass();
    // System.out.println(type); // java.util.ArrayList<java.lang.String>
    // pt = (ParameterizedType) type;
    // System.out.println(pt.getActualTypeArguments()[0]);

    // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP
    // System.setProperty("proxyPort", "8080");
    // System.setProperty("socksProxyHost", "proxy.cls.fr");
    // System.setProperty("socksProxyPort", "1080");
    // Authenticator.setDefault(new MyAuthenticator());

    // testBuildWPS();
    // testBuildChainWPS();

    // testBuildAndRunChainWPS();

    // testUnmarshallWPS();

    // for (ErrorType c: ErrorType.values()) {
    // if (c.toString().equalsIgnoreCase("system")) {
    // System.out.println(c.toString());
    // }
    // }

    // testBodyPost();
    // testUTF8EncodeDecode();

    // TestWPS test = new TestWPS();
    //        
    // TestWPS.GetObjectId id = test.new GetObjectId();j
    // System.out.println(id.hashCode());
    // TestWPS.GetObjectId id2 = test.new GetObjectId();
    // System.out.println(id2.hashCode());
    //        
    // TestWPS.GetObjectId id3 = id;
    // System.out.println(id3.hashCode());
    //        
    // String abc = new String("Australia");
    // System.out.println("Hash code for String object: " + abc.hashCode());
    // String abc2 = new String("Australia");
    // System.out.println("Hash code for String object: " + abc2.hashCode());
    //
    //        

    // try {
    // // Generate a DES key
    // KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    // SecretKey key = keyGen.generateKey();
    // System.out.println(key.hashCode());
    // // Get the bytes of the key
    // byte[] keyBytes = key.getEncoded();
    // int numBytes = keyBytes.length;
    // String string = new String(keyBytes);
    // System.out.println(string);
    //            
    //
    // // Generate a Blowfish key
    // keyGen = KeyGenerator.getInstance("Blowfish");
    // key = keyGen.generateKey();
    // System.out.println(key.hashCode());
    //        
    // // Generate a triple DES key
    // keyGen = KeyGenerator.getInstance("DESede");
    // key = keyGen.generateKey();
    // System.out.println(key.hashCode());
    // } catch (java.security.NoSuchAlgorithmException e) {
    // }
    getDescribeProcess();

    // testPackageAnnotation();
    // testGetFields();
}

From source file:Main.java

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

From source file:Main.java

private static String getSchemeAuthority(URI uri) {
    return uri.getScheme() + "_" + uri.getAuthority();
}

From source file:Main.java

/**
 * Removes query parameters from url (only for logging, as query parameters may contain sensible informations)
 *
 * @param uri// ww  w .j a  va2 s.  co m
 * @return URI without parameters
 */
public static String shortenUrl(URI uri) {
    return uri.getScheme() + "://" + uri.getHost() + uri.getPath();
}