Search in sources :

Example 16 with StringBuilderWriter

use of org.apache.groovy.io.StringBuilderWriter in project groovy by apache.

the class XmlUtil method serialize.

/**
 * Return a pretty version of the XML content contained in the given String.
 *
 * @param xmlString the String to serialize
 * @return the pretty String representation of the original content
 */
public static String serialize(String xmlString) {
    Writer sw = new StringBuilderWriter();
    serialize(asStreamSource(xmlString), sw);
    return sw.toString();
}
Also used : StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer)

Example 17 with StringBuilderWriter

use of org.apache.groovy.io.StringBuilderWriter in project groovy by apache.

the class JavaStubGenerator method getAnnotationValue.

private String getAnnotationValue(Object memberValue) {
    String val = "null";
    boolean replaceDollars = true;
    if (memberValue instanceof ListExpression) {
        StringBuilder sb = new StringBuilder("{");
        boolean first = true;
        ListExpression le = (ListExpression) memberValue;
        for (Expression e : le.getExpressions()) {
            if (first)
                first = false;
            else
                sb.append(",");
            sb.append(getAnnotationValue(e));
        }
        sb.append("}");
        val = sb.toString();
    } else if (memberValue instanceof ConstantExpression) {
        ConstantExpression ce = (ConstantExpression) memberValue;
        Object constValue = ce.getValue();
        if (constValue instanceof AnnotationNode) {
            Writer writer = new StringBuilderWriter();
            PrintWriter out = new PrintWriter(writer);
            printAnnotation(out, (AnnotationNode) constValue);
            val = writer.toString();
        } else if (constValue instanceof Number || constValue instanceof Boolean) {
            val = constValue.toString();
        } else {
            val = "\"" + escapeSpecialChars(constValue.toString()) + "\"";
            replaceDollars = false;
        }
    } else if (memberValue instanceof PropertyExpression) {
        // assume must be static class field or enum value or class that Java can resolve
        val = ((Expression) memberValue).getText();
    } else if (memberValue instanceof VariableExpression) {
        val = ((Expression) memberValue).getText();
        // check for an alias
        ImportNode alias = currentModule.getStaticImports().get(val);
        if (alias != null)
            val = alias.getClassName() + "." + alias.getFieldName();
    } else if (memberValue instanceof ClosureExpression) {
        // annotation closure; replaced with this specific class literal to cover the
        // case where annotation type uses Class<? extends Closure> for the closure's type
        val = "groovy.lang.Closure.class";
    } else if (memberValue instanceof ClassExpression) {
        val = ((Expression) memberValue).getText() + ".class";
    }
    return replaceDollars ? val.replace('$', '.') : val;
}
Also used : StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ConstructorCallExpression(org.codehaus.groovy.ast.expr.ConstructorCallExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) FileObject(javax.tools.FileObject) JavaFileObject(javax.tools.JavaFileObject) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ImportNode(org.codehaus.groovy.ast.ImportNode) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassHelper.isPrimitiveBoolean(org.codehaus.groovy.ast.ClassHelper.isPrimitiveBoolean) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 18 with StringBuilderWriter

use of org.apache.groovy.io.StringBuilderWriter in project groovy by apache.

the class JavaStubGenerator method generateStubContent.

private String generateStubContent(ClassNode classNode) {
    Writer writer = new StringBuilderWriter(8192);
    try (PrintWriter out = new PrintWriter(writer)) {
        boolean packageInfo = "package-info".equals(classNode.getNameWithoutPackage());
        String packageName = classNode.getPackageName();
        currentModule = classNode.getModule();
        if (packageName != null) {
            if (packageInfo) {
                printAnnotations(out, classNode.getPackage());
            }
            out.println("package " + packageName + ";");
        }
        // should just output the package statement for `package-info` class node
        if (!packageInfo) {
            printImports(out);
            printClassContents(out, classNode);
        }
    } finally {
        currentModule = null;
    }
    return writer.toString();
}
Also used : StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 19 with StringBuilderWriter

use of org.apache.groovy.io.StringBuilderWriter in project groovy by apache.

the class Groovy method execGroovy.

/**
 * Exec the statement.
 *
 * @param txt the groovy source to exec
 * @param out not used?
 */
protected void execGroovy(final String txt, final PrintStream out) {
    log.debug("execGroovy()");
    // Check and ignore empty statements
    if (txt.trim().isEmpty()) {
        return;
    }
    log.verbose("Script: " + txt);
    if (classpath != null) {
        log.debug("Explicit Classpath: " + classpath.toString());
    }
    if (fork) {
        log.debug("Using fork mode");
        try {
            createClasspathParts();
            createNewArgs(txt);
            super.setFork(fork);
            super.setClassname(useGroovyShell ? "groovy.lang.GroovyShell" : "org.codehaus.groovy.ant.Groovy");
            configureCompiler();
            super.execute();
        } catch (Exception e) {
            Writer writer = new StringBuilderWriter();
            new ErrorReporter(e, false).write(new PrintWriter(writer));
            String message = writer.toString();
            throw new BuildException("Script Failed: " + message, e, getLocation());
        }
        return;
    }
    Object mavenPom = null;
    final Project project = getProject();
    final ClassLoader baseClassLoader;
    ClassLoader savedLoader = null;
    final Thread thread = Thread.currentThread();
    boolean maven = "org.apache.commons.grant.GrantProject".equals(project.getClass().getName());
    // treat the case Ant is run through Maven, and
    if (maven) {
        if (contextClassLoader) {
            throw new BuildException("Using setContextClassLoader not permitted when using Maven.", getLocation());
        }
        try {
            final Object propsHandler = project.getClass().getMethod("getPropsHandler").invoke(project);
            final Field contextField = propsHandler.getClass().getDeclaredField("context");
            ReflectionUtils.trySetAccessible(contextField);
            final Object context = contextField.get(propsHandler);
            mavenPom = InvokerHelper.invokeMethod(context, "getProject", EMPTY_OBJECT_ARRAY);
        } catch (Exception e) {
            throw new BuildException("Impossible to retrieve Maven's Ant project: " + e.getMessage(), getLocation());
        }
        // load groovy into "root.maven" classloader instead of "root" so that
        // groovy script can access Maven classes
        baseClassLoader = mavenPom.getClass().getClassLoader();
    } else {
        baseClassLoader = GroovyShell.class.getClassLoader();
    }
    if (contextClassLoader || maven) {
        savedLoader = thread.getContextClassLoader();
        thread.setContextClassLoader(GroovyShell.class.getClassLoader());
    }
    final String scriptName = computeScriptName();
    final GroovyClassLoader classLoader = VMPluginFactory.getPlugin().doPrivileged((PrivilegedAction<GroovyClassLoader>) () -> new GroovyClassLoader(baseClassLoader));
    addClassPathes(classLoader);
    configureCompiler();
    final GroovyShell groovy = new GroovyShell(classLoader, new Binding(), configuration);
    try {
        parseAndRunScript(groovy, txt, mavenPom, scriptName, null, new AntBuilder(this));
    } finally {
        groovy.resetLoadedClasses();
        groovy.getClassLoader().clearCache();
        if (contextClassLoader || maven)
            thread.setContextClassLoader(savedLoader);
    }
}
Also used : Binding(groovy.lang.Binding) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) AntBuilder(groovy.ant.AntBuilder) MissingMethodException(groovy.lang.MissingMethodException) BuildException(org.apache.tools.ant.BuildException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyShell(groovy.lang.GroovyShell) GroovyClassLoader(groovy.lang.GroovyClassLoader) Project(org.apache.tools.ant.Project) Field(java.lang.reflect.Field) ErrorReporter(org.codehaus.groovy.tools.ErrorReporter) GroovyClassLoader(groovy.lang.GroovyClassLoader) BuildException(org.apache.tools.ant.BuildException) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 20 with StringBuilderWriter

use of org.apache.groovy.io.StringBuilderWriter in project groovy by apache.

the class GroovyTest method testFileNameInStackTrace.

private void testFileNameInStackTrace(final String target, final String fileNamePattern) {
    try {
        project.executeTarget(target);
        fail();
    } catch (final BuildException e) {
        assertEquals(BuildException.class, e.getClass());
        final Throwable cause = e.getCause();
        assertTrue(cause instanceof GroovyRuntimeException);
        final Writer sw = new StringBuilderWriter();
        cause.printStackTrace(new PrintWriter(sw));
        final String stackTrace = sw.toString();
        final Pattern pattern = Pattern.compile(fileNamePattern);
        assertTrue("Does >" + stackTrace + "< contain >" + fileNamePattern + "<?", pattern.matcher(stackTrace).find());
    }
}
Also used : StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) Pattern(java.util.regex.Pattern) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) BuildException(org.apache.tools.ant.BuildException) PrintWriter(java.io.PrintWriter) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Aggregations

StringBuilderWriter (org.apache.groovy.io.StringBuilderWriter)25 Writer (java.io.Writer)22 PrintWriter (java.io.PrintWriter)15 IOException (java.io.IOException)11 OutputStreamWriter (java.io.OutputStreamWriter)6 BuildException (org.apache.tools.ant.BuildException)5 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)4 Writable (groovy.lang.Writable)4 ErrorReporter (org.codehaus.groovy.tools.ErrorReporter)4 StringWriterIOException (groovy.lang.StringWriterIOException)3 GroovyClassLoader (groovy.lang.GroovyClassLoader)2 BufferedWriter (java.io.BufferedWriter)2 URISyntaxException (java.net.URISyntaxException)2 AntBuilder (groovy.ant.AntBuilder)1 GroovyPrintWriter (groovy.io.GroovyPrintWriter)1 Binding (groovy.lang.Binding)1 GString (groovy.lang.GString)1 GroovyShell (groovy.lang.GroovyShell)1 MissingMethodException (groovy.lang.MissingMethodException)1 Script (groovy.lang.Script)1