Search in sources :

Example 36 with PrintStream

use of java.io.PrintStream in project groovy-core by groovy.

the class Java2GroovyProcessor method mindmap.

public static String mindmap(String input) throws Exception {
    JavaRecognizer parser = getJavaParser(input);
    String[] tokenNames = parser.getTokenNames();
    parser.compilationUnit();
    AST ast = parser.getAST();
    // modify the Java AST into a Groovy AST
    modifyJavaASTintoGroovyAST(tokenNames, ast);
    String[] groovyTokenNames = getGroovyTokenNames(input);
    // groovify the fat Java-Like Groovy AST
    groovifyFatJavaLikeGroovyAST(ast, groovyTokenNames);
    // now output
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Visitor visitor = new MindMapPrinter(new PrintStream(baos), groovyTokenNames);
    AntlrASTProcessor traverser = new SourceCodeTraversal(visitor);
    traverser.process(ast);
    return new String(baos.toByteArray());
}
Also used : PrintStream(java.io.PrintStream) AST(antlr.collections.AST) Visitor(org.codehaus.groovy.antlr.treewalker.Visitor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MindMapPrinter(org.codehaus.groovy.antlr.treewalker.MindMapPrinter) AntlrASTProcessor(org.codehaus.groovy.antlr.AntlrASTProcessor) SourceCodeTraversal(org.codehaus.groovy.antlr.treewalker.SourceCodeTraversal)

Example 37 with PrintStream

use of java.io.PrintStream in project groovy-core by groovy.

the class AntlrParserPlugin method outputASTInVariousFormsIfNeeded.

private void outputASTInVariousFormsIfNeeded(SourceUnit sourceUnit, SourceBuffer sourceBuffer) {
    // straight xstream output of AST
    // uppercase to hide from jarjar
    String formatProp = System.getProperty("ANTLR.AST".toLowerCase());
    if ("xml".equals(formatProp)) {
        saveAsXML(sourceUnit.getName(), ast);
    }
    // 'pretty printer' output of AST
    if ("groovy".equals(formatProp)) {
        try {
            PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".pretty.groovy"));
            Visitor visitor = new SourcePrinter(out, tokenNames);
            AntlrASTProcessor treewalker = new SourceCodeTraversal(visitor);
            treewalker.process(ast);
        } catch (FileNotFoundException e) {
            System.out.println("Cannot create " + sourceUnit.getName() + ".pretty.groovy");
        }
    }
    // which is a really nice way of seeing the AST, folding nodes etc
    if ("mindmap".equals(formatProp)) {
        try {
            PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".mm"));
            Visitor visitor = new MindMapPrinter(out, tokenNames);
            AntlrASTProcessor treewalker = new PreOrderTraversal(visitor);
            treewalker.process(ast);
        } catch (FileNotFoundException e) {
            System.out.println("Cannot create " + sourceUnit.getName() + ".mm");
        }
    }
    // include original line/col info and source code on the mindmap output
    if ("extendedMindmap".equals(formatProp)) {
        try {
            PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".mm"));
            Visitor visitor = new MindMapPrinter(out, tokenNames, sourceBuffer);
            AntlrASTProcessor treewalker = new PreOrderTraversal(visitor);
            treewalker.process(ast);
        } catch (FileNotFoundException e) {
            System.out.println("Cannot create " + sourceUnit.getName() + ".mm");
        }
    }
    // html output of AST
    if ("html".equals(formatProp)) {
        try {
            PrintStream out = new PrintStream(new FileOutputStream(sourceUnit.getName() + ".html"));
            List<VisitorAdapter> v = new ArrayList<VisitorAdapter>();
            v.add(new NodeAsHTMLPrinter(out, tokenNames));
            v.add(new SourcePrinter(out, tokenNames));
            Visitor visitors = new CompositeVisitor(v);
            AntlrASTProcessor treewalker = new SourceCodeTraversal(visitors);
            treewalker.process(ast);
        } catch (FileNotFoundException e) {
            System.out.println("Cannot create " + sourceUnit.getName() + ".html");
        }
    }
}
Also used : PrintStream(java.io.PrintStream) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) FileOutputStream(java.io.FileOutputStream)

Example 38 with PrintStream

use of java.io.PrintStream in project groovy-core by groovy.

the class CompositeVisitorTest method assertCompositeTransparency.

private void assertCompositeTransparency(String input) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GroovyRecognizer parser;
    SourceBuffer sourceBuffer = new SourceBuffer();
    UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new StringReader(input), sourceBuffer);
    GroovyLexer lexer = new GroovyLexer(unicodeReader);
    unicodeReader.setLexer(lexer);
    parser = GroovyRecognizer.make(lexer);
    parser.setSourceBuffer(sourceBuffer);
    String[] tokenNames = parser.getTokenNames();
    parser.compilationUnit();
    AST ast = parser.getAST();
    // determine direct result
    Visitor directVisitor = new SourcePrinter(new PrintStream(baos), tokenNames, false);
    AntlrASTProcessor traverser = new SourceCodeTraversal(directVisitor);
    traverser.process(ast);
    String directResult = new String(baos.toByteArray());
    // determine composite result
    baos.reset();
    List wrappedVisitors = new ArrayList();
    wrappedVisitors.add(directVisitor);
    Visitor compositeVisitor = new CompositeVisitor(wrappedVisitors);
    traverser = new SourceCodeTraversal(compositeVisitor);
    traverser.process(ast);
    String compositeResult = new String(baos.toByteArray());
    assertEquals(directResult, compositeResult);
}
Also used : PrintStream(java.io.PrintStream) AST(antlr.collections.AST) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SourceBuffer(org.codehaus.groovy.antlr.SourceBuffer) AntlrASTProcessor(org.codehaus.groovy.antlr.AntlrASTProcessor) UnicodeEscapingReader(org.codehaus.groovy.antlr.UnicodeEscapingReader) GroovyLexer(org.codehaus.groovy.antlr.parser.GroovyLexer) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) List(java.util.List) GroovyRecognizer(org.codehaus.groovy.antlr.parser.GroovyRecognizer)

Example 39 with PrintStream

use of java.io.PrintStream in project groovy-core by groovy.

the class TraversalTestHelper method traverse.

// todo - the visitor doesn't always take PrintStreams as constructor params!  Could be a more reusable implementation than this...
public String traverse(String input, Class visitorClass, Boolean extraParam) throws Exception {
    if (!Visitor.class.isAssignableFrom(visitorClass)) {
        throw new RuntimeException("Invalid class for traversal: " + visitorClass.getName());
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GroovyRecognizer parser;
    SourceBuffer sourceBuffer = new SourceBuffer();
    UnicodeEscapingReader unicodeReader = new UnicodeEscapingReader(new StringReader(input), sourceBuffer);
    GroovyLexer lexer = new GroovyLexer(unicodeReader);
    unicodeReader.setLexer(lexer);
    parser = GroovyRecognizer.make(lexer);
    parser.setSourceBuffer(sourceBuffer);
    String[] tokenNames = parser.getTokenNames();
    parser.compilationUnit();
    AST ast = parser.getAST();
    Class[] paramTypes;
    Object[] params;
    if (extraParam == null) {
        paramTypes = new Class[] { PrintStream.class, String[].class };
        params = new Object[] { new PrintStream(baos), tokenNames };
    } else {
        paramTypes = new Class[] { PrintStream.class, String[].class, Boolean.TYPE };
        params = new Object[] { new PrintStream(baos), tokenNames, extraParam };
    }
    Constructor constructor = visitorClass.getConstructor(paramTypes);
    Visitor visitor = (Visitor) constructor.newInstance(params);
    AntlrASTProcessor traverser = new SourceCodeTraversal(visitor);
    traverser.process(ast);
    return new String(baos.toByteArray());
}
Also used : PrintStream(java.io.PrintStream) AST(antlr.collections.AST) Constructor(java.lang.reflect.Constructor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SourceBuffer(org.codehaus.groovy.antlr.SourceBuffer) AntlrASTProcessor(org.codehaus.groovy.antlr.AntlrASTProcessor) UnicodeEscapingReader(org.codehaus.groovy.antlr.UnicodeEscapingReader) GroovyLexer(org.codehaus.groovy.antlr.parser.GroovyLexer) StringReader(java.io.StringReader) GroovyRecognizer(org.codehaus.groovy.antlr.parser.GroovyRecognizer)

Example 40 with PrintStream

use of java.io.PrintStream in project groovy-core by groovy.

the class AntBuilderLocator method nodeCompleted.

/**
     * Determines, when the ANT Task that is represented by the "node" should perform.
     * Node must be an ANT Task or no "perform" is called.
     * If node is an ANT Task, it performs right after complete construction.
     * If node is nested in a TaskContainer, calling "perform" is delegated to that
     * TaskContainer.
     *
     * @param parent note: null when node is root
     * @param node   the node that now has all its children applied
     */
protected void nodeCompleted(final Object parent, final Object node) {
    if (parent == null)
        insideTask = false;
    antElementHandler.onEndElement(null, null, antXmlContext);
    lastCompletedNode = node;
    if (parent != null && !(parent instanceof Target)) {
        log.finest("parent is not null: no perform on nodeCompleted");
        // parent will care about when children perform
        return;
    }
    // inside defineTarget
    if (definingTarget != null && definingTarget == parent && node instanceof Task)
        return;
    if (definingTarget == node) {
        definingTarget = null;
    }
    // as in Target.execute()
    if (node instanceof Task) {
        Task task = (Task) node;
        final String taskName = task.getTaskName();
        if ("antcall".equals(taskName) && parent == null) {
            throw new BuildException("antcall not supported within AntBuilder, consider using 'ant.project.executeTarget('targetName')' instead.");
        }
        if (saveStreams) {
            // save original streams
            synchronized (AntBuilder.class) {
                int currentStreamCount = streamCount++;
                if (currentStreamCount == 0) {
                    // we are first, save the streams
                    savedProjectInputStream = project.getDefaultInputStream();
                    savedIn = System.in;
                    savedErr = System.err;
                    savedOut = System.out;
                    if (!(savedIn instanceof DemuxInputStream)) {
                        project.setDefaultInputStream(savedIn);
                        demuxInputStream = new DemuxInputStream(project);
                        System.setIn(demuxInputStream);
                    }
                    demuxOutputStream = new DemuxOutputStream(project, false);
                    System.setOut(new PrintStream(demuxOutputStream));
                    demuxErrorStream = new DemuxOutputStream(project, true);
                    System.setErr(new PrintStream(demuxErrorStream));
                }
            }
        }
        try {
            lastCompletedNode = performTask(task);
        } finally {
            if (saveStreams) {
                synchronized (AntBuilder.class) {
                    int currentStreamCount = --streamCount;
                    if (currentStreamCount == 0) {
                        // last to leave, turn out the lights: restore original streams
                        project.setDefaultInputStream(savedProjectInputStream);
                        System.setOut(savedOut);
                        System.setErr(savedErr);
                        if (demuxInputStream != null) {
                            System.setIn(savedIn);
                            DefaultGroovyMethodsSupport.closeQuietly(demuxInputStream);
                            demuxInputStream = null;
                        }
                        DefaultGroovyMethodsSupport.closeQuietly(demuxOutputStream);
                        DefaultGroovyMethodsSupport.closeQuietly(demuxErrorStream);
                        demuxOutputStream = null;
                        demuxErrorStream = null;
                    }
                }
            }
        }
        // restore dummy collector target
        if ("import".equals(taskName)) {
            antXmlContext.setCurrentTarget(collectorTarget);
        }
    } else if (node instanceof Target) {
        // restore dummy collector target
        antXmlContext.setCurrentTarget(collectorTarget);
    } else {
        final RuntimeConfigurable r = (RuntimeConfigurable) node;
        r.maybeConfigure(project);
    }
}
Also used : PrintStream(java.io.PrintStream)

Aggregations

PrintStream (java.io.PrintStream)1829 ByteArrayOutputStream (java.io.ByteArrayOutputStream)805 Test (org.junit.Test)583 File (java.io.File)331 IOException (java.io.IOException)295 FileOutputStream (java.io.FileOutputStream)207 ArrayList (java.util.ArrayList)89 FileNotFoundException (java.io.FileNotFoundException)84 OutputStream (java.io.OutputStream)81 Before (org.junit.Before)66 BufferedReader (java.io.BufferedReader)53 BufferedOutputStream (java.io.BufferedOutputStream)49 Map (java.util.Map)49 Date (java.util.Date)46 Path (org.apache.hadoop.fs.Path)42 UnsupportedEncodingException (java.io.UnsupportedEncodingException)41 InputStreamReader (java.io.InputStreamReader)38 Matchers.anyString (org.mockito.Matchers.anyString)38 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)36 List (java.util.List)35