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:org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine.java

private String getPathForResource(Resource res) {
    if (res == null)
        return "";

    String path = null;/*w w w .j  a va  2s.  c  o  m*/
    try {
        File file = res.getFile();
        if (file != null) {
            path = file.getAbsolutePath();
        }
    } catch (IOException e) {
        // ignore
    }
    if (path != null) {
        return path;
    }
    if (res.getDescription() != null) {
        return res.getDescription();
    }
    return "";
}

From source file:org.codehaus.groovy.grails.web.servlet.view.GroovyPageView.java

public static GroovyPagesException createGroovyPageException(Exception exception,
        GroovyPagesTemplateEngine engine, String pageUrl) {
    GroovyPageTemplate t = (GroovyPageTemplate) engine.createTemplate(pageUrl);
    StackTraceElement[] stackTrace = exception.getStackTrace();
    String className = stackTrace[0].getClassName();
    int lineNumber = stackTrace[0].getLineNumber();
    if (className.contains("_gsp")) {
        int[] lineNumbers = t.getMetaInfo().getLineNumbers();
        if (lineNumber < lineNumbers.length) {
            lineNumber = lineNumbers[lineNumber - 1];
        }//from www.  j a  va  2 s  .  co  m
    }

    Resource resource = pageUrl != null ? engine.getResourceForUri(pageUrl) : null;
    String file;
    try {
        file = resource != null && resource.exists() ? resource.getFile().getAbsolutePath() : pageUrl;
    } catch (IOException e) {
        file = pageUrl;
    }

    return new GroovyPagesException("Error processing GroovyPageView: " + exception.getMessage(), exception,
            lineNumber, file);
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java

private String searchPluginViewsInDevelopmentMode(String name) {

    String pluginViewLocation = null;
    for (Resource resource : GrailsPluginUtils.getPluginDirectories()) {
        try {//from   w ww .  j a v a2  s. co  m
            final String pathToLayoutInPlugin = "grails-app/views/layouts/" + name;
            final String absolutePathToResource = resource.getFile().getAbsolutePath();
            if (!absolutePathToResource.endsWith("/")) {
                resource = new FileSystemResource(absolutePathToResource + '/');
            }
            final Resource layoutPath = resource.createRelative(pathToLayoutInPlugin);
            if (layoutPath.exists()) {
                GrailsPluginInfo info = GrailsPluginUtils.getPluginBuildSettings()
                        .getPluginInfo(absolutePathToResource);
                pluginViewLocation = GrailsResourceUtils.WEB_INF + "/plugins/" + info.getFullName() + '/'
                        + pathToLayoutInPlugin;
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return pluginViewLocation;
}

From source file:org.compass.spring.LocalCompassBean.java

public void afterPropertiesSet() throws Exception {
    CompassConfiguration config = this.config;
    if (config == null) {
        config = newConfiguration();//from   w  w  w  .  j av  a  2  s  . com
    }

    if (classLoader != null) {
        config.setClassLoader(getClassLoader());
    }

    if (this.configLocation != null) {
        config.configure(this.configLocation.getURL());
    }

    if (this.configLocations != null) {
        for (Resource configLocation1 : configLocations) {
            config.configure(configLocation1.getURL());
        }
    }

    if (this.mappingScan != null) {
        config.addScan(this.mappingScan);
    }

    if (this.compassSettings != null) {
        config.getSettings().addSettings(this.compassSettings);
    }

    if (this.settings != null) {
        config.getSettings().addSettings(this.settings);
    }

    if (resourceLocations != null) {
        for (Resource resourceLocation : resourceLocations) {
            config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename());
        }
    }

    if (resourceJarLocations != null) {
        for (Resource resourceJarLocation : resourceJarLocations) {
            config.addJar(resourceJarLocation.getFile());
        }
    }

    if (classMappings != null) {
        for (String classMapping : classMappings) {
            config.addClass(ClassUtils.forName(classMapping, getClassLoader()));
        }
    }

    if (resourceDirectoryLocations != null) {
        for (Resource resourceDirectoryLocation : resourceDirectoryLocations) {
            File file = resourceDirectoryLocation.getFile();
            if (!file.isDirectory()) {
                throw new IllegalArgumentException("Resource directory location [" + resourceDirectoryLocation
                        + "] does not denote a directory");
            }
            config.addDirectory(file);
        }
    }

    if (mappingResolvers != null) {
        for (InputStreamMappingResolver mappingResolver : mappingResolvers) {
            config.addMappingResolver(mappingResolver);
        }
    }

    if (convertersByName != null) {
        for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) {
            config.registerConverter(entry.getKey(), entry.getValue());
        }
    }
    if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) {
        config.getSettings().setSetting(CompassEnvironment.NAME, beanName);
    }

    if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) {
        config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath());
    }

    if (applicationContext != null) {
        String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
        for (String name : names) {
            try {
                PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext
                        .getBean(name);
                Method method = findMethod(propConfigurer.getClass(), "mergeProperties");
                method.setAccessible(true);
                Properties props = (Properties) method.invoke(propConfigurer);
                method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class);
                method.setAccessible(true);
                method.invoke(propConfigurer, props);
                method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class,
                        Properties.class, Set.class);
                method.setAccessible(true);
                String nullValue = null;
                try {
                    Field field = propConfigurer.getClass().getDeclaredField("nullValue");
                    field.setAccessible(true);
                    nullValue = (String) field.get(propConfigurer);
                } catch (NoSuchFieldException e) {
                    // no field (old spring version)
                }
                for (Map.Entry entry : config.getSettings().getProperties().entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    value = (String) method.invoke(propConfigurer, value, props, new HashSet());
                    config.getSettings().setSetting(key, value.equals(nullValue) ? null : value);
                }
            } catch (Exception e) {
                log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e);
            }
        }
    }

    // we do this after the proeprties placeholder hack, so if other Compass beans are created beacuse
    // of it, we still maintain the correct thread local setting of the data source and transaction manager
    if (dataSource != null) {
        ExternalDataSourceProvider.setDataSource(dataSource);
        if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) {
            config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS,
                    ExternalDataSourceProvider.class.getName());
        }
    }

    String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY);
    if (compassTransactionFactory == null && transactionManager != null) {
        // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one.
        config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY,
                SpringSyncTransactionFactory.class.getName());
    }
    if (compassTransactionFactory != null
            && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) {
        if (transactionManager == null) {
            throw new IllegalArgumentException(
                    "When using SpringSyncTransactionFactory the transactionManager property must be set");
        }
    }
    SpringSyncTransactionFactory.setTransactionManager(transactionManager);

    if (postProcessor != null) {
        postProcessor.process(config);
    }
    this.compass = newCompass(config);
    this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(),
            new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass));
}

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

private void runScriptsWithMongoClient() {
    List<String> toExecute = new ArrayList<>();

    try {/*  www . j ava2s.  c  o m*/
        for (Resource scriptPath : scriptPaths) {
            if (scriptPath.getFile().isDirectory()) {
                Files.walkFileTree(scriptPath.getFile().toPath(), new JSFileVisitor(toExecute));
            } else {
                toExecute.add(scriptPath.getFile().getAbsolutePath());
            }
        }
        final Path allScripsFile = Files.createTempFile("ScriptRunner", ".js");
        StringBuilder builder = new StringBuilder();
        for (String path : toExecute) {
            builder.append(String.format("load('%s');\n", path));
        }
        FileUtils.writeStringToFile(allScripsFile.toFile(), builder.toString(), "UTF-8");
        runScript(allScripsFile);
        Files.deleteIfExists(allScripsFile);
    } catch (IOException | MongoDataException ex) {
        logger.error("Unable to run script using MongoClient", ex);
    }
}

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

private void runScript(DB db, Resource scriptPath) throws MongoDataException {
    String script;//from www  . j  av  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.craftercms.core.store.impl.filesystem.FileSystemContentStoreAdapter.java

@Override
public Context createContext(String id, String storeServerUrl, String username, String password,
        String rootFolderPath, boolean mergingOn, boolean cacheOn, int maxAllowedItemsInCache,
        boolean ignoreHiddenFiles) throws RootFolderNotFoundException, StoreException, AuthenticationException {
    Resource rootFolderResource = resourceLoader.getResource(rootFolderPath);

    if (!rootFolderResource.exists()) {
        throw new RootFolderNotFoundException("Root folder " + rootFolderPath
                + " not found (make sure that it has a valid URL " + "prefix (e.g. file:))");
    }/*from w  w w.  j  a v  a 2 s .c  o  m*/

    FileSystemFile rootFolder;
    try {
        rootFolder = new FileSystemFile(rootFolderResource.getFile());
    } catch (IOException e) {
        throw new StoreException("Unable to retrieve file handle for root folder " + rootFolderPath, e);
    }

    return new FileSystemContext(id, this, null, rootFolderPath, rootFolder, mergingOn, cacheOn,
            maxAllowedItemsInCache, ignoreHiddenFiles);
}

From source file:org.craftercms.deployer.impl.DeploymentResolverImpl.java

public DeploymentResolverImpl(@Value("${deployer.configLocation}") Resource configResource,
        @Value("${deployer.baseDeploymentConfig.yamlLocation}") Resource baseDeploymentYamlConfigResource,
        @Value("${deployer.baseDeploymentConfig.yamlOverrideLocation}") Resource baseDeploymentYamlConfigOverrideResource,
        @Value("${deployer.baseDeploymentConfig.appContextLocation}") Resource baseDeploymentAppContextResource,
        @Value("${deployer.baseDeploymentConfig.appContextOverrideLocation}") Resource baseDeploymentAppContextOverrideResource,
        @Autowired ApplicationContext mainApplicationContext,
        @Autowired DeploymentPipelineFactory deploymentPipelineFactory) throws IOException {
    this.configFolder = configResource.getFile();
    this.baseDeploymentYamlConfigResource = baseDeploymentYamlConfigResource;
    this.baseDeploymentYamlConfigOverrideResource = baseDeploymentYamlConfigOverrideResource;
    this.baseDeploymentAppContextResource = baseDeploymentAppContextResource;
    this.baseDeploymentAppContextOverrideResource = baseDeploymentAppContextOverrideResource;
    this.mainApplicationContext = mainApplicationContext;
    this.deploymentPipelineFactory = deploymentPipelineFactory;

    deploymentContextCache = new HashMap<>();
}

From source file:org.dataconservancy.access.connector.AbstractConnectorIT.java

@BeforeClass
public static void getAllTestEntities() throws IOException, InvalidXmlException {
    final String entitiesResource = "/entities";
    final Resource entities = rl.getResource(entitiesResource);
    assertNotNull(entities);/*from   w  w  w  .  j  a v a  2  s .  c om*/
    assertTrue(entities.exists() && entities.getFile().canRead() && entities.getFile().isDirectory());
    Collection<File> files = FileUtils.listFiles(entities.getFile(), new String[] { "xml" }, false);
    for (File f : files) {
        Dcp dcp = mb.buildSip(new FileInputStream(f));
        allTestEntities.addAll(dcp.getCollections());
        allTestEntities.addAll(dcp.getDeliverableUnits());
        allTestEntities.addAll(dcp.getEvents());
        allTestEntities.addAll(dcp.getFiles());
        allTestEntities.addAll(dcp.getManifestations());
    }

    for (DcsEntity e : allTestEntities) {
        allTestEntitiesById.put(e.getId(), e);
    }
}

From source file:org.dataconservancy.access.connector.AbstractEntityTest.java

@BeforeClass
public static void getAllTestEntities() throws IOException, InvalidXmlException {
    final String entitiesResource = "/entities";
    final Resource entities = rl.getResource(entitiesResource);
    assertNotNull(entities);//from   ww  w. ja v a2 s.  c  o m
    entitiesDir = entities.getFile();
    assertTrue(entitiesDir.exists() && entitiesDir.canRead() && entitiesDir.isDirectory());
    Collection<File> files = FileUtils.listFiles(entities.getFile(), new String[] { "xml" }, false);
    for (File f : files) {
        Dcp dcp = mb.buildSip(new FileInputStream(f));
        allTestEntities.addAll(dcp.getCollections());
        allTestEntities.addAll(dcp.getDeliverableUnits());
        allTestEntities.addAll(dcp.getEvents());
        allTestEntities.addAll(dcp.getFiles());
        allTestEntities.addAll(dcp.getManifestations());
    }

    for (DcsEntity e : allTestEntities) {
        allTestEntitiesById.put(e.getId(), e);
    }
}