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.spectralogic.ds3client.NetworkClientImpl.java

private static HttpHost buildHost(final ConnectionDetails connectionDetails) throws MalformedURLException {
    final URI proxyUri = connectionDetails.getProxy();
    if (proxyUri != null) {
        return new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());
    } else {//from  ww w  .  j ava 2s  .  co m
        final URL url = NetUtils.buildUrl(connectionDetails, "/");
        return new HttpHost(url.getHost(), NetUtils.getPort(url), url.getProtocol());
    }
}

From source file:it.uniud.ailab.dcore.wrappers.external.OpenNlpBootstrapperAnnotator.java

private static boolean isLocalFile(URL url) {
    String scheme = url.getProtocol();
    String host = url.getHost();/*from w  ww  .  ja  v a 2s .c o  m*/
    return "file".equalsIgnoreCase(scheme) && (host == null || "".equals(host));
}

From source file:JarUtils.java

/** Given a URL check if its a jar url(jar:<url>!/archive) and if it is,
 extract the archive entry into the given dest directory and return a file
 URL to its location. If jarURL is not a jar url then it is simply returned
 as the URL for the jar./*from www.j  a v  a  2s. c o  m*/
        
 @param jarURL the URL to validate and extract the referenced entry if its
   a jar protocol URL
 @param dest the directory into which the nested jar will be extracted.
 @return the file: URL for the jar referenced by the jarURL parameter.
 * @throws IOException 
 */
public static URL extractNestedJar(URL jarURL, File dest) throws IOException {
    // This may not be a jar URL so validate the protocol 
    if (jarURL.getProtocol().equals("jar") == false)
        return jarURL;

    String destPath = dest.getAbsolutePath();
    URLConnection urlConn = jarURL.openConnection();
    JarURLConnection jarConn = (JarURLConnection) urlConn;
    // Extract the archive to dest/jarName-contents/archive
    String parentArchiveName = jarConn.getJarFile().getName();
    // Find the longest common prefix between destPath and parentArchiveName
    int length = Math.min(destPath.length(), parentArchiveName.length());
    int n = 0;
    while (n < length) {
        char a = destPath.charAt(n);
        char b = parentArchiveName.charAt(n);
        if (a != b)
            break;
        n++;
    }
    // Remove any common prefix from parentArchiveName
    parentArchiveName = parentArchiveName.substring(n);

    File archiveDir = new File(dest, parentArchiveName + "-contents");
    if (archiveDir.exists() == false && archiveDir.mkdirs() == false)
        throw new IOException(
                "Failed to create contents directory for archive, path=" + archiveDir.getAbsolutePath());
    String archiveName = jarConn.getEntryName();
    File archiveFile = new File(archiveDir, archiveName);
    File archiveParentDir = archiveFile.getParentFile();
    if (archiveParentDir.exists() == false && archiveParentDir.mkdirs() == false)
        throw new IOException(
                "Failed to create parent directory for archive, path=" + archiveParentDir.getAbsolutePath());
    InputStream archiveIS = jarConn.getInputStream();
    FileOutputStream fos = new FileOutputStream(archiveFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    byte[] buffer = new byte[4096];
    int read;
    while ((read = archiveIS.read(buffer)) > 0) {
        bos.write(buffer, 0, read);
    }
    archiveIS.close();
    bos.close();

    // Return the file url to the extracted jar
    return archiveFile.toURL();
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.Utils.java

/**
 * Builds rewrite domain from backend route url.
 *
 * @param backendRoute Backend route.//from  ww w  .j a  va  2s .  c om
 * @param subzone      Subzone
 * @return Rewrite domain.
 * @throws MalformedURLException if backendRoute parameter has invalid format.
 */
public static String buildRewriteDomain(String backendRoute, String subzone) throws MalformedURLException {
    if (backendRoute == null || backendRoute.isEmpty()) {
        logger.error("Backend route can't be null.");
        return null;
    }

    String applicationRoute = backendRoute;

    if (!applicationRoute.startsWith(BMSClient.HTTP_SCHEME)) {
        applicationRoute = String.format("%s://%s", BMSClient.HTTPS_SCHEME, applicationRoute);
    } else if (!applicationRoute.startsWith(BMSClient.HTTPS_SCHEME)
            && applicationRoute.contains(BLUEMIX_NAME)) {
        applicationRoute = applicationRoute.replace(BMSClient.HTTP_SCHEME, BMSClient.HTTPS_SCHEME);
    }

    URL url = new URL(applicationRoute);

    String host = url.getHost();
    String rewriteDomain;
    String regionInDomain = "ng";
    int port = url.getPort();

    String serviceUrl = String.format("%s://%s", url.getProtocol(), host);

    if (port != 0) {
        serviceUrl += ":" + String.valueOf(port);
    }

    String[] hostElements = host.split("\\.");

    if (!serviceUrl.contains(STAGE1_NAME)) {
        // Multi-region: myApp.eu-gb.mybluemix.net
        // US: myApp.mybluemix.net
        if (hostElements.length == 4) {
            regionInDomain = hostElements[hostElements.length - 3];
        }

        // this is production, because STAGE1 is not found
        // Multi-Region Eg: eu-gb.bluemix.net
        // US Eg: ng.bluemix.net
        rewriteDomain = String.format("%s.%s", regionInDomain, BLUEMIX_DOMAIN);
    } else {
        // Multi-region: myApp.stage1.eu-gb.mybluemix.net
        // US: myApp.stage1.mybluemix.net
        if (hostElements.length == 5) {
            regionInDomain = hostElements[hostElements.length - 3];
        }

        if (subzone != null && !subzone.isEmpty()) {
            // Multi-region Dev subzone Eg: stage1-Dev.eu-gb.bluemix.net
            // US Dev subzone Eg: stage1-Dev.ng.bluemix.net
            rewriteDomain = String.format("%s-%s.%s.%s", STAGE1_NAME, subzone, regionInDomain, BLUEMIX_DOMAIN);
        } else {
            // Multi-region Eg: stage1.eu-gb.bluemix.net
            // US  Eg: stage1.ng.bluemix.net
            rewriteDomain = String.format("%s.%s.%s", STAGE1_NAME, regionInDomain, BLUEMIX_DOMAIN);
        }
    }

    return rewriteDomain;
}

From source file:org.apache.kylin.engine.mr.common.HadoopStatusGetter.java

private static boolean isValidURL(String value) {
    if (StringUtils.isNotEmpty(value)) {
        java.net.URL url;
        try {/* w  w  w .ja v a 2  s  .  c  o m*/
            url = new java.net.URL(value);
        } catch (MalformedURLException var5) {
            return false;
        }

        return StringUtils.isNotEmpty(url.getProtocol()) && StringUtils.isNotEmpty(url.getHost());
    }

    return false;
}

From source file:com.hypersocket.client.hosts.HostsFileManager.java

public static URL sanitizeURL(String url) throws MalformedURLException {

    URL u = new URL(url);
    String hostname = IPAddressValidator.getInstance().getGuaranteedHostname(u.getHost());
    return new URL(u.getProtocol(), hostname, u.getPort(), u.getFile());
}

From source file:org.wso2.carbon.appmgt.gateway.utils.GatewayUtils.java

public static String getAppRootURL(MessageContext messageContext) {

    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();

    try {/*from  w w w .ja  v  a 2 s  . com*/

        // SERVICE_PREFIX gives the URL of the root. e.g. https://192.168.0.1:8243

        // WARNING : Service prefix always gives the IP address even if the request is made with a host name.
        // So we should only get the protocol from the service prefix.

        String servicePrefix = axis2MessageContext.getProperty("SERVICE_PREFIX").toString();
        URL serverRootURL = new URL(servicePrefix);
        String protocol = serverRootURL.getProtocol();

        // Get the published gateway URL for the protocol
        Environment defaultGatewayEnv = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration()
                .getApiGatewayEnvironments().get(0);

        String commaSeparatedGatewayEndpoints = defaultGatewayEnv.getApiGatewayEndpoint();
        String[] gatewayEndpoints = commaSeparatedGatewayEndpoints.split(",");

        URL gatewayEndpointURL = null;
        for (String gatewayEndpoint : gatewayEndpoints) {
            URL parsedEndpointURL = new URL(gatewayEndpoint);

            if (parsedEndpointURL.getProtocol().equals(protocol)) {
                gatewayEndpointURL = parsedEndpointURL;
                break;
            }
        }

        String webAppContext = (String) messageContext.getProperty(RESTConstants.REST_API_CONTEXT);
        String webAppVersion = (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);

        URL appRootURL = new URL(gatewayEndpointURL.getProtocol(), gatewayEndpointURL.getHost(),
                gatewayEndpointURL.getPort(), webAppContext + "/" + webAppVersion + "/");
        return appRootURL.toString();
    } catch (MalformedURLException e) {
        log.error("Error occurred while constructing the app root URL.", e);
        return null;
    }
}

From source file:com.dianping.resource.io.util.ResourceUtils.java

/**
 * Resolve the given resource URL to a {@code java.io.File},
 * i.e. to a file in the file system./*from w  ww  .j  av a  2  s  .c  om*/
 * @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 java.io.FileNotFoundException if the URL cannot be resolved to
 * a file in the file system
 */
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
    Assert.notNull(resourceUrl, "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());
    }
}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * /*  ww  w. j  a  v  a  2s.  com*/
 * @param latitude
 * @param longitude
 * @return 
 */
public static HashMap reverse(double latitude, double longitude) {
    HashMap a = new HashMap();
    try {
        //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude));            
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng="
                + String.valueOf(latitude) + "," + String.valueOf(longitude));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream()));
        String textJson = "", tempJs;
        while ((tempJs = lector.readLine()) != null)
            textJson += tempJs;
        if (textJson == null)
            throw new Exception("Don't found item");
        JSONObject google = ((JSONObject) JSONValue.parse(textJson));
        a.put("status", google.get("status").toString());
        if (a.get("status").toString().equals("OK")) {
            JSONArray results = (JSONArray) google.get("results");
            JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components");
            for (int i = 0; i < address_components.size(); i++) {
                JSONObject items = (JSONObject) address_components.get(i);
                //if(((JSONObject)types.get(0)).get("").toString().equals("country"))
                if (items.get("types").toString().contains("country")) {
                    a.put("country", items.get("long_name").toString());
                    a.put("iso", items.get("short_name").toString());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        a = null;
        System.out.println("Error Google Geocoding: " + ex);
    }
    return a;
}

From source file:com.google.gwt.dev.resource.impl.ResourceOracleImpl.java

public static ClassPathEntry createEntryForUrl(TreeLogger logger, URL url)
        throws URISyntaxException, IOException {
    if (url.getProtocol().equals("file")) {
        File f = new File(url.toURI());
        String lowerCaseFileName = f.getName().toLowerCase(Locale.ENGLISH);
        if (f.isDirectory()) {
            return new DirectoryClassPathEntry(f);
        } else if (f.isFile() && lowerCaseFileName.endsWith(".jar")) {
            return ZipFileClassPathEntry.get(f);
        } else if (f.isFile() && lowerCaseFileName.endsWith(".zip")) {
            return ZipFileClassPathEntry.get(f);
        } else {//  www.  j a  va2 s .co  m
            // It's a file ending in neither jar nor zip, speculatively try to
            // open as jar/zip anyway.
            try {
                return ZipFileClassPathEntry.get(f);
            } catch (Exception ignored) {
            }
            if (logger.isLoggable(TreeLogger.TRACE)) {
                logger.log(TreeLogger.TRACE, "Unexpected entry in classpath; " + f
                        + " is neither a directory nor an archive (.jar or .zip)");
            }
            return null;
        }
    } else {
        logger.log(TreeLogger.WARN, "Unknown URL type for " + url, null);
        return null;
    }
}