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

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

Introduction

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

Prototype

File getFile() throws IOException;

Source Link

Document

Return a File handle for this resource.

Usage

From source file:net.sourceforge.vulcan.metrics.XmlMetricsPlugin.java

private void refreshTransformers() throws IOException {
    final Resource[] resources = resourceResolver.getResources(transformSourcePath);

    if (transformers.size() != resources.length) {
        loadTransformers();/*from   w w  w . j  a  v  a 2  s  . c  om*/
        return;
    }

    for (Resource r : resources) {
        final long lastModified = r.getFile().lastModified();
        if (lastModified > newestTransformDate) {
            loadTransformers();
            return;
        }
    }
}

From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java

@Override
public Long getTestCount(Project project) {
    Long testCount = Long.valueOf(FileUtils.getTestFiles(getTestDirectory(project)).size());

    try {/*from   ww w.  j  av  a2s  . c  o m*/
        Resource[] javaSources = new PathMatchingResourcePatternResolver().getResources(
                "file:" + FilenameUtils.separatorsToUnix(getJavaDirectory(project)) + "**/*.java");
        for (Resource resource : javaSources) {
            File file = resource.getFile();
            String testName = FilenameUtils.getBaseName(file.getName());
            String testPackage = file.getParentFile().getAbsolutePath()
                    .substring(getJavaDirectory(project).length()).replace(File.separatorChar, '.');

            if (knownToClasspath(testPackage, testName)) {
                testCount += getTestCaseInfoFromClass(testPackage, testName, file).size();
            } else {
                testCount += getTestCaseInfoFromFile(testPackage, testName, file).size();
            }
        }
    } catch (IOException e) {
        log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e);
    }

    return testCount;
}

From source file:org.globus.security.stores.ResourceSecurityWrapperStore.java

private boolean load(Resource resource, Set<V> currentRoots, Map<String, T> newWrapperMap)
        throws ResourceStoreException {
    if (!resource.isReadable()) {
        throw new ResourceStoreException("Cannot read file");
    }//from   ww w  . j  a  v a  2s .c o m
    try {
        if (resource.getFile().isDirectory()) {
            File directory = resource.getFile();
            currentRoots.addAll(addCredentials(directory));
            return true;
        }
    } catch (IOException e) {
        // This is ok, it just means the resource is not a
        // filesystemresources
        logger.log(Level.FINE, "Not a filesystem resource", e);
    }
    try {
        String resourceUri = resource.getURL().toExternalForm();
        T fbo = this.wrapperMap.get(resourceUri);
        if (fbo == null) {
            fbo = create(resource);
        }
        V target = fbo.create(resource);
        newWrapperMap.put(resourceUri, fbo);
        currentRoots.add(target);
        return true;
    } catch (IOException e) {
        throw new ResourceStoreException(e);
    }

}

From source file:gov.nih.nci.cabig.caaers2adeers.xslt.CustomXsltComponent.java

private void loadResource(XsltBuilder xslt, Resource resource) throws TransformerConfigurationException {
    log.debug("Loading resource by :" + this + " , resource : " + resource);
    try {//  w  ww.j a v  a 2s. c  o m
        if (resource instanceof UrlResource) {
            // prefer to use file when a file based url
            File file = resource.getFile();
            if (file != null) {
                // check if the file exists and report a better error as the XSLT
                // will just say it cannot compile the stylesheet file
                if (!file.exists()) {
                    throw new FileNotFoundException("File: " + file + " not found.");
                }
                xslt.setTransformerFile(file);
            } else {
                xslt.setTransformerURL(resource.getURL());
            }
        } else {
            // fallback and use input stream
            xslt.setTransformerInputStream(resource.getInputStream());
        }
    } catch (Exception e) {
        // include information about the resource in the caused exception, so its easier for
        // end users to know which resource failed
        throw new TransformerConfigurationException(e.getMessage() + " " + resource.toString(), e);
    }
}

From source file:com.breakidea.noah.web.velocity.VelocityEngineFactory.java

/**
 * Initialize a Velocity resource loader for the given VelocityEngine: either a standard Velocity FileResourceLoader
 * or a SpringResourceLoader.//from   w w  w . j  ava2 s .co  m
 * <p>
 * Called by {@code createVelocityEngine()}.
 * @param velocityEngine the VelocityEngine to configure
 * @param resourceLoaderPath the path to load Velocity resources from
 * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader
 * @see SpringResourceLoader
 * @see #initSpringResourceLoader
 * @see #createVelocityEngine()
 */
protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) {
    if (isPreferFileSystemAccess()) {
        // Try to load via the file system, fall back to SpringResourceLoader
        // (for hot detection of template changes, if possible).
        try {
            StringBuilder resolvedPath = new StringBuilder();
            String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
            for (int i = 0; i < paths.length; i++) {
                String path = paths[i];
                Resource resource = getResourceLoader().getResource(path);
                File file = resource.getFile(); // will fail if not resolvable in the file system
                if (logger.isDebugEnabled()) {
                    logger.debug("Resource loader path [" + path + "] resolved to file ["
                            + file.getAbsolutePath() + "]");
                }
                resolvedPath.append(file.getAbsolutePath());
                if (i < paths.length - 1) {
                    resolvedPath.append(',');
                }
            }

            velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString());
        } catch (IOException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath
                        + "] to [java.io.File]: using SpringResourceLoader", ex);
            }
            initSpringResourceLoader(velocityEngine, resourceLoaderPath);
        }
    } else {
        // Always load via SpringResourceLoader
        // (without hot detection of template changes).
        if (logger.isDebugEnabled()) {
            logger.debug("File system access not preferred: using SpringResourceLoader");
        }
        initSpringResourceLoader(velocityEngine, resourceLoaderPath);
    }
}

From source file:de.interseroh.report.services.BirtReportServiceBean.java

private String absolutePathOf(String reportFileName) throws IOException {
    String location = appendSeparatorIfNeeded(environment.getProperty(REPORT_SOURCE_URL_KEY)) + reportFileName;
    Resource resource = resourceLoader.getResource(location);
    return resource.getFile().getAbsolutePath();
}

From source file:it.publisys.ims.discovery.job.EntityTasks.java

private void loadEntities(EntityDescriptorType[] entityDescriptorTypes) {
    Resource resource = new ClassPathResource(METADATA_DIR + "/" + PROTECTEDAPP_GUARD_XML);

    try {/*ww w . jav  a 2 s  .  c o m*/
        final EntityManager manager = loadEntityManager(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM,
                resource.getFile().getAbsolutePath());

        // Store the new entity IDs for cleaning out old ones later
        List<String> newEntityIDs = new ArrayList<>();

        Arrays.stream(entityDescriptorTypes)
                .filter(entityDescriptor -> entityDescriptor.getSPSSODescriptorArray().length > 0)
                .forEach(entityDescriptor -> {
                    log.info("Loading SP metadata for : " + entityDescriptor.getEntityID());
                    try {
                        Metadata metadataHandler = manager.createNewEntityHandler();
                        metadataHandler.setPrivateData(entityDescriptor);

                        manager.addMetadata(metadataHandler);

                        newEntityIDs.add(entityDescriptor.getEntityID());
                    } catch (GuanxiException ge) {
                        log.warn(
                                String.format("Non sono riuscito a caricari i metadati del Service Provider %s",
                                        entityDescriptor.getEntityID()),
                                ge);
                    }
                });

        // Remove expired entities from the manager
        String[] oldEntityIDs = manager.getEntityIDs();
        for (String oldEntityID : oldEntityIDs) {
            if (!newEntityIDs.contains(oldEntityID)) {
                manager.removeMetadata(oldEntityID);
            }
        }
    } catch (Exception ge) {
        log.error("Could not get an entity handler from the metadata manager", ge);
    }
}

From source file:org.fao.faostat.api.core.schema.JSONSchemaPool.java

public JSONSchemaPool(Resource datasourcePath) throws Exception {
    try {/* w w w . j  a va  2s.co m*/
        this.setDatasourcePath(datasourcePath.getFile().getPath());
    } catch (IOException e) {
        throw new Exception(e.getMessage());
    }
}

From source file:org.jnap.core.assets.StaticAssetsHandler.java

public void handle() {
    try {//from   www  . ja  va  2 s.c o  m
        Resource[] resources = this.resourceResolver.getResources(source);
        if (destination != null) {
            Resource destRes = new ServletContextResource(servletContext, destination);
            resetResource(destRes);
            BufferedWriter writer = new BufferedWriter(
                    new FileWriterWithEncoding(destRes.getFile(), this.encoding, true));
            for (Resource resource : resources) {
                IOUtils.copy(resource.getInputStream(), writer);
            }
            IOUtils.closeQuietly(writer);
            resources = new Resource[1];
            resources[0] = destRes;
        }

        for (Resource resource : resources) {
            //            doHandle(resource);
            //            File file = resource.getFile();
            String digest = DigestUtils.shaHex(resource.getInputStream());
            availableStaticAssets.put(resource.getFilename(), digest);
            if (compress) {
                Resource compressedResource = doCompression(resource);
                digest = DigestUtils.shaHex(compressedResource.getInputStream());
                availableStaticAssets.put(compressedResource.getFilename(), digest);
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java

@Override
public List<TestCaseData> getTests(Project project) {
    List<TestCaseData> tests = new ArrayList<TestCaseData>();

    List<File> testFiles = FileUtils.getTestFiles(getTestDirectory(project));
    for (File file : testFiles) {
        String testName = FilenameUtils.getBaseName(file.getName());
        String testPackageName = file.getPath().substring(getTestDirectory(project).length(),
                file.getPath().length() - file.getName().length()).replace(File.separatorChar, '.');

        if (testPackageName.endsWith(".")) {
            testPackageName = testPackageName.substring(0, testPackageName.length() - 1);
        }/*from w  w w  .  j a  v a 2s  .  c  o m*/

        TestCaseData testCase = new TestCaseData();
        testCase.setType(TestCaseType.XML);
        testCase.setName(testName);
        testCase.setPackageName(testPackageName);
        testCase.setFile(file.getParentFile().getAbsolutePath() + File.separator
                + FilenameUtils.getBaseName(file.getName()));
        testCase.setLastModified(file.lastModified());

        tests.add(testCase);
    }

    try {
        Resource[] javaSources = new PathMatchingResourcePatternResolver().getResources(
                "file:" + FilenameUtils.separatorsToUnix(getJavaDirectory(project)) + "**/*.java");

        for (Resource resource : javaSources) {
            File file = resource.getFile();
            String testName = FilenameUtils.getBaseName(file.getName());
            String testPackage = file.getParentFile().getAbsolutePath()
                    .substring(getJavaDirectory(project).length()).replace(File.separatorChar, '.');

            if (knownToClasspath(testPackage, testName)) {
                tests.addAll(getTestCaseInfoFromClass(testPackage, testName, file));
            } else {
                tests.addAll(getTestCaseInfoFromFile(testPackage, testName, file));
            }
        }
    } catch (IOException e) {
        log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e);
    }

    return tests;
}