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:org.apache.taverna.databundle.DataBundles.java

/**
 * Deeply resolve a {@link Path} to JVM objects.
 * <p>/*from  w w w  .  j a v  a2s.  co m*/
 * This method is intended mainly for presentational uses 
 * with a particular input/output port from
 * {@link #getPorts(Path)} or {@link #getPort(Path, String)}.
 * <p>
 * Note that as all lists are resolved deeply (including lists of lists)
 * and when using options {@link ResolveOptions#STRING} or {@link ResolveOptions#BYTES}
 * the full content of the values are read into memory, this 
 * method can be time-consuming.
 * <p>
 * If the path is <code>null</code> or {@link #isMissing(Path)},
 * <code>null</code> is returned, unless the option
 * {@link ResolveOptions#REPLACE_NULL} is specified, which would return the
 * empty String "".
 * <p>
 * If the path {@link #isValue(Path)} and the option
 * {@link ResolveOptions#STRING} is specified, its
 * {@link #getStringValue(Path)} is returned (assuming an UTF-8 encoding).
 * NOTE: Binary formats (e.g. PNG) will NOT be represented correctly read as
 * UTF-8 String and should instead be read directly with
 * {@link Files#newInputStream(Path, java.nio.file.OpenOption...)}. Note
 * that this could consume a large amount of memory as no size checks are
 * performed.
 * <p>
 * If the option {@link ResolveOptions#URI} is specified, all non-missing 
 * non-error leaf values are resolved as a {@link URI}. If the path is a 
 * {@link #isReference(Path)} the URI will be the reference from 
 * {@link #getReference(Path)}, otherwise the URI will  
 * identify a {@link Path} within the current {@link Bundle}.
 * <p>
 * If the path {@link #isValue(Path)} and the option
 * {@link ResolveOptions#BYTES} is specified, the complete content is returned as
 * a <code>byte[]</code>. Note that this could consume a large amount of memory
 * as no size checks are performed.
 * <p>
 * If the path {@link #isError(Path)}, the corresponding
 * {@link ErrorDocument} is returned, except when the option
 * {@link ResolveOptions#REPLACE_ERRORS} is specified, which means errors are
 * returned as <code>null</code> (or <code>""</code> if {@link ResolveOptions#REPLACE_NULL} is also specified).
 * <p>
 * If the path {@link #isReference(Path)} and the option 
 * {@link ResolveOptions#URI} is <strong>not</strong> set, 
 * either a {@link File} or a {@link URL} is returned, 
 * depending on its protocol. If the reference protocol has no
 * corresponding {@link URLStreamHandler}, a {@link URI} is returned
 * instead. 
 * <p>
 * If the path {@link #isList(Path)}, a {@link List} is returned
 * corresponding to resolving the paths from {@link #getList(Path)}. using
 * this method with the same options.
 * <p>
 * If none of the above, the {@link Path} itself is returned. This is 
 * thus the default for non-reference non-error leaf values if neither 
 * {@link ResolveOptions#STRING}, {@link ResolveOptions#BYTES} or
 * {@link ResolveOptions#URI} are specified.
 * To force returning of {@link Path}s for all non-missing leaf values, specify
 * {@link ResolveOptions#PATH};
 * 
 * @param path
 *            Data bundle path to resolve
 * @param options
 *            Resolve options
 * @return <code>null</code>, a {@link String}, {@link ErrorDocument},
 *         {@link URL}, {@link File}, {@link Path} or {@link List}
 *         (containing any of these) depending on the path type and the options.
 * @throws IOException
 *             If the path (or any of the path in a contained list) can't be
 *             accessed
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object resolve(Path path, ResolveOptions... options) throws IOException {
    EnumSet<ResolveOptions> opt;
    if (options.length == 0) {
        opt = EnumSet.of(ResolveOptions.DEFAULT); // no-op
    } else {
        opt = EnumSet.of(ResolveOptions.DEFAULT, options);
    }

    if (opt.contains(ResolveOptions.BYTES) && opt.contains(ResolveOptions.STRING)) {
        throw new IllegalArgumentException("Incompatible options: BYTES and STRING");
    }
    if (opt.contains(ResolveOptions.BYTES) && opt.contains(ResolveOptions.PATH)) {
        throw new IllegalArgumentException("Incompatible options: BYTES and PATH");
    }
    if (opt.contains(ResolveOptions.BYTES) && opt.contains(ResolveOptions.URI)) {
        throw new IllegalArgumentException("Incompatible options: BYTES and URI");
    }
    if (opt.contains(ResolveOptions.STRING) && opt.contains(ResolveOptions.PATH)) {
        throw new IllegalArgumentException("Incompatible options: STRING and PATH");
    }
    if (opt.contains(ResolveOptions.STRING) && opt.contains(ResolveOptions.URI)) {
        throw new IllegalArgumentException("Incompatible options: STRING and URI");
    }
    if (opt.contains(ResolveOptions.PATH) && opt.contains(ResolveOptions.URI)) {
        throw new IllegalArgumentException("Incompatible options: PATH and URI");
    }

    if (path == null || isMissing(path)) {
        if (!opt.contains(ResolveOptions.REPLACE_NULL)) {
            return null;
        }
        if (opt.contains(ResolveOptions.BYTES)) {
            return new byte[0];
        }
        if (opt.contains(ResolveOptions.PATH)) {
            return path;
        }
        if (opt.contains(ResolveOptions.URI)) {
            return path.toUri();
        }
        // STRING and DEFAULT
        return "";

    }

    if (isList(path)) {
        List<Path> list = getList(path);
        List<Object> objectList = new ArrayList<Object>(list.size());
        for (Path pathElement : list) {
            objectList.add(resolve(pathElement, options));
        }
        return objectList;
    }
    if (opt.contains(ResolveOptions.PATH)) {
        return path;
    }
    if (isError(path)) {
        if (opt.contains(ResolveOptions.REPLACE_ERRORS)) {
            return opt.contains(ResolveOptions.REPLACE_NULL) ? "" : null;
        }
        return getError(path);
    }
    if (opt.contains(ResolveOptions.URI)) {
        if (isReference(path)) {
            return getReference(path);
        } else {
            return path.toUri();
        }
    }
    if (isReference(path)) {
        URI reference = getReference(path);
        String scheme = reference.getScheme();
        if ("file".equals(scheme)) {
            return new File(reference);
        } else {
            try {
                return reference.toURL();
            } catch (IllegalArgumentException | MalformedURLException e) {
                return reference;
            }
        }
    }
    if (isValue(path)) {
        if (opt.contains(ResolveOptions.BYTES)) {
            return Files.readAllBytes(path);
        }
        if (opt.contains(ResolveOptions.STRING)) {
            return getStringValue(path);
        }
    }
    // Fall-back - return Path as-is
    return path;
}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers,
        UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException {
    long readTime = 0;
    long connSetupTime = 0;
    long connTime = 0;
    int bytesRead = 0;
    if (DEBUG_DETAILED) {
        Log.d(TAG, id + "] Execute " + url);
    }//from   w w  w.ja v  a2 s . c  o  m
    long now = System.currentTimeMillis();
    long then;

    Map<?, ?> json = Collections.EMPTY_MAP;

    try {

        URI uri = new URI(url);
        int port = uri.getPort();

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");

        DefaultHttpClient httpclient;
        if ("https".equals(uri.getScheme())) {
            httpclient = MySSLSocketFactory.getNewHttpClient(port);
        } else {
            httpclient = new DefaultHttpClient(basicHttpParams);
        }

        //AndroidHttpClient.newInstance("Vuze Android Remote");

        // This doesn't set the "Authorization" header!?
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);

        // Prepare a request object
        HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException

        if (creds != null) {
            byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes();
            String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length);
            httpRequest.setHeader("Authorization", "Basic " + encoding);
        }

        if (jsonPost != null) {
            HttpPost post = (HttpPost) httpRequest;
            String postString = JSONUtils.encodeToJSON(jsonPost);
            if (AndroidUtils.DEBUG_RPC) {
                Log.d(TAG, id + "]  Post: " + postString);
            }

            AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getCompressedEntity(postString)
                    : new StringEntity(postString);
            post.setEntity(entity);

            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            setupRequestFroyo(httpRequest);
        }

        if (headers != null) {
            for (Header header : headers) {
                httpRequest.setHeader(header);
            }
        }

        // Execute the request
        HttpResponse response;

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connSetupTime = (then - now);
            now = then;
        }

        httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i < 2) {
                    return true;
                }
                return false;
            }
        });
        response = httpclient.execute(httpRequest);

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connTime = (then - now);
            now = then;
        }

        HttpEntity entity = response.getEntity();

        // XXX STATUSCODE!

        StatusLine statusLine = response.getStatusLine();
        if (AndroidUtils.DEBUG_RPC) {
            Log.d(TAG, "StatusCode: " + statusLine.getStatusCode());
        }

        if (entity != null) {

            long contentLength = entity.getContentLength();
            if (contentLength >= Integer.MAX_VALUE - 2) {
                throw new RPCException("JSON response too large");
            }

            // A Simple JSON Response Read
            InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getUngzippedContent(entity)
                    : entity.getContent();
            InputStreamReader isr = new InputStreamReader(instream, "utf8");

            StringBuilder sb = null;
            BufferedReader br = null;
            // JSONReader is 10x slower, plus I get more OOM errors.. :(
            //            final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false
            //                  : DEFAULT_USE_STRINGBUFFER;
            final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER;

            if (useStringBuffer) {
                // Setting capacity saves StringBuffer from going through many
                // enlargeBuffers, and hopefully allows toString to not make a copy
                sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512);
            } else {
                if (AndroidUtils.DEBUG_RPC) {
                    Log.d(TAG, "Using BR. ContentLength = " + contentLength);
                }
                br = new BufferedReader(isr, 8192);
                br.mark(32767);
            }

            try {

                // 9775 files on Nexus 7 (~2,258,731 bytes)
                // fastjson 1.1.46 (String)       :  527- 624ms
                // fastjson 1.1.39 (String)       :  924-1054ms
                // fastjson 1.1.39 (StringBuilder): 1227-1463ms
                // fastjson 1.1.39 (BR)           : 2233-2260ms
                // fastjson 1.1.39 (isr)          :      2312ms
                // GSON 2.2.4 (String)            : 1539-1760ms
                // GSON 2.2.4 (BufferedReader)    : 2646-3060ms
                // JSON-SMART 1.3.1 (String)      :  572- 744ms (OOMs more often than fastjson)

                if (useStringBuffer) {
                    char c[] = new char[8192];
                    while (true) {
                        int read = isr.read(c);
                        if (read < 0) {
                            break;
                        }
                        sb.append(c, 0, read);
                    }

                    if (AndroidUtils.DEBUG_RPC) {
                        then = System.currentTimeMillis();
                        if (DEBUG_DETAILED) {
                            if (sb.length() > 2000) {
                                Log.d(TAG, id + "] " + sb.substring(0, 2000) + "...");
                            } else {
                                Log.d(TAG, id + "] " + sb.toString());
                            }
                        }
                        bytesRead = sb.length();
                        readTime = (then - now);
                        now = then;
                    }

                    json = JSONUtils.decodeJSON(sb.toString());
                    //json = JSONUtilsGSON.decodeJSON(sb.toString());
                } else {

                    //json = JSONUtils.decodeJSON(isr);
                    json = JSONUtils.decodeJSON(br);
                    //json = JSONUtilsGSON.decodeJSON(br);
                }

            } catch (Exception pe) {

                //               StatusLine statusLine = response.getStatusLine();
                if (statusLine != null && statusLine.getStatusCode() == 409) {
                    throw new RPCException(response, "409");
                }

                try {
                    String line;
                    if (useStringBuffer) {
                        line = sb.subSequence(0, Math.min(128, sb.length())).toString();
                    } else {
                        br.reset();
                        line = br.readLine().trim();
                    }

                    isr.close();

                    if (AndroidUtils.DEBUG_RPC) {
                        Log.d(TAG, id + "]line: " + line);
                    }
                    Header contentType = entity.getContentType();
                    if (line.startsWith("<") || line.contains("<html")
                            || (contentType != null && contentType.getValue().startsWith("text/html"))) {
                        // TODO: use android strings.xml
                        throw new RPCException(response,
                                "Could not retrieve remote client location information.  The most common cause is being on a guest wifi that requires login before using the internet.");
                    }
                } catch (IOException ignore) {

                }

                Log.e(TAG, id, pe);
                if (statusLine != null) {
                    String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n"
                            + pe.getMessage();
                    throw new RPCException(msg, pe);
                }
                throw new RPCException(pe);
            } finally {
                closeOnNewThread(useStringBuffer ? isr : br);
            }

            if (AndroidUtils.DEBUG_RPC) {
                //               Log.d(TAG, id + "]JSON Result: " + json);
            }

        }
    } catch (RPCException e) {
        throw e;
    } catch (Throwable e) {
        Log.e(TAG, id, e);
        throw new RPCException(e);
    }

    if (AndroidUtils.DEBUG_RPC) {
        then = System.currentTimeMillis();
        Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime
                + "ms, parsed in " + (then - now) + "ms");
    }
    return json;
}

From source file:com.sworddance.util.UriFactoryImpl.java

public static boolean isHttpProtocol(URI uri) {
    if (uri != null) {
        String scheme = uri.getScheme();
        if (scheme != null) {
            return HTTP_SCHEMES.matcher(scheme).find();
        }/*  ww  w. j a  v a  2 s  . c  o m*/
    }
    return false;
}

From source file:com.sworddance.util.UriFactoryImpl.java

public static boolean hasQuestionableScheme(URI uri) {
    if (uri.isAbsolute()) {
        String scheme = uri.getScheme();
        return !KNOWN_GOOD_SCHEMES.matcher(scheme).find();
    } else {// w w w.j  a  v a 2 s . co  m
        return false;
    }
}

From source file:com.ibm.amc.FileManager.java

/**
 * Resolves an input URI to a URL suitable for WAMT. If the URI represents a temporary file,
 * converts it to the real file location.
 * //w w  w .  j  av  a  2 s  .  c  o  m
 * @param uri
 *            the input URI
 * @return the output URL
 */
public static URL resolveUriToUrl(URI uri) {
    // if a null is passed in, send one back
    if (uri == null)
        return null;

    try {
        return resolveUri(uri).toURL();
    } catch (MalformedURLException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("resolveUriToUrl()", "MalformedURLException:", e);
            logger.stacktrace(e);
        }
        if (uri.getScheme().equals(SCHEME)) {
            throw new AmcIllegalArgumentException(e, "CWZBA2002E_TEMPORARY_FILE_FAILED", uri.toString());
        } else {
            throw new AmcIllegalArgumentException("CWZBA2003E_INVALID_URI", uri.toString());
        }
    }
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * Purpose of this method is to process redirect case. A lot of sites are NOT compatible to HTTP RFCs. It means
 * that they may specify redirect in wrong way. For correct way refer to http://www.ietf.org/rfc/rfc2616.txt 14.30.
 *
 * Let's say we received redirect directive from external server after requested http://www.w3.org/Whois page.
 * Below are the variants we may've received and the ways we will treat them:
 * <code>//from   w w w .  j  a  v a 2 s.c  om
 * <ol>
 * <li> "http://www.w3.org/pub/WWW/People.html" - correct redirect, no questions
 * <li> "/pub/WWW/People.html" - resolve to http://www.w3.org/pub/WWW/People.html
 * <li> "pub/WWW/People.html" - resolve to http://www.w3.org/pub/WWW/People.html
 * <li> "" - resolve to http://www.w3.org/
 * </ol>
 * </code>
 *
 * Please add the cases if you found anything else we may suffer from on redirect matter.
 *
 * One more note. Why this couldn't be done in a regular method {@link #createUriWithSchemaAndPath(Object)} ,
 * why we need separate one. Regular one deals with user input with no URI context built in. Redirect case
 * ALWAYS has context - the page it was redirected from. User meaning of something.page is (try it in browser!)
 * http://something.page. Redirect meaning of the same is most likely http://theHostRedirectCameFrom/something.page.
 *
 * @param redirectTo string saying where we should be redirected
 * @param hostRedirectedFrom host we received redirect from
 * @return resolved URI
 */
public static URI createUriForRedirect(String redirectTo, String hostRedirectedFrom) {
    // empty redirect. Redirect to the main page.
    if (isEmpty(redirectTo)) {
        return createUriWithPath(hostRedirectedFrom);
    }

    URI idealCaseURI = createUriWithPath(redirectTo);
    if (idealCaseURI.getScheme() != null && idealCaseURI.getHost() != null && idealCaseURI.getPath() != null) {
        // that's it. Thanks our remote server for following RFC!
        return idealCaseURI;
    }

    // if we're failed with ideal case - let's try other ways
    notNull(hostRedirectedFrom,
            "Host we came from shouldn't be null because redirectTo doesn't have host information. redirectTo=",
            redirectTo);
    if (!redirectTo.startsWith(PATH_SEPARATOR)) {
        redirectTo = PATH_SEPARATOR + redirectTo;
    }
    return createUriWithSchema(hostRedirectedFrom + redirectTo);
}

From source file:com.microsoft.alm.common.utils.UrlHelper.java

/**
 * Given a git url, try parse the collection and project name out of this url
 * <p/>/*  w  ww  . j ava2s. c  o  m*/
 * valid schema:
 * schema://host[:port][/IIS-path]/collection[/project]/_git[/(_optimized|_full)]/repository[/]
 * <p/>
 * name restrictions for TFS:
 * http://go.microsoft.com/fwlink/?LinkId=77936
 *
 * @param gitUrl    git fetch/push url
 * @param validator a provided method to validate the validity of the parsed result
 *                  this abstracts the authentication requirement away from this utility
 * @return a parseResult,
 * parsed and validated result. If parsing isn't successful, every field is null
 */
public static ParseResult tryParse(final String gitUrl, final ParseResultValidator validator) {
    if (StringUtils.isEmpty(gitUrl)) {
        return ParseResult.FAILED;
    }

    final URI gitUri;
    try {
        gitUri = createUri(gitUrl);
    } catch (Throwable t) {
        logger.warn("tryParse: creating Uri failed for Git url: {}", gitUrl, t);
        return ParseResult.FAILED;
    }

    // only support http and https (ssh support will come later when the format of the url is better understood)
    try {
        final String scheme = gitUri.getScheme() != null ? gitUri.getScheme().toLowerCase() : null;
        if (HTTPS_PROTOCOL.equals(scheme) || HTTP_PROTOCOL.equals(scheme)) {
            return HttpGitUrlParser.tryParse(gitUri, validator);
        }
    } catch (Throwable t) {
        logger.error("tryParse: unexpected error for gitUrl = " + gitUrl);
        logger.warn("tryParse", t);
    }

    return ParseResult.FAILED;
}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Given a URI, return a new URI with the query, fragment, and top level of
 * the path removed./*ww  w  .  ja  va 2  s  .  c o m*/
 *
 * @param uri the input URI
 * @return the base URI
 */
public static URI parentUri(URI uri) throws URISyntaxException {
    if (uri == null) {
        return null;
    }
    String protocol = uri.getScheme();
    String host = uri.getHost();

    // Process the port number, if any
    int port = uri.getPort();

    // Process the path, if any
    String path = uri.getPath();
    if (!StringUtils.hasLength(path)) {
        path = "";
    } else {
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        if (!path.contains("/")) {
            path = "";
        } else {
            int lastSlash = path.lastIndexOf('/');
            path = path.substring(0, lastSlash);
        }
    }

    // Build the final URL and return it
    return new URI(protocol, null, host, port, path, null, null);
}

From source file:io.personium.core.rs.cell.MessageODataResource.java

/**
 * To????baseUrl??????.//from  ww  w .  ja va  2 s  . co  m
 * @param toValue to???
 * @param baseUrl baseUrl
 */
public static void validateToValue(String toValue, String baseUrl) {
    if (toValue == null) {
        return;
    }
    // URL??
    String checkBaseUrl = null;
    String[] uriList = toValue.split(",");
    for (String uriStr : uriList) {
        try {
            URI uri = new URI(uriStr);
            checkBaseUrl = uri.getScheme() + "://" + uri.getHost();
            int port = uri.getPort();
            if (port != -1) {
                checkBaseUrl += ":" + Integer.toString(port);
            }
            checkBaseUrl += "/";
        } catch (URISyntaxException e) {
            log.info(e.getMessage());
            throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName());
        }

        if (checkBaseUrl == null || !checkBaseUrl.equals(baseUrl)) {
            throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName());
        }
    }

}

From source file:org.hl7.fhir.client.ResourceAddress.java

public static URI appendHttpParameters(URI basePath, Map<String, String> parameters) {
    try {//from w w w  . ja v a 2s .  co m
        Set<String> httpParameterNames = parameters.keySet();
        String query = basePath.getQuery();

        for (String httpParameterName : httpParameterNames) {
            if (query != null) {
                query += "&";
            } else {
                query = "";
            }
            query += httpParameterName + "=" + parameters.get(httpParameterName);
        }

        return new URI(basePath.getScheme(), basePath.getUserInfo(), basePath.getHost(), basePath.getPort(),
                basePath.getPath(), query, basePath.getFragment());
    } catch (Exception e) {
        throw new EFhirClientException("Error appending http parameter", e);
    }
}