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.lightlink.utils.ClasspathScanUtils.java

public static List<String> getResourcesFromPackage(String packageName) throws IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> packageURLs;
    ArrayList<String> names = new ArrayList<String>();

    packageName = packageName.replace(".", "/");
    packageURLs = classLoader.getResources(packageName);

    while (packageURLs.hasMoreElements()) {
        URL packageURL = packageURLs.nextElement();
        // loop through files in classpath

        if (packageURL.getProtocol().equals("jar")) {
            String jarFileName;/*w ww .  j  a  v  a 2s . c o m*/
            JarFile jf;
            Enumeration<JarEntry> jarEntries;
            String entryName;

            // build jar file name, then loop through zipped entries
            jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
            jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
            jf = new JarFile(jarFileName);
            jarEntries = jf.entries();
            while (jarEntries.hasMoreElements()) {
                entryName = jarEntries.nextElement().getName();
                if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {
                    entryName = entryName.substring(packageName.length());
                    names.add(entryName);
                }
            }

        } else {

            findFromDirectory(packageURL, names);
        }
    }

    return names;
}

From source file:com.cloud.utils.PropertiesUtil.java

/**
 * Searches the class path and local paths to find the config file.
 * @param path path to find.  if it starts with / then it's absolute path.
 * @return File or null if not found at all.
 *//*from w  w  w .j a  v a 2  s. c  om*/

public static File findConfigFile(String path) {
    ClassLoader cl = PropertiesUtil.class.getClassLoader();
    URL url = cl.getResource(path);
    if (url != null && "file".equals(url.getProtocol())) {
        return new File(url.getFile());
    }

    url = ClassLoader.getSystemResource(path);
    if (url != null && "file".equals(url.getProtocol())) {
        return new File(url.getFile());
    }

    File file = new File(path);
    if (file.exists()) {
        return file;
    }

    String newPath = "conf" + (path.startsWith(File.separator) ? "" : "/") + path;
    url = ClassLoader.getSystemResource(newPath);
    if (url != null && "file".equals(url.getProtocol())) {
        return new File(url.getFile());
    }

    url = cl.getResource(newPath);
    if (url != null && "file".equals(url.getProtocol())) {
        return new File(url.getFile());
    }

    newPath = "conf" + (path.startsWith(File.separator) ? "" : File.separator) + path;
    file = new File(newPath);
    if (file.exists()) {
        return file;
    }

    newPath = System.getProperty("catalina.home");
    if (newPath == null) {
        newPath = System.getenv("CATALINA_HOME");
    }

    if (newPath == null) {
        newPath = System.getenv("CATALINA_BASE");
    }

    if (newPath == null) {
        return null;
    }

    file = new File(newPath + File.separator + "conf" + File.separator + path);
    if (file.exists()) {
        return file;
    }

    return null;
}

From source file:com.shishu.utility.url.TableUtil.java

/**
 * Reverses a url's domain. This form is better for storing in hbase. Because
 * scans within the same domain are faster.
 * <p>//from   www . j a  v  a 2s.co  m
 * E.g. "http://bar.foo.com:8983/to/index.html?a=b" becomes
 * "com.foo.bar:http:8983/to/index.html?a=b".
 *
 * @param url
 *          url to be reversed
 * @return Reversed url
 */
public static String reverseUrl(URL url) {
    String host = url.getHost();
    String file = url.getFile();
    String protocol = url.getProtocol();
    int port = url.getPort();

    StringBuilder buf = new StringBuilder();

    /* reverse host */
    reverseAppendSplits(host, buf);

    /* add protocol */
    buf.append(':');
    buf.append(protocol);

    /* add port if necessary */
    if (port != -1) {
        buf.append(':');
        buf.append(port);
    }

    /* add path */
    if (file.length() > 0 && '/' != file.charAt(0)) {
        buf.append('/');
    }
    buf.append(file);

    return buf.toString();
}

From source file:Main.java

private static URL getRootUrlForClass(Class<?> cls) {
    ClassLoader classLoader = cls.getClassLoader();
    String resource = cls.getName().replace('.', '/') + ".class";
    if (classLoader == null) {
        // A null class loader means the bootstrap class loader. In this case we use the
        // system class loader. This is safe since we can assume that the system class
        // loader uses parent first as delegation policy.
        classLoader = ClassLoader.getSystemClassLoader();
    }/*from  w w w. j  a va2s . co m*/
    URL url = classLoader.getResource(resource);
    if (url == null) {
        return null;
    }
    String file = url.getFile();
    if (file.endsWith(resource)) {
        try {
            return new URL(url.getProtocol(), url.getHost(), url.getPort(),
                    file.substring(0, file.length() - resource.length()));
        } catch (MalformedURLException ex) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:davmail.http.DavGatewaySSLProtocolSocketFactory.java

/**
 * Register custom Socket Factory to let user accept or reject certificate
 *//*from  ww  w  . j a v  a  2s  . co  m*/
public static void register() {
    String urlString = Settings.getProperty("davmail.url");
    try {
        URL url = new URL(urlString);
        String protocol = url.getProtocol();
        if ("https".equals(protocol)) {
            int port = url.getPort();
            if (port < 0) {
                port = HttpsURL.DEFAULT_PORT;
            }
            Protocol.registerProtocol(url.getProtocol(), new Protocol(protocol,
                    (ProtocolSocketFactory) new DavGatewaySSLProtocolSocketFactory(), port));
        }
    } catch (MalformedURLException e) {
        DavGatewayTray.error(new BundleMessage("LOG_INVALID_URL", urlString));
    }
}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentAnalyzer.java

public static String adjustAnchorUrl(String href, String urlString) throws MalformedURLException {
    if (href.trim().length() == 0) {
        return null;
    }//from   w  ww .  j  a v  a  2 s. c om
    if (href.startsWith("#")) {
        return null;
    }

    if (href.startsWith("http") == false) {
        if (href.startsWith("//")) {
            final URL url = new URL(urlString);
            href = url.getProtocol() + ":" + href;
        } else if (href.startsWith("/")) {
            final URL url = new URL(urlString);
            final String hostpart = url.getProtocol() + "://" + url.getHost();
            href = hostpart + href;
        } else if (href.startsWith(".")) {
            if (urlString.endsWith("/")) {
                href = urlString + href;
            } else {
                href = urlString.substring(0, urlString.lastIndexOf('/') + 1) + href;
            }
        } else {
            // ?????
            if (urlString.endsWith("/")) {
                // ????
                href = urlString + href;
            } else {
                href = urlString.substring(0, urlString.lastIndexOf('/') + 1) + href;
            }
        }
    }

    return href;
}

From source file:edu.kit.dama.staging.entities.AdalapiProtocolConfiguration.java

/**
 * Get the unique protocol identifier for the provided Url. The identifier
 * is generated using the schema:/*from w ww. ja  v a2  s  .  com*/
 *
 * protocol[@host][:port]
 *
 * Valid identifiers according to this schema are e.g. http@myHost;
 * http@myHost:8080; ftp@anotherHost; file
 *
 * As there is no host/port information for Urls accessed via file protocol,
 * there is only one valid identifier for file Urls.
 *
 * @param pUrl A sample URL (protocol and authority are sufficient, e.g.
 * http://remoteHost:8080) as it should be accessed by the provided protocol
 * implementation.
 *
 * @return The identifier string.
 */
public final static String getProtocolIdentifier(URL pUrl) {
    String protocol = pUrl.getProtocol();
    if (protocol == null) {
        throw new IllegalArgumentException("The provided Url " + pUrl + " has no protocol specified.");
    }
    String host = pUrl.getHost();
    int port = pUrl.getPort();

    if (host == null) {
        return protocol;
    } else {
        return protocol + "@" + host + ((port > -1) ? ":" + Integer.toString(port) : "");
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.core.util.FileUtils.java

/**
 * Make the given URL available as a file. A temporary file is created and
 * deleted upon a regular shutdown of the JVM. If the parameter {@code
 * aCache} is {@code true}, the temporary file is remembered in a cache and
 * if a file is requested for the same URL at a later time, the same file is
 * returned again. If the previously created file has been deleted
 * meanwhile, it is recreated from the URL.
 *
 * @param aUrl//from w ww  . ja  va  2s  .  c  om
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @return a file created from the given URL.
 * @throws IOException
 *             if the URL cannot be accessed to (re)create the file.
 */
public static synchronized File getUrlAsFile(URL aUrl, boolean aCache) throws IOException {
    // If the URL already points to a file, there is not really much to do.
    if ("file".equals(aUrl.getProtocol())) {
        return new File(aUrl.getPath());
    }

    // Lets see if we already have a file for this URL in our cache. Maybe
    // the file has been deleted meanwhile, so we also check if the file
    // actually still exists on disk.
    File file = urlFileCache.get(aUrl);
    if (!aCache || (file == null) || !file.exists()) {
        // Create a temporary file and try to preserve the file extension
        String suffix = ".temp";
        String name = new File(aUrl.getPath()).getName();
        int suffixSep = name.indexOf(".");
        if (suffixSep != -1) {
            suffix = name.substring(suffixSep + 1);
            name = name.substring(0, suffixSep);
        }

        // Get a temporary file which will be deleted when the JVM shuts
        // down.
        file = File.createTempFile(name, suffix);
        file.deleteOnExit();

        // Now copy the file from the URL to the file.
        InputStream is = null;
        OutputStream os = null;
        try {
            is = aUrl.openStream();
            os = new FileOutputStream(file);
            IOUtils.copy(is, os);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }

        // Remember the file
        if (aCache) {
            urlFileCache.put(aUrl, file);
        }
    }

    return file;
}

From source file:com.mashape.unirest.android.http.HttpClientHelper.java

private static 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  a v  a 2 s. co  m*/
    }

    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;
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java

/**
 * Tries to upload the given file to the given HTTP server (via POST
 * method)./* www  .j a v  a2 s  . co m*/
 * 
 * @param file
 *            the file to upload
 * @param url
 *            the URL of the server, that is supposed to handle the file
 * @param monitor
 *            a monitor to report progress to
 * @throws IOException
 *             if an I/O error occurs
 * 
 */

public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException {

    final String CRLF = "\r\n";
    final String doubleDash = "--";
    final String boundary = generateBoundary();

    HttpURLConnection connection = null;
    OutputStream urlConnectionOut = null;
    FileInputStream fileIn = null;

    if (monitor == null)
        monitor = new NullProgressMonitor();

    int contentLength = (int) file.length();

    if (contentLength == 0) {
        log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist");
        return;
    }

    monitor.beginTask("Uploading file " + file.getName(), contentLength);

    try {
        URL connectionURL = new URL(url);

        if (!"http".equals(connectionURL.getProtocol()))
            throw new IOException("only HTTP protocol is supported");

        connection = (HttpURLConnection) connectionURL.openConnection();
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);

        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName()
                + "\"; filename=\"" + file.getName() + "\"" + CRLF;

        String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF;

        String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF;

        contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length()
                + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length();

        connection.setFixedLengthStreamingMode(contentLength);

        connection.connect();

        urlConnectionOut = connection.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true);

        writer.append(doubleDash).append(boundary).append(CRLF);
        writer.append(contentDispositionLine);
        writer.append(contentTypeLine);
        writer.append(contentTransferEncoding);
        writer.append(CRLF);
        writer.flush();

        fileIn = new FileInputStream(file);
        byte[] buffer = new byte[8192];

        for (int read = 0; (read = fileIn.read(buffer)) > 0;) {
            if (monitor.isCanceled())
                return;

            urlConnectionOut.write(buffer, 0, read);
            monitor.worked(read);
        }

        urlConnectionOut.flush();

        writer.append(CRLF);
        writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost());
            return;
        }

        throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " ["
                + connection.getResponseMessage() + "]");
    } finally {
        IOUtils.closeQuietly(fileIn);
        IOUtils.closeQuietly(urlConnectionOut);

        if (connection != null)
            connection.disconnect();

        monitor.done();
    }
}