fr.dutra.tools.maven.deptree.core.AbstractTextVisitor.java Source code

Java tutorial

Introduction

Here is the source code for fr.dutra.tools.maven.deptree.core.AbstractTextVisitor.java

Source

/**
 * Copyright 2011 Alexandre Dutra
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package fr.dutra.tools.maven.deptree.core;

import java.io.BufferedWriter;
import java.io.IOException;

import org.apache.commons.io.output.StringBuilderWriter;

/**
 * Base class for visitors that generate an output that is identical
 * to the output generated by the Maven command:
 * <pre>mvn dependency:tree -DoutputType=text</pre>
 * 
 * @author Alexandre Dutra
 *
 */
public abstract class AbstractTextVisitor implements Visitor {

    private final StringBuilderWriter sbw;

    private final BufferedWriter bw;

    public AbstractTextVisitor() {
        sbw = new StringBuilderWriter();
        bw = new BufferedWriter(sbw);
    }

    public void visit(Node node) {
        try {
            writeNode(node);
            for (Node child : node.getChildNodes()) {
                visit(child);
            }
        } catch (IOException e) {
        }
    }

    private void writeNode(Node node) throws IOException {
        //the tree symbols
        writeTreeSymbols(node);
        //the node itself
        bw.write(node.getArtifactCanonicalForm());
        bw.newLine();
    }

    private void writeTreeSymbols(Node node) throws IOException {
        if (node.getParent() != null) {
            writeParentTreeSymbols(node.getParent());
            bw.write(getTreeSymbols(node));
        }
    }

    private void writeParentTreeSymbols(Node node) throws IOException {
        if (node.getParent() != null) {
            writeParentTreeSymbols(node.getParent());
            bw.write(getParentTreeSymbols(node));
        }
    }

    public abstract String getTreeSymbols(Node node);

    public abstract String getParentTreeSymbols(Node node);

    @Override
    public String toString() {
        try {
            bw.flush();
            sbw.flush();
            return sbw.toString();
        } catch (IOException e) {
            return null;
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
            }
            sbw.close();
        }
    }

}