Example usage for org.springframework.core.io ClassPathResource getPath

List of usage examples for org.springframework.core.io ClassPathResource getPath

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource getPath.

Prototype

public final String getPath() 

Source Link

Document

Return the path for this resource (as resource path within the class path).

Usage

From source file:org.apius.server.JseComponentBootstrap.java

/**
 * Takes two string parameters:/*from   w w w. j  a va  2s. com*/
 * 1) Classpath to the bean factory.
 * 2) Name (ref) of the Restlet Component as indicated in the bean factory XML file.
 * 
 * @param path
 * @param name
 * @return void
 */
public static void main(String[] args) throws Exception {

    String resourceClassPath = args[0];
    String componentBean = args[1];

    ClassPathResource resource = new ClassPathResource(resourceClassPath);
    ApplicationContext context = new ClassPathXmlApplicationContext(resource.getPath());

    Component component = (Component) context.getBean(componentBean);
    component.start();
}

From source file:org.shept.util.JarUtils.java

/**
 * Init this controllers ressources by copying them into the web container
 * (subpath of WEB-INF). This is useful for resources as pictures, sounds for access by plain HTML
 * This would not work if they stay just in the jar. 
 * (Well actually it would work with Mozilla browsers because they support url naming convention 
 * specifying resources inside a .jar-file. This isn't true for Internet Explorer).</p>
 * <p>Resource copying is done only if there are no resources in the destination path so you can
 * easily provide other than the default resources.</p>
 * Note that changing the names for destination directory in the servlet context requires that you
 * need to specify an imagePath for the taglibs. Alternatively you can also copy the taglibs into your
 * WEB-INF/tags directory and modify for a different behavior or look and feel. In this case you need
 * to specify your own (shept).tld file (copy implicit.tld from shept META-INF).
 *//*from   www . j a  v  a  2 s .  c  o  m*/

public static void copyResourcesOnce(ClassPathResource cpr, String destPath, String resName) {
    if (alreadyCopied.contains(resName))
        return;
    try {
        JarUtils.copyResources(cpr, destPath);
    } catch (IOException ex) {
        logger.error("Could not copy required resources from " + cpr.getPath() + " to " + destPath, ex);
    } catch (URISyntaxException e) {
        logger.error("Could not copy required resources from " + cpr.getPath() + " to " + destPath, e);
    }
    alreadyCopied.add(resName);
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*ww  w.ja  v  a2  s . c  o  m*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * @param resources Array of String resources (filenames) to be copied
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 */
public static void copyResources(String[] resources, ClassPathResource cpr, String webAppDestPath)
        throws IOException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();
    for (int i = 0; i < resources.length; i++) {
        File dstFile = new File(dstPath, resources[i]); //    (StringUtils.applyRelativePath(dstPath, images[i]));
        Resource fileRes = cpr.createRelative(resources[i]);
        if (!dstFile.exists() && fileRes.exists()) {
            FileOutputStream fos = new FileOutputStream(dstFile);
            FileCopyUtils.copy(fileRes.getInputStream(), fos);
            logger.info("Successfully copied file " + fileRes.getFilename() + " from " + cpr.getPath() + " to "
                    + dstFile.getPath());
        }
    }
}

From source file:chronos.mbeans.QuartzSchedulerAdapter.java

/**
 * @param factory/*  www  .  ja  v a2 s  .c om*/
 *        {@link StdSchedulerFactory}
 * @throws SchedulerException
 *         on exception
 */
private void createOwnScheduler(final StdSchedulerFactory factory) throws SchedulerException {
    logger.debug("Creating new Quartz scheduler...");
    final ClassPathResource resource = new ClassPathResource("quartz.properties");
    if (resource.exists() && resource.isReadable()) {
        logger.debug("Configuring Quartz from resource: " + resource.getPath());
        try {
            final InputStream is = resource.getInputStream();
            try {
                factory.initialize(is);
            } finally {
                is.close();
            }
        } catch (final IOException e) {
            logger.debug("Exception initializing from resource: " + e.getMessage(), e);
        }
    } else {
        logger.debug("Using minimal default properties");
        final Properties props = new Properties();
        props.put(PROP_SCHED_INSTANCE_NAME, schedulerInstanceName);
        props.put(PROP_THREAD_POOL_CLASS, SimpleThreadPool.class.getName());
        factory.initialize(props);
    }
}

From source file:com.geoapi.api.server.services.implementations.WebViewService.java

@GET
@Path("css/{name}")
@Produces("text/css")
public String css(@PathParam("name") String name) {
    ClassPathResource classPathResource = new ClassPathResource("com/geoapi/webview/css/" + name);
    try {// w w  w . j a  v a  2s . com
        File file = classPathResource.getFile();
        return readFileAsString(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String css = readFileAsString(classPathResource.getPath());
    return css;
}

From source file:com.geoapi.api.server.services.implementations.WebViewService.java

@GET
@Path("/doc/")
public String doc() {
    ClassPathResource classPathResource = new ClassPathResource("com/geoapi/webview/doc.html");
    try {//  ww  w.j av  a2s  . c  om
        File file = classPathResource.getFile();
        return readFileAsString(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String homepage = readFileAsString(classPathResource.getPath());
    return homepage;
}

From source file:com.geoapi.api.server.services.implementations.WebViewService.java

@GET
@Path("/")
public String homepage() {
    ClassPathResource classPathResource = new ClassPathResource("com/geoapi/webview/homepage.html");
    try {//  w ww.  j  av a  2 s  .  c  om
        File file = classPathResource.getFile();
        return readFileAsString(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String homepage = readFileAsString(classPathResource.getPath());
    return homepage;
}

From source file:com.geoapi.api.server.services.implementations.WebViewService.java

@GET
@Path("javascript/{name}")
@Produces("application/javascript")
public String javascript(@PathParam("name") String name) {
    ClassPathResource classPathResource = new ClassPathResource("com/geoapi/webview/javascript/" + name);
    try {/*from  w  ww. ja  v a 2 s .  c o  m*/
        File file = classPathResource.getFile();
        return readFileAsString(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String css = readFileAsString(classPathResource.getPath());
    return css;
}

From source file:org.sakaiproject.sitestats.impl.event.FileEventRegistry.java

private void loadEventRegistryFile() {
    boolean customEventRegistryFileLoaded = false;

    // user-specified tool events definition
    if (customEventRegistryFile != null) {
        File customDefs = new File(customEventRegistryFile);
        if (customDefs.exists()) {
            FileInputStream in = null;
            try {
                LOG.info("init(): - loading custom event registry from: " + customDefs.getAbsolutePath());
                in = new FileInputStream(customDefs);
                eventRegistry = DigesterUtil.parseToolEventsDefinition(in);
                customEventRegistryFileLoaded = true;
            } catch (Throwable t) {
                LOG.warn("init(): - trouble loading event registry from : " + customDefs.getAbsolutePath(), t);
            } finally {
                if (in != null)
                    try {
                        in.close();/*from  www  . j  a v  a 2 s  .c  om*/
                    } catch (IOException e) {
                        LOG.warn("init(): - failed to close inputstream (event registry from : "
                                + customDefs.getAbsolutePath() + ")");
                    }
            }
        } else {
            LOG.warn("init(): - custom event registry file not found: " + customDefs.getAbsolutePath());
        }
    }

    // default tool events definition
    if (!customEventRegistryFileLoaded) {
        ClassPathResource defaultDefs = new ClassPathResource(
                "org/sakaiproject/sitestats/config/" + FileEventRegistry.TOOL_EVENTS_DEF_FILE);
        try {
            LOG.info("init(): - loading default event registry from: " + defaultDefs.getPath()
                    + ". A custom one for adding/removing events can be specified in sakai.properties with the property: toolEventsDefinitionFile@org.sakaiproject.sitestats.api.StatsManager=${sakai.home}/toolEventsdef.xml.");
            eventRegistry = DigesterUtil.parseToolEventsDefinition(defaultDefs.getInputStream());
        } catch (Throwable t) {
            LOG.error("init(): - trouble loading default event registry from : " + defaultDefs.getPath(), t);
        }
    }

    // add user-specified tool
    List<ToolInfo> additions = null;
    if (customEventRegistryAdditionsFile != null) {
        File customDefs = new File(customEventRegistryAdditionsFile);
        if (customDefs.exists()) {
            FileInputStream in = null;
            try {
                LOG.info("init(): - loading custom event registry additions from: "
                        + customDefs.getAbsolutePath());
                in = new FileInputStream(customDefs);
                additions = DigesterUtil.parseToolEventsDefinition(in);
            } catch (Throwable t) {
                LOG.warn("init(): - trouble loading custom event registry additions from : "
                        + customDefs.getAbsolutePath(), t);
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException e) {
                        LOG.warn(
                                "init(): - failed to close inputstream (custom event registry additions from : "
                                        + customDefs.getAbsolutePath() + ")");
                    }
            }
        } else {
            LOG.warn("init(): - custom event registry additions file not found: "
                    + customDefs.getAbsolutePath());
        }
    }
    if (additions != null)
        eventRegistry = EventUtil.addToEventRegistry(additions, false, eventRegistry);

    // remove user-specified tool and/or events
    List<ToolInfo> removals = null;
    if (customEventRegistryRemovalsFile != null) {
        File customDefs = new File(customEventRegistryRemovalsFile);
        if (customDefs.exists()) {
            FileInputStream in = null;
            try {
                LOG.info("init(): - loading custom event registry removals from: "
                        + customDefs.getAbsolutePath());
                in = new FileInputStream(customDefs);
                removals = DigesterUtil.parseToolEventsDefinition(in);
            } catch (Throwable t) {
                LOG.warn("init(): - trouble loading custom event registry removals from : "
                        + customDefs.getAbsolutePath(), t);
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException e) {
                        LOG.warn("init(): - failed to close inputstream (custom event regitry removals from : "
                                + customDefs.getAbsolutePath() + ")");
                    }
            }
        } else {
            LOG.warn(
                    "init(): - custom event registry removals file not found: " + customDefs.getAbsolutePath());
        }
    }
    if (removals != null)
        eventRegistry = EventUtil.removeFromEventRegistry(removals, eventRegistry);

    // debug: print resulting list
    //      LOG.info("-------- Printing resulting eventRegistry list:");
    //      Iterator<ToolInfo> iT = eventRegistry.iterator();
    //      while(iT.hasNext()) LOG.info(iT.next().toString());
    //      LOG.info("------------------------------------------------------");
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*from   w  w  w  .j a v  a 2 s.co  m*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}