Example usage for java.net URL getProtocol

List of usage examples for java.net URL getProtocol

Introduction

In this page you can find the example usage for java.net URL getProtocol.

Prototype

public String getProtocol() 

Source Link

Document

Gets the protocol name of this URL .

Usage

From source file:com.textuality.keybase.lib.prover.Website.java

@Override
public boolean fetchProofData() {

    try {/*from  w ww  .  jav  a  2s  .c  o m*/
        JSONObject sigJSON = readSig(mProof.getSigId());

        // find the .well-known URL
        String wellKnownUrl = JWalk.getString(sigJSON, "api_url");

        // fetch the proof
        Fetch fetch = new Fetch(wellKnownUrl);
        String problem = fetch.problem();
        if (problem != null) {
            mLog.add(problem);
            return false;
        }

        String actualUrl = fetch.getActualUrl();

        // Paranoid Interlude:
        // A bad guy who cant post to the site might still be able to squeeze in a redirect
        //  to somewhere else, so lets ensure that the data is really coming from the site
        //
        String nametag = mProof.getNametag();
        URL url = new URL(actualUrl);
        String scheme = url.getProtocol();
        String host = url.getHost();
        if (!(scheme.equals("http") || scheme.equals("https")) && host.equals(nametag)) {
            mLog.add("Proof either doesnt come from " + nametag + " or isnt at an HTTP URL");
            return false;
        }

        // verify that message appears in gist
        if (!fetch.getBody().contains(mPgpMessage)) {
            mLog.add("Website claiming post doesnt contain signed PGP message");
            return false;
        }

        return true;

    } catch (KeybaseException e) {
        mLog.add("Keybase API problem: " + e.getLocalizedMessage());
    } catch (JSONException e) {
        mLog.add("Broken JSON message: " + e.getLocalizedMessage());
    } catch (MalformedURLException e) {
        mLog.add("Malformed proof URL");
    }
    return false;
}

From source file:uk.ac.ox.oucs.vle.TestPopulatorInput.java

public InputStream getInput(PopulatorContext context) {

    InputStream input;/*from w  w w .  j a  va  2  s. c  o m*/
    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {
        URL xcri = new URL(context.getURI());
        if ("file".equals(xcri.getProtocol())) {
            input = xcri.openStream();

        } else {
            HttpHost targetHost = new HttpHost(xcri.getHost(), xcri.getPort(), xcri.getProtocol());

            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(context.getUser(), context.getPassword()));

            HttpGet httpget = new HttpGet(xcri.toURI());
            HttpResponse response = httpclient.execute(targetHost, httpget);
            HttpEntity entity = response.getEntity();

            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                throw new IllegalStateException(
                        "Invalid response [" + response.getStatusLine().getStatusCode() + "]");
            }

            input = entity.getContent();
        }
    } catch (MalformedURLException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IllegalStateException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (IOException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    } catch (URISyntaxException e) {
        throw new PopulatorException(e.getLocalizedMessage());

    }

    return input;
}

From source file:com.dianping.cosmos.monitor.HttpClientService.java

private HttpUriRequest getGetRequest(String url, boolean useURI) throws Exception {
    HttpUriRequest request;//from  w w w.  j  a v a2  s.c  o m
    if (useURI) {
        URL requestURL = new URL(url);
        URI uri = new URI(requestURL.getProtocol(), null, requestURL.getHost(), requestURL.getPort(),
                requestURL.getPath(), requestURL.getQuery(), null);
        request = new HttpGet(uri);
    } else {
        request = new HttpGet(url);
    }
    return request;
}

From source file:com.textuality.keybase.lib.prover.HackerNews.java

@Override
public boolean fetchProofData() {

    try {//from www .ja va  2s.  co  m
        JSONObject sigJSON = readSig(mProof.getSigId());

        // the magic string is the base64 of the SHA of the raw message
        mShortenedMessageHash = JWalk.getString(sigJSON, "sig_id_short");

        // The api form is off at firebasio, so well use the proof URL
        String hnUrl = mProof.getProofUrl();

        Fetch fetch = new Fetch(hnUrl);
        String problem = fetch.problem();
        if (problem != null) {
            mLog.add(problem);
            return false;
        }

        // Paranoid Interlude:
        // Lets make sure source has right host and there's an id=<nametag> in the path
        //
        String nametag = mProof.getNametag();
        URL url = new URL(hnUrl);
        String scheme = url.getProtocol();
        String host = url.getHost();
        if (!((scheme.equals("http") || scheme.equals("https")) && host.equals("news.ycombinator.com")
                && hnUrl.contains("id=" + nametag))) {
            mLog.add("Proof either doesnt come from news.ycombinator.com or isnt specific to " + nametag);
            return false;
        }

        if (!(fetch.getBody().contains(mShortenedMessageHash))) {
            mLog.add("Hacker News post doesnt contain signed PGP message");
            return false;
        }

        return true;

    } catch (KeybaseException e) {
        mLog.add("Keybase API problem: " + e.getLocalizedMessage());
    } catch (JSONException e) {
        mLog.add("Broken JSON message: " + e.getLocalizedMessage());
    } catch (MalformedURLException e) {
        mLog.add("Malformed URL for proof post");
    }
    return false;
}

From source file:com.ge.predix.sample.blobstore.connector.spring.BlobstoreServiceConnectorCreator.java

/**
 * Creates the BlobStore context using S3Client
 *
 * @param serviceInfo Object Store Service Info Object
 * @param serviceConnectorConfig Cloud Foundry Service Connector Configuration
 *
 * @return BlobstoreService Instance of the ObjectStore Service
 *//*from w  w w .ja  v a  2  s .c  o m*/
@Override
public BlobstoreService create(BlobstoreServiceInfo serviceInfo,
        ServiceConnectorConfig serviceConnectorConfig) {
    log.info("create() invoked with serviceInfo? = " + (serviceInfo == null));
    ClientConfiguration config = new ClientConfiguration();
    config.setProtocol(Protocol.HTTPS);

    S3ClientOptions options = new S3ClientOptions();
    config.setSignerOverride("S3SignerType");

    BasicAWSCredentials creds = new BasicAWSCredentials(serviceInfo.getObjectStoreAccessKey(),
            serviceInfo.getObjectStoreSecretKey());
    AmazonS3Client s3Client = new AmazonS3Client(creds, config);
    s3Client.setEndpoint(serviceInfo.getUrl());
    s3Client.setS3ClientOptions(options);

    try {
        // Remove the Credentials from the Object Store URL
        URL url = new URL(serviceInfo.getUrl());
        String urlWithoutCredentials = url.getProtocol() + "://" + url.getHost();

        // Return BlobstoreService
        return new BlobstoreService(s3Client, serviceInfo.getBucket(), urlWithoutCredentials);
    } catch (MalformedURLException e) {
        log.error("create(): Couldnt parse the URL provided by VCAP_SERVICES. Exception = " + e.getMessage());
        throw new RuntimeException("Blobstore URL is Invalid", e);
    }
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

private void addTaxiiCredentials(CredentialsProvider credsProvider) {
    URL url = settings.getPollEndpoint();
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword()));
}

From source file:fr.gael.dhus.owcclient.OwcClientWebapp.java

@Override
public void configure(String dest_folder) throws IOException {
    String configurationFolder = "fr/gael/dhus/owcclient";
    URL u = Thread.currentThread().getContextClassLoader().getResource(configurationFolder);
    if (u != null && "jar".equals(u.getProtocol())) {
        extractJarFolder(u, configurationFolder, dest_folder);
    } else if (u != null) {
        File webAppFolder = new File(dest_folder);
        copyFolder(new File(u.getFile()), webAppFolder);
    }/*from w ww.j a v  a  2  s . c  o m*/

}

From source file:com.brightcove.com.zartan.verifier.video.PdFlvUrlVerifier.java

@ZartanCheck(value = "Primary Rendition is delivered over http")
public ResultEnum assertPrimaryRenditionProtocolCorrect(UploadData upData) throws Throwable {
    URL u = getPrimaryRenditionUrl(upData);
    assertEquals("Protocol should be http", "http", u.getProtocol());
    return ResultEnum.PASS;
}

From source file:net.hillsdon.reviki.wiki.renderer.creole.CreoleLinkContentsSplitter.java

/**
 * Splits links of the form target or text|target where target is
 * // w  ww. j ava  2 s .co  m
 * PageName wiki:PageName PageName#fragment wiki:PageName#fragment
 * A String representing an absolute URI scheme://valid/absolute/uri
 * Any character not in the `unreserved`, `punct`, `escaped`, or `other` categories (RFC 2396),
 * and not equal '/' or '@', is %-encoded. 
 * 
 * @param in The String to split
 * @return The split LinkParts
 */
LinkParts split(final String in) {
    String target = StringUtils.trimToEmpty(StringUtils.substringBefore(in, "|"));
    String text = StringUtils.trimToNull(StringUtils.substringAfter(in, "|"));
    if (target == null) {
        target = "";
    }
    if (text == null) {
        text = target;
    }
    // Link target can be PageName, wiki:PageName or a URL.
    URI uri = null;
    try {
        URL url = new URL(target);

        uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        if (uri.getPath() == null || !uri.isAbsolute()) {
            uri = null;
        }
    } catch (URISyntaxException e) {
        // uri remains null
    } catch (MalformedURLException e) {
        // uri remains null
    }

    if (uri != null) {
        return new LinkParts(text, uri);
    } else {
        // Split into wiki:pageName
        String[] parts = target.split(":", 2);
        String wiki = null;
        String pageName = target;
        if (parts.length == 2) {
            wiki = parts[0];
            pageName = parts[1];
        }

        // Split into pageName#fragment
        parts = pageName.split("#", 2);
        String fragment = null;
        if (parts.length == 2) {
            pageName = parts[0];
            fragment = parts[1];
        }

        // Split into pageName/attachment
        parts = pageName.split("/", 2);
        String attachment = null;
        if (parts.length == 2) {
            pageName = parts[0];
            attachment = parts[1];
        }

        return new LinkParts(text, wiki, pageName, fragment, attachment);
    }
}

From source file:fr.eolya.utils.http.HttpUtils.java

public static String urlGetAbsoluteURL(String urlReferer, String urlHref) {
    try {/*from   w  ww.  j a va 2 s  .co m*/
        if (urlHref.equals(""))
            return "";

        // Case 1 : urlHref starts with "http://"
        if (urlHref.startsWith("http://") || urlHref.startsWith("https://")) {
            return urlHref;
        }

        URL url = new URL(urlReferer);

        // Case 1.1 : urlHref starts with "//"
        if (urlHref.startsWith("//")) {
            return url.getProtocol() + ":" + urlHref;
        }

        String urlRefererHost = url.getProtocol() + "://" + url.getHost();
        if (url.getPort() != -1) {
            urlRefererHost = urlRefererHost + ":" + String.valueOf(url.getPort());
        }

        // Case 2 : urlHref looks like "?..."
        if (urlHref.startsWith("?")) {
            // find "?" in urlReferer
            /*
            if (urlReferer.indexOf("?")!=-1)
               return urlReferer.substring(0,urlReferer.indexOf("?")) + urlHref;
            else
               return urlReferer + urlHref;
             */
            return urlRefererHost + "/" + url.getPath() + urlHref;
        }

        // Case 3 : urlHref looks like "/path/file.html..."
        if (urlHref.startsWith("/")) {
            return urlRefererHost + urlHref;
        }

        // Case 4 : urlHref looks like "path/file.html..."
        String urlRefererPath = url.getPath();
        if ("".equals(urlRefererPath))
            urlRefererPath = "/";

        //if (urlRefererPath.indexOf(".")==-1 && urlRefererPath.lastIndexOf("/") != urlRefererPath.length()-1)
        //   urlRefererPath = urlRefererPath + "/";

        int offset = urlRefererPath.lastIndexOf("/");
        /*
        if (offset <= 0) {
           urlRefererPath = "";
        } else {
           urlRefererPath = urlRefererPath.substring(0, offset);
        }
         */
        urlRefererPath = urlRefererPath.substring(0, offset);

        return urlRefererHost + urlRefererPath + "/" + urlHref;

    } catch (Exception e) {
        //e.printStackTrace ();
    }
    return "";
}