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:de.langmi.spring.batch.examples.complex.support.CustomMultiResourcePartitioner.java

/**
 * Assign the filename of each of the injected resources to an
 * {@link ExecutionContext}.//from  ww w  . j a  v  a 2s .co m
 * 
 * @see Partitioner#partition(int)
 */
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
    Map<String, ExecutionContext> map = new HashMap<String, ExecutionContext>(gridSize);
    int i = 0;
    for (Resource resource : resources) {
        ExecutionContext context = new ExecutionContext();
        Assert.state(resource.exists(), "Resource does not exist: " + resource);
        try {
            context.putString(keyName, resource.getURL().toExternalForm());
            context.put("outputFileName", createOutputFilename(i, resource));
        } catch (IOException e) {
            throw new IllegalArgumentException("File could not be located for: " + resource, e);
        }
        map.put(PARTITION_KEY + i, context);
        i++;
    }
    return map;
}

From source file:de.langmi.spring.batch.examples.readers.file.multiresourcepartitioner.CustomMultiResourcePartitioner.java

/**
 * Assign the filename of each of the injected resources to an
 * {@link ExecutionContext}./*ww w.j ava 2  s. co  m*/
 * 
 * @see Partitioner#partition(int)
 */
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
    Map<String, ExecutionContext> map = new HashMap<String, ExecutionContext>(gridSize);
    int i = 0;
    for (Resource resource : resources) {
        ExecutionContext context = new ExecutionContext();
        Assert.state(resource.exists(), "Resource does not exist: " + resource);
        try {
            context.putString(inputKeyName, resource.getURL().toExternalForm());
            context.put(outputKeyName, createOutputFilename(i, resource));
        } catch (IOException e) {
            throw new IllegalArgumentException("File could not be located for: " + resource, e);
        }
        map.put(PARTITION_KEY + i, context);
        i++;
    }
    return map;
}

From source file:com.iterranux.droolsjbpmCore.runtime.build.impl.KieModuleBuilder.java

/**
 * Builds all kmodules from grails plugins or the kmodule from the parent application that it can find on the classpath.
 * Kmodules are registered under the release id:
 *
 *      org.grails.plugins : Plugin Name : Plugin Version
 *
 *//*from  w  w w  .j  av a  2  s  .  c  o m*/
@PostConstruct
public void buildKmodulesForGrailsModules() throws IOException {

    log.debug("Starting build of KieModules for grails modules");

    //Find all kmodule.xml
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    String pattern = "/droolsjbpm/*/kmodule.xml";
    org.springframework.core.io.Resource[] resources = resolver.getResources("classpath*:" + pattern);

    for (org.springframework.core.io.Resource kmoduleXml : resources) {

        if (!isTestResource(kmoduleXml.getURL())) {

            String moduleName = extractModuleNameFromKmoduleXmlUrl(kmoduleXml.getURL().toString());
            buildKmoduleForGrailsModule(moduleName, kmoduleXml);

        }

    }
    log.debug("Finished build of KieModules for grails modules");
}

From source file:io.wcm.devops.conga.resource.ClasspathResourceCollectionImpl.java

ClasspathResourceCollectionImpl(String path, ResourceLoader resourceLoader) {
    super(path, resourceLoader.getClassLoader());
    this.resourceLoader = resourceLoader;

    try {/*from   w w w . j av  a2  s. co  m*/
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                this.classLoader);
        org.springframework.core.io.Resource[] classpathResources = resolver
                .getResources("classpath*:" + convertPath(path) + "/*");
        for (org.springframework.core.io.Resource resource : classpathResources) {
            if (isFolder(resource)) {
                folderPaths.add(path + "/" + resource.getFilename());
            } else {
                fileUrls.add(resource.getURL());
            }
        }
    } catch (FileNotFoundException ex) {
        // empty folder
    } catch (IOException ex) {
        throw new ResourceException("Unable to enumerate classpath resources at " + path, ex);
    }
}

From source file:org.syncope.core.rest.controller.ConfigurationController.java

@PreAuthorize("hasRole('CONFIGURATION_LIST')")
@RequestMapping(method = RequestMethod.GET, value = "/mailTemplates")
public ModelAndView getMailTemplates() {
    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();

    Set<String> htmlTemplates = new HashSet<String>();
    Set<String> textTemplates = new HashSet<String>();

    try {/*  w  w  w .j av a2s .c om*/
        for (Resource resource : resResolver.getResources("classpath:/mailTemplates/*.vm")) {

            String template = resource.getURL().toExternalForm();
            if (template.endsWith(".html.vm")) {
                htmlTemplates.add(template.substring(template.indexOf("mailTemplates/") + 14,
                        template.indexOf(".html.vm")));
            } else if (template.endsWith(".txt.vm")) {
                textTemplates.add(template.substring(template.indexOf("mailTemplates/") + 14,
                        template.indexOf(".txt.vm")));
            } else {
                LOG.warn("Unexpected template found: {}, ignoring...", template);
            }
        }
    } catch (IOException e) {
        LOG.error("While searching for class implementing {}", Validator.class.getName(), e);
    }

    // Only templates available both as HTML and TEXT are considered
    htmlTemplates.retainAll(textTemplates);

    return new ModelAndView().addObject(htmlTemplates);
}

From source file:com.iflytek.edu.cloud.frame.support.jdbc.CustomSQL.java

public void init() {
    reloadSQLFiles = Boolean.valueOf(System.getProperty("reloadSQLFiles"));

    try {//from ww  w . ja  v a2 s. c  om
        engine = Engine.getEngine();

        Resource[] configs = loadConfigs();
        for (Resource _config : configs) {
            logger.info("Loading " + _config.getURL().getPath());
            configMap.put(_config.getURL().getPath(), _config.lastModified());
            read(_config.getInputStream());
        }
    } catch (Exception e) {
        logger.error("", e);
    }
}

From source file:com.haulmont.cuba.web.sys.WebJarResourceResolver.java

protected void scanResources(ApplicationContext applicationContext) throws IOException {
    // retrieve all resources from all JARs
    Resource[] resources = applicationContext.getResources("classpath*:META-INF/resources/webjars/**");

    for (Resource resource : resources) {
        URL url = resource.getURL();
        String urlString = url.toString();
        int classPathStartIndex = urlString.indexOf(CLASSPATH_WEBJAR_PREFIX);
        if (classPathStartIndex > 0) {
            String resourcePath = urlString.substring(classPathStartIndex + CLASSPATH_WEBJAR_PREFIX.length());
            if (!Strings.isNullOrEmpty(resourcePath) && !resourcePath.endsWith("/")) {
                mapping.put(resourcePath, new UrlHolder(url));
            }/* w ww  .j a  v  a2 s .c  o m*/
        } else {
            log.debug("Ignored WebJAR resource {} since it does not contain class path prefix {}", urlString,
                    CLASSPATH_WEBJAR_PREFIX);
        }
    }

    this.fullPathIndex = getFullPathIndex(mapping.keySet());
}

From source file:org.alloy.metal.xml.merge.ImportProcessor.java

public List<ResourceInputStream> extract(List<ResourceInputStream> sources) throws MergeException {
    try {/*from  w w w  .  ja v  a  2 s.  c  o  m*/
        DynamicResourceIterator resourceList = new DynamicResourceIterator();
        resourceList.addAll(sources);

        while (resourceList.hasNext()) {
            ResourceInputStream myStream = resourceList.nextResource();
            Document doc = builder.parse(myStream);
            NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
            int length = nodeList.getLength();
            for (int j = 0; j < length; j++) {
                Element element = (Element) nodeList.item(j);
                Resource resource = loader.getResource(element.getAttribute("resource"));
                ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(),
                        resource.getURL().toString());
                resourceList.addEmbeddedResource(ris);
                element.getParentNode().removeChild(element);
            }
            if (length > 0) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer xmlTransformer = tFactory.newTransformer();
                xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
                xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

                DOMSource source = new DOMSource(doc);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
                StreamResult result = new StreamResult(writer);
                xmlTransformer.transform(source, result);

                byte[] itemArray = baos.toByteArray();

                resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(
                        new ByteArrayInputStream(itemArray), null, myStream.getNames()));
            } else {
                myStream.reset();
            }
        }

        return resourceList;
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:com.gst.infrastructure.core.boot.EmbeddedTomcatWithSSLConfiguration.java

public File getFile(Resource resource) throws IOException {
    try {/*from   w  w w  .  j  av a  2  s.  co m*/
        return resource.getFile();
    } catch (IOException e) {
        // Uops.. OK, try again (below)
    }

    try {
        URL url = resource.getURL();
        /**
         * // If this creates filenames that are too long on Win, // then
         * could just use resource.getFilename(), // even though not unique,
         * real risk prob. min.bon String tempDir =
         * System.getProperty("java.io.tmpdir"); tempDir = tempDir + "/" +
         * getClass().getSimpleName() + "/"; String path = url.getPath();
         * String uniqName = path.replace("file:/", "").replace('!', '_');
         * String tempFullPath = tempDir + uniqName;
         **/
        // instead of File.createTempFile(prefix?, suffix?);
        File targetFile = new File(resource.getFilename());
        long len = resource.contentLength();
        if (!targetFile.exists() || targetFile.length() != len) { // Only
                                                                  // copy
                                                                  // new
                                                                  // files
            FileUtils.copyURLToFile(url, targetFile);
        }
        return targetFile;
    } catch (IOException e) {
        // Uops.. erm, give up:
        throw new IOException("Cannot obtain a File for Resource: " + resource.toString(), e);
    }

}

From source file:org.solmix.runtime.support.spring.SpringResourceResolver.java

@Override
public <T> T resolve(String resourceName, Class<T> resourceType) {

    try {//  www.j ava 2s .co  m
        T resource = null;
        if (resourceName == null) {
            String names[] = context.getBeanNamesForType(resourceType);
            if (names != null && names.length > 0) {
                resource = resourceType.cast(context.getBean(names[0], resourceType));
            }
        } else {
            resource = resourceType.cast(context.getBean(resourceName, resourceType));
        }
        return resource;
    } catch (NoSuchBeanDefinitionException def) {
        //ignore
    }
    try {
        if (ClassLoader.class.isAssignableFrom(resourceType)) {
            return resourceType.cast(context.getClassLoader());
        } else if (URL.class.isAssignableFrom(resourceType)) {
            Resource r = context.getResource(resourceName);
            if (r != null && r.exists()) {
                r.getInputStream().close(); //checks to see if the URL really can resolve
                return resourceType.cast(r.getURL());
            }
        }
    } catch (IOException e) {
        //ignore
    }
    return null;
}