groovy.lang.Writable Java Examples

The following examples show how to use groovy.lang.Writable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: ozark   Author: mvc-spec   File: GroovyViewEngine.java    License: Apache License 2.0 5 votes vote down vote up
public void processView(ViewEngineContext context) throws ViewEngineException {

        Map<String, Object> model = new HashMap<>(context.getModels().asMap());
        model.put("request", context.getRequest(HttpServletRequest.class));
        Charset charset = resolveCharsetAndSetContentType(context);
        try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);
            InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
            InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");) {
            Template template = markupTemplateEngine.createTemplate(in);
            Writable output = template.make(model);
            output.writeTo(writer);
        } catch (IOException | CompilationFailedException | ClassNotFoundException e) {
            throw new ViewEngineException(e);
        }
    }
 
Example #2
Source Project: groovy   Author: apache   File: StreamingJsonBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes the given Writable as the value of the given attribute name
 *
 * @param name The attribute name 
 * @param json The writable value
 * @throws IOException
 */
public void call(String name, Writable json) throws IOException {
    writeName(name);
    verifyValue();
    if(json instanceof GString) {
        writer.write(generator.toJson(json.toString()));
    }
    else {
        json.writeTo(writer);
    }
}
 
Example #3
Source Project: groovy   Author: apache   File: Node.java    License: Apache License 2.0 5 votes vote down vote up
public Writer writeTo(final Writer out) throws IOException {
    if (this.replacementNodeStack.empty()) {
        for (Object child : this.children) {
            if (child instanceof Writable) {
                ((Writable) child).writeTo(out);
            } else {
                out.write(child.toString());
            }
        }
        return out;
    } else {
        return ((Writable) this.replacementNodeStack.peek()).writeTo(out);
    }
}
 
Example #4
Source Project: groovy   Author: apache   File: XmlUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static String asString(GPathResult node) {
    // little bit of hackery to avoid Groovy dependency in this file
    try {
        Object builder = Class.forName("groovy.xml.StreamingMarkupBuilder").getDeclaredConstructor().newInstance();
        InvokerHelper.setProperty(builder, "encoding", "UTF-8");
        Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node);
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + w.toString();
    } catch (Exception e) {
        return "Couldn't convert node to string because: " + e.getMessage();
    }
}
 
Example #5
Source Project: groovy   Author: apache   File: XmlUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static String asString(Writable writable) {
    if (writable instanceof GPathResult) {
        return asString((GPathResult) writable); //GROOVY-4285
    }
    Writer sw = new StringBuilderWriter();
    try {
        writable.writeTo(sw);
    } catch (IOException e) {
        // ignore
    }
    return sw.toString();
}
 
Example #6
Source Project: groovy   Author: apache   File: EncodingGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Produces a Writable that writes the hex encoding of the byte[]. Calling
 * toString() on this Writable returns the hex encoding as a String. The hex
 * encoding includes two characters for each byte and all letters are lower case.
 *
 * @param data byte array to be encoded
 * @return object which will write the hex encoding of the byte array
 * @see Integer#toHexString(int)
 */
public static Writable encodeHex(final byte[] data) {
    return new Writable() {
        public Writer writeTo(Writer out) throws IOException {
            for (byte datum : data) {
                // convert byte into unsigned hex string
                String hexString = Integer.toHexString(datum & 0xFF);

                // add leading zero if the length of the string is one
                if (hexString.length() < 2) {
                    out.write("0");
                }

                // write hex string to writer
                out.write(hexString);
            }
            return out;
        }

        public String toString() {
            Writer buffer = new StringBuilderWriter();

            try {
                writeTo(buffer);
            } catch (IOException e) {
                throw new StringWriterIOException(e);
            }

            return buffer.toString();
        }
    };
}
 
Example #7
Source Project: groovy   Author: apache   File: IOGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Filter the lines from this Reader, and return a Writable which can be
 * used to stream the filtered lines to a destination.  The closure should
 * return <code>true</code> if the line should be passed to the writer.
 *
 * @param reader  this reader
 * @param closure a closure used for filtering
 * @return a Writable which will use the closure to filter each line
 *         from the reader when the Writable#writeTo(Writer) is called.
 * @since 1.0
 */
public static Writable filterLine(Reader reader, @ClosureParams(value=SimpleType.class, options="java.lang.String") final Closure closure) {
    final BufferedReader br = new BufferedReader(reader);
    return new Writable() {
        public Writer writeTo(Writer out) throws IOException {
            BufferedWriter bw = new BufferedWriter(out);
            String line;
            BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
            while ((line = br.readLine()) != null) {
                if (bcw.call(line)) {
                    bw.write(line);
                    bw.newLine();
                }
            }
            bw.flush();
            return out;
        }

        public String toString() {
            Writer buffer = new StringBuilderWriter();
            try {
                writeTo(buffer);
            } catch (IOException e) {
                throw new StringWriterIOException(e);
            }
            return buffer.toString();
        }
    };
}
 
Example #8
Source Project: groovy   Author: apache   File: InvokerHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Appends an object to an Appendable using Groovy's default representation for the object.
 */
public static void append(Appendable out, Object object) throws IOException {
    if (object instanceof String) {
        out.append((String) object);
    } else if (object instanceof Object[]) {
        out.append(toArrayString((Object[]) object));
    } else if (object instanceof Map) {
        out.append(toMapString((Map) object));
    } else if (object instanceof Collection) {
        out.append(toListString((Collection) object));
    } else if (object instanceof Writable) {
        Writable writable = (Writable) object;
        Writer stringWriter = new StringBuilderWriter();
        writable.writeTo(stringWriter);
        out.append(stringWriter.toString());
    } else if (object instanceof InputStream || object instanceof Reader) {
        // Copy stream to stream
        try (Reader reader =
                     object instanceof InputStream
                             ? new InputStreamReader((InputStream) object)
                             : (Reader) object) {
            char[] chars = new char[8192];
            for (int i; (i = reader.read(chars)) != -1; ) {
                for (int j = 0; j < i; j++) {
                    out.append(chars[j]);
                }
            }
        }
    } else {
        out.append(toString(object));
    }
}
 
Example #9
Source Project: nifi   Author: apache   File: GroovySessionFile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Write flow file contents through writer with defined charset.
 *
 * @param charset charset to use for writer
 * @param c       content defined as writable
 * @return reference to self
 */
public GroovySessionFile write(String charset, Writable c) {
    this.write(new OutputStreamCallback() {
        public void process(OutputStream out) throws IOException {
            Writer w = new OutputStreamWriter(out, charset);
            c.writeTo(w);
            w.flush();
            w.close();
        }
    });
    return this;
}
 
Example #10
Source Project: nifi   Author: apache   File: GroovySessionFile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Append the existing content of the flow file through Writer with defined charset.
 *
 * @param charset charset to use for writer
 * @param c       content to append.
 * @return reference to self
 */
public GroovySessionFile append(String charset, Writable c) {
    this.append(new OutputStreamCallback() {
        public void process(OutputStream out) throws IOException {
            Writer w = new OutputStreamWriter(out, charset);
            c.writeTo(w);
            w.flush();
            w.close();
        }
    });
    return this;
}
 
Example #11
Source Project: jbake   Author: jbake-org   File: GroovyTemplateEngine.java    License: MIT License 5 votes vote down vote up
@Override
public void renderDocument(final Map<String, Object> model, final String templateName, final Writer writer) throws RenderingException {
    try {
        Template template = findTemplate(templateName);
        Writable writable = template.make(wrap(model));
        writable.writeTo(writer);
    } catch (Exception e) {
        throw new RenderingException(e);
    }
}
 
Example #12
Source Project: jbake   Author: jbake-org   File: GroovyMarkupTemplateEngine.java    License: MIT License 5 votes vote down vote up
@Override
public void renderDocument(final Map<String, Object> model, final String templateName, final Writer writer) throws RenderingException {
    try {
        Template template = templateEngine.createTemplateByPath(templateName);
        Map<String, Object> wrappedModel = wrap(model);
        Writable writable = template.make(wrappedModel);
        writable.writeTo(writer);
    } catch (Exception e) {
        throw new RenderingException(e);
    }
}
 
Example #13
Source Project: myexcel   Author: liaochong   File: GroovyTemplateHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected <F> void render(Map<String, F> renderData, Writer out) throws Exception {
    Writable output = templateEngine.make(renderData);
    output.writeTo(out);
}
 
Example #14
Source Project: mdw   Author: CenturyLinkCloud   File: XmlBuilder.java    License: Apache License 2.0 4 votes vote down vote up
public Object call(Closure<?> closure) {
    result = (Writable) bind(closure);
    return result;
}
 
Example #15
Source Project: cuba   Author: cuba-platform   File: CubaApplicationServlet.java    License: Apache License 2.0 4 votes vote down vote up
protected String prepareErrorHtml(HttpServletRequest req, Throwable exception) {
    Messages messages = AppBeans.get(Messages.NAME);
    Configuration configuration = AppBeans.get(Configuration.NAME);

    WebConfig webConfig = configuration.getConfig(WebConfig.class);
    GlobalConfig globalConfig = configuration.getConfig(GlobalConfig.class);

    // SimpleTemplateEngine requires mutable map
    Map<String, Object> binding = new HashMap<>();
    binding.put("tryAgainUrl", "?restartApp");
    binding.put("productionMode", webConfig.getProductionMode());
    binding.put("messages", messages);
    binding.put("exception", exception);
    binding.put("exceptionName", exception.getClass().getName());
    binding.put("exceptionMessage", exception.getMessage());
    binding.put("exceptionStackTrace", ExceptionUtils.getStackTrace(exception));

    Locale locale = resolveLocale(req, messages, globalConfig);

    String serverErrorPageTemplatePath = webConfig.getServerErrorPageTemplate();

    String localeString = messages.getTools().localeToString(locale);
    String templateContent = getLocalizedTemplateContent(resources, serverErrorPageTemplatePath, localeString);
    if (templateContent == null) {
        templateContent = resources.getResourceAsString(serverErrorPageTemplatePath);

        if (templateContent == null) {
            throw new IllegalStateException("Unable to find server error page template " + serverErrorPageTemplatePath);
        }
    }

    SimpleTemplateEngine templateEngine = new SimpleTemplateEngine(getServletContext().getClassLoader());
    Template template = getTemplate(templateEngine, templateContent);

    Writable writable = template.make(binding);

    String html;
    try {
        html = writable.writeTo(new StringWriter()).toString();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write server error page", e);
    }

    return html;
}
 
Example #16
Source Project: groovy   Author: apache   File: StreamingJsonBuilder.java    License: Apache License 2.0 4 votes vote down vote up
public Object invokeMethod(String name, Object args) {
    if (args != null && Object[].class.isAssignableFrom(args.getClass())) {
        try {
            Object[] arr = (Object[]) args;

            final int len = arr.length;
            switch (len) {
                case 1:
                    final Object value = arr[0];
                    if(value instanceof Closure) {
                        call(name, (Closure)value);
                    }
                    else if(value instanceof Writable) {
                        call(name, (Writable)value);
                    }
                    else {
                        call(name, value);
                    }
                    return null;
                case 2:
                    if(arr[len -1] instanceof Closure) {
                        final Object obj = arr[0];
                        final Closure callable = (Closure) arr[1];
                        if(obj instanceof Iterable) {
                            call(name, (Iterable)obj, callable);
                            return null;
                        }
                        else if(obj.getClass().isArray()) {
                            call(name, Arrays.asList( (Object[])obj), callable);
                            return null;
                        }
                        else {
                            call(name, obj, callable);
                            return null;
                        }
                    }
                default:
                    final List<Object> list = Arrays.asList(arr);
                    call(name, list);

            }
        } catch (IOException ioe) {
            throw new JsonException(ioe);
        }
    }

    return this;
}
 
Example #17
Source Project: groovy   Author: apache   File: GStringTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make() {
    return make(null);
}
 
Example #18
Source Project: groovy   Author: apache   File: GStringTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make(final Map map) {
    final Closure template = ((Closure) this.template.clone()).asWritable();
    Binding binding = new Binding(map);
    template.setDelegate(binding);
    return (Writable) template;
}
 
Example #19
Source Project: groovy   Author: apache   File: MarkupTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make() {
    return make(Collections.emptyMap());
}
 
Example #20
Source Project: groovy   Author: apache   File: MarkupTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make(final Map binding) {
    return DefaultGroovyMethods.newInstance(templateClass, new Object[]{MarkupTemplateEngine.this, binding, modeltypes, templateConfiguration});
}
 
Example #21
Source Project: groovy   Author: apache   File: SimpleTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make() {
    return make(null);
}
 
Example #22
Source Project: groovy   Author: apache   File: XmlTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make() {
    return make(new HashMap());
}
 
Example #23
Source Project: groovy   Author: apache   File: XmlTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
public Writable make(Map map) {
    if (map == null) {
        throw new IllegalArgumentException("map must not be null");
    }
    return new XmlWritable(script, new Binding(map));
}
 
Example #24
Source Project: groovy   Author: apache   File: StreamingTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Writable make() {
    return make(null);
}
 
Example #25
Source Project: groovy   Author: apache   File: StreamingTemplateEngine.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Writable make(final Map map) {
    //we don't need a template.clone here as curry calls clone under the hood
    final Closure template = this.template.curry(new Object[]{map});
    return (Writable) template;
}
 
Example #26
Source Project: groovy   Author: apache   File: NioExtensions.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Converts this Path to a {@link groovy.lang.Writable} or delegates to default
 * {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#asType(Object, Class)}.
 *
 * @param path a Path
 * @param c    the desired class
 * @return the converted object
 * @since 2.3.0
 */
@SuppressWarnings("unchecked")
public static <T> T asType(Path path, Class<T> c) {
    if (c == Writable.class) {
        return (T) asWritable(path);
    }
    return DefaultGroovyMethods.asType((Object) path, c);
}
 
Example #27
Source Project: groovy   Author: apache   File: ResourceGroovyMethods.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Converts this File to a {@link groovy.lang.Writable} or delegates to default
 * {@link DefaultGroovyMethods#asType(java.lang.Object, java.lang.Class)}.
 *
 * @param f a File
 * @param c the desired class
 * @return the converted object
 * @since 1.0
 */
@SuppressWarnings("unchecked")
public static <T> T asType(File f, Class<T> c) {
    if (c == Writable.class) {
        return (T) asWritable(f);
    }
    return DefaultGroovyMethods.asType((Object) f, c);
}
 
Example #28
Source Project: groovy   Author: apache   File: NioExtensions.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Filters the lines of a Path and creates a Writable in return to
 * stream the filtered lines.
 *
 * @param self    a Path
 * @param closure a closure which returns a boolean indicating to filter
 *                the line or not
 * @return a Writable closure
 * @throws java.io.IOException if <code>self</code> is not readable
 * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure)
 * @since 2.3.0
 */
public static Writable filterLine(Path self, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
    return IOGroovyMethods.filterLine(newReader(self), closure);
}
 
Example #29
Source Project: groovy   Author: apache   File: NioExtensions.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Filters the lines of a Path and creates a Writable in return to
 * stream the filtered lines.
 *
 * @param self    a Path
 * @param charset opens the file with a specified charset
 * @param closure a closure which returns a boolean indicating to filter
 *                the line or not
 * @return a Writable closure
 * @throws java.io.IOException if an IOException occurs
 * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure)
 * @since 2.3.0
 */
public static Writable filterLine(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
    return IOGroovyMethods.filterLine(newReader(self, charset), closure);
}
 
Example #30
Source Project: groovy   Author: apache   File: XmlUtil.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return a pretty String version of the XML content produced by the Writable.
 *
 * @param writable the Writable to serialize
 * @return the pretty String representation of the content from the Writable
 */
public static String serialize(Writable writable) {
    return serialize(asString(writable));
}