001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: *
017: * $Header:$
018: */
019: package org.apache.beehive.controls.runtime.generator;
020:
021: import java.io.IOException;
022: import java.io.Writer;
023:
024: /**
025: * The IndentingWriter class is a simple implementation of an indenting code writer
026: */
027: public class IndentingWriter extends Writer {
028: /** current depth:
029: * <PRE>
030: * // depth = 0;
031: * {
032: * // depth now is 2
033: * {
034: * // depth now is 4
035: * }
036: * // depth now is 2
037: * }
038: * // depth now is 0
039: * </PRE>
040: */
041: protected int depth = 0;
042:
043: public IndentingWriter(Writer delegate) {
044: this (
045: delegate,
046: Integer
047: .getInteger(
048: "org.apache.beehive.controls.runtime.generator.indentLevel",
049: 4).intValue());
050: }
051:
052: public IndentingWriter(Writer delegate, int indentLevel) {
053: _out = delegate;
054: this ._indentLevel = indentLevel;
055: }
056:
057: public void write(char cbuf[], int off, int len) throws IOException {
058: if (off < 0 || off + len > cbuf.length)
059: throw new ArrayIndexOutOfBoundsException();
060:
061: for (int i = off; i < off + len; i++) {
062: char c = cbuf[i];
063: if (c == '}') {
064: decrDepth();
065: } else if ((c == ' ' || c == '\t') && _needIndent) {
066: continue;
067: }
068:
069: if (_needIndent)
070: indent();
071: _out.write(c);
072:
073: if (c == '\n') {
074: _needIndent = true;
075: } else if (c == '{') {
076: incrDepth();
077: }
078: }
079: }
080:
081: public void flush() throws IOException {
082: _out.flush();
083: }
084:
085: public void close() throws IOException {
086: _out.close();
087: }
088:
089: private void indent() throws IOException {
090: for (int i = 0; i < depth; i++) {
091: _out.write(' ');
092: }
093: _needIndent = false;
094: }
095:
096: private void incrDepth() {
097: depth += _indentLevel;
098: }
099:
100: private void decrDepth() {
101: depth -= _indentLevel;
102: if (depth < 0)
103: depth = 0;
104: }
105:
106: protected Writer _out;
107: protected int _indentLevel;
108: private boolean _needIndent = false;
109: }
|