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:net.acesinc.convergentui.ConvergentUIResponseFilter.java

@Override
public Object run() {

    String origBody = contentManager.getDownstreamResponse();
    if (origBody == null || origBody.isEmpty()) {
        return null;
    }/*from w w w . ja v a 2 s.c  om*/

    String composedBody = null;
    log.trace("Response from downstream server: " + origBody);

    Document doc = Jsoup.parse(origBody);
    if (hasReplaceableElements(doc)) {
        log.debug("We have replaceable elements. Let's get em!");
        Elements elementsToUpdate = doc.select("div[data-loc]");
        for (Element e : elementsToUpdate) {
            StringBuilder content = new StringBuilder();
            String location = e.dataset().get("loc");
            String fragmentName = e.dataset().get("fragment-name");
            String cacheName = e.dataset().get("cache-name");
            boolean useCaching = !Boolean.valueOf(e.dataset().get("disable-caching"));
            boolean failQuietly = Boolean.valueOf(e.dataset().get("fail-quietly"));
            URL url = null;
            try {
                url = new URL(location);
                String protocol = url.getProtocol();
                String service = url.getHost();

                log.debug("Fetching content at location [ " + location + " ] with cacheName = [ " + cacheName
                        + " ]");

                try {
                    RequestContext context = RequestContext.getCurrentContext();
                    ContentResponse response = contentManager.getContentFromService(location, cacheName,
                            useCaching, context);

                    log.trace(response.toString());

                    if (!response.isError()) {
                        Object resp = response.getContent();
                        if (String.class.isAssignableFrom(resp.getClass())) {
                            String subContentResponse = (String) resp;
                            //TODO You better trust the source of your downstream HTML!
                            //                    String cleanedContent = Jsoup.clean(subContentResponse, Whitelist.basic()); //this totally stripped the html out...
                            Document subDocument = Jsoup.parse(subContentResponse);

                            if (fragmentName != null) {
                                Elements fragments = subDocument
                                        .select("div[data-fragment-name=\"" + fragmentName + "\"]");

                                if (fragments != null && fragments.size() > 0) {
                                    if (fragments.size() == 1) {
                                        Element frag = fragments.first();

                                        //need to see if there are images that we need to replace the urls on
                                        Elements images = frag.select("img");
                                        for (Element i : images) {
                                            String src = i.attr("src");
                                            if (src.startsWith("/") && !src.startsWith("//")) {
                                                i.attr("src", "/cui-req://" + protocol + "://" + service + src);
                                            } //else what do we do about relative urls?
                                        }

                                        content.append(frag.toString());

                                    } else {
                                        for (Element frag : fragments) {
                                            content.append(frag.toString()).append("\n\n");
                                        }
                                    }
                                } else {
                                    log.debug("Found no matching fragments for [ " + fragmentName + " ]");
                                    if (failQuietly) {
                                        content.append("<div class='cui-error'></div>");
                                    } else {
                                        content.append(
                                                "<span class='cui-error'>Failed getting content from remote service. Possible reason in reponse below</span>");
                                        content.append(subDocument.toString());
                                    }
                                }
                            } else {
                                //take the whole thing and cram it in there!
                                content.append(subDocument.toString());
                            }
                        } else {
                            //not text...
                            if (!failQuietly) {
                                content.append(
                                        "<span class='cui-error'>Failed getting content from remote service. Reason: content was not text</span>");
                            } else {
                                content.append("<div class='cui-error'></div>");
                            }
                        }

                    } else {
                        if (!failQuietly) {
                            content.append(
                                    "<span class='cui-error'>Failed getting content from remote service. Reason: "
                                            + response.getMessage() + "</span>");
                        } else {
                            content.append("<div class='cui-error'></div>");
                        }
                    }

                    //now append it to the page
                    if (!content.toString().isEmpty()) {
                        e.html(content.toString());
                    }
                } catch (Throwable t) {
                    if (!failQuietly) {
                        e.html("<span class='cui-error'>Failed getting content from remote service. Reason: "
                                + t.getMessage() + "</span>");
                    }
                    log.warn("Failed replacing content", t);
                }
            } catch (MalformedURLException ex) {
                log.warn("location was invalid: [ " + location + " ]", ex);
                if (!failQuietly) {
                    content.append(
                            "<span class='cui-error'>Failed getting content from remote service. Reason: data-loc was an invalid location.</span>");
                } else {
                    content.append("<div class='cui-error'></div>");
                }
            }

        }

        composedBody = doc.toString();
    } else {
        log.debug("Document has no replaeable elements. Skipping");
    }

    try {
        addResponseHeaders();
        if (composedBody != null && !composedBody.isEmpty()) {
            writeResponse(composedBody, getMimeType(RequestContext.getCurrentContext()));
        } else {
            writeResponse(origBody, getMimeType(RequestContext.getCurrentContext()));
        }
    } catch (Exception ex) {
        log.error("Error sending response", ex);

    }
    return null;
}

From source file:com.connectsdk.core.upnp.Device.java

public Device(String url, String searchTarget) throws IOException {
    URL urlObject = new URL(url);

    if (urlObject.getPort() == -1) {
        baseURL = String.format("%s://%s", urlObject.getProtocol(), urlObject.getHost());
    } else {/* ww  w .  j  a  v a  2  s.  co m*/
        baseURL = String.format("%s://%s:%d", urlObject.getProtocol(), urlObject.getHost(),
                urlObject.getPort());
    }
    ipAddress = urlObject.getHost();
    port = urlObject.getPort();
    this.searchTarget = searchTarget;
    UUID = null;

    if (searchTarget.equalsIgnoreCase("urn:dial-multiscreen-org:service:dial:1"))
        applicationURL = getApplicationURL(url);
}

From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java

/**
 * authenticates the context if user and password are set
 *//*from w w w.  ja  v  a  2  s . c om*/
private HttpClientContext initAuthIfNeeded(String url) {

    HttpClientContext context = HttpClientContext.create();
    if (this.user.isEmpty() || this.password.isEmpty()) {
        log.debug(
                "http connection without autentication, because no user / password ist known to HttpUtilImpl ...");
        return context;
    }

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password));
    URL url4Host;
    try {
        url4Host = new URL(url);
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        return context;
    }

    HttpHost targetHost = new HttpHost(url4Host.getHost(), url4Host.getPort(), url4Host.getProtocol());
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}

From source file:org.tomitribe.tribestream.registryng.bootstrap.Provisioning.java

private void seedDatabase() {
    final File dir = new File(location);
    if (dir.isDirectory()) {
        doSeeding(dir);/*from   ww w.  j  a v  a 2s . co  m*/
        return;
    }

    // else try classpath

    final URL res = Thread.currentThread().getContextClassLoader().getResource(location);
    if (res == null) {
        LOGGER.log(Level.WARNING, "Cannot find seed-db resource in the classpath.");
        return;
    }
    if (!"file".equals(res.getProtocol())) {
        LOGGER.log(Level.WARNING, "Cannot load initial OpenAPI documents because seed-db is at {0}!", res);
        return;
    }
    doSeeding(new File(res.getFile()));

}

From source file:wsattacker.plugin.dos.dosExtension.requestSender.RequestSenderImpl.java

private String sendRequestHttpClient(RequestObject requestObject) {

    // get Post Request
    HttpPost post = this.createHttpPostMethod(requestObject);

    // set afterReceive to default value to handle missing responses
    afterReceive = 0;//from   w ww. j  a  v a  2  s .  co  m

    // Get HTTP client and execute request
    try {
        URL url = new URL(requestObject.getEndpoint());
        String protocol = url.getProtocol();

        HttpClient httpClient;
        if (protocol.equalsIgnoreCase("https")) {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String string)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String string)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);

            SSLSocketFactory sf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", url.getPort(), sf);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(httpsScheme);

            // apache HttpClient version >4.2 should use
            // BasicClientConnectionManager
            ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

            httpClient = new DefaultHttpClient(cm);
        } else {
            httpClient = new DefaultHttpClient();
        }

        httpClient.getParams().setParameter("http.socket.timeout", TIMEOUT);
        httpClient.getParams().setParameter("http.connection.timeout", TIMEOUT);
        httpClient.getParams().setParameter("http.connection-manager.max-per-host", TIMEOUT);
        httpClient.getParams().setParameter("http.connection-manager.max-total", new Integer(3000));
        // > params.setDefaultMaxConnectionsPerHost(3000);
        // > params.setMaxTotalConnections(3000);

        beforeSend = System.nanoTime();

        HttpResponse response = httpClient.execute(post);
        StringWriter writer = new StringWriter();
        IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
        responseString = writer.toString();

        afterReceive = System.nanoTime();
        // System.out.println("Response status code: " + result);
        // System.out.println("Response body: " + responseString);
    } catch (IOException ex) {
        // Logger.getLogger(RequestSender.class.getName()).log(Level.SEVERE,
        // null, ex);
        System.out.println("--RequestSender - IO Exception: " + ex.getMessage());

        // ex.printStackTrace();
    } catch (Exception e) {
        // Request timed out!?
        System.out.println("--RequestSender - unexpected Exception: " + e.getMessage());
    } finally {
        // Release current connection to the connection pool
        // post.releaseConnection();

        if (responseString == null) {
            responseString = "";
        }

        // Set afterReceive to beforeSend if afterReceive is 0 so that there 
        // is no huge negative response time when the web service doesn't answer
        if (afterReceive == 0) {
            afterReceive = beforeSend;
        }
    }

    return responseString;
}

From source file:com.crazytest.config.TestCase.java

protected void postWithoutToken(String endpoint, List<NameValuePair> params) throws Exception {
    String endpointString = hostUrl + endpoint;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(new UrlEncodedFormEntity(params));

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;
    LOGGER.info("request: {}", postRequest.getRequestLine());

}

From source file:org.openremote.android.console.net.ORConnection.java

/**
 * Establish the HttpBasicAuthentication httpconnection depend on param <b>isNeedHttpBasicAuth</b>
 * and param <b>isUseSSLfor</b> with url caller, and then the caller can deal with the
 * httprequest result within ORConnectionDelegate instance.
 *
 * @param context               global Android application context
 * @param httpMethod            enum POST or GET
 * @param useHTTPAuth           indicates whether the HTTP 'Authentication' header should be added
 *                              to the HTTP request
 * @param url                   the URL to connect to
 * @param delegateParam         callback delegate to deal with return values, data and exceptions
 *///  w  w w  .j a  v  a 2 s. c  o m
public ORConnection(final Context context, ORHttpMethod httpMethod, boolean useHTTPAuth, String url,
        ORConnectionDelegate delegateParam) {
    initHandler(context);

    delegate = delegateParam;
    this.context = context;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 4 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);

    httpClient = new DefaultHttpClient(params);

    try {
        URL targetUrl = new URL(url);
        targetUrl.toURI();
        if ("https".equals(targetUrl.getProtocol())) {
            Scheme sch = new Scheme(targetUrl.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    targetUrl.getPort());
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }
    }

    catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + url);
        return;
    } catch (URISyntaxException e) {
        Log.e(LOG_CATEGORY, "Could not convert " + url + " to a compliant URI");
        return;
    }

    if (ORHttpMethod.POST.equals(httpMethod)) {
        httpRequest = new HttpPost(url);
    } else if (ORHttpMethod.GET.equals(httpMethod)) {
        httpRequest = new HttpGet(url);
    }

    if (httpRequest == null) {
        Log.e(LOG_CATEGORY, "Create HttpRequest fail:" + url);
        return;
    }

    if (useHTTPAuth) {
        SecurityUtil.addCredentialToHttpRequest(context, httpRequest);
    }

    execute();
}

From source file:com.crazytest.config.TestCase.java

protected void post(String endpoint, List<NameValuePair> params) throws Exception {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(new UrlEncodedFormEntity(params));

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;
    LOGGER.info("request: {}", postRequest.getRequestLine());

}

From source file:com.crazytest.config.TestCase.java

protected void postWithCredential(String endpoint, String params)
        throws UnsupportedEncodingException, URISyntaxException, MalformedURLException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID + params;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;

    LOGGER.info("request: {}", postRequest.getRequestLine());
    LOGGER.info("request: {}", postRequest.getParams().getParameter("licenseeID"));
}

From source file:com.crazytest.config.TestCase.java

protected void putWithCredential(String endpoint, List<NameValuePair> params)
        throws MalformedURLException, URISyntaxException, UnsupportedEncodingException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPut putRequest = new HttpPut(uri);
    putRequest.setEntity(new UrlEncodedFormEntity(params));

    putRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    putRequest.setHeader("User-Agent", "Safari");
    this.putRequest = putRequest;

    LOGGER.info("request: {}", putRequest.getRequestLine());
}