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:org.cloudfoundry.reconfiguration.util.StandardCloudUtils.java

private Set<String> getCloudServiceClasses(Resource resource) {
    Set<String> cloudServiceClasses = new HashSet<String>();

    BufferedReader in = null;//from   ww  w .  ja  v  a  2  s. c om
    try {
        in = new BufferedReader(new InputStreamReader(resource.getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            cloudServiceClasses.add(line.trim());
        }
    } catch (IOException e) {
        this.logger
                .warning(String.format("Unable to read cloud service classes from %s", resource.getFilename()));
    } finally {
        IoUtils.closeQuietly(in);
    }

    return cloudServiceClasses;
}

From source file:com.thinkbiganalytics.ui.service.StandardUiTemplateService.java

/**
 * Loads and merges function definition files.
 *
 * @return the function definitions// w  w w  . ja  v a 2  s  .  c  o m
 */
public Map<String, Object> loadFunctionsDefinitions(@Nonnull final String name, @Nonnull final String pattern) {
    // Attempt to load resources
    final Resource[] resources;
    try {
        resources = fileResourceService.loadResources(pattern);
    } catch (final IOException e) {
        log.error("Unable to load Spark function definitions", e);
        return Collections.emptyMap();
    }

    // Merge resources into map
    final Map<String, Object> merged = new LinkedHashMap<>();
    merged.put("!name", name);

    for (final Resource resource : resources) {
        // Deserialize resource
        Map<String, Object> functions = null;
        try {
            final String json = fileResourceService.resourceAsString(resource);
            functions = (json != null) ? ObjectMapperSerializer.deserialize(json, Map.class) : null;
        } catch (final RuntimeException e) {
            log.error("Failed to parse {} functions: {}", name, resource.getFilename(), e);
        }

        // Merge definitions
        if (functions != null) {
            try {
                merge(merged, functions, null);
            } catch (final Exception e) {
                log.error("Failed to merge {} functions: {}", name, resource.getFilename(), e);
            }
        }
    }

    return merged;
}

From source file:com.ibm.tap.trails.framework.PropertiesLoaderSupport.java

/**
 * Load properties into the given instance.
 * //from  w w w.j  a v a2 s  .  c o  m
 * @param props
 *            the Properties instance to load into
 * @throws java.io.IOException
 *             in case of I/O errors
 * @see #setLocations
 */
protected void loadProperties(Properties props) throws IOException {
    if (this.locations != null) {
        for (Resource location : this.locations) {
            if (logger.isInfoEnabled()) {
                logger.info("Loading properties file from " + location);
            }
            InputStream is = null;
            try {
                is = location.getInputStream();

                String filename = null;
                try {
                    filename = location.getFilename();
                } catch (IllegalStateException ex) {
                    // resource is not file-based. See SPR-7552.
                }

                if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
                    this.propertiesPersister.loadFromXml(props, is);
                } else {
                    if (this.fileEncoding != null) {
                        this.propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding));
                    } else {
                        this.propertiesPersister.load(props, is);
                    }
                }
            } catch (IOException ex) {
                if (this.ignoreResourceNotFound) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
                    }
                } else {
                    throw ex;
                }
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    }
}

From source file:com.jiangnan.es.orm.mybatis.extend.SqlSessionFactoryBean.java

private void autoParse(Configuration configuration) throws IOException {
    String scanMappingResourceDir = this.baseScan;
    List<String> lists = new ArrayList<String>();

    String testPath = "classpath*:" + scanMappingResourceDir + "/*-mybatis.xml";
    ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
    Resource[] source = new Resource[0];
    try {/* ww  w .j a va  2s  . c o m*/
        source = resourceLoader.getResources(testPath);
    } catch (IOException e) {
        logger.warn("[" + scanMappingResourceDir + "]XML?");
    }

    for (int i = 0; i < source.length; i++) {
        Resource resource = source[i];
        lists.add(scanMappingResourceDir + "/" + resource.getFilename());
    }
    for (String resource : lists) {
        InputStream inputStream = Resources.getResourceAsStream(resource);
        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
                configuration.getSqlFragments());
        mapperParser.parse();
    }
}

From source file:com.thinkbiganalytics.ui.service.UiTemplateService.java

/**
 * Loads and merges function definition files.
 *
 * @return the function definitions/*from  w w  w.j a  v  a 2  s . co m*/
 */
private Map<String, Object> loadFunctionsDefinitions(@Nonnull final String name,
        @Nonnull final String pattern) {
    // Attempt to load resources
    final Resource[] resources;
    try {
        resources = fileResourceService.loadResources(pattern);
    } catch (final IOException e) {
        log.error("Unable to load Spark function definitions", e);
        return Collections.emptyMap();
    }

    // Merge resources into map
    final Map<String, Object> merged = new LinkedHashMap<>();
    merged.put("!name", name);

    for (final Resource resource : resources) {
        // Deserialize resource
        Map<String, Object> functions = null;
        try {
            final String json = fileResourceService.resourceAsString(resource);
            functions = (json != null) ? ObjectMapperSerializer.deserialize(json, Map.class) : null;
        } catch (final RuntimeException e) {
            log.error("Failed to parse {} functions: {}", name, resource.getFilename(), e);
        }

        // Merge definitions
        if (functions != null) {
            try {
                merge(merged, functions, null);
            } catch (final Exception e) {
                log.error("Failed to merge {} functions: {}", name, resource.getFilename(), e);
            }
        }
    }

    return merged;
}

From source file:com.siberhus.tdfl.DataFileLoader.java

/**
 * /*from  www.  jav  a 2s .  co  m*/
 */
private void _load() {
    Resource sources[] = getSources();
    if (sources == null) {
        return;
    }

    DataFileReader reader = null;
    DataFileWriter successWriter = null, errorWriter = null;

    for (int i = 0; i < sources.length; i++) {
        Resource source = sources[i];
        try {
            String filename = source.getFilename();
            DataFileHandler fileHandler = null;
            for (DataFileHandler fh : dataFileHandlers) {
                if (fh.accept(filename)) {
                    fileHandler = fh;
                    break;
                }
            }
            if (fileHandler == null) {
                throw new DataFileLoaderException("No handler found for filename: " + filename);
            }

            reader = fileHandler.getReader();
            reader.setResource(source);
            successWriter = fileHandler.getSuccessWriter();
            if (successWriter != null) {
                Resource successResource = fileHandler.getSuccessResourceCreator().create(source);
                successWriter.setResource(successResource);
            }
            errorWriter = fileHandler.getErrorWriter();
            if (errorWriter != null) {
                Resource errorResource = fileHandler.getErrorResourceCreator().create(source);
                errorWriter.setResource(errorResource);
            }

            DataContext dataContext = new DataContext(this.attributes);
            dataContext.resource = source;
            dataContext.resourceNum = i;
            dataContext.startTime = new Date();
            if (dataFileProcessor instanceof DataContextAware) {
                ((DataContextAware) dataFileProcessor).setDataContext(dataContext);
            }
            try {
                doReadProcessWrite(dataContext, reader, successWriter, errorWriter);
                dataContext.exitStatus = ExitStatus.COMPLETED;
            } catch (Exception e) {
                dataContext.exitStatus = ExitStatus.FAILED;
                throw e;
            } finally {
                dataContext.finishTime = new Date();
                //may persist dataContext here

                if (reader != null)
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                if (successWriter != null)
                    try {
                        successWriter.close();
                    } catch (Exception e) {
                    }
                if (errorWriter != null)
                    try {
                        errorWriter.close();
                    } catch (Exception e) {
                    }
            }

            if (shouldDeleteIfFinish) {
                logger.info("Deleting file " + source);
                source.getFile().delete();
            } else if (destination != null) {
                File destFile = destination.getFile();
                logger.debug("Moving file: " + source.getFile().getCanonicalPath() + " to file: "
                        + destFile.getCanonicalPath());
                if (resource.getFile().isDirectory()) {
                    FileUtils.moveFileToDirectory(source.getFile(), destFile, true);
                } else {
                    FileUtils.moveFile(source.getFile(), destFile);
                }
            }

        } catch (Exception e) {
            if (stopOnError) {
                if (e instanceof DataFileLoaderException) {
                    throw (DataFileLoaderException) e;
                } else {
                    throw new DataFileLoaderException(e.getMessage(), e);
                }
            } else {
                logger.error(e.getMessage(), e);
            }
        }
    } //for each resource
}

From source file:egovframework.rte.fdl.property.impl.EgovPropertyServiceImpl.java

/**
 * ?  ? egovProperties? /*from   w ww. j  a v  a2 s .  c o  m*/
 * @param resources
 *        
 * @param encoding
 *        ?
 * @throws Exception
 */
private void loadPropertyRes(Resource resource, String encoding) throws Exception {
    if (EgovPropertyService.LOGGER.isDebugEnabled()) {
        EgovPropertyService.LOGGER.debug(messageSource.getMessage("debug.properties.filename",
                new String[] { resource.getFilename(), encoding }, Locale.getDefault()));
    }
    ExtendedProperties egovProperty = new ExtendedProperties();
    egovProperty.load(resource.getInputStream(), encoding);
    egovProperties.combine(egovProperty);
}

From source file:com.opengamma.component.ComponentManager.java

/**
 * Loads the component configuration based on the specified resource.
 * //w w w  . j a v a  2s.co m
 * @param resource  the configuration resource to load, not null
 * @return this manager, for chaining, not null
 */
public ComponentManager load(Resource resource) {
    _logger.logInfo("  Using item: " + ResourceUtils.getLocation(resource));
    if (resource.getFilename().endsWith(".properties")) {
        String nextConfig = loadProperties(resource);
        if (nextConfig == null) {
            throw new OpenGammaRuntimeException("The properties file must contain the key '" + MANAGER_NEXT_FILE
                    + "' to specify the next file to load: " + resource);
        }
        return load(nextConfig);
    }
    if (resource.getFilename().endsWith(".ini")) {
        loadIni(resource);
        return this;
    }
    throw new OpenGammaRuntimeException("Unknown file format: " + resource);
}

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

@DirtiesContext
@Test/*from  w  ww . j a va2 s  . c om*/
public void testXmlStream() throws Exception {

    resultEndpoint.expectedMessageCount(1);

    Resource xmlResource = new ClassPathResource("se/inera/axel/shs/camel/xmlFile.xml");

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(ShsHeaders.DATAPART_TRANSFERENCODING, "base64");
    headers.put(ShsHeaders.DATAPART_CONTENTTYPE, "text/xml");
    headers.put(ShsHeaders.DATAPART_FILENAME, xmlResource.getFilename());
    headers.put(ShsHeaders.DATAPART_CONTENTLENGTH, xmlResource.contentLength());
    headers.put(ShsHeaders.DATAPART_TYPE, "xml");

    template.sendBodyAndHeaders("direct:camelToShsConverter", xmlResource.getInputStream(), 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(), xmlResource.getFilename());
    Assert.assertEquals(datapart.getDataPartType(), "xml");
    Assert.assertEquals((long) datapart.getContentLength(), xmlResource.contentLength());

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

}