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.pksoftware.springstrap.sapi.util.WebappZipper.java

/**
  * Zip it/*from   ww w .ja  v a  2 s  .co m*/
  * @param zipFile output ZIP file location
  */
public void addResource(String resourcePath, boolean fromContext) {
    byte[] buffer = new byte[1024];

    try {
        logger.info("Adding resource: {}", resourcePath);

        PathMatchingResourcePatternResolver resolver;

        if (fromContext) {
            resolver = new ServletContextResourcePatternResolver(servletContext);
        } else {
            resolver = new PathMatchingResourcePatternResolver();
        }

        // Ant-style path matching
        Resource[] resources = resolver.getResources(resourcePath);

        for (Resource resource : resources) {
            String fileAbsolute = resource.getURL().toString();
            String fileRelative = null;
            boolean addFile = false;

            if (fromContext) {
                //File comes from webapp folder
                fileRelative = "www" + servletContext.getContextPath()
                        + ((ServletContextResource) resource).getPath();
                if (!fileRelative.endsWith("/")) {
                    addFile = true;
                }

            } else {
                //Files comes from webjar
                int jarSeparatorIndex = fileAbsolute.indexOf("!/");

                if (jarSeparatorIndex != -1) {
                    String relativeFileName = fileAbsolute.substring(jarSeparatorIndex);

                    Pattern pathPattern = Pattern.compile("\\!\\/webjar(\\/[a-z0-9_]+)+\\/www\\/");
                    Matcher pathMatcher = pathPattern.matcher(relativeFileName);
                    if (pathMatcher.find()) {
                        fileRelative = pathMatcher.replaceFirst("www" + servletContext.getContextPath() + "/");
                        addFile = true;
                    }
                }
            }

            if (addFile && null != fileRelative) {
                logger.debug("Adding File: {} => {}", fileAbsolute, fileRelative);

                if (null != files.get(fileRelative)) {
                    continue;
                }

                if (fileRelative.startsWith("temp")) {
                    logger.error(fileAbsolute);
                }

                files.put(fileRelative, resource);

                ZipEntry ze = new ZipEntry(fileRelative);
                zos.putNextEntry(ze);

                InputStream in = null;
                try {
                    in = resource.getInputStream();

                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                } catch (FileNotFoundException fio) {
                    logger.error(fio.getMessage());
                } finally {
                    if (null != in) {
                        in.close();
                    }
                }
            }
        }

        zos.closeEntry();
        //remember close it

        logger.info("Done");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.quartzdesk.executor.dao.schema.DatabaseSchemaManager.java

/**
 * Returns the list of QuartzDesk database schema SQL init scripts.
 *
 * @return the list of SQL init scripts.
 *//*from  w  w w .  j a va  2 s.  c o m*/
public List<URL> getInitScriptUrls() {
    try {
        // find all .sql scripts
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] scriptResources = resolver.getResources(initScriptsRoot + "/*.sql");

        List<URL> scriptUrls = new ArrayList<URL>();
        for (Resource scriptResource : scriptResources) {
            scriptUrls.add(scriptResource.getURL());
        }

        // sort the scripts by their name
        Collections.sort(scriptUrls, new Comparator<URL>() {
            @Override
            public int compare(URL o1, URL o2) {
                return o1.getPath().compareTo(o2.getPath());
            }
        });

        return scriptUrls;
    } catch (IOException e) {
        throw new DaoException("Error getting database schema SQL init script URLs.", e);
    }
}

From source file:grails.plugin.searchable.internal.compass.config.CompassXmlConfigurationSearchableCompassConfigurator.java

/**
 * Configure Compass ready for it to be built
 *
 * @param compassConfiguration runtime configuration instance
 * @param configurationContext a context allowing flexible parameter passing
 *///from w ww  .  j a v a2 s  . c o  m
public void configure(CompassConfiguration compassConfiguration, Map configurationContext) {
    Assert.notNull(compassConfiguration, "compassConfiguration cannot be null");
    Assert.notNull(resourceLoader, "resourceLoader cannot be null");

    Resource resource = resourceLoader.getResource("classpath:/compass.cfg.xml");
    if (resource.exists()) {
        Assert.notNull(configurationContext, "configurationContext cannot be null");
        try {
            LOG.debug("Configuring Compass with compass config file [" + resource.getURL() + "]");
            compassConfiguration.configure(resource.getURL());
        } catch (IOException ex) {
            LOG.error("Failed to configure Compass with classpath resource, even though it apparently exists: "
                    + ex, ex);
            throw new IllegalStateException(
                    "Failed to configure Compass with classpath resource, even though it apparently exists: "
                            + ex);
        }
        configurationContext.put(CONFIGURED, true);
    }
}

From source file:org.codehaus.groovy.grails.plugins.searchable.compass.config.CompassXmlConfigurationSearchableCompassConfigurator.java

/**
 * Configure Compass ready for it to be built
 *
 * @param compassConfiguration runtime configuration instance
 * @param configurationContext a context allowing flexible parameter passing
 *//*  w  ww.j  a  va  2  s  . c om*/
public void configure(CompassConfiguration compassConfiguration, Map configurationContext) {
    Assert.notNull(compassConfiguration, "compassConfiguration cannot be null");
    Assert.notNull(resourceLoader, "resourceLoader cannot be null");

    Resource resource = resourceLoader.getResource("classpath:/compass.cfg.xml");
    if (resource.exists()) {
        Assert.notNull(configurationContext, "configurationContext cannot be null");
        try {
            LOG.debug("Configuring Compass with compass config file [" + resource.getURL().toString() + "]");
            compassConfiguration.configure(resource.getURL());
        } catch (IOException ex) {
            LOG.error("Failed to configure Compass with classpath resource, even though it apparently exists: "
                    + ex, ex);
            throw new IllegalStateException(
                    "Failed to configure Compass with classpath resource, even though it apparently exists: "
                            + ex);
        }
        configurationContext.put(CONFIGURED, Boolean.TRUE);
    }
}

From source file:edu.monash.merc.system.scheduling.impl.RifcsProcessor.java

@PostConstruct
public void initProcess() {
    try {//  w  w w  .  ja  v  a  2 s . co  m
        Resource rootRes = this.resourceLoader.getResource("/");
        //root full path
        String rootFullPath = rootRes.getURL().getPath();

        //root relative path
        String rootRelPath = getRootRelPath(rootFullPath);

        //get the pre-defined files location
        Resource rifcsResource = this.resourceLoader.getResource("classpath:rifcs");

        //rifcs directory
        this.rifcsDir = rifcsResource.getURL().getPath();
        if (StringUtils.isBlank(this.rifcsDir)) {
            throw new DMConfigException("The pre-defined rifcs files directory not found");
        }

        String rifcsEnabledStr = this.systemPropSettings.getPropValue(SystemPropConts.RDA_RIFCS_ENABLED);
        this.rifcsEnabled = Boolean.valueOf(rifcsEnabledStr);
        String rificsRepubStr = this.systemPropSettings
                .getPropValue(RifcsPropConts.TPB_RIFCS_REPUBLISH_REQUIRED);
        boolean rifcsRepublishRequired = Boolean.valueOf(rificsRepubStr);
        this.rifcsStoreLocation = DMUtil
                .normalizePath(this.systemPropSettings.getPropValue(RifcsPropConts.TPB_RIFCS_DATA_STORE));
        String tpbGroupName = this.systemPropSettings.getPropValue(RifcsPropConts.TPB_RIFCS_TPB_GROUP_NAME);
        String serverName = this.systemPropSettings.getPropValue(RifcsPropConts.TPB_SERVER_NAME);
        String rifcsKeyPrefix = this.systemPropSettings.getPropValue(RifcsPropConts.TPB_RIFCS_KEY_PREFIX);
        String rifcsTemplate = this.systemPropSettings.getPropValue(RifcsPropConts.TPB_RIFCS_TEMPLATE_FILE);

        rifcsInfoBean = new RifcsInfoBean();
        rifcsInfoBean.setRepublishRequired(rifcsRepublishRequired);
        rifcsInfoBean.setRifcsStoreLocation(this.rifcsStoreLocation);
        rifcsInfoBean.setTpbGroupName(tpbGroupName);
        rifcsInfoBean.setServerName(serverName);
        rifcsInfoBean.setAppRootRelPath(rootRelPath);
        rifcsInfoBean.setRifcsKeyPrefix(rifcsKeyPrefix);
        rifcsInfoBean.setRifcsTemplate(rifcsTemplate);

        //check if it is valid or not
        if (!rifcsInfoBean.valid()) {
            throw new DMConfigException("Some configuration values missed in the rifcs.properties file");
        }
    } catch (Exception ex) {
        throw new DMConfigException("Failed to load rifcs properties, " + ex.getMessage());
    }
}

From source file:org.codehaus.groovy.grails.plugins.searchable.compass.config.mapping.CompassMappingXmlSearchableGrailsDomainClassMappingConfigurator.java

/**
 * Configure the Mapping in the CompassConfiguration for the given domain class
 *
 * @param compassConfiguration          the CompassConfiguration instance
 * @param configurationContext          a configuration context, for flexible parameter passing
 * @param searchableGrailsDomainClasses searchable domain classes to map
 */// w w w  . j  a va2 s .c  o m
public void configureMappings(CompassConfiguration compassConfiguration, Map configurationContext,
        Collection searchableGrailsDomainClasses) {
    Assert.notNull(resourceLoader, "resourceLoader cannot be null");
    if (configurationContext.containsKey(CompassXmlConfigurationSearchableCompassConfigurator.CONFIGURED)) {
        return;
    }

    for (Iterator iter = searchableGrailsDomainClasses.iterator(); iter.hasNext();) {
        GrailsDomainClass grailsDomainClass = (GrailsDomainClass) iter.next();
        Resource resource = getMappingResource(grailsDomainClass);
        Assert.isTrue(resource.exists(),
                "expected mapping resource [" + resource + "] to exist but it does not");
        try {
            compassConfiguration.addURL(resource.getURL());
        } catch (IOException ex) {
            String message = "Failed to configure Compass with mapping resource for class ["
                    + grailsDomainClass.getClazz().getName() + "] and resource ["
                    + getMappingResourceName(grailsDomainClass) + "]";
            LOG.error(message, ex);
            throw new IllegalStateException(message + ": " + ex);
        }
    }
}

From source file:grails.plugin.searchable.internal.compass.config.mapping.CompassMappingXmlSearchableGrailsDomainClassMappingConfigurator.java

/**
 * Configure the Mapping in the CompassConfiguration for the given domain class
 *
 * @param compassConfiguration          the CompassConfiguration instance
 * @param configurationContext          a configuration context, for flexible parameter passing
 * @param searchableGrailsDomainClasses searchable domain classes to map
 * @param allSearchableGrailsDomainClasses all searchable domain classes, whether configured here or elsewhere
 *//*w w w  . j  a  v  a2s .co m*/
public void configureMappings(CompassConfiguration compassConfiguration, Map configurationContext,
        Collection searchableGrailsDomainClasses, Collection allSearchableGrailsDomainClasses) {
    Assert.notNull(resourceLoader, "resourceLoader cannot be null");
    if (configurationContext.containsKey(CompassXmlConfigurationSearchableCompassConfigurator.CONFIGURED)) {
        return;
    }

    for (Iterator iter = searchableGrailsDomainClasses.iterator(); iter.hasNext();) {
        GrailsDomainClass grailsDomainClass = (GrailsDomainClass) iter.next();
        Resource resource = getMappingResource(grailsDomainClass);
        Assert.isTrue(resource.exists(),
                "expected mapping resource [" + resource + "] to exist but it does not");
        try {
            compassConfiguration.addURL(resource.getURL());
        } catch (IOException ex) {
            String message = "Failed to configure Compass with mapping resource for class ["
                    + grailsDomainClass.getClazz().getName() + "] and resource ["
                    + getMappingResourceName(grailsDomainClass) + "]";
            LOG.error(message, ex);
            throw new IllegalStateException(message + ": " + ex);
        }
    }
}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

private List<UpgradeOp> buildUpgradeOps() throws IOException {
    List<UpgradeOp> ops = new ArrayList<UpgradeOp>();
    for (Resource script : scripts) {
        URL url = script.getURL();

        url.getFile();//from   w  w  w .  j  a v a2  s.  co m

        String name = url.getPath();
        int idx;
        if ((idx = name.lastIndexOf("/")) > -1) {
            name = name.substring(idx + 1);
        }

        // Java identifiers (i.e. .java upgrade 'scripts') may only contain
        // _ and currency symbols. So we use $ for a dash (-) and  for dot
        // (.) as underscore is already used
        name = name.replace("_DASH_", "-");
        name = name.replace("_DOT_", ".");

        int moduleIdx = name.indexOf('_');
        String moduleName = name.substring(0, moduleIdx);
        name = name.substring(moduleIdx + 1);
        idx = name.lastIndexOf('.');
        ops.add(new UpgradeOp(new Version(name.substring(0, idx)), url, moduleName, name.substring(idx + 1)));
    }
    Collections.sort(ops);
    return ops;
}