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.conversantmedia.mapreduce.tool.RunJob.java

/**
 * Finds the first non-jar'd MANIFEST.MF. We assume this one is it.
 * No good way to determine otherwise, but there should only be one that
 * isn't jar'd if run via hadoop command.
 * /*from   w w w . j  a  v a 2 s .c o m*/
 * @return   location of the manifest 
 */
private static URL findManifestForDriver() {
    try {
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader()
                .getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {
            URL manifestUrl = resources.nextElement();
            // If it is a 'jar' we would have gotten from getImplementationVersion call
            if (!StringUtils.equals("jar", manifestUrl.getProtocol())) {
                return manifestUrl;
            }
        }
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
    return null;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
 * FUNKTIONIERT NICHT, HOST WIRD NICHT UEBERNOMMEN
 * Clones a http method and sets a new url
 * @param src/*from  w w w . j  a  va  2  s .  c om*/
 * @param url
 * @return
 */
private static HttpMethod clone(HttpMethod src, URL url) {
    HttpMethod trg = HttpMethodCloner.clone(src);
    HostConfiguration trgConfig = trg.getHostConfiguration();
    trgConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());
    trg.setPath(url.getPath());
    trg.setQueryString(url.getQuery());

    return trg;
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
    HttpClientContext context = null;//from ww  w  .  j a  v  a 2s . c  om
    HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
    if (username != null && password != null) {

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, password));

        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, new BasicScheme());

        // Add AuthCache to the execution context
        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } else {
        context = null;
    }
    return context;
}

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

/**
 * Detect the groupmembers of current server url
 *///from   w ww .j ava2  s  .c o m
public static boolean detectGroupMembers(Context context) {
    Log.i(LOG_CATEGORY, "Detecting group members with current controller server url "
            + AppSettingsModel.getCurrentServer(context));

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);
    HttpClient httpClient = new DefaultHttpClient(params);
    String url = AppSettingsModel.getSecuredServer(context);
    HttpGet httpGet = new HttpGet(url + "/rest/servers");

    if (httpGet == null) {
        Log.e(LOG_CATEGORY, "Create HttpRequest fail.");

        return false;
    }

    SecurityUtil.addCredentialToHttpRequest(context, httpGet);

    // TODO : fix the exception handling in this method -- it is ridiculous.

    try {
        URL uri = new URL(url);

        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }

        HttpResponse httpResponse = httpClient.execute(httpGet);

        try {
            if (httpResponse.getStatusLine().getStatusCode() == Constants.HTTP_SUCCESS) {
                InputStream data = httpResponse.getEntity().getContent();

                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document dom = builder.parse(data);
                    Element root = dom.getDocumentElement();

                    NodeList nodeList = root.getElementsByTagName("server");
                    int nodeNums = nodeList.getLength();
                    List<String> groupMembers = new ArrayList<String>();

                    for (int i = 0; i < nodeNums; i++) {
                        groupMembers.add(nodeList.item(i).getAttributes().getNamedItem("url").getNodeValue());
                    }

                    Log.i(LOG_CATEGORY, "Detected groupmembers. Groupmembers are " + groupMembers);

                    return saveGroupMembersToFile(context, groupMembers);
                } catch (IOException e) {
                    Log.e(LOG_CATEGORY, "The data is from ORConnection is bad", e);
                } catch (ParserConfigurationException e) {
                    Log.e(LOG_CATEGORY, "Cant build new Document builder", e);
                } catch (SAXException e) {
                    Log.e(LOG_CATEGORY, "Parse data error", e);
                }
            }

            else {
                Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error");
            }
        }

        catch (IllegalStateException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

        catch (IOException e) {
            Log.e(LOG_CATEGORY, "detectGroupMembers Parse data error", e);
        }

    }

    catch (MalformedURLException e) {
        Log.e(LOG_CATEGORY, "Create URL fail:" + url);
    }

    catch (ConnectException e) {
        Log.e(LOG_CATEGORY, "Connection refused: " + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (ClientProtocolException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (SocketTimeoutException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IOException e) {
        Log.e(LOG_CATEGORY, "Can't Detect groupmembers with current controller server "
                + AppSettingsModel.getCurrentServer(context), e);
    }

    catch (IllegalArgumentException e) {
        Log.e(LOG_CATEGORY, "Host name can be null :" + AppSettingsModel.getCurrentServer(context), e);
    }

    return false;
}

From source file:org.wso2.developerstudio.appcloud.utils.client.HttpsJaggeryClient.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base, String urlStr) {
    try {/*from w  ww.  ja  va 2 s.  c om*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        URL url = new URL(urlStr);
        int port = url.getPort();
        if (port == -1) {
            port = 443;
        }
        String protocol = url.getProtocol();
        if ("https".equals(protocol)) {
            if (port == -1) {
                port = 443;
            }
        } else if ("http".equals(protocol)) {
            if (port == -1) {
                port = 80;
            }
        }
        sr.register(new Scheme(protocol, ssf, port));

        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Throwable ex) {
        ex.printStackTrace();
        log.error("Trust Manager Error", ex);
        return null;
    }
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static File download(File file, URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    OutputStream out = null;//from  w  w  w .  j a v  a 2 s.  c o  m
    file.getParentFile().mkdirs();
    try {
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpGet request = new HttpGet(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        InputStream in = response.getEntity().getContent();
        out = new BufferedOutputStream(new FileOutputStream(file));
        copy(in, out);
        return file;
    } catch (Exception e) {
        logWarning(e);
        ;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:it.geosolutions.geostore.core.security.password.URLMasterPasswordProvider.java

static InputStream input(URL url, File configDir) throws IOException {
    //check for a file url
    if (url == null) {
        //default master password
        url = URLMasterPasswordProvider.class.getClassLoader().getResource("passwd");
    }/*  w w w. j  a v a 2 s  . c om*/
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }

        //check if the file is relative
        if (!f.isAbsolute()) {
            //make it relative to the config directory for this password provider
            f = new File(configDir, f.getPath());
        }
        return new FileInputStream(f);
    } else {
        return url.openStream();
    }
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

private static String normalizeURL(String uriString) throws RemoteException {
    try {/*from   w  w  w. ja va  2s  .  com*/
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (Exception e) {
        throw new RemoteException(e.getMessage());
    }
    return uriString;
}

From source file:com.netflix.config.ConfigurationManager.java

private static String getConfigName(URL propertyFile) {
    String name = propertyFile.toExternalForm();
    name = name.replace('\\', '/'); // Windows
    final String scheme = propertyFile.getProtocol().toLowerCase();
    if ("jar".equals(scheme) || "zip".equals(scheme)) {
        // Use the unqualified name of the jar file.
        final int bang = name.lastIndexOf("!");
        if (bang >= 0) {
            name = name.substring(0, bang);
        }// w  w  w . j  av  a2 s.c  o  m
        final int slash = name.lastIndexOf("/");
        if (slash >= 0) {
            name = name.substring(slash + 1);
        }
    } else {
        // Use the URL of the enclosing directory.
        final int slash = name.lastIndexOf("/");
        if (slash >= 0) {
            name = name.substring(0, slash);
        }
    }
    return name;
}

From source file:cn.org.rapid_framework.generator.util.ResourceHelper.java

/**
 * Resolve the given resource URL to a <code>java.io.File</code>,
 * i.e. to a file in the file system./*w  ww . j av  a  2  s . co m*/
 * @param resourceUrl the resource URL to resolve
 * @param description a description of the original resource that
 * the URL was created for (for example, a class path location)
 * @return a corresponding File object
 * @throws FileNotFoundException if the URL cannot be resolved to
 * a file in the file system
 */
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
    if (resourceUrl == null)
        throw new IllegalArgumentException("Resource URL must not be null");

    if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
        throw new FileNotFoundException(description + " cannot be resolved to absolute file path "
                + "because it does not reside in the file system: " + resourceUrl);
    }
    try {
        return new File(toURI(resourceUrl).getSchemeSpecificPart());
    } catch (URISyntaxException ex) {
        // Fallback for URLs that are not valid URIs (should hardly ever happen).
        return new File(resourceUrl.getFile());
    }
}