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:de.thetaphi.forbiddenapis.CliMain.java

private void printHelp(Options options) {
    final HelpFormatter formatter = new HelpFormatter();
    String cmdline = "java " + getClass().getName();
    try {/*from   w  w w  . j  a v a 2  s .  co m*/
        final URLConnection conn = getClass().getResource(getClass().getSimpleName() + ".class")
                .openConnection();
        if (conn instanceof JarURLConnection) {
            final URL jarUrl = ((JarURLConnection) conn).getJarFileURL();
            if ("file".equalsIgnoreCase(jarUrl.getProtocol())) {
                final String cwd = new File(".").getCanonicalPath(),
                        path = new File(jarUrl.toURI()).getCanonicalPath();
                cmdline = "java -jar "
                        + (path.startsWith(cwd) ? path.substring(cwd.length() + File.separator.length())
                                : path);
            }
        }
    } catch (IOException ioe) {
        // ignore, use default cmdline value
    } catch (URISyntaxException use) {
        // ignore, use default cmdline value
    }
    formatter.printHelp(cmdline + " [options]", "Scans a set of class files for forbidden API usage.", options,
            String.format(Locale.ENGLISH,
                    "Exit codes: %d = SUCCESS, %d = forbidden API detected, %d = invalid command line, %d = unsupported JDK version, %d = other error (I/O,...)",
                    EXIT_SUCCESS, EXIT_VIOLATION, EXIT_ERR_CMDLINE, EXIT_UNSUPPORTED_JDK, EXIT_ERR_OTHER));
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Returns true if the URL is a file URL
 * // w w w  .jav a  2s.  c  om
 * @param url
 *            the file URL
 * @return true if the supplied url is a file url
 */
public static boolean isFileURL(URL url) {
    return url.getProtocol().equalsIgnoreCase("file");
}

From source file:com.googlecode.l10nmavenplugin.validators.property.UrlValidator.java

/**
 * ERROR if URL does not match regexp./*  ww w .j a  va 2s  .c  o m*/
 * 
 * ERROR if URL does not support https context and is an HTML import.
 * 
 * Performs a MessageFormat if needed.
 * 
 * @note the {@link org.apache.commons.validator.UrlValidator} from Apache does not seem to support scheme relative URLs.
 * 
 * @param key
 * @param message
 * @param propertyName
 * @return Number of errors
 */
public int validate(Property property, List<L10nReportItem> reportItems) {
    int nbErrors = 0;
    String formattedMessage = property.getMessage();

    try {
        if (formattingParametersExtractor.isParametric(formattedMessage)) {
            formattedMessage = formattingParametersExtractor.defaultFormat(property.getMessage());
        }
        // Unescape HTML in case URL is used in HTML context (ex: &amp; -> &)
        String url = StringEscapeUtils.unescapeHtml(formattedMessage);
        Matcher m = URL_VALIDATION_PATTERN.matcher(url);

        if (!m.matches()) {
            nbErrors++;
            L10nReportItem reportItem = new L10nReportItem(Type.URL_VALIDATION, "Invalid URL syntax.", property,
                    formattedMessage);
            reportItems.add(reportItem);
            logger.log(reportItem);

        } else {
            // If URL path extension is an HTML include (.js, .css, .jpg, ...) check that URL inherits https protocol
            // Context is mandatory for scheme relative URLs
            URL context = new URL("https://");
            URL resultingURL = new URL(context, url);

            String extension = FilenameUtils.getExtension(resultingURL.getPath());
            if (HTML_URL_INCLUDE_EXTESIONS.contains(extension) && !"https".equals(resultingURL.getProtocol())) {
                nbErrors++;
                L10nReportItem reportItem = new L10nReportItem(Type.URL_VALIDATION,
                        "URL for external HTML import [." + extension
                                + "] must be scheme relative to avoid mixed content in HTTPS context.",
                        property, formattedMessage);
                reportItems.add(reportItem);
                logger.log(reportItem);
            }
        }

    } catch (IllegalArgumentException e) {
        // Catch MessageFormat errors in case of malformed message
        nbErrors++;
        L10nReportItem reportItem = new L10nReportItem(Type.MALFORMED_PARAMETER,
                "URL contains malformed parameters: " + e.getMessage(), property, formattedMessage);
        reportItems.add(reportItem);
        logger.log(reportItem);
    } catch (MalformedURLException e) {
        nbErrors++;
        L10nReportItem reportItem = new L10nReportItem(Type.URL_VALIDATION, "Malformed URL: " + e.getMessage(),
                property, formattedMessage);
        reportItems.add(reportItem);
        logger.log(reportItem);
    }

    return nbErrors;
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Returns true if the supplied URL is using one of the formats supported by
 * open-delta - the supported formats are http, ftp and file.
 * /*w ww  .  j av a  2 s . co m*/
 * @param url
 *            the url
 * @return true if the url is one of the supported formats
 */
public static boolean checkURLValidProtocol(URL url) {
    return (url.getProtocol().equalsIgnoreCase("http")
            || (url.getProtocol().equalsIgnoreCase("ftp") || (url.getProtocol().equalsIgnoreCase("file"))));
}

From source file:org.fao.geonet.utils.GeonetHttpRequestFactory.java

/**
 * Ceate an XmlRequest from a url./*from   w  w  w  . jav  a 2  s  .c  om*/
 *
 * @param url the url of the request.
 * @return the XmlRequest.
 */
public final XmlRequest createXmlRequest(URL url) {
    final int port = url.getPort();
    final XmlRequest request = createXmlRequest(url.getHost(), port, url.getProtocol());

    request.setAddress(url.getPath());
    request.setQuery(url.getQuery());
    request.setFragment(url.getRef());
    request.setUserInfo(url.getUserInfo());
    request.setCookieStore(new BasicCookieStore());
    return request;
}

From source file:com.fluidops.iwb.api.solution.AbstractSingleFileBasedSolutionService.java

@Override
public InstallationResult install(URL solutionArtifact) throws RemoteException {
    if (solutionArtifact == null) {
        return null;
    }/*from   w w  w . j  a v  a2  s  .c o m*/
    // check whether URL is a file URL pointing to a local file
    if (solutionArtifact.getProtocol().equals("file")) {
        File file;
        try {
            file = new File(solutionArtifact.toURI());
        } catch (Exception e) {
            file = new File(solutionArtifact.getPath());
        }
        return install(file);
    }
    logger.info("Installing solution from URL " + solutionArtifact.toString());
    InstallationResult res = doInstall(solutionArtifact);
    return res;
}

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

private String getCookie(URL url, HttpConnectionInterceptorContext context) {
    try {//from   w  w w  .  j  av  a2 s .c om
        URL sessionURL = new URL(
                String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort()));

        HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded");
        conn.setRequestBody(sessionRequestBody);

        //when we request the session we need all interceptors except this one

        conn.requestInterceptors.addAll(context.connection.requestInterceptors);
        conn.requestInterceptors.remove(this);
        conn.responseInterceptors.addAll(context.connection.responseInterceptors);
        conn.responseInterceptors.remove(this);

        HttpURLConnection connection = conn.execute().getConnection();
        String cookieHeader = connection.getHeaderField("Set-Cookie");
        int responseCode = connection.getResponseCode();

        if (responseCode / 100 == 2) {

            if (sessionHasStarted(connection.getInputStream())) {
                return cookieHeader.substring(0, cookieHeader.indexOf(";"));
            } else {
                return null;
            }

        } else if (responseCode == 401) {
            shouldAttemptCookieRequest = false;
            logger.severe("Credentials are incorrect, cookie authentication will not be"
                    + " attempted again by this interceptor object");
        } else if (responseCode / 100 == 5) {
            logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth",
                    responseCode);
        } else {
            // catch any other response code
            logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, "
                    + "cookie authentication will not be attempted again", responseCode);
            shouldAttemptCookieRequest = false;
        }

    } catch (MalformedURLException e) {
        logger.log(Level.SEVERE, "Failed to create URL for _session endpoint", e);
    } catch (UnsupportedEncodingException e) {
        logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to read cookie response header", e);
    }
    return null;
}

From source file:com.ironiacorp.scm.subversion.SubversionRepository.java

/**
 * If the location is of the type "file", return the real physical location of the repository in
 * the server. Otherwise, return null;/*w  w  w  . ja va  2 s . co m*/
 * 
 * @return The pathname for the repository if it's local, null otherwise.
 */
private String getLocalPath() {
    try {
        URL url = new URL(getLocation());
        if (url.getProtocol().equals("file")) {
            return url.getPath();
        }
    } catch (MalformedURLException e) {
        // This will never happen, as the location is always checked when first set.
        throw new IllegalArgumentException("exception.repository.invalidLocation", e);
    }

    return null;
}

From source file:com.conwet.wirecloud.ide.WirecloudAPI.java

public WirecloudAPI(URL deploymentServer) {
    try {//from www .j  av a  2 s  .c om
        deploymentServer = new URL(deploymentServer.getProtocol(), deploymentServer.getHost(),
                deploymentServer.getPort(), deploymentServer.getPath());
    } catch (Exception e) {
        // Should not happen as the URL is build from a valid URL
        e.printStackTrace();
    }
    this.url = deploymentServer;
    this.AUTH_ENDPOINT = DEFAULT_AUTH_ENDPOINT;
    this.TOKEN_ENDPOINT = DEFAULT_TOKEN_ENDPOINT;
    try {
        this.UNIVERSAL_REDIRECT_URI = new URL(deploymentServer, DEFAULT_UNIVERSAL_REDIRECT_URI_PATH).toString();
    } catch (MalformedURLException e) {
        // Should not happen as the URL is build from a valid URL using a
        // constant
        e.printStackTrace();
    }
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }/*from  w ww  .  j av  a2s  .  com*/
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}