public static String generateScript(GroovyMap groovyMap, String templateName) throws GFacException { URL templateUrl = ApplicationSettings.loadFile(templateName); if (templateUrl == null) { String error = "Template file '" + templateName + "' not found"; throw new GFacException(error); } File template = new File(templateUrl.getPath()); TemplateEngine engine = new GStringTemplateEngine(); Writable make; try { make = engine.createTemplate(template).make(groovyMap); } catch (Exception e) { throw new GFacException("Error while generating script using groovy map", e); } return make.toString(); }
@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); } }
@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); } }
public static String template(TemplateEngine engine, String name, Map<String, ?> model) throws IOException, CompilationFailedException, ClassNotFoundException { Writable writable = getTemplate(engine, name).make(model); StringWriter result = new StringWriter(); writable.writeTo(result); return result.toString(); }
public static String generateModuleCodeFromTemplate(String moduleName, String codeTemplate) { try { Map bindings = new HashMap(); bindings.put("moduleName", moduleName); SimpleTemplateEngine simpleTemplateEngine = new SimpleTemplateEngine(); Template template = simpleTemplateEngine.createTemplate(codeTemplate); Writable writable = template.make(bindings); String finalScript = writable.toString(); return finalScript; } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } return null; }
public static String fillTemplate(String templateString, Map bindings) throws RuntimeException { try { SimpleTemplateEngine simpleTemplateEngine = new SimpleTemplateEngine(); Template template = simpleTemplateEngine.createTemplate(templateString); Writable writable = template.make(bindings); String finalScript = writable.toString(); return finalScript; } catch (CompilationFailedException | ClassNotFoundException | IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage()); } }
/** * 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); } }
public Writable make(final Map map) { return new Writable() { /** * Write the template document with the set binding applied to the writer. * * @see groovy.lang.Writable#writeTo(java.io.Writer) */ public Writer writeTo(Writer writer) { Binding binding; if (map == null) binding = new Binding(); else binding = new Binding(map); Script scriptObject = InvokerHelper.createScript(script.getClass(), binding); PrintWriter pw = new PrintWriter(writer); scriptObject.setProperty("out", pw); scriptObject.run(); pw.flush(); return writer; } /** * Convert the template and binding into a result String. * * @see java.lang.Object#toString() */ public String toString() { Writer sw = new StringBuilderWriter(); writeTo(sw); return sw.toString(); } }; }
private static String asString(GPathResult node) { // little bit of hackery to avoid Groovy dependency in this file try { Object builder = ((Class) Class.forName("groovy.xml.StreamingMarkupBuilder")).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(); } }
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(); }
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); } }
/** * 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 (int i = 0; i < data.length; i++) { // convert byte into unsigned hex string String hexString = Integer.toHexString(data[i] & 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(); } }; }
/** * 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(); } }; }
/** * Writes an object to a Writer using Groovy's default representation for the object. */ public static void write(Writer out, Object object) throws IOException { if (object instanceof String) { out.write((String) object); } else if (object instanceof Object[]) { out.write(toArrayString((Object[]) object)); } else if (object instanceof Map) { out.write(toMapString((Map) object)); } else if (object instanceof Collection) { out.write(toListString((Collection) object)); } else if (object instanceof Writable) { Writable writable = (Writable) object; writable.writeTo(out); } else if (object instanceof InputStream || object instanceof Reader) { // Copy stream to stream Reader reader; if (object instanceof InputStream) { reader = new InputStreamReader((InputStream) object); } else { reader = (Reader) object; } char[] chars = new char[8192]; int i; while ((i = reader.read(chars)) != -1) { out.write(chars, 0, i); } reader.close(); } else { out.write(toString(object)); } }
/** * 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 Reader reader; if (object instanceof InputStream) { reader = new InputStreamReader((InputStream) object); } else { reader = (Reader) object; } char[] chars = new char[8192]; int i; while ((i = reader.read(chars)) != -1) { for (int j = 0; j < i; j++) { out.append(chars[j]); } } reader.close(); } else { out.append(toString(object)); } }
@Override public void evaluate(Writer output, Map<String, Object> binding) throws GrafikonException { if (templateGString == null) { initialize(); } Writable result = templateGString.make(binding); try { result.writeTo(output); output.flush(); } catch (IOException e) { throw new GrafikonException("Error writing output.", e); } }
/** * Sends data to the HL7 recipient. Template data, recipient name and template name are in the parameters map. * * @param parameters the parameters map * @throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException when cannot generate data * @throws TemplateNotFoundException when a template does not exist in database * @throws RecipientNotFoundException when a recipient does not exist * from xml template or when template is incorrect */ @Transactional public void handleAction(Map<String, Object> parameters) throws IOException, ClassNotFoundException, ParserConfigurationException, SAXException { String templateName = (String) parameters.get(Constants.TEMPLATE_NAME_PARAM); String recipientName = (String) parameters.get(Constants.RECIPIENT_NAME_PARAM); CdaTemplate cdaTemplate = iheTemplateDataService.findByName(templateName); if (cdaTemplate == null) { LOGGER.error("Cannot find {} template", templateName); throw new TemplateNotFoundException(templateName); } HL7Recipient hl7Recipient = hl7RecipientsService.getRecipientbyName(recipientName); if (hl7Recipient == null) { LOGGER.error("Cannot find {} recipient", recipientName); throw new RecipientNotFoundException(templateName); } Byte[] templateData = (Byte[]) iheTemplateDataService.getDetachedField(cdaTemplate, TEMPLATE_DATA_FIELD_NAME); StreamingTemplateEngine streamingTemplateEngine = new StreamingTemplateEngine(); Template template = streamingTemplateEngine.createTemplate(new String(ArrayUtils.toPrimitive(templateData))); Writable writable = template.make(parameters); LOGGER.info("Template with name {}:\n{}", cdaTemplate.getTemplateName(), writable.toString()); if (hl7Recipient.getRecipientUsername() != null && hl7Recipient.getRecipientPassword() != null) { iheTemplateService.sendTemplateToRecipientUrlWithBasicAuthentication(hl7Recipient, writable.toString()); } else { iheTemplateService.sendTemplateToRecipientUrl(hl7Recipient.getRecipientUrl(), writable.toString()); } }
private static ArrayList<String> process(File template_file, HashMap<String, Object> all_mail_vars) throws IOException, CompilationFailedException, ClassNotFoundException { Template template = template_engine.createTemplate(template_file); Writable writable = template.make(all_mail_vars); TemplateWriter tw = new TemplateWriter(); writable.writeTo(tw); return tw.getContent(); }
public static void main(String... args) throws ClassNotFoundException, IOException { Method[] methodDeclarations = Class.forName("com.github.timofeevda.gwt.rxjs.interop.observable.Observable") .getDeclaredMethods(); Set<String> importsSet = generateImportsSet(methodDeclarations); List<GeneratedMethodDefinition> generatedMethodDefinitions = generateMethodsDefintions(methodDeclarations); SimpleTemplateEngine templateEngine = new SimpleTemplateEngine(); InputStream templateStream = MethodDefinitionsTestsGenerator.class.getResourceAsStream("/definitions.template"); Map<String, Object> templateBindings = new HashMap<>(); templateBindings.put("methods", generatedMethodDefinitions); templateBindings.put("importsSet", importsSet); File destinationFile = new File(args[0]); destinationFile.mkdirs(); File testDefinitonsFile = new File(args[0] + File.separator + "MethodsDefinitionsTest.java"); testDefinitonsFile.createNewFile(); Writable writable = templateEngine.createTemplate(new BufferedReader(new InputStreamReader(templateStream))).make(templateBindings); writable.writeTo(new PrintWriter(new FileOutputStream(testDefinitonsFile))); }
public Object call(Closure<?> closure) { result = (Writable) bind(closure); return result; }
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; }
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; }
public Writable make() { return make(null); }
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; }
public Writable make() { return make(Collections.emptyMap()); }
public Writable make(final Map binding) { return DefaultGroovyMethods.newInstance(templateClass, new Object[]{MarkupTemplateEngine.this, binding, modeltypes, templateConfiguration}); }
public Writable make() { return make(new HashMap()); }
public Writable make(Map map) { if (map == null) { throw new IllegalArgumentException("map must not be null"); } return new XmlWritable(script, new Binding(map)); }
@Override public Writable make() { return make(null); }
@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; }
@Deprecated public static void write(Writer self, Writable writable) throws IOException { IOGroovyMethods.write(self, writable); }
@Deprecated public static Writable filterLine(File self, Closure closure) throws IOException { return ResourceGroovyMethods.filterLine(self, closure); }
@Deprecated public static Writable filterLine(File self, String charset, Closure closure) throws IOException { return ResourceGroovyMethods.filterLine(self, closure); }
@Deprecated public static Writable filterLine(Reader reader, final Closure closure) { return IOGroovyMethods.filterLine(reader, closure); }
@Deprecated public static Writable filterLine(InputStream self, Closure predicate) { return IOGroovyMethods.filterLine(self, predicate); }