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.paxml.core.PaxmlResource.java

/**
 * Create from a spring resource./*from  ww w.j av  a2  s . c  o m*/
 * 
 * @param res
 *            the spring resource
 * @return the paxml resource
 */
public static PaxmlResource createFromResource(Resource res) {
    URL url;
    try {
        url = res.getURL();
    } catch (IOException e) {
        throw new PaxmlRuntimeException("Cannot create paxmlResource from spring resource: " + res, e);
    }
    return createFromPath(url.toString());
}

From source file:com.intuit.cto.selfservice.service.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to/* w  w  w.  j  av  a  2s. c  o  m*/
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    FileUtils.copyURLToFile(url, targetFile);
                    counter++;
                }
            }
        }
    }
    logger.info("Unpacked {} files from {} to {}", new Object[] { counter, locationPattern, toDir });
    return counter;
}

From source file:de.tudarmstadt.ukp.lmf.hibernate.HibernateConnect.java

/**
 * Creates Hibernate {@link Configuration} and adds all files from Hibernate mapping folder to
 * the model./*from ww w .j av  a  2 s  .  c  o  m*/
 *
 * @param dbConfig
 *            database configuration holder
 *
 * @return the created Hibernate Configuration
 */
public static Configuration getConfiguration(DBConfig dbConfig) {
    Configuration cfg = new Configuration()
            .addProperties(getProperties(dbConfig.getJdbc_url(), dbConfig.getJdbc_driver_class(),
                    dbConfig.getDb_vendor(), dbConfig.getUser(), dbConfig.getPassword(), dbConfig.isShowSQL()));

    // load hibernate mappings
    ClassLoader cl = HibernateConnect.class.getClassLoader();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    Resource[] mappings = null;
    try {
        mappings = resolver.getResources("hibernatemap/access/**/*.hbm.xml");
        for (Resource mapping : mappings) {
            cfg.addURL(mapping.getURL());
        }

    } catch (IOException e) {
        logger.error("Hibernate mappings not found!");
        e.printStackTrace();
    }

    return cfg;
}

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

public static boolean isGriffonResource(Resource r) {
    try {
        return isGriffonPath(r.getURL().getFile());
    } catch (IOException e) {
        return false;
    }//from  ww w .j a v  a  2  s.co  m
}

From source file:io.servicecomb.foundation.common.utils.Log4jUtils.java

private static void outputFile(List<Resource> resList, Properties properties)
        throws IOException, URISyntaxException {
    //??class???outputFile??log???
    //must create org.slf4j.impl.Log4jLoggerAdapter by LoggerExtFactory
    //in order to redefine Log4jLoggerAdapter before other class load Log4jLoggerAdapter
    Logger log = LoggerFactory.getLogger(Log4jUtils.class);

    String content = genFileContext(resList, properties);
    //????,??//  www .  ja  v  a2s .  c o m
    //log.info("Merged log4j:\n{}", content);

    Resource res = resList.get(resList.size() - 1);
    // ?res.getFilejar??getFile
    File file = new File(res.getURL().getPath());
    if (!file.getParentFile().canWrite()) {
        log.error("Can not output {},because can not write to directory of file {}", MERGED_FILE,
                res.getURL().getPath());
        return;
    }

    File mergedfile = new File(res.getFile().getParentFile(), MERGED_FILE);
    FileUtils.writeStringToFile(mergedfile, content);
    log.info("Write merged log4j config file to {}", mergedfile.getAbsolutePath());
}

From source file:org.uimafit.factory.TypeSystemDescriptionFactory.java

/**
 * Resolve a list of patterns to a set of URLs.
 *
 * @return an array of locations./*from   w  ww.  j  a v a 2 s  .  c om*/
 * @throws ResourceInitializationException
 *             if the locations could not be resolved.
 */
public static String[] resolve(String... patterns) throws ResourceInitializationException {
    Set<String> locations = new HashSet<String>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        // Scan auto-import locations. Using a set to avoid scanning a pattern twice.
        for (String pattern : new TreeSet<String>(Arrays.asList(patterns))) {
            String p = pattern.trim();
            if (p.length() == 0) {
                continue;
            }
            for (Resource r : resolver.getResources(pattern)) {
                locations.add(r.getURL().toString());
            }
        }
        return locations.toArray(new String[locations.size()]);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:ch.vorburger.mariadb4j.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * /*from ww w .j  a v  a 2 s  .  c om*/
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on
 *             classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            final URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                final File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    tryN(5, 500, new Procedure<IOException>() {

                        @Override
                        public void apply() throws IOException {
                            FileUtils.copyURLToFile(url, targetFile);
                        }
                    });
                    counter++;
                }
            }
        }
    }
    if (counter > 0) {
        Object[] info = new Object[] { counter, locationPattern, toDir };
        logger.info("Unpacked {} files from {} to {}", info);
    }
    return counter;
}

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

public static Resource getAppDir(Resource resource) {
    if (resource == null)
        return null;

    try {//from  ww w. ja  va2 s  .c  o m
        String url = resource.getURL().toString();

        int i = url.lastIndexOf(GRIFFON_APP_DIR);
        if (i > -1) {
            url = url.substring(0, i + 10);
            return new UrlResource(url);
        }

        return null;
    } catch (MalformedURLException e) {
        return null;
    } catch (IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error reading URL whilst resolving app dir from [" + resource + "]: " + e.getMessage(),
                    e);
        }
        return null;
    }
}

From source file:org.codehaus.griffon.runtime.spring.GriffonRuntimeConfigurator.java

private static BeanBuilder loadPluginGroovyResources(RuntimeSpringConfiguration config,
        GriffonApplication application) {
    ClassLoader classLoader = ApplicationClassLoader.get();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader);
    GroovyClassLoader gcl = new GroovyClassLoader(classLoader);
    BeanBuilder bb = new BeanBuilder(null, config, classLoader);
    try {/* w w w . ja  va 2 s  .com*/
        Resource[] resources = resolver.getResources("classpath*:/META-INF/spring/springbeans.groovy");
        for (Resource resource : resources) {
            try {
                Class scriptClass = gcl.parseClass(new GroovyCodeSource(resource.getURL()));
                reloadSpringResourcesConfig(application, bb, scriptClass);
            } catch (Exception ex) {
                LOG.error("[RuntimeConfiguration] Unable to load beans from " + resource, sanitize(ex));
            }
        }
    } catch (IOException ioe) {
        LOG.error("[RuntimeConfiguration] Unable to load beans from plugin resources", sanitize(ioe));
    }
    return bb;
}

From source file:org.openbaton.integration.test.utils.Utils.java

public static List<URL> getFilesAsURL(String location) {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = {};//from  w  w w  .  java2  s. c o  m
    try {
        resources = resolver.getResources(location);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    List<URL> urls = new LinkedList<>();
    for (Resource resource : resources) {
        try {
            urls.add(resource.getURL());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return urls;
}