Example usage for org.springframework.core.io Resource getFilename

List of usage examples for org.springframework.core.io Resource getFilename

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getFilename.

Prototype

@Nullable
String getFilename();

Source Link

Document

Determine a filename for this resource, i.e.

Usage

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

@DirtiesContext
@Test/*w ww.j av  a2  s  . 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:org.apache.uima.ruta.resource.MultiTreeWordList.java

/**
 * Load a resource in this word list./*from   w  w  w .  j ava 2s .  c  o m*/
 * 
 * @param resource
 *          Resource to load. The resource's name must end with .txt or .mtwl.
 * @throws IOException
 *           When there is a problem reading the resource.
 */
private void load(Resource resource) throws IOException {
    final String name = resource.getFilename();
    InputStream stream = null;
    try {
        stream = resource.getInputStream();
        if (name == null) {
            throw new IllegalArgumentException("List does not have a name.");
        } else if (name.endsWith(".txt")) {
            buildNewTree(stream, name);
        } else if (name.endsWith(".mtwl")) {
            persistence.readMTWL(root, stream, "UTF-8");
        } else {
            throw new IllegalArgumentException("File name should end with .mtwl or .txt, found " + name);
        }
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:annis.administration.DefaultAdministrationDao.java

private void bulkloadTableFromResource(String table, Resource resource) {
    log.debug("bulk-loading data from '" + resource.getFilename() + "' into table '" + table + "'");
    String sql = "COPY " + table + " FROM STDIN WITH DELIMITER E'\t' NULL AS 'NULL'";

    try {//from w w  w . j a  v a2 s. co m
        // retrieve the currently open connection if running inside a transaction
        Connection con = DataSourceUtils.getConnection(dataSource);

        // Postgres JDBC4 8.4 driver now supports the copy API
        PGConnection pgCon = (PGConnection) con;
        pgCon.getCopyAPI().copyIn(sql, resource.getInputStream());

        DataSourceUtils.releaseConnection(con, dataSource);

    } catch (SQLException e) {
        throw new DatabaseAccessException(e);
    } catch (IOException e) {
        throw new FileAccessException(e);
    }
}

From source file:annis.administration.DefaultAdministrationDao.java

private <T> T querySqlFromScript(String script, ResultSetExtractor<T> resultSetExtractor) {
    File fScript = new File(scriptPath, script);
    if (fScript.canRead() && fScript.isFile()) {
        Resource resource = new FileSystemResource(fScript);
        log.debug("executing SQL script: " + resource.getFilename());
        String sql = readSqlFromResource(resource, null);
        return jdbcTemplate.query(sql, resultSetExtractor);
    } else {//from  w  w  w. j  a v a2s.  c o m
        log.debug("SQL script " + fScript.getName() + " does not exist");
        return null;
    }
}

From source file:annis.administration.DefaultAdministrationDao.java

@Override
public boolean executeSqlFromScript(String script, MapSqlParameterSource args) {
    File fScript = new File(scriptPath, script);
    if (fScript.canRead() && fScript.isFile()) {
        Resource resource = new FileSystemResource(fScript);
        log.debug("executing SQL script: " + resource.getFilename());
        String sql = readSqlFromResource(resource, args);
        jdbcTemplate.execute(sql);/*from  w w w.  ja  v a2  s.co  m*/
        return true;
    } else {
        log.debug("SQL script " + fScript.getName() + " does not exist");
        return false;
    }
}

From source file:com.edgenius.wiki.service.impl.SystemPropertyPlaceholderConfigurer.java

/**
 * Loading global content from Global configure xml file (defined by geniuswiki.properties), then
 * push all value to <code>com.edgenius.core.Global</code> class, which value become static and ready for 
 * later use. /*w  ww . j a  v a2  s  .  co m*/
 *
 * There 3 level global setting. First, server.properties will assign a global.xml, this file usually is outside
 * the deploy file, and put together with data file, this is makes upgrade easily. <br>
 * Second, there is global.default.xml is inside classpath. This file is useful when installer initialized setup 
 * system. see publish process.<br>
 * Third, if both above file not exist, Global.java even has its default value. and it also will automatically generate
 * global.xml in this case. <br>
 * @param globalConf 
 *   
 */
private void initGlobal(Resource globalConf) {
    GlobalSetting setting = null;
    try {
        //http://forum.springframework.org/showthread.php?p=201562#post201562
        //don't use Resource.getInputStream() as it can not handle file://c:/var/data format: error is try to get unknown host "c"
        setting = GlobalSetting.loadGlobalSetting(new FileInputStream(globalConf.getFile()));
    } catch (Exception e) {
        log.info("Unable to load global xml, try load global default xml then...");
        setting = null;
    }
    if (setting == null) {
        //try to load global.default.xml from class path.
        try {
            setting = GlobalSetting.loadGlobalSetting(FileUtil.getFileInputStream(Global.DEFAULT_GLOBAL_XML));
        } catch (Exception e) {
            log.warn("Loading global default xml failed, using Global class default instead.");
        }
        if (setting == null) {
            //the third option, just use Global.java value
            //no global file found, so keep Global default static value instead.
            setting = new GlobalSetting();
            Global.syncTo(setting);
        }

        if (globalConf.exists()) {
            //global exist, maybe wrong format, then try to backup original one
            try {
                String dir = FileUtil.getFileDirectory(globalConf.getFile().getAbsolutePath());
                String name = globalConf.getFilename() + "."
                        + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".failure.backup";
                File orig = new File(FileUtil.getFullPath(dir, name));
                FileUtils.copyFile(globalConf.getFile(), orig);
                log.info("Original global conf file rename to " + name);
            } catch (Exception e) {
                log.warn("Unable backup original global conf file, old one will replaced.");
            }
        }
        //Anyway, global.xml file under data root is missed or crashed, then create or recreate required.
        //As I want to user SettingService.saveOrUpdateGlobalSetting() to save rather than create duplicated code,
        //so here a little bit tricky,  I put a flag value to tell SettingService trigger saving in afterProperties()
        log.info("System is going to create/recreate new global.xml in your data root directory.");
        System.setProperty("rebuild.global.xml", "true");

    }

    //finally, initial Global static varible according to setting
    Global.syncFrom(setting);
}

From source file:se.inera.intyg.intygstjanst.web.service.bean.IntygBootstrapBean.java

private void addSjukfall(final Resource metadata, final Resource content) {
    try {// ww  w  .j  ava  2 s . c o  m
        Certificate certificate = new CustomObjectMapper().readValue(metadata.getInputStream(),
                Certificate.class);
        if (!isSjukfallsGrundandeIntyg(certificate.getType())) {
            return;
        }

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    Certificate certificate = new CustomObjectMapper().readValue(metadata.getInputStream(),
                            Certificate.class);
                    certificate.setDocument(IOUtils.toString(content.getInputStream(), "UTF-8"));

                    ModuleApi moduleApi = moduleRegistry.getModuleApi(certificate.getType());
                    Utlatande utlatande = moduleApi.getUtlatandeFromJson(certificate.getDocument());

                    if (certificateToSjukfallCertificateConverter.isConvertableFk7263(utlatande)) {
                        SjukfallCertificate sjukfallCertificate = certificateToSjukfallCertificateConverter
                                .convertFk7263(certificate, utlatande);
                        entityManager.persist(sjukfallCertificate);
                    }

                } catch (Throwable t) {
                    status.setRollbackOnly();
                    LOG.error("Loading of Sjukfall intyg failed for {}: {}", metadata.getFilename(),
                            t.getMessage());
                }
            }
        });

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:annis.administration.AdministrationDao.java

private void bulkloadTableFromResource(String table, Resource resource) {
    log.debug("bulk-loading data from '" + resource.getFilename() + "' into table '" + table + "'");
    String sql = "COPY " + table + " FROM STDIN WITH DELIMITER E'\t' NULL AS 'NULL'";

    try {//from   w ww .j  a  v  a  2 s.c  om
        // retrieve the currently open connection if running inside a transaction
        Connection originalCon = DataSourceUtils.getConnection(getDataSource());
        Connection con = originalCon;
        if (con instanceof DelegatingConnection) {
            DelegatingConnection<?> delCon = (DelegatingConnection<?>) con;
            con = delCon.getInnermostDelegate();
        }

        Preconditions.checkState(con instanceof PGConnection,
                "bulk-loading only works with a PostgreSQL JDBC connection");

        // Postgres JDBC4 8.4 driver now supports the copy API
        PGConnection pgCon = (PGConnection) con;
        pgCon.getCopyAPI().copyIn(sql, resource.getInputStream());

        DataSourceUtils.releaseConnection(originalCon, getDataSource());

    } catch (SQLException e) {
        throw new DatabaseAccessException(e);
    } catch (IOException e) {
        throw new FileAccessException(e);
    }
}