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.opensymphony.xwork2.util.finder.UrlSet.java

private List<URL> getUrls(ClassLoaderInterface classLoader, Set<String> protocols) throws IOException {

    if (protocols == null) {
        return getUrls(classLoader);
    }// w w  w. jav a2 s  .c om

    List<URL> list = new ArrayList<URL>();

    //find jars
    ArrayList<URL> urls = Collections.list(classLoader.getResources("META-INF"));

    for (URL url : urls) {
        if (protocols.contains(url.getProtocol())) {
            String externalForm = url.toExternalForm();
            //build a URL pointing to the jar, instead of the META-INF dir
            url = new URL(StringUtils.substringBefore(externalForm, "META-INF"));
            list.add(url);
        } else if (LOG.isDebugEnabled())
            LOG.debug("Ignoring URL [#0] because it is not a valid protocol", url.toExternalForm());

    }
    return list;
}

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

@Test
@SuppressWarnings("deprecation")
public void testCreateUrlFromString() throws Exception {

    String urlString = "file:///c:/tmp/";
    URL url = FsHelper.createUrlFromString(urlString, true);

    assertTrue("protocol", "file".equals(url.getProtocol()));
    assertTrue("path " + url.getPath(), "/c:/tmp/".equals(url.getPath()));

    String urlString2 = "file:/c:/tmp/";
    URL url2 = FsHelper.createUrlFromString(urlString2, true);
    assertTrue("protocol", "file".equals(url2.getProtocol()));
    assertTrue("path " + url.getPath(), "/c:/tmp/".equals(url2.getPath()));

    String urlString3 = "../dir/";
    URL url3 = FsHelper.createUrlFromString(urlString3, true);
    assertTrue("protocol", "file".equals(url3.getProtocol()));

    tryExpectingException(() -> {//from  w w w  . jav a  2 s . co  m
        FsHelper.createUrlFromString("..\\dir\\");
    });
    tryExpectingException(() -> {
        FsHelper.createUrlFromString("c:\\dir\\");
    });
    tryExpectingException(() -> {
        FsHelper.createUrlFromString("http://file/");
    });
    tryExpectingException(() -> {
        FsHelper.createUrlFromString("file:\\\file\\");
    });
    tryExpectingException(() -> {
        FsHelper.createUrlFromString(null, true);
    });
}

From source file:com.opensymphony.xwork2.util.finder.UrlSet.java

private List<URL> getUrls(ClassLoaderInterface classLoader) throws IOException {
    List<URL> list = new ArrayList<URL>();

    //find jars/*w  w w  .j a v a 2  s  .  co  m*/
    ArrayList<URL> urls = Collections.list(classLoader.getResources("META-INF"));

    for (URL url : urls) {
        if ("jar".equalsIgnoreCase(url.getProtocol())) {
            String externalForm = url.toExternalForm();
            //build a URL pointing to the jar, instead of the META-INF dir
            url = new URL(StringUtils.substringBefore(externalForm, "META-INF"));
            list.add(url);
        } else if (LOG.isDebugEnabled())
            LOG.debug("Ignoring URL [#0] because it is not a jar", url.toExternalForm());

    }

    //usually the "classes" dir
    list.addAll(Collections.list(classLoader.getResources("")));
    return list;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.worker.DedicatedWorkerGlobalScope.java

/**
 * Constructor./*from   w w  w  . j  ava  2s .  com*/
 * @param browserVersion the simulated browser version
 * @param worker the started worker
 * @throws Exception in case of problem
 */
DedicatedWorkerGlobalScope(final Window owningWindow, final Context context,
        final BrowserVersion browserVersion, final Worker worker) throws Exception {
    context.initStandardObjects(this);

    final ClassConfiguration config = AbstractJavaScriptConfiguration
            .getClassConfiguration(DedicatedWorkerGlobalScope.class, browserVersion);
    final HtmlUnitScriptable prototype = JavaScriptEngine.configureClass(config, null, browserVersion);
    setPrototype(prototype);

    owningWindow_ = owningWindow;
    final URL currentURL = owningWindow.getWebWindow().getEnclosedPage().getUrl();
    origin_ = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();

    worker_ = worker;
}

From source file:com.comcast.cns.io.HTTPEndpointAsyncPublisher.java

@Override
public void send() throws Exception {

    HttpAsyncRequester requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy(),
            httpParams);/*from   www. j  av a 2 s.  c om*/
    final URL url = new URL(endpoint);
    final HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
            url.getPath() + (url.getQuery() == null ? "" : "?" + url.getQuery()));
    composeHeader(request);

    String msg = null;

    if (message.getMessageStructure() == CNSMessageStructure.json) {
        msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http);
    } else {
        msg = message.getMessage();
    }

    if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
        msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http);
    }

    logger.debug("event=send_async_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\"");

    request.setEntity(new NStringEntity(msg));

    requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
            connectionPool, new BasicHttpContext(), new FutureCallback<HttpResponse>() {

                public void completed(final HttpResponse response) {

                    int statusCode = response.getStatusLine().getStatusCode();

                    // accept all 2xx status codes

                    if (statusCode >= 200 && statusCode < 300) {
                        callback.onSuccess();
                    } else {
                        logger.warn(target + "://" + url.getPath() + "?" + url.getQuery() + " -> "
                                + response.getStatusLine());
                        callback.onFailure(statusCode);
                    }
                }

                public void failed(final Exception ex) {
                    logger.warn(target + " " + url.getPath() + " " + url.getQuery(), ex);
                    callback.onFailure(0);
                }

                public void cancelled() {
                    logger.warn(target + " " + url.getPath() + " " + url.getQuery() + " -> " + "cancelled");
                    callback.onFailure(1);
                }
            });
}

From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java

@Override
public String call() throws IOException {
    String response = "";
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
        return response;
    }//from www . j a  v a  2 s .  co  m

    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(AuthScope.ANY, credentials);

    HttpHost proxy = null;
    if (httpProxy != null && !httpProxy.isEmpty()) {
        try {
            URL url = new URL(httpProxy);
            proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
            if (altLogger != null) {
                altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage());
            }
        }
    }

    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultCredentialsProvider(credProvider);
    if (proxy != null) {
        builder.setProxy(proxy);
    }
    CloseableHttpClient httpClient = builder.build();

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase());
            if (altLogger != null) {
                altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase());
            }
        }
    } catch (Exception e) {
        logger.error("Failed to submit result to Gerrit", e);
        if (altLogger != null) {
            altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString());
        }
    }
    return response;
}

From source file:fr.gael.dhus.server.http.webapp.solr.SolrWebapp.java

@Override
public void configure(String dest_folder) throws IOException {
    String configurationFolder = "fr/gael/dhus/server/http/webapp/solr/web";
    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  ww  w.  java 2 s .  c om
}

From source file:at.gv.egiz.pdfas.web.servlets.ProvidePDFServlet.java

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from w w w.  j a  v a 2 s . c  o m*/
        String invokeURL = PdfAsHelper.getInvokeURL(request, response);

        if (invokeURL == null || !WebConfiguration.isProvidePdfURLinWhitelist(invokeURL)) {

            if (invokeURL != null) {
                logger.warn(invokeURL + " is not allowed by whitelist");
            }

            String template = PdfAsHelper.getProvideTemplate();
            template = template.replace(PDF_DATA_URL, PdfAsHelper.generatePdfURL(request, response));
            // Deliver to Browser directly!
            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        } else {
            // Redirect Browser
            String template = PdfAsHelper.getInvokeRedirectTemplateSL();

            URL url = new URL(invokeURL);
            int p = url.getPort();
            //no port, but http or https --> use default port
            if ((url.getProtocol().equalsIgnoreCase("https") || url.getProtocol().equalsIgnoreCase("http"))
                    && p == -1) {
                p = url.getDefaultPort();
            }
            String invokeUrlProcessed = url.getProtocol() + "://" + // "http" + "://
                    url.getHost() + // "myhost"
                    ":" + // ":"
                    p + // "8080"
                    url.getPath();

            template = template.replace("##INVOKE_URL##", invokeUrlProcessed);

            String extraParams = UrlParameterExtractor.buildParameterFormString(url);
            template = template.replace("##ADD_PARAMS##", extraParams);

            byte[] signedData = PdfAsHelper.getSignedPdf(request, response);
            if (signedData != null) {
                template = template.replace("##PDFLENGTH##", String.valueOf(signedData.length));
            } else {
                throw new PdfAsException("No Signature data available");
            }

            String target = PdfAsHelper.getInvokeTarget(request, response);

            if (target == null) {
                target = "_self";
            }

            template = template.replace("##TARGET##", StringEscapeUtils.escapeHtml4(target));

            template = template.replace("##PDFURL##",
                    URLEncoder.encode(PdfAsHelper.generatePdfURL(request, response), "UTF-8"));
            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        }
    } catch (Exception e) {
        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:com.netflix.genie.client.security.oauth2.TokenFetcher.java

/**
 * Constructor./*from w  w w.  j a  v a2s  .  co  m*/
 *
 * @param oauthUrl     The url of the IDP from where to get the credentials.
 * @param clientId     The clientId to use to get the credentials.
 * @param clientSecret The clientSecret to use to get the credentials.
 * @param grantType    The type of the grant.
 * @param scope        The scope of the credentials returned.
 * @throws GenieClientException If there is any problem.
 */
public TokenFetcher(final String oauthUrl, final String clientId, final String clientSecret,
        final String grantType, final String scope) throws GenieClientException {

    log.debug("Constructor called.");

    if (StringUtils.isBlank(oauthUrl)) {
        throw new IllegalArgumentException("URL cannot be null or empty");
    }

    if (StringUtils.isBlank(clientId)) {
        throw new IllegalArgumentException("Client Id cannot be null or empty");
    }

    if (StringUtils.isBlank(clientSecret)) {
        throw new IllegalArgumentException("Client Secret cannot be null or empty");
    }

    if (StringUtils.isBlank(grantType)) {
        throw new IllegalArgumentException("Grant Type cannot be null or empty");
    }

    if (StringUtils.isBlank(scope)) {
        throw new IllegalArgumentException("Scope cannot be null or empty");
    }

    try {
        final URL url = new URL(oauthUrl);

        // Construct the Base path of the type http[s]://serverhost/ for retrofit to work.
        final String oAuthServerUrl = url.getProtocol() + "://" + url.getHost() + "/";
        final Retrofit retrofit = new Retrofit.Builder().baseUrl(oAuthServerUrl)
                .addConverterFactory(JacksonConverterFactory.create()).build();

        this.oauthUrl = oauthUrl;

        // Instantiate the token service
        tokenService = retrofit.create(TokenService.class);

        // Construct the fields map to send to the IDP url.
        credentialParams.put(CLIENT_ID, clientId);
        credentialParams.put(CLIENT_SECRET, clientSecret);
        credentialParams.put(GRANT_TYPE, grantType);
        credentialParams.put(SCOPE, scope);
    } catch (Exception e) {
        throw new GenieClientException("Could not instantiate Token Service due to exception " + e);
    }
}

From source file:com.esri.geoportal.commons.robots.BotsParser.java

private URL getRobotsTxtUrl(URL baseUrl) {
    try {//from  w  w  w  . j  a  v  a  2s  .c om
        if (baseUrl != null) {
            if (baseUrl.getPort() >= 0) {
                return new URL(String.format("%s://%s:%d/robots.txt", baseUrl.getProtocol(), baseUrl.getHost(),
                        baseUrl.getPort()));
            } else {
                return new URL(String.format("%s://%s/robots.txt", baseUrl.getProtocol(), baseUrl.getHost()));
            }
        }
    } catch (MalformedURLException ex) {
        LOG.warn("Invalid robots.txt url.", ex);
    }
    return null;
}