001    package nl.tudelft.tbm.eeni.owl2java.formatter;
002    
003    import java.io.IOException;
004    import java.io.StringWriter;
005    import java.io.Writer;
006    import java.util.Properties;
007    
008    /**
009     * Stream writer that formats source code
010     */
011    public class CodeFormattingWriter extends StringWriter {
012        // The CodeFormatter instance
013        CodeFormatter formatter;
014    
015        // The writer that we'll write the formatting result to
016        Writer destination;
017    
018        /**
019         * Creates a new code-formatting wrapper with default formatter settings
020         */
021        public CodeFormattingWriter(Writer destination) {
022            this(destination, new CodeFormatter());
023        }
024    
025        /**
026         * Creates a new code-formatting wrapper with specified formatter settings;
027         * if formatterOptions is null, use default formatter settings
028         */
029        public CodeFormattingWriter(Writer destination, Properties formatterSettings) {
030            this(destination, new CodeFormatter(formatterSettings));
031        }
032    
033        /**
034         * Creates a new code-formatting wrapper, reusing an existing code formatter
035         * instance
036         */
037        public CodeFormattingWriter(Writer destination, CodeFormatter formatter) {
038            // Check for null values
039            assert destination != null : "destination argument is null";
040            assert formatter != null : "formatter argument is null";
041    
042            this.destination = destination;
043            this.formatter = formatter;
044        }
045    
046        /**
047         * Formats the contents of the string buffer, then flushes
048         *
049         * @see java.io.Writer#close()
050         */
051        @Override
052        public void close() throws IOException {
053            // Close the string buffer
054            super.close();
055    
056            // Format the contents of the string buffer
057            String formattedCode = formatter.format(getBuffer().toString());
058    
059            // Write the formatted code to the destination stream
060            destination.write(formattedCode);
061    
062            // Close the destination stream
063            destination.close();
064            this.destination = null;
065        }
066    
067        /**
068         * Flush is ignored by formattedWriter
069         *
070         * @see java.io.Writer#flush()
071         */
072        @Override
073        public void flush() {
074            // Ignore flush signal
075        }
076    }