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:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//from  w  ww .  ja v a 2  s  . c o  m
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:org.mrgeo.utils.HadoopUtils.java

public static String findContainingJar(Class clazz) {
    ClassLoader loader = clazz.getClassLoader();
    String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
    try {/*from  www  .  j a  va2 s. c  o m*/
        for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                //toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:com.zimbra.cs.servlet.util.AuthUtil.java

public static String getRedirectURL(HttpServletRequest req, Server server, boolean isAdminRequest,
        boolean relative) throws ServiceException, MalformedURLException {
    String redirectUrl;//from ww  w .j  a  v  a 2  s .com
    if (isAdminRequest) {
        redirectUrl = getAdminURL(server, relative);
    } else {
        redirectUrl = getMailURL(server, relative);
    }
    if (!relative) {
        URL url = new URL(redirectUrl);

        // replace host of the URL to the host the request was sent to
        String reqHost = req.getServerName();
        String host = url.getHost();

        if (!reqHost.equalsIgnoreCase(host)) {
            URL destUrl = new URL(url.getProtocol(), reqHost, url.getPort(), url.getFile());
            redirectUrl = destUrl.toString();
        }
    }
    return redirectUrl;
}

From source file:fr.ardeconnect.proxy.Service.java

static public HttpURLConnection getHUC(String address) {
    HttpURLConnection http = null;
    try {// ww w.  jav a  2  s .  co  m
        URL url = new URL(address);

        if (url.getProtocol().equalsIgnoreCase("https")) {
            // only use trustAllHosts and DO_NOT_VERIFY in development
            // process
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            http = https;
        } else {
            http = (HttpURLConnection) url.openConnection();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return http;
}

From source file:wuit.crawler.searcher.Crawler.java

public static DSCrawlerUrl parsePageUrl(String url, String pageUrl) {
    DSCrawlerUrl info = new DSCrawlerUrl();
    try {/*w  w  w  . ja v a2 s.  c  o  m*/
        if (url.toLowerCase().indexOf("http:") == 0) {
            info.url = url;
            getUrlInfo(info);
        } else {
            URL _pageUrl = new URL(pageUrl);
            int index = pageUrl.lastIndexOf("/");
            //url = url.replaceAll("\\.\\.", "");
            while (url.indexOf(".") == 0) {
                url = url.substring(1, url.length());
            }
            if (url.indexOf("/") == 0)
                info.url = _pageUrl.getProtocol() + "://" + _pageUrl.getHost() + url;
            else
                info.url = _pageUrl.getProtocol() + "://" + _pageUrl.getHost() + "/" + url;
            /////////////////                
            //                System.out.println(url);
            //                System.out.println(info.url); 
            ///////////                
            getUrlInfo(info);
        }
    } catch (Exception e) {
        return null;
    }
    return info;
}

From source file:javarestart.WebClassLoaderRegistry.java

public static WebClassLoader resolveClassLoader(URL url) {
    if (url.getPath().endsWith("/..")) {
        return null;
    }//w  w  w .j  a v a 2  s .com
    WebClassLoader cl = null;
    URL baseURL = normalizeURL(url);
    try {
        URL rootURL = new URL(baseURL, "/");
        while (((cl = associatedClassloaders.get(baseURL)) == null) && !baseURL.equals(rootURL)) {
            baseURL = new URL(baseURL, "..");
        }
    } catch (MalformedURLException e) {
    }

    if (cl == null) {
        try {
            JSONObject desc = Utils.getJSON(new URL(url.getProtocol(), url.getHost(), url.getPort(),
                    url.getPath() + "?getAppDescriptor"));
            if (desc != null) {
                cl = new WebClassLoader(url, desc);
            }
        } catch (Exception e) {
        }
    }
    associatedClassloaders.put(normalizeURL(url), cl);
    if (cl != null) {
        URL clURL = normalizeURL(cl.getBaseURL());
        associatedClassloaders.put(clURL, cl);
        classloaders.put(clURL, cl);
    }
    return cl;
}

From source file:gr.wavesoft.webng.io.web.WebStreams.java

public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException {
    try {//from   www  . j ava2s .  c  o  m

        // WebRequest connection
        ClientConnectionRequest connRequest = connectionManager.requestConnection(
                new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null);

        ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
        try {

            // Prepare request
            BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath());

            // Setup headers
            if (headers != null) {
                for (String k : headers.keySet()) {
                    request.addHeader(k, headers.get(k));
                }
            }

            // Send request
            conn.sendRequestHeader(request);

            // Fetch response
            HttpResponse response = conn.receiveResponseHeader();
            conn.receiveResponseEntity(response);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
                // Replace entity
                response.setEntity(managedEntity);
            }

            // Do something useful with the response
            // The connection will be released automatically 
            // as soon as the response content has been consumed
            return response;

        } catch (IOException ex) {
            // Abort connection upon an I/O error.
            conn.abortConnection();
            throw ex;
        }

    } catch (HttpException ex) {
        throw new IOException("HTTP Exception occured", ex);
    } catch (InterruptedException ex) {
        throw new IOException("InterruptedException", ex);
    } catch (ConnectionPoolTimeoutException ex) {
        throw new IOException("ConnectionPoolTimeoutException", ex);
    }

}

From source file:org.unitedinternet.cosmo.dav.caldav.report.MultigetReport.java

private static URL normalizeHref(URL context, String href) throws CosmoDavException {
    URL url = null;/*  w ww.j  a v a  2  s  .c  o  m*/
    try {
        url = new URL(context, href);
        // check that the URL is escaped. it's questionable whether or
        // not we should all unescaped URLs, but at least as of
        // 10/02/2007, iCal 3.0 generates them
        url.toURI();
        return url;
    } catch (URISyntaxException e) {
        try {
            URI escaped = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(),
                    url.getRef());
            return new URL(escaped.toString());
        } catch (URISyntaxException | MalformedURLException e2) {
            throw new BadRequestException("Malformed unescaped href " + href + ": " + e.getMessage());
        }
    } catch (MalformedURLException e) {
        throw new BadRequestException("Malformed href " + href + ": " + e.getMessage());
    }
}

From source file:com.reizes.shiva.utils.CommonUtil.java

/**
 * http  https URL ??  //from   ww  w  .j  a  v a 2s  .c om
 * @param url
 * @return
 * @throws MalformedURLException 
 */
public static boolean isValidHttpUrl(String url) {
    if (url.length() > 255) { // 255?  url ?  ?
        return false;
    }

    String[] schemes = { "http", "https" };
    UrlValidator urlValidator = new UrlValidator(schemes);
    if (urlValidator.isValid(url)) {
        return true;
    }

    // ?   ??  
    URL urlTemp;
    try {
        urlTemp = new URL(url);
    } catch (MalformedURLException e) {
        return false;
    }
    String forUnicodeUrl = urlTemp.getProtocol() + "://" + IDN.toASCII(urlTemp.getHost());
    if (urlValidator.isValid(forUnicodeUrl)) {
        // ???  http://.com  www      ? 
        return true;
    }

    String regex = "([a-zA-Z0-9-.\\-&/%=?:#$(),.+;~\\_]+)"; // ?  ??  
    if (urlTemp.getHost().startsWith("\"")) {
        // ?? ? ??  ? URL
        return false;
    } else if (urlTemp.getHost().startsWith(".")) {
        // ?? ? ??  ? URL
        return false;
    } else if (urlTemp.getProtocol().startsWith("http") && urlTemp.getHost().matches(regex)) {
        return true;
    }

    return false;
}

From source file:com.izforge.izpack.util.SelfModifier.java

/**
 * Retrieve the jar file the specified class was loaded from.
 *
 * @return null if file was not loaded from a jar file
 * @throws SecurityException if access to is denied by SecurityManager
 *///from w  w w  .j  av  a  2  s  .c  o  m
public static File findJarFile(Class<?> clazz) {
    String resource = clazz.getName().replace('.', '/') + ".class";

    URL url = ClassLoader.getSystemResource(resource);
    if (!"jar".equals(url.getProtocol())) {
        return null;
    }

    String path = url.getFile();
    // starts at "file:..." (use getPath() as of 1.3)
    path = path.substring(0, path.lastIndexOf('!'));

    File file;

    // getSystemResource() returns a valid URL (eg. spaces are %20), but a
    // file
    // Constructed w/ it will expect "%20" in path. URI and File(URI)
    // properly
    file = new File(URI.create(path));

    return file;
}