001/*
002// Licensed to Julian Hyde under one or more contributor license
003// agreements. See the NOTICE file distributed with this work for
004// additional information regarding copyright ownership.
005//
006// Julian Hyde licenses this file to you under the Apache License,
007// Version 2.0 (the "License"); you may not use this file except in
008// compliance with the License. You may obtain a copy of the License at:
009//
010// http://www.apache.org/licenses/LICENSE-2.0
011//
012// Unless required by applicable law or agreed to in writing, software
013// distributed under the License is distributed on an "AS IS" BASIS,
014// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015// See the License for the specific language governing permissions and
016// limitations under the License.
017*/
018package org.olap4j.mdx;
019
020import org.olap4j.impl.Spacer;
021
022import java.io.PrintWriter;
023import java.io.Writer;
024
025/**
026 * Writer for MDX parse tree.
027 *
028 * <p>Typical use is with the {@link ParseTreeNode#unparse(ParseTreeWriter)}
029 * method as follows:
030 *
031 * <blockquote>
032 * <pre>
033 * ParseTreeNode node;
034 * StringWriter sw = new StringWriter();
035 * PrintWriter pw = new PrintWriter(sw);
036 * ParseTreeWriter mdxWriter = new ParseTreeWriter(pw);
037 * node.unparse(mdxWriter);
038 * pw.flush();
039 * String mdx = sw.toString();
040 * </pre>
041 * </blockquote>
042 *
043 *
044 * @see org.olap4j.mdx.ParseTreeNode#unparse(ParseTreeWriter)
045 *
046 * @author jhyde
047 * @since Jun 4, 2007
048 */
049public class ParseTreeWriter {
050    private final PrintWriter pw;
051    private final Spacer spacer = new Spacer();
052
053    private static final int INDENT = 4;
054
055    /**
056     * Creates a ParseTreeWriter.
057     *
058     * @param pw Underlying writer
059     */
060    public ParseTreeWriter(PrintWriter pw) {
061        this((Writer)pw);
062    }
063
064    /**
065     * Creates a ParseTreeWriter.
066     *
067     * @param w Underlying writer
068     */
069    public ParseTreeWriter(Writer w) {
070        this.pw = new PrintWriter(w) {
071            @Override
072            public void println() {
073                super.println();
074                spacer.spaces(this);
075            }
076        };
077    }
078
079    /**
080     * Returns the print writer.
081     *
082     * @return print writer
083     */
084    public PrintWriter getPrintWriter() {
085        return pw;
086    }
087
088    /**
089     * Increases the indentation level.
090     */
091    public void indent() {
092        spacer.add(INDENT);
093    }
094
095    /**
096     * Decreases the indentation level.
097     */
098    public void outdent() {
099        spacer.subtract(INDENT);
100    }
101}
102
103// End ParseTreeWriter.java