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:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 */// w ww  .  j a va2  s.  c om
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:com.splicemachine.mrio.api.SpliceTableMapReduceUtil.java

/**
 * Find a jar that contains a class of the same name, if any.
 * It will return a jar file, even if that is not the first thing
 * on the class path that has a class with the same name.
 *
 * This is shamelessly copied from JobConf
 *
 * @param my_class the class to find./*from ww w.  j  ava 2  s . c om*/
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration itr = loader.getResources(class_file); 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());
                }
                // URLDecoder is a misnamed class, since it actually decodes
                // x-www-form-urlencoded MIME type rather than actual
                // URL encoding (which the file path has). Therefore it would
                // decode +s to ' 's which is incorrect (spaces are actually
                // either unencoded or encoded as "%20"). Replace +s first, so
                // that they are kept sacred during the decoding process.
                toReturn = toReturn.replaceAll("\\+", "%2B");
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:com.eviware.soapui.support.Tools.java

public static String getEndpointFromUrl(URL baseUrl) {
    StringBuilder result = new StringBuilder();
    result.append(baseUrl.getProtocol()).append("://");
    result.append(baseUrl.getHost());/*from  w  ww. jav  a 2 s .  c om*/
    if (baseUrl.getPort() > 0) {
        result.append(':').append(baseUrl.getPort());
    }

    return result.toString();
}

From source file:de.jlo.talendcomp.jasperrepo.RepositoryClient.java

public static String checkRepositoryUrl(String urlStr) {
    if (urlStr == null || urlStr.isEmpty()) {
        throw new IllegalArgumentException("url cannot be null or empty");
    }/*from   www. j a  v a2 s  . c om*/
    if (urlStr.endsWith(repositoryUrlPath)) {
        // everything is fine
        return urlStr;
    } else {
        // extract url parts
        try {
            URL url = new URL(urlStr);
            String host = url.getHost();
            String prot = url.getProtocol();
            int port = url.getPort();
            String path = url.getPath();
            if (path.length() > 1) {
                int pos = path.indexOf('/', 1);
                if (pos > 0) {
                    path = path.substring(0, pos);
                }
                path = path + repositoryUrlPath;
            } else {
                path = repositoryUrlPath;
            }
            StringBuilder newUrl = new StringBuilder();
            newUrl.append(prot);
            newUrl.append("://");
            newUrl.append(host);
            if (port > 0) {
                newUrl.append(":");
                newUrl.append(port);
            }
            newUrl.append(path);
            System.out.println("Given URL:" + urlStr + " changed to a repository URL:" + newUrl.toString());
            return newUrl.toString();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("URL: " + urlStr + " is not valied:" + e.getMessage(), e);
        }
    }
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call to the OCC web services
 * /*from  w w  w. ja va 2 s . co  m*/
 * @param url
 *           The url
 * @param isAuthorizedRequest
 *           Whether this request requires the authorization token sending
 * @param httpMethod
 *           method type (GET, PUT, POST, DELETE)
 * @param httpBody
 *           Data to be sent in the body (Can be empty)
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 */
public static String getResponse(Context context, String url, Boolean isAuthorizedRequest, String httpMethod,
        Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException {
    // Refresh if necessary
    if (isAuthorizedRequest && WebServiceAuthProvider.tokenExpiredHint(context)) {
        WebServiceAuthProvider.refreshAccessToken(context);
    }

    boolean refreshLimitReached = false;
    int refreshed = 0;

    String response = "";
    while (!refreshLimitReached) {
        // If we have refreshed max number of times, we will not do so again
        if (refreshed == 1) {
            refreshLimitReached = true;
        }

        // Make the connection and get the response
        OutputStream os;
        HttpURLConnection connection;

        if (httpMethod.equals("GET") && httpBody != null && !httpBody.isEmpty()) {
            url = url + "?" + encodePostBody(httpBody);
        }
        URL requestURL = new URL(addParameters(context, url));

        if (StringUtils.equalsIgnoreCase(requestURL.getProtocol(), "https")) {
            trustAllHosts();
            HttpsURLConnection https = createSecureConnection(requestURL);
            https.setHostnameVerifier(DO_NOT_VERIFY);
            if (isAuthorizedRequest) {
                String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token");
                https.setRequestProperty("Authorization", authValue);
            }
            connection = https;
        } else {
            connection = createConnection(requestURL);
        }
        connection.setRequestMethod(httpMethod);

        if (!httpMethod.equals("GET") && !httpMethod.equals("DELETE")) {
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();

            if (httpBody != null && !httpBody.isEmpty()) {
                os = new BufferedOutputStream(connection.getOutputStream());
                os.write(encodePostBody(httpBody).getBytes());
                os.flush();
            }
        }

        response = "";
        try {
            LoggingUtils.d(LOG_TAG, connection.toString());
            response = readFromStream(connection.getInputStream());
        } catch (FileNotFoundException e) {
            LoggingUtils.e(LOG_TAG,
                    "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                    context);
            response = readFromStream(connection.getErrorStream());
        } finally {
            connection.disconnect();
        }

        // Allow for calls to return nothing
        if (response.length() == 0) {
            return "";
        }

        // Check for JSON parsing errors (will throw JSONException is can't be parsed)
        JSONObject object = new JSONObject(response);

        // If no error, return response
        if (!object.has("error")) {
            return response;
        }
        // If there is a refresh token error, refresh the token
        else if (object.getString("error").equals("invalid_token")) {
            if (refreshLimitReached) {
                // Give up
                return response;
            } else {
                // Refresh the token
                WebServiceAuthProvider.refreshAccessToken(context);
                refreshed++;
            }
        }
    } // while(!refreshLimitReached)

    // There is an error other than a refresh error, so return the response
    return response;
}

From source file:sce.RESTAppMetricJob.java

public static URL convertToURLEscapingIllegalCharacters(String string) {
    try {//from   ww w  .ja  v a  2 s . c om
        String decodedURL = URLDecoder.decode(string, "UTF-8");
        URL url = new URL(decodedURL);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL();
    } catch (MalformedURLException | URISyntaxException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * <pre>/*w  w  w .  j a  v a2s . c  o m*/
 * This method finds all classes that are located in the package identified by
 * the given
 * &lt;code&gt;
 * packageName
 * &lt;/code&gt;
 * .
 * &lt;br&gt;
 * &lt;b&gt;ATTENTION:&lt;/b&gt;
 * &lt;br&gt;
 * This is a relative expensive operation. Depending on your classpath
 * multiple directories,JAR, and WAR files may need to scanned.
 * 
 * &#064;param packageName is the name of the {@link Package} to scan.
 * &#064;param includeSubPackages - if
 * &lt;code&gt;
 * true
 * &lt;/code&gt;
 *  all sub-packages of the
 *        specified {@link Package} will be included in the search.
 * &#064;return a {@link Set} will the fully qualified names of all requested
 *         classes.
 * &#064;throws IOException if the operation failed with an I/O error.
 * &#064;see http://m-m-m.svn.sourceforge.net/svnroot/m-m-m/trunk/mmm-util/mmm-util-reflect/src/main/java/net/sf/mmm/util/reflect/ReflectionUtil.java
 * </pre>
 */
public static Set<String> findFileNames(String packageName, boolean includeSubPackages, String packagePattern,
        String... endWiths) throws IOException {

    Set<String> classSet = new HashSet<String>();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = packageName.replace('.', '/');
    String pathWithPrefix = path + '/';
    Enumeration<URL> urls = classLoader.getResources(path);
    StringBuilder qualifiedNameBuilder = new StringBuilder(packageName);
    qualifiedNameBuilder.append('.');

    int qualifiedNamePrefixLength = qualifiedNameBuilder.length();

    while (urls.hasMoreElements()) {

        URL packageUrl = urls.nextElement();
        String urlString = URLDecoder.decode(packageUrl.getFile(), "UTF-8");
        String protocol = packageUrl.getProtocol().toLowerCase();
        log.debug(urlString);

        if ("file".equals(protocol)) {

            File packageDirectory = new File(urlString);

            if (packageDirectory.isDirectory()) {
                if (includeSubPackages) {
                    findClassNamesRecursive(packageDirectory, classSet, qualifiedNameBuilder,
                            qualifiedNamePrefixLength, packagePattern);
                } else {
                    for (String fileName : packageDirectory.list()) {
                        String simpleClassName = fixClassName(fileName);
                        if (simpleClassName != null) {
                            qualifiedNameBuilder.setLength(qualifiedNamePrefixLength);
                            qualifiedNameBuilder.append(simpleClassName);
                            if (qualifiedNameBuilder.toString().matches(packagePattern))
                                classSet.add(qualifiedNameBuilder.toString());
                        }
                    }
                }
            }
        } else if ("jar".equals(protocol)) {
            // somehow the connection has no close method and can NOT be
            // disposed
            JarURLConnection connection = (JarURLConnection) packageUrl.openConnection();
            JarFile jarFile = connection.getJarFile();
            Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
            while (jarEntryEnumeration.hasMoreElements()) {
                JarEntry jarEntry = jarEntryEnumeration.nextElement();
                String absoluteFileName = jarEntry.getName();
                // if (absoluteFileName.endsWith(".class")) { //original
                if (endWith(absoluteFileName, endWiths)) { // modified
                    if (absoluteFileName.startsWith("/")) {
                        absoluteFileName.substring(1);
                    }
                    // special treatment for WAR files...
                    // "WEB-INF/lib/" entries should be opened directly in
                    // contained jar
                    if (absoluteFileName.startsWith("WEB-INF/classes/")) {
                        // "WEB-INF/classes/".length() == 16
                        absoluteFileName = absoluteFileName.substring(16);
                    }
                    boolean accept = true;
                    if (absoluteFileName.startsWith(pathWithPrefix)) {
                        String qualifiedName = absoluteFileName.replace('/', '.');
                        if (!includeSubPackages) {
                            int index = absoluteFileName.indexOf('/', qualifiedNamePrefixLength + 1);
                            if (index != -1) {
                                accept = false;
                            }
                        }
                        if (accept) {
                            String className = fixClassName(qualifiedName);

                            if (className != null) {
                                if (qualifiedNameBuilder.toString().matches(packagePattern))
                                    classSet.add(className);
                            }
                        }
                    }
                }
            }
        } else {
            log.debug("unknown protocol -> " + protocol);
        }
    }
    return classSet;
}

From source file:com.surenpi.autotest.suite.SuiteRunnerLauncher.java

/**
 * ??// w  w  w .j a  va2  s . com
 * @param param
 */
private static void compile(RunnerParam param) {
    URL itemUrl = SuiteRunnerLauncher.class.getResource("/");
    if (itemUrl == null) {
        logger.warn("Can not get base url from root. Try use current dir.");

        try {
            itemUrl = new File(".").toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    logger.debug("Base url : {}", itemUrl);

    String protocol = itemUrl.getProtocol();
    if ("file".equals(protocol)) {
        String file = itemUrl.getFile();
        File[] subFiles = new File(file).listFiles(new PageXmlFilter());

        Generator generator = new DefaultXmlCodeGenerator() {
            @Override
            protected void done() {
                super.done();
            }
        };

        for (File pageFile : subFiles) {
            generator.generate(pageFile.getName(), param.compileDstDir);
        }

        JDTUtils utils = new JDTUtils(param.compileDstDir);
        utils.compileAllFile();

        try {
            logger.info("Compile dest dir: {}.", new File(param.compileDstDir).getAbsolutePath());

            ClassLoader loader = new URLClassLoader(
                    new URL[] { new File(param.compileDstDir).toURI().toURL() }) {
                @Override
                protected Class<?> findClass(String s) throws ClassNotFoundException {
                    return super.findClass(s);
                }
            };

            Thread.currentThread().setContextClassLoader(loader);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.stallion.utils.ResourceHelpers.java

public static List<String> listFilesInDirectory(String plugin, String path) {
    String ending = "";
    String starting = "";
    if (path.contains("*")) {
        String[] parts = StringUtils.split(path, "*", 2);
        String base = parts[0];//w w  w .ja v  a  2 s . c o  m
        if (!base.endsWith("/")) {
            path = new File(base).getParent();
            starting = FilenameUtils.getName(base);
        } else {
            path = base;
        }
        ending = parts[1];
    }

    Log.info("listFilesInDirectory Parsed Path {0} starting:{1} ending:{2}", path, starting, ending);
    URL url = PluginRegistry.instance().getJavaPluginByName().get(plugin).getClass().getResource(path);
    Log.info("URL: {0}", url);

    List<String> filenames = new ArrayList<>();
    URL dirURL = getClassForPlugin(plugin).getResource(path);
    Log.info("Dir URL is {0}", dirURL);
    // Handle file based resource folder
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        String fullPath = dirURL.toString().substring(5);
        File dir = new File(fullPath);
        // In devMode, use the source resource folder, rather than the compiled version
        if (Settings.instance().getDevMode()) {
            String devPath = fullPath.replace("/target/classes/", "/src/main/resources/");
            File devFolder = new File(devPath);
            if (devFolder.exists()) {
                dir = devFolder;
            }
        }
        Log.info("List files from folder {0}", dir.getAbsolutePath());
        List<String> files = list();
        for (String name : dir.list()) {
            if (!empty(ending) && !name.endsWith(ending)) {
                continue;
            }
            if (!empty(starting) && !name.endsWith("starting")) {
                continue;
            }
            // Skip special files, hidden files
            if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#")
                    || name.contains("_flymake.")) {
                continue;
            }
            filenames.add(path + name);
        }
        return filenames;
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = null;
        try {
            jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            Log.finer("Jar file entry: {0}", name);
            if (name.startsWith(path)) { //filter according to the path
                String entry = name.substring(path.length());
                int checkSubdir = entry.indexOf("/");
                if (checkSubdir >= 0) {
                    // if it is a subdirectory, we just return the directory name
                    entry = entry.substring(0, checkSubdir);
                }
                if (!empty(ending) && !name.endsWith(ending)) {
                    continue;
                }
                if (!empty(starting) && !name.endsWith("starting")) {
                    continue;
                }
                // Skip special files, hidden files
                if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#")
                        || name.contains("_flymake.")) {
                    continue;
                }
                result.add(entry);
            }
        }
        return new ArrayList<>(result);
    }
    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
    /*
    try {
    URL url1 = getClassForPlugin(plugin).getResource(path);
    Log.info("URL1 {0}", url1);
    if (url1 != null) {
        Log.info("From class folder contents {0}", IOUtils.toString(url1));
        Log.info("From class folder contents as stream {0}", IOUtils.toString(getClassForPlugin(plugin).getResourceAsStream(path)));
    }
    URL url2 = getClassLoaderForPlugin(plugin).getResource(path);
    Log.info("URL1 {0}", url2);
    if (url2 != null) {
        Log.info("From classLoader folder contents {0}", IOUtils.toString(url2));
        Log.info("From classLoader folder contents as stream {0}", IOUtils.toString(getClassLoaderForPlugin(plugin).getResourceAsStream(path)));
    }
            
    } catch (IOException e) {
    Log.exception(e, "error loading path " + path);
    }
    //  Handle jar based resource folder
    try(
        InputStream in = getResourceAsStream(plugin, path);
        BufferedReader br = new BufferedReader( new InputStreamReader( in ) ) ) {
    String resource;
    while( (resource = br.readLine()) != null ) {
        Log.finer("checking resource for inclusion in directory scan: {0}", resource);
        if (!empty(ending) && !resource.endsWith(ending)) {
            continue;
        }
        if (!empty(starting) && !resource.endsWith("starting")) {
            continue;
        }
        // Skip special files, hidden files
        if (resource.startsWith(".") || resource.startsWith("~") || resource.startsWith("#") || resource.contains("_flymake.")) {
            continue;
        }
        Log.finer("added resource during directory scan: {0}", resource);
        filenames.add(path + resource);
    }
    } catch (IOException e) {
    throw new RuntimeException(e);
    }
    return filenames;
    */
}

From source file:com.jajja.jorm.Database.java

private static void configure() {
    try {//  w  ww.  j av  a 2  s . co m
        configurations = new HashMap<String, Configuration>();
        Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources("jorm.properties");
        URL local = null;
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            if (url.getProtocol().equals("jar")) {
                configure(url);
            } else {
                local = url;
            }
        }
        if (local != null) {
            configure(local);
        }

        for (Entry<String, Configuration> entry : configurations.entrySet()) {
            String database = entry.getKey();
            Configuration configuration = entry.getValue();
            int index = database.indexOf(Context.CONTEXT_SEPARATOR);
            if (index > 0) {
                Configuration base = configurations.get(database.substring(0, index));
                if (base != null) {
                    configuration.inherit(base);
                }
            }
            configuration.init();
            configure(database, configuration.dataSource);
            Database.get().log.debug("Configured " + configuration);
        }
    } catch (IOException ex) {
        Database.get().log.warn("Failed to find resource 'jorm.properties': " + ex.getMessage(), ex);
        configurations = null;
    }
}