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

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

Introduction

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

Prototype

URI getURI() throws IOException;

Source Link

Document

Return a URI handle for this resource.

Usage

From source file:org.craftercms.commons.mongo.MongoScriptRunner.java

private void runScript(DB db, Resource scriptPath) throws MongoDataException {
    String script;/*from ww w . j  a  v a  2  s . c  o  m*/
    try {
        if (scriptPath.getFile().isDirectory()) {
            final File[] files = scriptPath.getFile().listFiles(new FilenameFilter() {
                @Override
                public boolean accept(final File dir, final String name) {
                    return name.toLowerCase().endsWith(".js");
                }
            });
            List<File> orderFiles = Arrays.asList(files);
            Collections.sort(orderFiles, new Comparator<File>() {
                @Override
                public int compare(final File o1, final File o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            logger.debug("Directory {} files to exec {}", scriptPath.getFile(), orderFiles);
            for (File file : orderFiles) {
                runScript(db, new FileSystemResource(file.getPath()));
            }
        } else {
            logger.debug("Running Script {}", scriptPath.getURI());
            try {
                script = IOUtils.toString(scriptPath.getInputStream(), "UTF-8");
            } catch (IOException e) {
                throw new MongoDataException("Unable to read script at " + scriptPath.getURI().toString());
            }

            CommandResult result = db.doEval(script);
            if (!result.ok()) {
                Exception ex = result.getException();

                throw new MongoDataException(
                        "An error occurred while running script at " + scriptPath.getURI().toString(), ex);

            }
            logger.info("Mongo script at {} executed successfully", scriptPath.getDescription());
        }
    } catch (IOException ex) {
        logger.error("Unable to read files from {}", ex);
    }
}

From source file:org.jahia.services.templates.TemplatePackageDeployer.java

private void resetModuleAttributes(JCRSessionWrapper session, JahiaTemplatesPackage pack)
        throws RepositoryException {
    JCRNodeWrapper modules = session.getNode("/modules");
    JCRNodeWrapper m = modules.getNode(pack.getIdWithVersion());

    m.setProperty("j:title", pack.getName());
    if (pack.getModuleType() != null) {
        m.setProperty("j:moduleType", pack.getModuleType());
    }/* ww w.  j  a v  a2s  . c  o  m*/
    m.setProperty("j:modulePriority", pack.getModulePriority());
    List<Value> l = new ArrayList<Value>();
    for (String d : pack.getDepends()) {
        String v = templatePackageRegistry.getModuleId(d);
        if (v != null) {
            l.add(session.getValueFactory().createValue(v));
        } else {
            logger.warn("Cannot find dependency {} for package '{}'", d, pack.getName());
        }
    }
    Value[] values = new Value[pack.getDepends().size()];
    m.setProperty("j:dependencies", l.toArray(values));

    if (pack.getModuleType() == null) {
        String moduleType = guessModuleType(session, pack);
        pack.setModuleType(moduleType);
    }

    if (!m.hasNode("templates")) {
        m.addNode("templates", "jnt:templatesFolder");
    }
    if (!m.hasNode("permissions")) {
        m.addNode("permissions", "jnt:permission");
    }
    JCRNodeWrapper perms = m.getNode("permissions");
    if (!perms.hasNode("components")) {
        perms.addNode("components", "jnt:permission");
    }
    if (!perms.hasNode("templates")) {
        perms.addNode("templates", "jnt:permission");
    }

    JCRNodeWrapper tpls = m.getNode("templates");
    if (!tpls.hasProperty("j:rootTemplatePath")
            && JahiaTemplateManagerService.MODULE_TYPE_MODULE.equals(pack.getModuleType())) {
        tpls.setProperty("j:rootTemplatePath", "/base");
    }

    if (pack.getResourceBundleName() != null) {
        List<String> langs = new ArrayList<String>();
        Resource[] resources = pack.getResources("resources");
        for (Resource resource : resources) {
            try {
                String key = resource.getURI().getPath().substring(1).replace("/", ".");
                if (key.startsWith(pack.getResourceBundleName())) {
                    String langCode = StringUtils.substringBetween(key, pack.getResourceBundleName() + "_",
                            ".properties");
                    if (langCode != null) {
                        langs.add(langCode);
                    }
                }
            } catch (IOException e) {
                logger.error("Cannot get resources", e);
            }
        }
        JCRNodeWrapper moduleNode = m.getParent();
        if (moduleNode.hasProperty("j:languages")) {
            Value[] oldValues = m.getParent().getProperty("j:languages").getValues();
            for (Value value : oldValues) {
                if (!langs.contains(value.getString())) {
                    langs.add(value.getString());
                }
            }
        }
        moduleNode.setProperty("j:languages", langs.toArray(new String[langs.size()]));
    }
}

From source file:org.jbb.lib.mvc.WildcardReloadableResourceBundleMessageSource.java

private void processResource(Resource resource, List<String> resultBaseNameList) {
    String uri = null;//  w w w  .  ja va 2s  .c om
    try {
        uri = resource.getURI().toString();
    } catch (IOException e) {
        log.debug("Error when getting URI from resource: {}", resource, e);
        return;
    }

    String baseName = null;
    if (resource instanceof FileSystemResource) {
        baseName = substringBetween(uri, "/classes/", PROPERTIES_SUFFIX);
    } else if (resource instanceof ClassPathResource) {
        baseName = substringBefore(uri, PROPERTIES_SUFFIX);
    } else if (resource instanceof UrlResource) {
        baseName = "classpath:" + substringBetween(uri, ".jar!/", PROPERTIES_SUFFIX);
    }

    if (baseName != null) {
        String fullName = processBasename(baseName);
        resultBaseNameList.add(fullName);
    }
}

From source file:org.kuali.rice.krad.datadictionary.ReloadingDataDictionary.java

/**
 * After dictionary has been loaded, determine the source files and add them
 * to the monitor//from   ww w  .  j  ava 2s .  c om
 * 
 * @see org.kuali.rice.krad.datadictionary.DataDictionary#parseDataDictionaryConfigurationFiles(boolean)
 */
@Override
public void parseDataDictionaryConfigurationFiles(boolean allowConcurrentValidation) {
    ConfigurationService configurationService = KRADServiceLocator.getKualiConfigurationService();

    // class directory part of the path that should be replaced
    String classesDir = configurationService.getPropertyValueAsString(CLASS_DIR_CONFIG_PARM);

    // source directory where dictionary files are found
    String sourceDir = configurationService.getPropertyValueAsString(SOURCE_DIR_CONFIG_PARM);

    // interval to poll for changes in milliseconds
    int reloadInterval = Integer.parseInt(configurationService.getPropertyValueAsString(INTERVAL_CONFIG_PARM));

    FileMonitor dictionaryFileMonitor = new FileMonitor(reloadInterval);

    dictionaryUrlMonitor = new URLMonitor(reloadInterval);
    dictionaryUrlMonitor.addListener(this);

    // need to copy the configFileLocations list here because it gets
    // cleared out after processing by super
    List<String> configLocations = new ArrayList<String>(configFileLocations);

    super.parseDataDictionaryConfigurationFiles(allowConcurrentValidation);
    for (String configLocation : configLocations) {
        Resource classFileResource = getFileResource(configLocation);
        try {
            if (classFileResource.getURI().toString().startsWith("jar:")) {
                LOG.debug("Monitoring dictionary file at URI: " + classFileResource.getURI().toString());
                dictionaryUrlMonitor.addURI(classFileResource.getURL());
            } else {
                String filePathClassesDir = classFileResource.getFile().getAbsolutePath();
                String sourceFilePath = StringUtils.replace(filePathClassesDir, classesDir, sourceDir);
                File dictionaryFile = new File(filePathClassesDir);
                if (dictionaryFile.exists()) {
                    LOG.debug("Monitoring dictionary file: " + dictionaryFile.getName());
                    dictionaryFileMonitor.addFile(dictionaryFile);
                }
            }
        } catch (Exception e) {
            LOG.info("Exception in picking up dictionary file for monitoring:  " + e.getMessage(), e);
        }
    }

    // add the dictionary as a listener for file changes
    dictionaryFileMonitor.addListener(this);
}

From source file:org.kuali.rice.krad.devtools.datadictionary.ReloadingDataDictionary.java

/**
 * After dictionary has been loaded, determine the source files and add them
 * to the monitor/* w w w.  j a  v a2s.c  o  m*/
 *
 * @see org.kuali.rice.krad.datadictionary.DataDictionary#parseDataDictionaryConfigurationFiles(boolean)
 */
@Override
public void parseDataDictionaryConfigurationFiles(boolean allowConcurrentValidation) {
    ConfigurationService configurationService = CoreApiServiceLocator.getKualiConfigurationService();

    // class directory part of the path that should be replaced
    String classesDir = configurationService.getPropertyValueAsString(CLASS_DIR_CONFIG_PARM);

    // source directory where dictionary files are found
    String sourceDir = configurationService.getPropertyValueAsString(SOURCE_DIR_CONFIG_PARM);

    // interval to poll for changes in milliseconds
    int reloadInterval = Integer.parseInt(configurationService.getPropertyValueAsString(INTERVAL_CONFIG_PARM));

    dictionaryFileMonitor = new FileMonitor(reloadInterval);
    dictionaryFileMonitor.addListener(this);

    dictionaryUrlMonitor = new URLMonitor(reloadInterval);
    dictionaryUrlMonitor.addListener(this);

    super.parseDataDictionaryConfigurationFiles(allowConcurrentValidation);

    // need to hold mappings of file/url to namespace so we can correctly add beans to the associated
    // namespace when reloading the resource
    fileToNamespaceMapping = new HashMap<String, String>();
    urlToNamespaceMapping = new HashMap<String, String>();

    // add listener for each dictionary file
    for (Map.Entry<String, List<String>> moduleDictionary : moduleDictionaryFiles.entrySet()) {
        String namespace = moduleDictionary.getKey();
        List<String> configLocations = moduleDictionary.getValue();

        for (String configLocation : configLocations) {
            Resource classFileResource = getFileResource(configLocation);

            try {
                if (classFileResource.getURI().toString().startsWith("jar:")) {
                    LOG.trace("Monitoring dictionary file at URI: " + classFileResource.getURI().toString());

                    dictionaryUrlMonitor.addURI(classFileResource.getURL());
                    urlToNamespaceMapping.put(classFileResource.getURL().toString(), namespace);
                } else {
                    String filePathClassesDir = classFileResource.getFile().getAbsolutePath();
                    String sourceFilePath = StringUtils.replace(filePathClassesDir, classesDir, sourceDir);

                    File dictionaryFile = new File(filePathClassesDir);
                    if (dictionaryFile.exists()) {
                        LOG.trace("Monitoring dictionary file: " + dictionaryFile.getName());

                        dictionaryFileMonitor.addFile(dictionaryFile);
                        fileToNamespaceMapping.put(dictionaryFile.getAbsolutePath(), namespace);
                    }
                }
            } catch (Exception e) {
                LOG.info("Exception in picking up dictionary file for monitoring:  " + e.getMessage(), e);
            }
        }
    }
}

From source file:org.LexGrid.LexBIG.test.ContentLoadingTestListener.java

/**
 * Load.//w ww.ja v a 2 s.  co m
 * 
 * @param content
 *            the content
 * @throws Exception
 *             the exception
 */
protected void load(LoadContent content) throws Exception {
    String[] paths = StringUtils.split(content.contentPath(), ',');

    for (String path : paths) {
        LexBIGServiceManager lbsm = LexBIGServiceImpl.defaultInstance().getServiceManager(null);

        Resource resource = this.getResource(path);

        Loader loader = lbsm.getLoader(content.loader());

        loader.getOptions().getBooleanOption(BaseLoader.ASYNC_OPTION).setOptionValue(false);

        loader.load(resource.getURI());

        assertTrue(loader.getStatus().getState().equals(ProcessState.COMPLETED));
        assertFalse(loader.getStatus().getErrorsLogged().booleanValue());

        try {
            lbsm.activateCodingSchemeVersion(loader.getCodingSchemeReferences()[0]);

            lbsm.setVersionTag(loader.getCodingSchemeReferences()[0],
                    LBConstants.KnownTags.PRODUCTION.toString());
        } catch (Exception e) {
            //error activating -- it could be a ValueSetDefinition.
        }
    }
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

public static void createParentDir(Resource resource) throws IOException {
    Path resourcePath = Paths.get(resource.getURI());
    Path resourceDir = resourcePath.getParent();
    if (Files.notExists(resourceDir)) {
        log.info("Directory {} doesn't exist. Creating it now.", resourceDir);
        Files.createDirectories(resourceDir);
    }/* w  w  w  .  j  a  v  a  2  s.  com*/
}

From source file:org.openlegacy.designtime.mains.DesignTimeExecuterImpl.java

@Override
public void copyCodeGenerationTemplates(File projectPath) {
    File templatesDir = new File(projectPath, TEMPLATES_DIR);
    templatesDir.mkdirs();/*from w w  w  .ja  v  a2s. co m*/
    PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
    Resource[] defaultTemplates;
    OutputStream fos = null;
    try {
        defaultTemplates = pathResolver.getResources(DEFAULT_TEMPLATES_PATTERN);
        for (Resource resource : defaultTemplates) {
            String uri = resource.getURI().toString();
            String fileRelativePath = uri.substring(uri.indexOf("!") + 2);
            File targetFile = new File(templatesDir, fileRelativePath);
            targetFile.getParentFile().mkdirs();
            fos = new FileOutputStream(targetFile);
            IOUtils.copy(resource.getInputStream(), fos);
            IOUtils.closeQuietly(fos);
        }
    } catch (IOException e) {
        throw (new GenerationException("Error creating custom templates", e));
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.openlegacy.support.DefaultRegistryLoader.java

private static Class<?> getClassFromResource(String packagePath, Resource resource)
        throws IOException, ClassNotFoundException {
    String resourcePath = resource.getURI().toString();
    String resourceRelativePath = resourcePath.substring(resourcePath.indexOf(packagePath),
            resourcePath.indexOf(".class"));
    String className = ClassUtils.convertResourcePathToClassName(resourceRelativePath);

    Class<?> beanClass = Class.forName(className);
    return beanClass;
}

From source file:org.polyfill.services.FinancialTimesPolyfillLoaderService.java

private String getBaseDirectoryName(Resource resource) throws IOException {
    // using string manipulation to handle path here because if resource is from jar,
    // we cannot create a file/path instance from it
    String dirPathString = FilenameUtils.getFullPathNoEndSeparator(resource.getURI().toString());
    return FilenameUtils.getName(dirPathString);
}