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

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

Introduction

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

Prototype

@Override
public File getFile() throws IOException 

Source Link

Document

This implementation returns a File reference for the underlying class path resource, provided that it refers to a file in the file system.

Usage

From source file:org.dspace.servicemanager.config.DSpaceConfigurationService.java

/**
 * Loads up the configuration from the DSpace configuration files.
 * <P>/*  w  w w.ja  v a2 s  .c  om*/
 * Determines the home directory of DSpace, and then loads the configurations
 * based on the configuration definition file in that location
 * (using Apache Commons Configuration).
 * @param providedHome DSpace home directory, or null.
 */
private void loadInitialConfig(String providedHome) {
    // Determine the DSpace home directory
    homePath = getDSpaceHome(providedHome);

    // Based on homePath get full path to the configuration definition
    String configDefinition = homePath + File.separatorChar + DSPACE_CONFIG_DEFINITION_PATH;

    // Check if our configuration definition exists in the homePath
    File configDefFile = new File(configDefinition);
    if (!configDefFile.exists()) {
        try {
            //If it doesn't exist, check for a configuration definition on Classpath
            // (NOTE: This is mostly for Unit Testing to find the test config-definition.xml)
            ClassPathResource resource = new ClassPathResource(DSPACE_CONFIG_DEFINITION_PATH);
            configDefinition = resource.getFile().getAbsolutePath();
        } catch (IOException ioe) {
            log.error("Error attempting to load configuration definition from classpath", ioe);
        }
    }

    try {
        // Load our configuration definition, which in turn loads all our config files/settings
        // See: http://commons.apache.org/proper/commons-configuration/userguide_v1.10/howto_configurationbuilder.html
        configurationBuilder = new DefaultConfigurationBuilder(configDefinition);

        // Actually parser our configuration definition & return the resulting Configuration
        configuration = configurationBuilder.getConfiguration();
    } catch (ConfigurationException ce) {
        log.error("Unable to load configurations based on definition at " + configDefinition);
        System.err.println("Unable to load configurations based on definition at " + configDefinition);
        throw new RuntimeException(ce);
    }

    // Finally, set any dynamic, default properties
    setDynamicProperties();

    log.info("Started up configuration service and loaded settings: " + toString());
}

From source file:org.easycloud.las.core.util.Files.java

/**
 * This method will look under the current user directory, scan recursively
 * and return the contents of the first file that matches the passed name. It
 * does no additional searching once the first file is encountered, so if
 * there are other files with the same name in another directory, they may not
 * be encountered, so no "duplicate file error " will be thrown.
 * <p/>//from   ww  w .j ava  2 s. c  o  m
 * This method makes every effort to find a file. If it cant find it anywhere
 * under the current user directory, it looks on the local class path. If it
 * cant find it there, it looks on the System class path.
 *
 * @param shortFileName the name, with no directory info, of the file to find
 * @return the found file
 */
public static File findFile(String shortFileName) throws FileNotFoundException {
    File file = null;
    try {
        ClassPathResource res = new ClassPathResource(shortFileName);
        file = res.getFile();
    } catch (IOException ioe) {
        // Fall-through and try other methods
    }
    if (file == null) {
        File rootDir = new File(new File("").getAbsolutePath());
        file = getFile(rootDir, shortFileName);
    }
    if (file == null) {
        file = findFileOnSystemClasspath(shortFileName);
    }
    if (file == null) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Failed to find file locally or on classpath. File name=" + shortFileName);
        }
        throw new FileNotFoundException(shortFileName);
    }
    return file;
}

From source file:org.emonocot.test.TakeScreenshotListener.java

/**
 * @param failure Set the failure/*from www .j a va  2 s.  c  o  m*/
 */
public final void testFailure(final Failure failure) {
    String screenshotName = null;
    try {
        File file = ((TakesScreenshot) WebDriverFacade.getWebDriver()).getScreenshotAs(OutputType.FILE);
        ClassPathResource root = new ClassPathResource("/");
        screenshotName = File.separator + "screenshots" + File.separator
                + failure.getDescription().getClassName() + "-" + failure.getDescription().getMethodName()
                + ".png";
        screenshotName = screenshotName.replace(" ", "_");
        screenshotName = screenshotName.replace(":", "");
        screenshotName = screenshotName.replaceAll("_+", "_");

        File screenshotDirectory = new File(root.getFile().getParentFile().getAbsolutePath() + File.separator
                + "screenshots" + File.separator);
        if (!screenshotDirectory.exists()) {
            screenshotDirectory.mkdir();
        }
        File screenshot = new File(root.getFile().getParentFile().getAbsolutePath() + screenshotName);
        screenshot.createNewFile();
        FileUtils.copyFile(file, screenshot);
    } catch (IOException e) {
        System.err.println("Error writing screenshot " + screenshotName);
        e.printStackTrace();
    }
}

From source file:org.jasig.cas.adaptors.ldap.AbstractLdapTests.java

@BeforeClass
public static void beforeClass() throws Exception {
    final ClassPathResource properties = new ClassPathResource("ldap.properties");
    final ClassPathResource schema = new ClassPathResource("schema/standard-ldap.schema");

    DIRECTORY = new InMemoryTestLdapDirectoryServer(properties.getFile(),
            new ClassPathResource("ldif/ldap-base.ldif").getFile(), schema.getFile());
}

From source file:org.jbb.lib.properties.FreshInstallPropertiesCreatorTest.java

@Test
public void shouldCopyDefaultPropertyFiles_whenPropertyFilesDoNotExists() throws Exception {
    // given/*from  w  w w .j  a  v a 2s .  co  m*/
    File tempFolder = temp.newFolder();
    File firstPropertyFile = new File(tempFolder.getAbsolutePath() + "/test1.properties");
    File secondPropertyFile = new File(tempFolder.getAbsolutePath() + "/test2.properties");

    assertThat(firstPropertyFile).doesNotExist();
    assertThat(secondPropertyFile).doesNotExist();

    ClassPathResource defaultFirstPropertyFile = new ClassPathResource("test1.properties");
    ClassPathResource defaultSecondPropertyFile = new ClassPathResource("test2.properties");

    when(propertyFilesResolverMock.resolvePropertyFileNames(TestProperties.class)).thenReturn(
            Sets.newHashSet(firstPropertyFile.getAbsolutePath(), secondPropertyFile.getAbsolutePath()));

    // when
    propertiesCreator.putDefaultPropertiesIfNeeded(TestProperties.class);

    // then
    assertThat(firstPropertyFile).exists();
    assertThat(secondPropertyFile).exists();

    assertThat(firstPropertyFile).hasSameContentAs(defaultFirstPropertyFile.getFile());
    assertThat(secondPropertyFile).hasSameContentAs(defaultSecondPropertyFile.getFile());
}

From source file:org.jbb.lib.properties.FreshInstallPropertiesCreatorTest.java

@Test
public void shouldAddMissingPropertiesToTarget_whenPropertyFilesExists_butIsNotComplete() throws Exception {
    // given//from   w  w  w.  j av  a  2 s  .c  o m
    File tempFolder = temp.newFolder();
    File targetPropertyFile = new File(tempFolder.getAbsolutePath() + "/test3.properties");
    FileUtils.copyURLToFile(new ClassPathResource("test3-missing.properties").getURL(), targetPropertyFile);
    ClassPathResource referencePropertyFile = new ClassPathResource("test3.properties");

    when(propertyFilesResolverMock.resolvePropertyFileNames(TestMissingProperties.class))
            .thenReturn(Sets.newHashSet(targetPropertyFile.getAbsolutePath()));

    // when
    propertiesCreator.putDefaultPropertiesIfNeeded(TestMissingProperties.class);

    // then
    assertThat(targetPropertyFile).exists();
    assertThat(targetPropertyFile).hasSameContentAs(referencePropertyFile.getFile());
}

From source file:org.jbb.lib.properties.FreshInstallPropertiesCreatorTest.java

@Test
public void shouldDeleteObsoletePropertiesToTarget_whenPropertyFilesExists_butHasOldPropertyKeys()
        throws Exception {
    // given/*  ww w  .  j  av a  2  s  . com*/
    File tempFolder = temp.newFolder();
    File targetPropertyFile = new File(tempFolder.getAbsolutePath() + "/test4.properties");
    FileUtils.copyURLToFile(new ClassPathResource("test4-obsolete.properties").getURL(), targetPropertyFile);
    ClassPathResource referencePropertyFile = new ClassPathResource("test4.properties");

    when(propertyFilesResolverMock.resolvePropertyFileNames(TestObsoleteProperties.class))
            .thenReturn(Sets.newHashSet(targetPropertyFile.getAbsolutePath()));

    // when
    propertiesCreator.putDefaultPropertiesIfNeeded(TestObsoleteProperties.class);

    // then
    assertThat(targetPropertyFile).exists();
    assertThat(targetPropertyFile).hasSameContentAs(referencePropertyFile.getFile());
}

From source file:org.kuali.ole.sys.service.impl.ReportGenerationServiceImpl.java

/**
 * remove the file extension of the given template if any
 * /*w ww .  j  av a2  s  .com*/
 * @param template the given template
 * @return the template without file extension
 */
protected String removeTemplateExtension(ClassPathResource template) throws IOException {
    String realTemplateName = template.getFile().getAbsolutePath();

    int lastIndex = realTemplateName.lastIndexOf(".");
    String realTemplateNameWithoutExtension = lastIndex > 0 ? realTemplateName.substring(0, lastIndex)
            : realTemplateName;

    return realTemplateNameWithoutExtension;
}

From source file:org.metamorfosis.framework.SpringContextTest.java

public void testClassPathResource() throws IOException {
    ClassPathResource resource = new ClassPathResource("templates/internalTemplate.ftl");
    File file = resource.getFile();
    log.debug("classpath file: " + file);
    String filename = resource.getFilename();
    log.debug("filename: " + filename);
    String path = resource.getPath();
    log.debug("path: " + path);
    String absolutePath = file.getAbsolutePath();
    log.debug("absolutePath: " + absolutePath);

    resource = new ClassPathResource("overview.html");
    InputStream inputStream = resource.getInputStream();
    log.debug(inputStream);/*from   w w w.  j  av  a  2  s  .c  o m*/
}

From source file:org.mifos.framework.util.DbUnitUtilities.java

public IDataSet getDataSetFromClasspathFile(String filename, String directory)
        throws IOException, DataSetException {
    ClassPathResource resource = new ClassPathResource(directory + filename);
    File file = resource.getFile();
    if (file == null) {
        throw new FileNotFoundException("Couldn't find file:" + filename);
    }/*from www.  j  a v a  2  s .  co m*/
    FlatXmlDataSetBuilder fb = new FlatXmlDataSetBuilder();
    fb.setColumnSensing(true);
    fb.setDtdMetadata(false);
    return fb.build(file);
}