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:se.inera.axel.shs.camel.CamelShsDataPartConverterTest.java

@DirtiesContext
@Test(expectedExceptions = IllegalDatapartContentException.class)
public void testPdfWithIncompatibleTransferEncoding() throws Throwable {

    resultEndpoint.expectedMessageCount(1);

    Resource pdfResource = new ClassPathResource("se/inera/axel/shs/camel/pdfFile.pdf");
    File pdfFile = pdfResource.getFile();

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, "7BIT");
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, "application/pdf");
    headers.put(ShsHeaders.DATAPART_TYPE, "pdf");

    try {//from   www . j  av  a 2s.co  m
        template.sendBodyAndHeaders("direct:camelToShsConverter", pdfFile, headers);
    } catch (CamelExecutionException e) {
        throw e.getCause();
    }

}

From source file:net.alpha.velocity.spring.support.VelocityEngineFactory.java

/**
 * Initialize a Velocity resource loader for the given VelocityEngine:
 * either a standard Velocity FileResourceLoader or a SpringResourceLoader.
 * <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/*from ww  w  .j a  v  a2 s  .  co  m*/
 * @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:org.motechproject.mobile.web.ivr.intellivr.IntellIVRController.java

public void init() {
    Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    try {//www . j a  va2  s  .co m
        Schema schema = factory.newSchema(schemaResource.getFile());
        parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        validator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Error initializing controller:", e);
    } catch (IOException e) {
        log.error("Error initializing controller:", e);
    } catch (ParserConfigurationException e) {
        log.error("Error initializing controller:", e);
    } catch (FactoryConfigurationError e) {
        log.error("Error initializing controller:", e);
    }
    try {
        JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.mobile.omp.manager.intellivr");
        marshaller = jaxbc.createMarshaller();
        unmarshaller = jaxbc.createUnmarshaller();
    } catch (JAXBException e) {
        log.error("Error initializing controller:", e);
    }
}

From source file:se.inera.axel.shs.camel.CamelShsDataPartConverterTest.java

@DirtiesContext
@Test/*from  w w w  .j ava  2s .c  o m*/
public void testPdfFile() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    Resource pdfResource = new ClassPathResource("se/inera/axel/shs/camel/pdfFile.pdf");
    File pdfFile = pdfResource.getFile();

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, "base64");
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, "application/pdf");
    headers.put(ShsHeaders.DATAPART_TYPE, "pdf");

    template.sendBodyAndHeaders("direct:camelToShsConverter", pdfFile, headers);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getExchanges();
    Exchange exchange = exchanges.get(0);
    Message in = exchange.getIn();
    DataPart datapart = in.getMandatoryBody(DataPart.class);
    assertNotNull(datapart);

    Assert.assertEquals(datapart.getFileName(), pdfResource.getFilename());
    Assert.assertEquals(datapart.getDataPartType(), "pdf");
    Assert.assertEquals((long) datapart.getContentLength(), pdfResource.contentLength());

    Assert.assertEquals(IOUtils.toString(datapart.getDataHandler().getInputStream()),
            IOUtils.toString(pdfResource.getInputStream()));

}

From source file:com.beyondjservlet.gateway.velocity.VelocityEngineFactory.java

/**
 * Initialize a Velocity resource loader for the given VelocityEngine:
 * either a standard Velocity FileResourceLoader or a SpringResourceLoader.
 * <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/*from  w ww .  ja va  2s .c  o m*/
 * @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:org.craftercms.search.impl.SearchServiceIT.java

@Before
public void setUp() throws Exception {
    for (Map.Entry<String, String> docEntry : getTestDocs().entrySet()) {
        searchService.update(SITE, docEntry.getKey(), docEntry.getValue(), true);
    }/*from   ww w.j a  v  a  2  s .c o  m*/

    Resource wpReasonsPdf = new ClassPathResource("/docs/" + WP_REASONS_PDF_ID);

    Map<String, String> additionalFields = new HashMap<String, String>(2);
    additionalFields.put("testField1", "This is a test");
    additionalFields.put("testField2", "This is another test");

    searchService.updateDocument(SITE, WP_REASONS_PDF_ID, wpReasonsPdf.getFile(), additionalFields);

    searchService.commit();
}

From source file:net.sourceforge.vulcan.spring.SpringProjectDomBuilder.java

@Override
protected Transformer createTransformer(String format) throws NoSuchTransformFormatException {
    if (!transformResources.containsKey(format)) {
        throw new NoSuchTransformFormatException();
    }//from ww  w . j  a  v a  2  s  .c  o  m

    final Resource resource = applicationContext.getResource(transformResources.get(format));

    try {
        final SAXSource source = new SAXSource(XMLReaderFactory.createXMLReader(),
                new InputSource(resource.getInputStream()));

        try {
            // Try to tell the xsl where it is for the sake of xsl:include
            source.setSystemId(resource.getFile().getAbsolutePath());
        } catch (FileNotFoundException ignore) {
            // Not all resources are backed by files.
        }

        return transformerFactory.newTransformer(source);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

}

From source file:com.netflix.genie.web.configs.MvcConfigUnitTests.java

/**
 * Make sure we can get a valid job resource when all conditions are met.
 *
 * @throws IOException for any problem/* www  . jav  a  2s  . co m*/
 */
@Test
public void canGetJobsDir() throws IOException {
    final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
    final String jobsDirLocation = UUID.randomUUID().toString() + "/";
    final JobsProperties jobsProperties = new JobsProperties();
    jobsProperties.getLocations().setJobs(jobsDirLocation);

    final Resource jobsDirResource = Mockito.mock(Resource.class);
    Mockito.when(resourceLoader.getResource(jobsDirLocation)).thenReturn(jobsDirResource);
    Mockito.when(jobsDirResource.exists()).thenReturn(true);

    final File file = Mockito.mock(File.class);
    Mockito.when(jobsDirResource.getFile()).thenReturn(file);
    Mockito.when(file.isDirectory()).thenReturn(true);

    final Resource jobsDir = this.mvcConfig.jobsDir(resourceLoader, jobsProperties);
    Assert.assertNotNull(jobsDir);
}

From source file:org.fao.faostat.api.core.ExcelExporter.java

public ExcelExporter(Resource excelPath) throws Exception {
    try {//  w  w w. j a  v  a  2s  .  co m
        this.setExcelPath(excelPath.getFile().getPath());
    } catch (IOException e) {
        throw new Exception(e.getMessage());
    }
}

From source file:com.netflix.genie.web.configs.MvcConfigUnitTests.java

/**
 * Test to make sure we can't create a jobs dir resource if the directory can't be created when the input jobs
 * dir is invalid in any way./*from  w  ww.  j  av a  2s .  co m*/
 *
 * @throws IOException On error
 */
@Test
public void cantGetJobsDirWhenJobsDirInvalid() throws IOException {
    final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
    final String jobsDirLocation = UUID.randomUUID().toString();
    final JobsProperties jobsProperties = new JobsProperties();
    jobsProperties.getLocations().setJobs(jobsDirLocation);

    final Resource tmpResource = Mockito.mock(Resource.class);
    Mockito.when(resourceLoader.getResource(jobsDirLocation)).thenReturn(tmpResource);
    Mockito.when(tmpResource.exists()).thenReturn(true);

    final File file = Mockito.mock(File.class);
    Mockito.when(tmpResource.getFile()).thenReturn(file);
    Mockito.when(file.isDirectory()).thenReturn(false);

    try {
        this.mvcConfig.jobsDir(resourceLoader, jobsProperties);
        Assert.fail();
    } catch (final IllegalStateException ise) {
        Assert.assertThat(ise.getMessage(),
                Matchers.is(jobsDirLocation + " exists but isn't a directory. Unable to continue"));
    }

    final String localJobsDir = jobsDirLocation + "/";
    Mockito.when(file.isDirectory()).thenReturn(true);
    final Resource jobsDirResource = Mockito.mock(Resource.class);
    Mockito.when(resourceLoader.getResource(localJobsDir)).thenReturn(jobsDirResource);
    Mockito.when(tmpResource.exists()).thenReturn(false);

    Mockito.when(jobsDirResource.exists()).thenReturn(false);
    Mockito.when(jobsDirResource.getFile()).thenReturn(file);
    Mockito.when(file.mkdirs()).thenReturn(false);

    try {
        this.mvcConfig.jobsDir(resourceLoader, jobsProperties);
        Assert.fail();
    } catch (final IllegalStateException ise) {
        Assert.assertThat(ise.getMessage(),
                Matchers.is("Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist."));
    }
}