001 /*
002 // $Id: ParseTreeWriter.java 349 2010-08-12 08:49:13Z jhyde $
003 // This software is subject to the terms of the Eclipse Public License v1.0
004 // Agreement, available at the following URL:
005 // http://www.eclipse.org/legal/epl-v10.html.
006 // Copyright (C) 2007-2010 Julian Hyde
007 // All Rights Reserved.
008 // You must accept the terms of that agreement to use this software.
009 */
010 package org.olap4j.mdx;
011
012 import java.io.PrintWriter;
013 import java.io.Writer;
014
015 /**
016 * Writer for MDX parse tree.
017 *
018 * <p>Typical use is with the {@link ParseTreeNode#unparse(ParseTreeWriter)}
019 * method as follows:
020 *
021 * <blockquote>
022 * <pre>
023 * ParseTreeNode node;
024 * StringWriter sw = new StringWriter();
025 * PrintWriter pw = new PrintWriter(sw);
026 * ParseTreeWriter mdxWriter = new ParseTreeWriter(pw);
027 * node.unparse(mdxWriter);
028 * pw.flush();
029 * String mdx = sw.toString();
030 * </pre>
031 * </blockquote>
032 *
033 *
034 * @see org.olap4j.mdx.ParseTreeNode#unparse(ParseTreeWriter)
035 *
036 * @author jhyde
037 * @version $Id: ParseTreeWriter.java 349 2010-08-12 08:49:13Z jhyde $
038 * @since Jun 4, 2007
039 */
040 public class ParseTreeWriter {
041 private final PrintWriter pw;
042 private int linePrefixLength;
043 private String linePrefix;
044
045 private static final int INDENT = 4;
046 private static String bigString = " ";
047
048 /**
049 * Creates a ParseTreeWriter.
050 *
051 * @param pw Underlying writer
052 */
053 public ParseTreeWriter(PrintWriter pw) {
054 this((Writer)pw);
055 }
056
057 /**
058 * Creates a ParseTreeWriter.
059 *
060 * @param w Underlying writer
061 */
062 public ParseTreeWriter(Writer w) {
063 this.pw = new PrintWriter(w) {
064 @Override
065 public void println() {
066 super.println();
067 print(linePrefix);
068 }
069 };
070 this.linePrefixLength = 0;
071 setPrefix();
072 }
073
074 /**
075 * Returns the print writer.
076 *
077 * @return print writer
078 */
079 public PrintWriter getPrintWriter() {
080 return pw;
081 }
082
083 /**
084 * Increases the indentation level.
085 */
086 public void indent() {
087 linePrefixLength += INDENT;
088 setPrefix();
089 }
090
091 private void setPrefix() {
092 linePrefix = spaces(linePrefixLength);
093 }
094
095 /**
096 * Decreases the indentation level.
097 */
098 public void outdent() {
099 linePrefixLength -= INDENT;
100 setPrefix();
101 }
102
103 /**
104 * Returns a string of N spaces.
105 * @param n Number of spaces
106 * @return String of N spaces
107 */
108 private static synchronized String spaces(int n)
109 {
110 while (n > bigString.length()) {
111 bigString = bigString + bigString;
112 }
113 return bigString.substring(0, n);
114 }
115 }
116
117 // End ParseTreeWriter.java