Example usage for org.springframework.core.io Resource getURL

List of usage examples for org.springframework.core.io Resource getURL

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getURL.

Prototype

URL getURL() throws IOException;

Source Link

Document

Return a URL handle for this resource.

Usage

From source file:org.codehaus.griffon.commons.GriffonResourceUtils.java

/**
 * Retrieves the static resource path for the given Griffon resource artifact (controller/taglib etc.)
 *
 * @param resource The Resource/*from   www  .  j  av  a 2 s  .  com*/
 * @param contextPath The additonal context path to prefix
 * @return The resource path
 */
public static String getStaticResourcePathForResource(Resource resource, String contextPath) {

    if (contextPath == null)
        contextPath = "";
    if (resource == null)
        return contextPath;

    String url;
    try {
        url = resource.getURL().toString();
    } catch (IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error reading URL whilst resolving static resource path from [" + resource + "]: "
                    + e.getMessage(), e);
        }
        return contextPath;
    }

    Matcher m = PLUGIN_RESOURCE_PATTERN.matcher(url);
    if (m.find()) {
        return (contextPath.length() > 0 ? contextPath + "/" : "") + m.group(1);
    }

    return contextPath;
}

From source file:org.jdal.swing.form.FormUtils.java

/**
 * Load Icon from url//from   w  w  w  .j a v  a  2 s.c o  m
 * @param url
 * @return Icon, null on faliure
 */
public static Icon getIcon(String url) {
    Resource resource = new ClassPathResource(url);
    Icon icon = null;
    try {
        Image image = Toolkit.getDefaultToolkit().getImage(resource.getURL());
        icon = new ImageIcon(image);
    } catch (IOException e) {
        log.error(e);
    }
    return icon;
}

From source file:org.paxml.core.ResourceLocator.java

/**
 * Make an Spring resource string from relative path which contains
 * wildcards./*from   www. j  av  a  2 s. co m*/
 * 
 * @param base
 *            the base Spring resource
 * @param relative
 *            the relative path
 * @return the absolute spring resource path
 */
public static String getRelativeResource(final Resource base, final String relative) {
    String result;
    // find from both class path and file system
    final boolean root = relative.startsWith("/") || relative.startsWith("\\");

    try {
        URL url = base.getURL();

        if (root) {
            result = url.getProtocol() + ":" + relative;
        } else {
            String path = FilenameUtils.getFullPathNoEndSeparator(url.getFile());
            result = url.getProtocol() + ":" + path + "/" + relative;
        }

    } catch (IOException e) {
        throw new PaxmlRuntimeException("Cannot get the relative path for plan file: " + base, e);
    }
    return result;
}

From source file:com.edgenius.core.util.FileUtil.java

/**
 * //from w  w w  . ja  va  2  s .c o m
 * @param location
 * @return
 * @throws IOException 
 */
public static InputStream getFileInputStream(String location) throws IOException {
    //Don't user DefaultResourceLoader directly, as test it try to find host "c" if using method resource.getInputStream()
    // while location is "file://c:/var/test" etc.

    DefaultResourceLoader loader = new DefaultResourceLoader();
    Resource res = loader.getResource(location);
    if (ResourceUtils.isJarURL(res.getURL())) {
        //it is in jar file, we just assume it won't be changed in runtime, so below method is safe.
        try {
            return res.getInputStream();
        } catch (IOException e) {
            throw (e);
        }
    } else {
        //in Tomcat, the classLoader cache the input stream even using thread scope classloader, but it is still failed
        //if the reload in same thread. For example, DataRoot class save and reload in same thread when install.
        //So, we assume if the file is not inside jar file, we will always reload the file into a new InputStream from file system.

        //if it is not jar resource, then try to refresh the input stream by file system
        return new FileInputStream(res.getFile());
    }
}

From source file:org.apache.uima.ruta.descriptor.RutaDescriptorBuilder.java

public static URL checkImportExistence(String candidate, String extension, ClassLoader classloader)
        throws IOException {
    String p = candidate.replaceAll("[.]", "/");
    p += extension;//from w  w w.j av  a2  s .co m
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classloader);
    String prefix = "classpath*:";
    String pattern = prefix + p;
    Resource[] resources = resolver.getResources(pattern);
    if (resources == null || resources.length == 0) {
        return null;
    } else {
        Resource resource = resources[0];
        URL url = resource.getURL();
        return url;
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java

/**
 * Make a given classpath location available as a folder. A temporary folder is created and
 * deleted upon a regular shutdown of the JVM. This method must not be used for creating
 * executable binaries. For this purpose, getUrlAsExecutable should be used.
 *
 * @param aClasspathBase/* w w w . ja v  a 2 s. co m*/
 *            a classpath location as used by
 *            {@link PathMatchingResourcePatternResolver#getResources(String)}
 * @param aCache
 *            use the cache or not.
 * @see PathMatchingResourcePatternResolver
 */
public static File getClasspathAsFolder(String aClasspathBase, boolean aCache) throws IOException {
    synchronized (classpathFolderCache) {
        File folder = classpathFolderCache.get(aClasspathBase);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        if (!aCache || (folder == null) || !folder.exists()) {
            folder = File.createTempFile("dkpro-package", "");
            folder.delete();
            FileUtils.forceMkdir(folder);

            Resource[] roots = resolver.getResources(aClasspathBase);
            for (Resource root : roots) {
                String base = root.getURL().toString();
                Resource[] resources = resolver.getResources(base + "/**/*");
                for (Resource resource : resources) {
                    if (!resource.isReadable()) {
                        // This is true for folders/packages
                        continue;
                    }

                    // Relativize
                    String res = resource.getURL().toString();
                    if (!res.startsWith(base)) {
                        throw new IOException("Resource location does not start with base location");
                    }
                    String relative = resource.getURL().toString().substring(base.length());

                    // Make sure the target folder exists
                    File target = new File(folder, relative).getAbsoluteFile();
                    if (target.getParentFile() != null) {
                        FileUtils.forceMkdir(target.getParentFile());
                    }

                    // Copy data
                    InputStream is = null;
                    OutputStream os = null;
                    try {
                        is = resource.getInputStream();
                        os = new FileOutputStream(target);
                        IOUtils.copyLarge(is, os);
                    } finally {
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(os);
                    }

                    // WORKAROUND: folders get written as files if inside jars
                    // delete files of size zero
                    if (target.length() == 0) {
                        FileUtils.deleteQuietly(target);
                    }
                }
            }

            if (aCache) {
                classpathFolderCache.put(aClasspathBase, folder);
            }
        }

        return folder;
    }
}

From source file:com.textocat.textokit.morph.dictionary.MorphDictionaryAPIFactory.java

private static synchronized void initialize() {
    if (defaultApi != null) {
        return;/*from   ww w.  j  a  v a 2  s. com*/
    }
    log.info("Searching for MorphDictionaryAPI implementations...");
    Set<String> implClassNames = Sets.newHashSet();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        for (Resource implDeclRes : resolver
                .getResources("classpath*:META-INF/uima-ext/morph-dictionary-impl.txt")) {
            InputStream is = implDeclRes.getInputStream();
            try {
                String implClassName = IOUtils.toString(is, "UTF-8").trim();
                if (!implClassNames.add(implClassName)) {
                    throw new IllegalStateException(
                            String.format(
                                    "The classpath contains duplicate declaration of implementation '%s'. "
                                            + "Last one has been read from %s.",
                                    implClassName, implDeclRes.getURL()));
                }
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (implClassNames.isEmpty()) {
        throw new IllegalStateException(String.format("Can't find an implementation of MorphDictionaryAPI"));
    }
    if (implClassNames.size() > 1) {
        throw new IllegalStateException(String.format("More than one implementations have been found:\n%s\n"
                + "Adjust the app classpath or get an implementation by ID.", implClassNames));
    }
    String implClassName = implClassNames.iterator().next();
    log.info("Found MorphDictionaryAPI implementation: {}", implClassName);
    try {
        @SuppressWarnings("unchecked")
        Class<? extends MorphDictionaryAPI> implClass = (Class<? extends MorphDictionaryAPI>) Class
                .forName(implClassName);
        defaultApi = implClass.newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can't instantiate the MorphDictionaryAPI implementation", e);
    }
}

From source file:com.netxforge.oss2.core.xml.CastorUtils.java

/**
 * Unmarshal a Castor XML configuration file.  Uses Java 5 generics for
 * return type.//from  ww w. jav  a2s.c  o m
 *
 * @param clazz the class representing the marshalled XML configuration file
 * @param resource the marshalled XML configuration file to unmarshal
 * @param preserveWhitespace whether or not to preserve whitespace
 * @return Unmarshalled object representing XML file
 * @throws org.exolab.castor.xml.MarshalException if the underlying Castor
 *      Unmarshaller.unmarshal() call throws a org.exolab.castor.xml.MarshalException
 * @throws org.exolab.castor.xml.ValidationException if the underlying Castor
 *      Unmarshaller.unmarshal() call throws a org.exolab.castor.xml.ValidationException
 * @throws java.io.IOException if the resource could not be opened
 */
public static <T> T unmarshal(Class<T> clazz, Resource resource, boolean preserveWhitespace)
        throws MarshalException, ValidationException, IOException {
    InputStream in;
    try {
        in = resource.getInputStream();
    } catch (IOException e) {
        IOException newE = new IOException(
                "Failed to open XML configuration file for resource '" + resource + "': " + e);
        newE.initCause(e);
        throw newE;
    }

    try {
        InputSource source = new InputSource(in);
        try {
            source.setSystemId(resource.getURL().toString());
        } catch (Throwable t) {
            // ignore
        }
        return unmarshal(clazz, source, preserveWhitespace);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.resource.ResourceInjection2.java

public void getResource() throws Exception {
    System.out.println(resources.length);
    for (Resource resource : resources) {
        System.out.println(resource.getURL());
    }//from   ww  w  . java  2  s  .c om
}

From source file:ws.antonov.config.provider.ResourceConfigProvider.java

protected ContentType determineContentType(Resource configFile) throws IOException {
    if (configFile.getURL().getPath().endsWith(".xml"))
        return ContentType.XML;
    else if (configFile.getURL().getPath().endsWith(".js") || configFile.getURL().getPath().endsWith(".json"))
        return ContentType.JSON;
    else if (configFile.getURL().getPath().endsWith(".txt"))
        return ContentType.TEXT;
    else if (configFile.getURL().getPath().endsWith(".properties"))
        return ContentType.PROPS;
    else//  www. j  a v a 2  s .c o  m
        return ContentType.PROTOBUF;
}