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:net.sf.jooreports.web.spring.controller.AbstractDocumentGenerator.java

private void renderDocument(Object model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    DocumentConverter converter = (DocumentConverter) getApplicationContext().getBean("documentConverter");
    DocumentFormatRegistry formatRegistry = (DocumentFormatRegistry) getApplicationContext()
            .getBean("documentFormatRegistry");
    String outputExtension = FilenameUtils.getExtension(request.getRequestURI());
    DocumentFormat outputFormat = formatRegistry.getFormatByFileExtension(outputExtension);
    if (outputFormat == null) {
        throw new ServletException("unsupported output format: " + outputExtension);
    }//from  w  ww  .java 2  s  . c  om
    File templateFile = null;
    String documentName = FilenameUtils.getBaseName(request.getRequestURI());
    Resource templateDirectory = getTemplateDirectory(documentName);
    if (templateDirectory.exists()) {
        templateFile = templateDirectory.getFile();
    } else {
        templateFile = getTemplateFile(documentName).getFile();
        if (!templateFile.exists()) {
            throw new ServletException("template not found: " + documentName);
        }
    }

    DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
    DocumentTemplate template = documentTemplateFactory.getTemplate(templateFile);

    ByteArrayOutputStream odtOutputStream = new ByteArrayOutputStream();
    try {
        template.createDocument(model, odtOutputStream);
    } catch (DocumentTemplateException exception) {
        throw new ServletException(exception);
    }
    response.setContentType(outputFormat.getMimeType());
    response.setHeader("Content-Disposition",
            "inline; filename=" + documentName + "." + outputFormat.getFileExtension());

    if ("odt".equals(outputFormat.getFileExtension())) {
        // no need to convert
        response.getOutputStream().write(odtOutputStream.toByteArray());
    } else {
        ByteArrayInputStream odtInputStream = new ByteArrayInputStream(odtOutputStream.toByteArray());
        DocumentFormat inputFormat = formatRegistry.getFormatByFileExtension("odt");
        converter.convert(odtInputStream, inputFormat, response.getOutputStream(), outputFormat);
    }
}

From source file:org.jasig.portlet.campuslife.dao.ScreenScrapingService.java

/**
 * Set the AntiSamy policy to be used to clean and validate HTML content.
 * //from   w  ww . j  a v  a  2 s.c  o  m
 * @param config
 * @throws PolicyException
 * @throws IOException
 */
public void setPolicy(Resource config) throws PolicyException, IOException {
    this.policy = Policy.getInstance(config.getFile());
}

From source file:org.jnap.core.assets.LessAssetsHandler.java

@Override
public void handle() {
    LessEngine less = new LessEngine(getOptions());
    try {/*ww  w.j  av  a2  s  . c  o  m*/
        Resource sourceRes = new ServletContextResource(servletContext, source);
        Resource destRes = new ServletContextResource(servletContext, destination);
        resetResource(destRes);
        less.compile(sourceRes.getFile(), destRes.getFile());
    } catch (Exception e) {
        logger.error("Error compiling LESS file!", e);
    }
}

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

@Test
public void testGetStreamOk() throws IOException, DcsConnectorFault, SAXException, InvalidXmlException {
    final Resource entitiesDir = rl.getResource("/entities");
    assertTrue(entitiesDir.exists() && entitiesDir.getFile().canRead());

    final InputStream entityIn = underTest.getStream(String.format(ENTITY_ID, "test1"));
    assertNotNull(entityIn);//  w w  w . j a va 2s. co m
    final File test1Entity = new File(entitiesDir.getFile(), "test1.xml");
    final String entityString = IOUtils.toString(entityIn);
    XMLAssert.assertXMLEqual(IOUtils.toString(new FileInputStream(test1Entity)), entityString);
    assertEquals(mb.buildSip(new FileInputStream(test1Entity)),
            mb.buildSip(IOUtils.toInputStream(entityString)));
}

From source file:common.email.MailServiceImpl.java

public void setPath(Resource res) {
    try {/*from  w  w  w .  j a va 2  s  .  com*/
        File f = res.getFile();
        this.templatePath = f.getCanonicalPath() + "/";
    } catch (IOException e) {
        throw new NullPointerException("folder not found for Email templates: " + res);
    }
    //System.out.println("----------------------------path = "+this.path);
}

From source file:com.epam.catgenome.common.AbstractJUnitTest.java

protected File getResourceFileCopy(String resourcePath) throws IOException {
    Resource resource = context.getResource(resourcePath);
    final File tmp = new File(fileManager.getTempDir(), resource.getFilename());
    FileUtils.copyFile(resource.getFile(), tmp);
    FileUtils.forceDeleteOnExit(tmp);/* ww w  .  ja  v  a  2s.c o  m*/
    return tmp;
}

From source file:fr.acxio.tools.agia.file.pdf.MergePDFProcessor.java

@Override
public Map<String, Object> process(Map<String, Object> sItem) throws Exception {
    Map<String, Object> aResult = null;
    if (sourceFactory != null) {
        Map<String, Object> aSourceParams = new HashMap<String, Object>(sItem);
        aSourceParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC, getStepExecution());
        PDDocumentContainer aContainer = null;
        try {//from   w w  w. ja va  2 s.  c  om
            aContainer = documentFactory.fromParts(sourceFactory, aSourceParams);

            if (LOGGER.isInfoEnabled()) {
                if ((aContainer == null) || (aContainer.getParts() == null)) {
                    LOGGER.info("No file to merge");
                } else {
                    LOGGER.info("{} file(s) to merge", aContainer.getParts().size());
                }
            }

            int aPartsCount = aContainer.getParts().size();
            if (aPartsCount > 0) {
                aResult = new HashMap<String, Object>(sItem);

                Resource aDestinationResource = destinationFactory.getResource(aSourceParams);

                File aDestFile = aDestinationResource.getFile();
                if (aDestFile.exists()) {
                    if (forceReplace && !aDestFile.delete()) {
                        throw new IOException("Destination '" + aDestFile + "' cannot be replaced");
                    }
                } else if (aDestFile.getParentFile() != null && !aDestFile.getParentFile().exists()
                        && !aDestFile.getParentFile().mkdirs()) {
                    throw new IOException("Destination '" + aDestFile + "' directory cannot be created");
                }

                PDDocument destination = aContainer.getParts().get(0);
                PDFMergerUtility merger = new PDFMergerUtility();
                for (int i = 1; i < aPartsCount; i++) {
                    merger.appendDocument(destination, aContainer.getParts().get(i));
                }

                destination.save(aDestFile.getAbsolutePath());

                aResult.put(key, aDestFile.getAbsolutePath());

                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Merged to : {}", aResult.get(key));
                }
            }
        } finally {
            if (aContainer != null) {
                aContainer.close();
            }
        }
    }
    return aResult;
}

From source file:com.ogaclejapan.dotapk.controller.ApkApiController.java

@RequestMapping(value = "/{name:.+}", method = RequestMethod.GET)
public void download(@PathVariable String name, HttpServletResponse response) throws Exception {
    log.info("download: " + name);

    Resource file = new FileSystemResource(apkManager.getByName(name));
    response.setContentType("application/vnd.android.package-archive");
    response.setContentLength((int) FileUtils.sizeOf(file.getFile()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFile().getName() + "\"");
    FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());

}

From source file:org.fao.fenix.wds.core.datasource.DatasourcePool.java

/**
 * @param datasourcePath Directory where the datasources JSON file is stored.
 * @throws WDSException// w  w w . j  a  v a2s  .  c om
 *
 * Custom constructor for the class, the <code>datasourcePath</code>
 * is injected by Spring.
 */
public DatasourcePool(Resource datasourcePath) throws WDSException {
    datasources = new HashMap<String, DatasourceBean>();
    try {
        this.setDatasourcePath(datasourcePath.getFile().getPath());
    } catch (IOException e) {
        throw new WDSException(e.getMessage());
    }
}

From source file:fr.acxio.tools.agia.io.AbstractFileOperations.java

protected boolean isDirectory(Resource sResource) throws IOException {
    if (sResource.exists()) {
        return sResource.getFile().isDirectory();
    } else {/* w w  w  .j  a  v a  2s  .c  om*/
        // Dirty trick to tell if the resource is a directory or not when it does not exist yet
        return sResource.createRelative(SAME_RELATIVE_PATH).getFile().getCanonicalPath()
                .equals(sResource.getFile().getCanonicalPath());
    }
}