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:com.nesscomputing.migratory.loader.HttpLoader.java

@Override
public boolean accept(final URI uri) {
    return (uri != null) && ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()));
}

From source file:com.anrisoftware.simplerest.oanda.core.DefaultAccount.java

/**
 * @see DefaultAccountFactory#create(URI)
 *//*from  ww  w  . j  a va2  s  .  c  o  m*/
@AssistedInject
DefaultAccount(@Assisted URI uri) {
    isTrue(uri.getScheme().equals(URI_SCHEME), URI_MESSAGE);
    String[] split = split(uri.getSchemeSpecificPart(), ":");
    setAccount(split[0]);
    setAccessToken(split[1]);
}

From source file:voldemort.client.HttpStoreClientFactory.java

@Override
protected void validateUrl(URI url) {
    if (!URL_SCHEME.equals(url.getScheme()))
        throw new IllegalArgumentException("Illegal scheme in bootstrap URL for HttpStoreClientFactory:"
                + " expected '" + URL_SCHEME + "' but found '" + url.getScheme() + "'.");
}

From source file:com.orange.spring.cloud.connector.s3.heroku.S3ServiceInfoCreator.java

public S3ServiceInfo createServiceInfo(S3DetectableService s3DetectableService) {
    Map<String, String> env = environment.getEnv();
    String accessKeyId = env.get(s3DetectableService.getAccessKeyIdEnvKey());
    String secretAccessKey = env.get(s3DetectableService.getSecretAccessKeyEnvKey());
    String bucketName = env.get(s3DetectableService.getBucketNameEnvKey());
    String finalUrl = this.getFinalUrl(s3DetectableService, bucketName);
    URI finalUri = URI.create(finalUrl);
    return new S3ServiceInfo(bucketName, finalUri.getScheme(), finalUri.getHost(), finalUri.getPort(),
            accessKeyId, secretAccessKey, finalUri.getPath());
}

From source file:com.subgraph.vega.impl.scanner.handlers.DirParentCheck.java

private HttpUriRequest createRequest(IWebPath path) {
    final IWebPath parent = path.getParentPath();
    String basePath = parent.getParentPath().getFullPath();
    String newPath = basePath + "foo/" + path.getPathComponent();
    final URI originalUri = path.getUri();
    try {/* ww  w . java  2s . c o  m*/
        final URI newUri = new URI(originalUri.getScheme(), originalUri.getAuthority(), newPath, null, null);
        return new HttpGet(newUri);
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:com.abiquo.model.enumerator.RemoteServiceType.java

public String fixUri(final URI uri) {
    String protocol = uri.getScheme();
    String domainName = uri.getHost();
    Integer port = uri.getPort();
    String path = uri.getPath();//www.  j  av  a2s. com

    String domainHost = domainName + (port != null ? ":" + port : "");

    String fullURL = StringUtils.join(new String[] { fixProtocol(protocol), domainHost });

    if (!StringUtils.isEmpty(path)) {
        fullURL = UriHelper.appendPathToBaseUri(fullURL, path);
    }

    return fullURL;
}

From source file:com.mycompany.projecta.JenkinsScraper.java

public String scrape(String urlString, String username, String password)
        throws ClientProtocolException, IOException {
    URI uri = URI.create(urlString);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/*from  ww w . j a v  a 2s  .c o  m*/
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpGet httpGet = new HttpGet(uri);
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    HttpResponse response = httpClient.execute(host, httpGet, localContext);

    String resp = response.toString();

    return EntityUtils.toString(response.getEntity());
}

From source file:com.googlecode.jsonschema2pojo.ContentResolver.java

private JsonNode resolveFromClasspath(URI uri) {

    String path = removeStart(removeStart(uri.toString(), uri.getScheme() + ":"), "/");
    InputStream contentAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);

    if (contentAsStream == null) {
        throw new IllegalArgumentException("Couldn't read content from the classpath, file not found: " + uri);
    }/* ww w . ja va 2s . c o m*/

    try {
        return OBJECT_MAPPER.readTree(contentAsStream);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("Error parsing document: " + uri, e);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Unrecognised URI, can't resolve this: " + uri, e);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unrecognised URI, can't resolve this: " + uri, e);
    }
}

From source file:edu.washington.cs.mystatus.odk.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 *
 * @param urlString/*from w ww.j a  va2  s  . c om*/
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient) {
    URI u = null;
    try {
        URL url = new URL(urlString);
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    if (u.getHost() == null) {
        return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
    }

    // if https then enable preemptive basic auth...
    if (u.getScheme().equals("https")) {
        enablePreemptiveBasicAuth(localContext, u.getHost());
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (statusCode != HttpStatus.SC_OK) {
            WebUtils.discardEntityBytes(response);
            if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                // clear the cookies -- should not be necessary?
                MyStatus.getInstance().getCookieStore().clear();
            }
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            WebUtils.discardEntityBytes(response);
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }
        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
                isr = null;
            } finally {
                if (isr != null) {
                    try {
                        // ensure stream is consumed...
                        final long count = 1024L;
                        while (isr.skip(count) == count)
                            ;
                    } catch (Exception e) {
                        // no-op
                    }
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        clearHttpConnectionManager();
        e.printStackTrace();
        String cause;
        Throwable c = e;
        while (c.getCause() != null) {
            c = c.getCause();
        }
        cause = c.toString();
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:com.nesscomputing.cache.CacheTopologyProvider.java

@Inject
CacheTopologyProvider(final CacheConfiguration config, final ReadOnlyDiscoveryClient discoveryClient,
        @Named("cacheName") String cacheName) {
    this.discoveryClient = discoveryClient;
    this.cacheName = cacheName;

    List<URI> uris = config.getCacheUri();
    if (uris != null) {
        ImmutableList.Builder<InetSocketAddress> addrBuilder = ImmutableList.builder();
        for (URI uri : uris) {
            if ("memcache".equals(uri.getScheme())) {
                addrBuilder.add(new InetSocketAddress(uri.getHost(), uri.getPort()));
            } else {
                LOG.warn("Ignored uri %s due to wrong scheme", uri);
            }/*from   w ww . ja v a  2s .c o m*/
        }
        addrs = addrBuilder.build();
        LOG.info("Using configured caches: %s", addrs);
    } else {
        addrs = null;
        LOG.info("Using dynamically discovered caches.");
    }
}