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.globus.workspace.scheduler.defaults.pilot.PilotSlotManagement.java

public void setLogdirResource(Resource logdirResource) throws IOException {
    this.logdirPath = logdirResource.getFile().getAbsolutePath();
}

From source file:org.grails.dev.support.DevelopmentResourceLoader.java

/**
 * Retrieves the real location of a GSP within a Grails project.
 * @param location The location of the GSP at deployment time
 * @return The location of the GSP at development time
 *//*from  ww  w .  ja  va2s. c o m*/
protected String getRealLocationInProject(String location) {

    if (new File(location).exists()) {
        return "file:" + location;
    }
    // don't mess with locations that are URLs (in other words, locations that have schemes)
    if (HAS_SCHEME_PATTERN.matcher(location).matches())
        return location;
    if (!location.startsWith(SLASH))
        location = SLASH + location;

    // don't mess with locations that are URLs (in other words, locations that have schemes)
    if (HAS_SCHEME_PATTERN.matcher(location).matches())
        return location;

    // If the location (minus the "grails-app/.*" ending so that it matches the key value used in BuildSettings for
    // the inline plugin map) matches an "inline" plugin, use the location as-is
    // for the resource location.  Otherwise, perform the logic to "normalize" the resource location based on
    // its relativity to the application (i.e. is it from a non-inline plugin, etc).
    if (BuildSettingsHolder.getSettings()
            .isInlinePluginLocation(new File(location.replaceAll(GRAILS_APP_DIR_PATTERN, "")))) {
        return "file:" + location;
    }

    if (!location.startsWith(GrailsResourceUtils.WEB_INF)) {
        return GrailsResourceUtils.WEB_APP_DIR + location;
    }

    final String noWebInf = location.substring(GrailsResourceUtils.WEB_INF.length() + 1);
    final String defaultPath = "file:" + baseLocation + SLASH + noWebInf;
    if (!noWebInf.startsWith(PLUGINS_PREFIX)) {
        return defaultPath;
    }

    if (application != null) {

        BuildSettings settings = BuildSettingsHolder.getSettings();
        PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();
        String pluginPath = GrailsStringUtils.substringAfter(noWebInf, SLASH);
        String pluginName = GrailsStringUtils.substringBefore(pluginPath, SLASH);
        String remainingPath = GrailsStringUtils.substringAfter(pluginPath, SLASH);
        org.grails.io.support.Resource r = pluginBuildSettings.getPluginDirForName(pluginName);
        if (r != null) {
            try {
                return "file:" + r.getFile().getAbsolutePath() + SLASH + remainingPath;
            } catch (IOException e) {
                LOG.debug("Unable to locate plugin resource -- returning default path " + defaultPath + ".", e);
                return defaultPath;
            }
        }

        if (settings != null) {
            return "file:" + settings.getProjectPluginsDir().getAbsolutePath() + SLASH + pluginName + SLASH
                    + remainingPath;
        }
    }

    return defaultPath;
}

From source file:org.grails.plugins.DefaultGrailsPlugin.java

@Override
public void refresh() {
    // do nothing
    org.grails.io.support.Resource descriptor = getDescriptor();
    if (application == null || descriptor == null) {
        return;//  w ww  .  ja  v  a 2  s. c o  m
    }

    ClassLoader parent = application.getClassLoader();
    GroovyClassLoader gcl = new GroovyClassLoader(parent);
    try {
        initialisePlugin(gcl.parseClass(descriptor.getFile()));
    } catch (Exception e) {
        LOG.error("Error refreshing plugin: " + e.getMessage(), e);
    }
}

From source file:org.grails.spring.beans.factory.GrailsApplicationFactoryBean.java

public void afterPropertiesSet() throws Exception {
    if (descriptor != null && descriptor.exists()) {
        LOG.info("Loading Grails application with information from descriptor.");

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        List<Class<?>> classes = new ArrayList<Class<?>>();
        InputStream inputStream = null;
        try {/*from  ww  w.  ja v  a 2 s. c o m*/
            inputStream = descriptor.getInputStream();

            // Get all the resource nodes in the descriptor.
            // Xpath: /grails/resources/resource, where root is /grails
            GPathResult root = SpringIOUtils.createXmlSlurper().parse(inputStream);
            GPathResult resources = (GPathResult) root.getProperty("resources");
            GPathResult grailsClasses = (GPathResult) resources.getProperty("resource");

            // Each resource node should contain a full class name,
            // so we attempt to load them as classes.
            for (int i = 0; i < grailsClasses.size(); i++) {
                GPathResult node = (GPathResult) grailsClasses.getAt(i);
                String className = node.text();
                try {
                    Class<?> clazz = Class.forName(className, true, classLoader);
                    classes.add(clazz);
                } catch (ClassNotFoundException e) {
                    LOG.warn("Class with name [" + className
                            + "] was not found, and hence not loaded. Possible empty class or script definition?");
                }
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        Class<?>[] loadedClasses = classes.toArray(new Class[classes.size()]);
        grailsApplication = new DefaultGrailsApplication(loadedClasses, classLoader);
    } else if (!Environment.isWarDeployed()) {
        org.grails.io.support.Resource[] buildResources = GrailsPluginUtils.getPluginBuildSettings()
                .getArtefactResourcesForCurrentEnvironment();

        Resource[] resources = new Resource[buildResources.length];

        for (int i = 0; i < buildResources.length; i++) {
            org.grails.io.support.Resource buildResource = buildResources[i];
            resources[i] = new FileSystemResource(buildResource.getFile());
        }

        grailsApplication = new DefaultGrailsApplication(resources);
    } else {
        grailsApplication = new DefaultGrailsApplication();
    }

    Holders.setGrailsApplication(grailsApplication);
}

From source file:org.grails.web.pages.GroovyPageResourceLoader.java

protected boolean isInlinePlugin(GrailsPluginInfo pluginInfo) throws IOException {
    // unfortunately pluginSettings.isInlinePluginLocation() does not work, paths are compare incorrectly
    for (org.grails.io.support.Resource pluginDirResource : pluginSettings.getInlinePluginDirectories()) {
        if (compareFilePaths(pluginDirResource.getFile(), pluginInfo.getPluginDir().getFile())) {
            return true;
        }//from   w  ww . ja va 2  s  .c  om
    }
    return false;
}

From source file:org.granite.grails.web.GrailsGAEWebSWFServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);

    // Get the name of the Groovy script (intern the name so that we can lock on it)
    String pageName = "/swf" + request.getServletPath();

    Resource requestedFile = getResourceForUri(pageName);

    File swfFile = requestedFile.getFile();
    if (swfFile == null || !swfFile.exists()) {
        response.sendError(404, "\"" + pageName + "\" not found.");
        return;//from   ww w  .  j av  a2  s  . c o m
    }

    response.setContentType("application/x-shockwave-flash");
    response.setContentLength((int) swfFile.length());
    response.setBufferSize((int) swfFile.length());
    response.setDateHeader("Expires", 0);

    byte[] buf = new byte[1000000];
    FileInputStream is = null;
    try {
        is = new FileInputStream(swfFile);
        OutputStream os = response.getOutputStream();
        int read = is.read(buf, 0, 1000000);
        while (read > 0) {
            os.write(buf, 0, read);
            read = is.read(buf, 0, 1000000);
        }
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:org.granite.grails.web.GrailsWebSWFServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);

    // Get the name of the Groovy script (intern the name so that we can lock on it)
    String pageName = "/swf" + request.getServletPath();
    Resource requestedFile = getResourceForUri(pageName);
    File swfFile = requestedFile.getFile();
    if (swfFile == null || !swfFile.exists()) {
        response.sendError(404, "\"" + pageName + "\" not found.");
        return;//from w  w w  .  j  a v  a2s.  c  o m
    }
    response.setContentType("application/x-shockwave-flash");
    response.setContentLength((int) swfFile.length());
    response.setBufferSize((int) swfFile.length());
    response.setDateHeader("Expires", 0);

    FileInputStream is = null;
    FileChannel inChan = null;
    try {
        is = new FileInputStream(swfFile);
        OutputStream os = response.getOutputStream();
        inChan = is.getChannel();
        long fSize = inChan.size();
        MappedByteBuffer mBuf = inChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
        byte[] buf = new byte[(int) fSize];
        mBuf.get(buf);
        os.write(buf);
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
        if (inChan != null) {
            try {
                inChan.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:org.impalaframework.config.LocationModificationStateHolder.java

public boolean isModifiedSinceLastCheck() {

    Assert.notNull(locations, "locations cannot be null");

    boolean load = false;

    long newLastModified = 0L;

    for (Resource resource : locations) {
        try {//from w  w  w. j av  a  2s  .c o  m
            File file = resource.getFile();
            long fileLastModified = file.lastModified();
            newLastModified = Math.max(newLastModified, fileLastModified);

            if (log.isDebugEnabled())
                log.debug("Last modified for resource " + file + ": " + fileLastModified);

        } catch (IOException e) {
            System.out.println("Unable to get last modified for resource " + resource);
        }
    }

    long oldLastModified = this.lastModified;
    long diff = newLastModified - oldLastModified;
    if (diff > 0) {
        if (oldLastModified == 0L) {
            load = returnOnFirstCheck;
        } else {
            load = true;
        }

        if (log.isDebugEnabled())
            log.debug("File has been updated more recently - reloading. Old: " + oldLastModified + ", new: "
                    + newLastModified);
    }

    this.lastModified = newLastModified;

    return load;
}

From source file:org.impalaframework.web.module.monitor.BaseStagingFileModuleRuntimeMonitor.java

/**
 * Attempts to return {@link File} from resource. If this fails, logs and returns null.
 *///ww  w . j  av  a2 s  .  c  o m
protected File getFileFromResource(Resource resource) {
    File file;
    try {
        file = resource.getFile();
    } catch (IOException e) {
        logger.error("Problem getting file for module resource " + resource.getDescription(), e);
        file = null;
    }
    return file;
}

From source file:org.impalaframework.web.resolver.ServletContextModuleLocationResolver.java

/**
 * Returns the module-specific libraries corresponding with the supplied
 * module name. Expects libraries to be in the directory
 * WEB-INF/modules/lib/module_name/*from   ww w . jav a 2 s .  c  om*/
 */
public List<Resource> getApplicationModuleLibraryLocations(String moduleName) {
    String parent = relativeModuleRootLocation + "/lib/" + moduleName;
    Resource parentResource = new ServletContextResource(servletContext, parent);
    try {
        File file = parentResource.getFile();
        if (file.exists()) {
            File[] files = file.listFiles(new ExtensionFileFilter(".jar"));
            if (files != null && files.length > 0) {
                return Arrays.asList(ResourceUtils.getResources(files));
            }
        }
    } catch (IOException e) {
        logger.warn("Unable to get file corresponding with ");
    }
    return null;
}