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

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *///ww w. j av  a 2s  .com
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userpass + "'");
    }

    String username = userpass[0];
    String password = userpass[1]; // TODO enable reading this secretly

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:com.spotify.helios.cli.CliConfig.java

public static CliConfig fromEnvVar(Map<String, Object> config) throws URISyntaxException {
    final String master = environment.get("HELIOS_MASTER");
    if (master == null) {
        return fromMap(config);
    }/*w ww.jav  a 2 s  .  com*/

    // Specifically only include relevant bits according to the env var setting, rather than
    // strictly overlaying config so that if the config file has a setting for master endpoints, the
    // file doesn't override the env var if it's a domain:// as masterEndpoints takes precedence
    // over domains.
    final URI uri = new URI(master);
    final Builder<String, Object> builder = ImmutableMap.<String, Object>builder();
    // Always include the srvName bit if it's specified, so it can be specified in the file and
    // a domain flag could be passed on the command line, and it would work as you'd hope.
    if (config.containsKey(SRV_NAME_KEY)) {
        builder.put(SRV_NAME_KEY, config.get(SRV_NAME_KEY));
    }

    // TODO (dxia) Remove DEPRECATED_SITE_SCHEME after a period of time
    final String scheme = uri.getScheme();
    switch (scheme) {
    case DOMAIN_SCHEME:
    case DEPRECATED_SITE_SCHEME:
        builder.put(DOMAINS_KEY, ImmutableList.of(uri.getHost())).build();
        break;
    case HTTP_SCHEME:
        builder.put(MASTER_ENDPOINTS_KEY, ImmutableList.of(master));
        break;
    default:
        throw new RuntimeException(
                "Unknown Scheme " + scheme + " in HELIOS_MASTER env variable setting of [" + master + "]");
    }

    return fromMap(builder.build());
}

From source file:com.adaptris.core.fs.FsHelper.java

/**
 * Creates a {@link URL} based on the passed destination.
 * <p>//ww w.  ja v  a2  s  . co  m
 * If a {@code scheme} is present and is equal to {@code file} then the URL is deemed to be <strong>absolute</strong> and is used
 * as is. If the {@code scheme} is null then the URL is considered a {@code "file"} URL, and <strong>relative</strong>> to the
 * current working directory.
 * </p>
 * 
 * @param s the string to convert to a URL.
 * @param backslashConvert whether or not to convert backslashes into forward slashes.
 * 
 */
public static URL createUrlFromString(String s, boolean backslashConvert)
        throws IOException, URISyntaxException {
    String destToConvert = backslashConvert ? backslashToSlash(s) : s;
    URI configuredUri = null;
    try {
        configuredUri = new URI(destToConvert);
    } catch (URISyntaxException e) {
        // Specifically here to cope with file:///c:/ (which is
        // technically illegal according to RFC2396 but we need
        // to support it
        if (destToConvert.split(":").length >= 3) {
            configuredUri = new URI(URLEncoder.encode(destToConvert, "UTF-8"));
        } else {
            throw e;
        }
    }
    String scheme = configuredUri.getScheme();

    if ("file".equals(scheme)) {
        // nb for some reason, configuredUri.toUrl() doesn't work...
        // return configuredUri.toURL();
        return new URL(configuredUri.toString());
    } else {
        if (scheme == null) {
            return new URL("file:///" + configuredUri.toString());
        } else {
            throw new IllegalArgumentException("Illegal URL [" + s + "]");
        }
    }
}

From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;//  w w w.j  a  v a 2  s .co m
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpGet, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static boolean validateUrl(String url, List<String> errorMsgs) {
    if (errorMsgs == null) {
        errorMsgs = new ArrayList<String>();
    }//  www. j  av  a2  s . c  o m
    boolean result = true;
    try {
        URI uri = new URI(url);
        String schema = uri.getScheme();
        if (!"https".equalsIgnoreCase(schema) && !"http".equalsIgnoreCase(schema)) {
            errorMsgs.add("URL should starts with http or https");
            result = false;
        }
        if ("https".equalsIgnoreCase(schema) && uri.getHost().matches(Constants.IP_PATTERN)) {
            errorMsgs.add("You should use FQDN instead of ip address when using https protocol");
            result = false;
        }
    } catch (URISyntaxException e) {
        logger.error("invalid URL syntax ", e);
        errorMsgs.add("invalid URL syntax");
        return false;
    }

    return result;
}

From source file:com.fujitsu.dc.core.rs.cell.MessageODataResource.java

/**
 * To????baseUrl??????./*from   w w  w.java2s .c  o  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 DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName());
        }

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

}

From source file:com.net.cookie.HttpCookie.java

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

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * Returns a new {@link URI} containing only the scheme, user info, host,
 * and port of the given {@link URI}.//from ww w.j a v  a 2s. com
 *
 * @param uri
 *        the {@link URI} to remove the path and query parts from (must not
 *        be <code>null</code>)
 * @return a new {@link URI} containing only the scheme, user info, host,
 *         and port of the given {@link URI}
 */
public static URI removePathAndQueryParts(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    try {
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
    } catch (final URISyntaxException e) {
        final IllegalArgumentException e2 = new IllegalArgumentException(
                MessageFormat.format(Messages.getString("URIUtils.IllegalURIFormat"), uri)); //$NON-NLS-1$
        e2.initCause(e);
        throw e2;
    }
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * Returns a new {@link URI} containing only the scheme, user info, host,
 * port, and path of the given {@link URI}.
 *
 * @param uri/*  ww w . j a va 2s  .  c o m*/
 *        the {@link URI} to remove the query parts from (must not be
 *        <code>null</code>)
 * @return a new {@link URI} containing only the scheme, user info, host,
 *         port, and path of the given {@link URI}
 */
public static URI removeQueryParts(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    try {
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
                null);
    } catch (final URISyntaxException e) {
        final IllegalArgumentException e2 = new IllegalArgumentException(
                MessageFormat.format(Messages.getString("URIUtils.IllegalURIFormat"), uri)); //$NON-NLS-1$
        e2.initCause(e);
        throw e2;
    }
}

From source file:com.net.cookie.HttpCookie.java

/**
 * Returns true if {@code cookie} should be sent to {@code uri} with respect to the cookie's
 * secure attribute. Secure cookies should not be sent in insecure (ie. non-HTTPS) requests.
 *///w w w  .  ja v  a2s  . c om
static boolean secureMatches(HttpCookie cookie, URI uri) {
    return !cookie.getSecure() || "https".equalsIgnoreCase(uri.getScheme());
}