001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: ResourceReaderFactoryBean.java 14 2011-02-15 22:40:49Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.spring;
009    
010    import java.io.IOException;
011    import java.io.InputStream;
012    import java.io.InputStreamReader;
013    import java.io.StringWriter;
014    
015    import org.springframework.beans.factory.config.AbstractFactoryBean;
016    import org.springframework.core.io.Resource;
017    
018    /**
019     * Spring factory bean that reads in a Spring {@link Resource} and converts it to a {@link String}.
020     */
021    public class ResourceReaderFactoryBean extends AbstractFactoryBean<String> {
022    
023        private Resource resource;
024        private String charset = "UTF-8";
025    
026        /**
027         * Configure the resource containing the {@link String value}.
028         */
029        public void setResource(Resource resource) {
030            this.resource = resource;
031        }
032    
033        /**
034         * Configure the character encoding for the resource. Default is {@code UTF-8}.
035         */
036        public void setCharacterEncoding(String charset) {
037            this.charset = charset;
038        }
039    
040        @Override
041        public Class<String> getObjectType() {
042            return String.class;
043        }
044    
045        @Override
046        public void afterPropertiesSet() throws Exception {
047            super.afterPropertiesSet();
048            if (this.resource == null)
049                throw new Exception("no resource configured");
050        }
051    
052        @Override
053        protected String createInstance() throws IOException {
054            InputStream input = this.resource.getInputStream();
055            try {
056                InputStreamReader reader = new InputStreamReader(input, this.charset);
057                StringWriter writer = new StringWriter();
058                char[] buf = new char[4096];
059                int r;
060                while ((r = reader.read(buf)) != -1)
061                    writer.write(buf, 0, r);
062                return writer.toString();
063            } finally {
064                try {
065                    input.close();
066                } catch (IOException e) {
067                    // ignore
068                }
069            }
070        }
071    }
072