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:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource createPath(Resource resource, String path) {
    Assert.isInstanceOf(FileSystemResource.class, resource, "Expected a FileSystemResource");
    try {/*from w w w  .j  a v  a 2 s . com*/
        if (!resource.exists()) {
            File rootFile = resource.getFile();
            while (rootFile.getAbsolutePath().length() > 1 && !rootFile.exists()) {
                rootFile = rootFile.getParentFile();
            }
            IOUtils.makeDirectories(resource.getFile(), rootFile);
        }
        FileSystemResource relativeResource = (FileSystemResource) resource.createRelative(path);
        if (!relativeResource.exists()) {
            if (relativeResource.getPath().endsWith("/")) {
                IOUtils.makeDirectories(relativeResource.getFile(), resource.getFile());
            } else {
                IOUtils.makeDirectories(relativeResource.getFile().getParentFile(), resource.getFile());
            }
        }
        return relativeResource;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public List<Resource> listAllChildren(Resource resource, ResourceFilter filter) {
    // FIXME looks very similar to listChildren, can we combine
    List<Resource> children = new ArrayList<Resource>();
    File[] files;/*from  w ww .j  av a2 s.  co  m*/
    try {
        files = resource.getFile().listFiles();
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }
    if (files == null) {
        return children;
    }
    for (File file : files) {
        Resource fileResource = createResource(file.getAbsolutePath() + "/");
        if (file.isDirectory()) {
            List<Resource> rscs = listAllChildren(fileResource, filter);
            children.addAll(rscs);
        } else {
            if (filter == null || filter.accept(fileResource)) {
                children.add(fileResource);
            }
        }
    }
    return children;
}

From source file:net.nan21.dnet.core.web.controller.data.AbstractDsReadController.java

@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_PRINT)
@ResponseBody/*from   w w  w  .jav a2  s  . com*/
public String print(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString,
        @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_INFO, required = true, defaultValue = "") String exportInfoString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.DS_ACTION_PRINT });
        }

        if (logger.isDebugEnabled()) {

            logger.debug("  --> request-filter: {} ", new String[] { filterString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
            logger.debug("  --> request-result-range: {} ",
                    new String[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_EXPORT, null);

        IDsService<M, F, P> service = this.findDsService(resourceName);

        IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json");

        F filter = marshaller.readFilterFromString(filterString);
        P params = marshaller.readParamsFromString(paramString);

        ExportInfo exportInfo = marshaller.readDataFromString(exportInfoString, ExportInfo.class);
        exportInfo.prepare(service.getModelClass());

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize)
                .addFilter(filter).addParams(params);

        if (orderBy != null && !orderBy.equals("")) {
            List<SortToken> sortTokens = marshaller.readListFromString(orderBy, SortToken.class);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        if (filterRulesString != null && !filterRulesString.equals("")) {
            List<FilterRule> filterRules = marshaller.readListFromString(filterRulesString, FilterRule.class);
            builder.addFilterRules(filterRules);
        }

        List<M> data = service.find(builder);

        File _tplDir = null;
        String _tplName = null;

        String _tpl = this.getSettings().getParam(SysParams_Core.CORE_PRINT_HTML_TPL);

        if (_tpl == null || "".equals(_tpl)) {
            _tpl = "print-template/print.ftl";
        }

        _tpl = Session.user.get().getWorkspace().getWorkspacePath() + "/" + _tpl;
        File _tplFile = new File(_tpl);

        _tplDir = _tplFile.getParentFile();
        _tplName = _tplFile.getName();

        if (!_tplFile.exists()) {

            // _tplDir = _tplFile.getParentFile();

            if (!_tplDir.exists()) {
                _tplDir.mkdirs();
            }

            Resource resource = new ClassPathResource("WEB-INF/freemarker/print.ftl");
            FileUtils.copyFile(resource.getFile(), _tplFile);

        }

        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
        cfg.setDirectoryForTemplateLoading(_tplDir);

        Map<String, Object> root = new HashMap<String, Object>();

        root.put("printer", new ModelPrinter());
        root.put("data", data);
        root.put("filter", filter);
        root.put("params", params);
        root.put("client", Session.user.get().getClient());

        Map<String, Object> reportConfig = new HashMap<String, Object>();
        reportConfig.put("logo", this.getSettings().getParam(SysParams_Core.CORE_LOGO_URL_REPORT));
        reportConfig.put("runBy", Session.user.get().getName());
        reportConfig.put("runAt", new Date());
        reportConfig.put("title", exportInfo.getTitle());
        reportConfig.put("orientation", exportInfo.getLayout());
        reportConfig.put("columns", exportInfo.getColumns());
        reportConfig.put("filter", exportInfo.getFilter());

        root.put("cfg", reportConfig);

        if (dataFormat.equals(Constants.DATA_FORMAT_HTML)) {
            response.setContentType("text/html; charset=UTF-8");
        }

        Template temp = cfg.getTemplate(_tplName);
        Writer out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding());
        temp.process(root, out);
        out.flush();
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;
        // return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:org.benassi.bookeshop.web.util.PdfCatalogueGenerator.java

public ByteArrayInputStream getPdfCatalogueStream() {

    Resource jreport = applicationContext.getResource("classpath:reports/report.jrxml");

    java.sql.Connection connection = null;
    java.sql.Statement statement = null;

    try {//from w w  w .j  av a 2 s .  c o m
        connection = dataSource.getConnection();
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(query);

        logger.warn("Not using compiled jasper design, compiling jasper design from 'reports/report.jrxml' ");
        //Certainly not in production ! Jasper reports should be pre compiled
        JasperDesign jasperDesign = JRXmlLoader.load(jreport.getFile());
        JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
        JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(resultSet);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, jrResultSetDataSource);

        byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
        return new ByteArrayInputStream(bytes);

    } catch (Exception e) {
        logger.error("Error generating PDF catalogue.", e);
        return null;
    } finally {
        try {
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            logger.error("Error closing database connection when generating PDF catalogue.", e);
        }
    }
}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

protected String uploadFile(String path) throws IOException {
    Resource resource = new ClassPathResource("file/testupload.file");
    String uploadUrl = path + "?upload&position=0&type=path";
    HttpPost post = createPost(uploadUrl);
    post.setHeader("content-type", "application/octet-stream");
    FileEntity entity = new FileEntity(resource.getFile());
    post.setEntity(entity);/*ww  w .j ava 2s.com*/
    return simpleCall(post);
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public void rename(Resource oldResource, Resource newResource) {
    Assert.isInstanceOf(FileSystemResource.class, oldResource, "Expected a FileSystemResource");
    Assert.isInstanceOf(FileSystemResource.class, newResource, "Expected a FileSystemResource");
    try {/*  w w  w  . ja  v a 2 s  .  c  o  m*/
        oldResource.getFile().renameTo(newResource.getFile());
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }

}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTask.java

/**
 * Constructor. Schedules this task to be run by the task scheduler.
 *
 * @param properties       The disk cleanup properties to use.
 * @param scheduler        The scheduler to use to schedule the cron trigger.
 * @param jobsDir          The resource representing the location of the job directory
 * @param jobSearchService The service to find jobs with
 * @param jobsProperties   The jobs properties to use
 * @param processExecutor  The process executor to use to delete directories
 * @param registry         The metrics registry
 * @throws IOException When it is unable to open a file reference to the job directory
 *//*from w  w w  .j  a va  2 s .co  m*/
@Autowired
public DiskCleanupTask(@NotNull final DiskCleanupProperties properties, @NotNull final TaskScheduler scheduler,
        @NotNull final Resource jobsDir, @NotNull final JobSearchService jobSearchService,
        @NotNull final JobsProperties jobsProperties, @NotNull final Executor processExecutor,
        @NotNull final Registry registry) throws IOException {
    // Job Directory is guaranteed to exist by the MvcConfig bean creation but just in case someone overrides
    if (!jobsDir.exists()) {
        throw new IOException("Jobs dir " + jobsDir + " doesn't exist. Unable to create task to cleanup.");
    }

    this.properties = properties;
    this.jobsDir = jobsDir.getFile();
    this.jobSearchService = jobSearchService;
    this.runAsUser = jobsProperties.getUsers().isRunAsUserEnabled();
    this.processExecutor = processExecutor;

    this.numberOfDeletedJobDirs = registry.gauge("genie.tasks.diskCleanup.numberDeletedJobDirs.gauge",
            new AtomicLong());
    this.numberOfDirsUnableToDelete = registry.gauge("genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge",
            new AtomicLong());
    this.unableToGetJobCounter = registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate");
    this.unableToDeleteJobDirCounter = registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate");

    // Only schedule the task if we don't need sudo while on a non-unix system
    if (this.runAsUser && !SystemUtils.IS_OS_UNIX) {
        log.error("System is not UNIX like. Unable to schedule disk cleanup due to needing Unix commands");
    } else {
        final CronTrigger trigger = new CronTrigger(properties.getExpression(), JobConstants.UTC);
        scheduler.schedule(this, trigger);
    }
}

From source file:com.thoughtworks.go.http.mocks.MockServletContext.java

@Override
public String getRealPath(String path) {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    try {/*from w w  w  .j  a v  a2  s.c om*/
        return resource.getFile().getAbsolutePath();
    } catch (IOException ex) {
        logger.warn("Couldn't determine real path of resource " + resource, ex);
        return null;
    }
}