org.stringtemplate.v4.ST Java Examples
The following examples show how to use
org.stringtemplate.v4.ST.
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 File: ObjectModelAdaptor.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
@Override public synchronized Object getProperty(Interpreter interp, ST self, Object o, Object property, String propertyName) throws STNoSuchPropertyException { if ( o==null ) { throw new NullPointerException("o"); } Class<?> c = o.getClass(); if ( property==null ) { return throwNoSuchProperty(c, propertyName, null); } Member member = findMember(c, propertyName); if ( member!=null ) { try { if ( member instanceof Method ) { return ((Method)member).invoke(o); } else if ( member instanceof Field ) { return ((Field)member).get(o); } } catch (Exception e) { throwNoSuchProperty(c, propertyName, e); } } return throwNoSuchProperty(c, propertyName, null); }
Example #2
Source File: ShExGenerator.java From org.hl7.fhir.core with Apache License 2.0 | 6 votes |
/** * Generate a definition for a referenced element * @param sd Containing structure definition * @param ed Inner element * @return ShEx representation of element reference */ private String genInnerTypeDef(StructureDefinition sd, ElementDefinition ed) { String path = ed.hasBase() ? ed.getBase().getPath() : ed.getPath();; ST element_reference = tmplt(SHAPE_DEFINITION_TEMPLATE); element_reference.add("resourceDecl", ""); // Not a resource element_reference.add("id", path); String comment = ed.getShort(); element_reference.add("comment", comment == null? " " : "# " + comment); List<String> elements = new ArrayList<String>(); for (ElementDefinition child: profileUtilities.getChildList(sd, path, null)) elements.add(genElementDefinition(sd, child)); element_reference.add("elements", StringUtils.join(elements, "\n")); return element_reference.render(); }
Example #3
Source File: CodeGenerator.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
public void write(ST code, String fileName) { try { // long start = System.currentTimeMillis(); Writer w = tool.getOutputFileWriter(g, fileName); STWriter wr = new AutoIndentWriter(w); wr.setLineWidth(lineWidth); code.write(wr); w.close(); // long stop = System.currentTimeMillis(); } catch (IOException ioe) { tool.errMgr.toolError(ErrorType.CANNOT_WRITE_FILE, ioe, fileName); } }
Example #4
Source File: MapModelAdaptor.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
@Override public Object getProperty(Interpreter interp, ST self, Object o, Object property, String propertyName) throws STNoSuchPropertyException { Object value; Map<?, ?> map = (Map<?, ?>)o; if ( property==null ) value = map.get(STGroup.DEFAULT_KEY); else if ( property.equals("keys") ) value = map.keySet(); else if ( property.equals("values") ) value = map.values(); else if ( map.containsKey(property) ) value = map.get(property); else if ( map.containsKey(propertyName) ) { // if can't find the key, try toString version value = map.get(propertyName); } else value = map.get(STGroup.DEFAULT_KEY); // not found, use default if ( value==STGroup.DICT_KEY ) { value = property; } return value; }
Example #5
Source File: CodeGeneratingVisitor.java From compiler with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override public void visit(final Block n) { final ST st = stg.getInstanceOf("Block"); final List<String> statements = new ArrayList<String>(); for (final Node node : n.getStatements()) { node.accept(this); final String statement = code.removeLast(); if (!statement.isEmpty()) statements.add(statement); } st.add("statements", statements); code.add(st.render()); }
Example #6
Source File: PySnippetExecutor.java From bookish with MIT License | 6 votes |
public void execSnippets(ChapDocInfo doc) { String basename = doc.getSourceBaseName(); MultiMap<String, ExecutableCodeDef> labelToDefs = collectSnippetsByLabel(doc); // for each group of code with same label, create executable py file for (String label : labelToDefs.keySet()) { List<ExecutableCodeDef> defs = (List<ExecutableCodeDef>)labelToDefs.get(label); List<ST> snippets = getSnippetTemplates(doc, label, pycodeTemplates, defs); ST file = pycodeTemplates.getInstanceOf("pyfile"); file.add("snippets", snippets); file.add("buildDir", tool.getBuildDir()); file.add("outputDir", tool.outputDir); file.add("basename", basename); file.add("label", label); String pycode = file.render(); execAndSaveOutput(doc, label, pycode); } }
Example #7
Source File: CodeGeneratingVisitor.java From compiler with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override public void visit(final FixPExpression n) { final ST st = stg.getInstanceOf("FixP"); this.varDecl.start(n); st.add("staticDeclarations", this.varDecl.getCode()); final List<String> body = new ArrayList<String>(); for (final Node node : n.getBody().getStatements()) { node.accept(this); body.add(code.removeLast()); } st.add("body", body); code.add(st.render()); }
Example #8
Source File: BenderConfig.java From bender with Apache License 2.0 | 6 votes |
/** * Parses an input String and replaces instances of {@literal <XXX>}" with the value of the XXX OS * Environment Variable. This is used as a pre-parser for the Config files, allowing environment * variables to be swapped at run-time. * * @param raw A raw string (not necessarily valid configuration data) * @return A parsed string with OS variables swapped in * @throws ConfigurationException If any discovered {@literal <WRAPPED_VALUES>} are not found in * System.getenv(). */ public static String swapEnvironmentVariables(String raw) throws ConfigurationException { ErrorBuffer errors = new ErrorBuffer(); ST template = new ST(raw); STGroup g = template.groupThatCreatedThisInstance; g.setListener(errors); Map<String, String> env = System.getenv(); for (String envName : env.keySet()) { if (envName.contains(".")) { logger.warn("skipping " + envName + " because it contains '.' which is not allowed"); continue; } template.add(envName, env.get(envName)); } String parsed = template.render(); if (errors.errors.size() > 0) { throw new ConfigurationException(errors.toString()); } return parsed; }
Example #9
Source File: Trans.java From cs652 with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static void main(String[] args) { String code = "int x;\n" + "A b;\n"; ANTLRInputStream input = new ANTLRInputStream(code); LangLexer lexer = new LangLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); LangParser parser = new LangParser(tokens); ParseTree tree = parser.file(); // start up System.out.println(tree.toStringTree(parser)); ParseTreeWalker walker = new ParseTreeWalker(); Gen listener = new Gen(); walker.walk(listener, tree); ST output = listener.file.getTemplate(); System.out.println(output.render()); }
Example #10
Source File: DocGenerator.java From fix-orchestra with Apache License 2.0 | 6 votes |
private void generateGroupDetail(final Path messagesDocPath, final GroupType group) throws Exception { final ST stGroupStart; stGroupStart = stGroup.getInstanceOf("groupStart"); stGroupStart.add("groupType", group); final FieldType field = getField(group.getNumInGroup().getId().intValue()); stGroupStart.add("fieldType", field); final ST stComponentEnd = stGroup.getInstanceOf("componentEnd"); final List<Object> members = group.getComponentRefOrGroupRefOrFieldRef(); final Path path = messagesDocPath.resolve(String.format("%s-%s.html", group.getName(), group.getScenario())); try (final STWriterWrapper writer = getWriter(path)) { stGroupStart.write(writer, templateErrorListener); generateMembers(members, writer); stComponentEnd.write(writer, templateErrorListener); } }
Example #11
Source File: JTreeScopeStackModel.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public void addAttributeDescriptions(ST st, StringTree node, Set<String> names) { Map<String, Object> attrs = st.getAttributes(); if ( attrs==null ) return; for (String a : attrs.keySet()) { String descr; if ( st.debugState!=null && st.debugState.addAttrEvents!=null ) { List<AddAttributeEvent> events = st.debugState.addAttrEvents.get(a); StringBuilder locations = new StringBuilder(); int i = 0; if ( events!=null ) { for (AddAttributeEvent ae : events) { if ( i>0 ) locations.append(", "); locations.append(ae.getFileName()+":"+ae.getLine()); i++; } } if ( locations.length()>0 ) { descr = a+" = "+attrs.get(a)+" @ "+locations.toString(); } else { descr = a + " = " +attrs.get(a); } } else { descr = a + " = " +attrs.get(a); } if (!names.add(a)) { StringBuilder builder = new StringBuilder(); builder.append("<html><font color=\"gray\">"); builder.append(StringRenderer.escapeHTML(descr)); builder.append("</font></html>"); descr = builder.toString(); } node.addChild( new StringTree(descr) ); } }
Example #12
Source File: CodeGeneratingVisitor.java From compiler with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public void visit(final Pair n) { super.visit(n); final ST st = stg.getInstanceOf("Pair"); st.add("map", n.env.getId()); st.add("value", code.removeLast()); st.add("key", code.removeLast()); code.add(st.render()); }
Example #13
Source File: Utils.java From AudioBookConverter with GNU General Public License v2.0 | 5 votes |
public static String renderPart(Part part, Map<String, Function<Part, Object>> context) { String partFormat = AppProperties.getProperty("part_format"); if (partFormat == null) { partFormat = "<if(WRITER)><WRITER> <endif>" + "<if(SERIES)>- [<SERIES><if(BOOK_NUMBER)> -<BOOK_NUMBER><endif>] - <endif>" + "<if(TITLE)><TITLE><endif>" + "<if(NARRATOR)> (<NARRATOR>)<endif>" + "<if(YEAR)>-<YEAR><endif>" + "<if(PART)>, Part <PART><endif>"; AppProperties.setProperty("part_format", partFormat); } ST partTemplate = new ST(partFormat); context.forEach((key, value) -> { partTemplate.add(key, value.apply(part)); }); String result = partTemplate.render(); char[] toRemove = new char[]{':', '\\', '/', '>', '<', '|', '?', '*', '"'}; for (char c : toRemove) { result = StringUtils.remove(result, c); } String mp3Filename; if (StringUtils.isBlank(result)) { mp3Filename = "NewBook"; } else { mp3Filename = result; } return mp3Filename; }
Example #14
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static void test4() throws IOException { String templates = "main(t) ::= <<\n"+"hi: <t>\n"+">>\n"+"foo(x,y={hi}) ::= \"<bar(x,y)>\"\n"+"bar(x,y) ::= << <y> >>\n"+"ignore(m) ::= \"<m>\"\n"; STGroup group = new STGroupString(templates); ST st = group.getInstanceOf("main"); ST foo = group.getInstanceOf("foo"); st.add("t", foo); ST ignore = group.getInstanceOf("ignore"); ignore.add("m", foo); // embed foo twice! st.inspect(); st.render(); }
Example #15
Source File: ObjectModelAdaptor.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public synchronized Object getProperty(Interpreter interp, ST self, Object o, Object property, String propertyName) throws STNoSuchPropertyException { if (o == null) { throw new NullPointerException("o"); } Class<?> c = o.getClass(); if ( property==null ) { return throwNoSuchProperty(c, propertyName, null); } Member member = findMember(c, propertyName); if ( member!=null ) { try { if (member instanceof Method) { return ((Method)member).invoke(o); } else if (member instanceof Field) { return ((Field)member).get(o); } } catch (Exception e) { throwNoSuchProperty(c, propertyName, e); } } return throwNoSuchProperty(c, propertyName, null); }
Example #16
Source File: DefaultToolListener.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public void warning(ANTLRMessage msg) { ST msgST = tool.errMgr.getMessageTemplate(msg); String outputMsg = msgST.render(); if (tool.errMgr.formatWantsSingleLineMessage()) { outputMsg = outputMsg.replace('\n', ' '); } System.err.println(outputMsg); }
Example #17
Source File: BuildDependencyGenerator.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public ST getDependencies() { loadDependencyTemplates(); ST dependenciesST = templates.getInstanceOf("dependencies"); dependenciesST.add("in", getDependenciesFileList()); dependenciesST.add("out", getGeneratedFileList()); dependenciesST.add("grammarFileName", g.fileName); return dependenciesST; }
Example #18
Source File: GenDOT.java From cs652 with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static String gen(LinkViz graph) { STGroup templates = new STGroupFile("DOT.stg"); ST fileST = templates.getInstanceOf("file"); fileST.add("gname", "testgraph"); for (LinkViz.Link x : graph.links) { ST edgeST = templates.getInstanceOf("edge"); edgeST.add("from", x.from); edgeST.add("to", x.to); fileST.add("edges", edgeST); } return fileST.render(); // render (eval) template to text }
Example #19
Source File: JTreeScopeStackModel.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public void addAttributeDescriptions(ST st, StringTree node, Set<String> names) { Map<String, Object> attrs = st.getAttributes(); if ( attrs==null ) return; for (String a : attrs.keySet()) { String descr; if ( st.debugState!=null && st.debugState.addAttrEvents!=null ) { List<AddAttributeEvent> events = st.debugState.addAttrEvents.get(a); StringBuilder locations = new StringBuilder(); int i = 0; if ( events!=null ) { for (AddAttributeEvent ae : events) { if ( i>0 ) locations.append(", "); locations.append(ae.getFileName()+":"+ae.getLine()); i++; } } if ( locations.length()>0 ) { descr = a+" = "+attrs.get(a)+" @ "+locations.toString(); } else { descr = a+" = "+attrs.get(a); } } else { descr = a+" = "+attrs.get(a); } if ( !names.add(a) ) { StringBuilder builder = new StringBuilder(); builder.append("<html><font color=\"gray\">"); builder.append(StringRenderer.escapeHTML(descr)); builder.append("</font></html>"); descr = builder.toString(); } node.addChild(new StringTree(descr)); } }
Example #20
Source File: GenerateSinglePatternMatcherBenchmarkTest.java From stringbench with Apache License 2.0 | 5 votes |
public static void generate(String pkg, String algorithm) throws IOException { ST st = new ST(new String(Files.readAllBytes(Paths.get("src/test/resources/TemplateSinglePatternMatcherBenchmarkTest.java")), StandardCharsets.UTF_8)); st.add("pkg", pkg); st.add("algorithm", algorithm); String text = st.render(); Path dir = Paths.get("src/test/java/com/almondtools/stringbench/singlepattern",pkg); Files.createDirectories(dir); Files.write(dir.resolve(algorithm + "BenchmarkTest.java"), text.getBytes(StandardCharsets.UTF_8)); }
Example #21
Source File: PySnippetExecutor.java From bookish with MIT License | 5 votes |
public List<ST> getSnippetTemplates(ChapDocInfo doc, String label, STGroup pycodeTemplates, List<ExecutableCodeDef> defs) { List<ST> snippets = new ArrayList<>(); for (ExecutableCodeDef def : defs) { // avoid generating output for disable=true snippets if output available String basename = doc.getSourceBaseName(); String snippetsDir = tool.getBuildDir()+"/snippets"; String chapterSnippetsDir = snippetsDir+"/"+basename; String errFilename = chapterSnippetsDir+"/"+basename+"_"+label+"_"+def.index+".err"; String outFilename = chapterSnippetsDir+"/"+basename+"_"+label+"_"+def.index+".out"; if ( ((new File(errFilename)).exists()&&(new File(outFilename)).exists()) && !def.isEnabled ) { continue; } String tname = def.isOutputVisible ? "pyeval" : "pyfig"; ST snippet = pycodeTemplates.getInstanceOf(tname); snippet.add("def",def); // Don't allow "plt.show()" to execute, strip it String code = null; if ( def.code!=null ) { code = def.code.replace("plt.show()", ""); } if ( code!=null && code.trim().length()==0 ) { code = null; } code = HTMLEscaper.stripBangs(code); snippet.add("code", code); snippets.add(snippet); } return snippets; }
Example #22
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static void test3() throws IOException { String templates = "main() ::= <<\n"+"Foo: <{bar};format=\"lower\">\n"+">>\n"; String tmpdir = System.getProperty("java.io.tmpdir"); writeFile(tmpdir, "t.stg", templates); STGroup group = new STGroupFile(tmpdir+"/"+"t.stg"); ST st = group.getInstanceOf("main"); st.inspect(); }
Example #23
Source File: StateGenerator.java From fix-orchestra with Apache License 2.0 | 5 votes |
private void generateStatesEnum(StateMachineType stateMachine) throws Exception { String name = stateMachine.getName(); try ( final STWriterWrapper writer = getWriter(srcPath.resolve(String.format("%s.java", name)))) { final ST stInterface = stGroup.getInstanceOf("state_enum"); stInterface.add("stateMachine", stateMachine); stInterface.add("package", this.srcPackage); stInterface.write(writer, templateErrorListener); } }
Example #24
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static void test2() throws IOException { // test rig String templates = "t1(q1=\"Some\\nText\") ::= <<\n"+ "<q1>\n" +">>\n"+"\n"+"t2(p1) ::= <<\n"+ "<p1>\n"+ ">>\n"+ "\n"+ "main() ::= <<\n" +"START-<t1()>-END\n"+"\n"+"START-<t2(p1=\"Some\\nText\")>-END\n"+">>\n"; String tmpdir = System.getProperty("java.io.tmpdir"); writeFile(tmpdir, "t.stg", templates); STGroup group = new STGroupFile(tmpdir+"/"+"t.stg"); ST st = group.getInstanceOf("main"); STViz viz = st.inspect(); }
Example #25
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
protected void updateStack(InstanceScope scope, STViewFrame m) { List<ST> stack = Interpreter.getEnclosingInstanceStack(scope, true); m.setTitle("STViz - ["+Misc.join(stack.iterator(), " ")+"]"); // // also do source stack // StackTraceElement[] trace = st.newSTEvent.stack.getStackTrace(); // StringWriter sw = new StringWriter(); // for (StackTraceElement e : trace) { // sw.write(e.toString()+"\n"); // } }
Example #26
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static void test4() throws IOException { String templates = "main(t) ::= <<\n"+"hi: <t>\n"+">>\n"+"foo(x,y={hi}) ::= \"<bar(x,y)>\"\n"+"bar(x,y) ::= << <y> >>\n"+"ignore(m) ::= \"<m>\"\n"; STGroup group = new STGroupString(templates); ST st = group.getInstanceOf("main"); ST foo = group.getInstanceOf("foo"); st.add("t", foo); ST ignore = group.getInstanceOf("ignore"); ignore.add("m", foo); // embed foo twice! st.inspect(); st.render(); }
Example #27
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static void test2() throws IOException { // test rig String templates = "t1(q1=\"Some\\nText\") ::= <<\n"+ "<q1>\n" +">>\n"+"\n"+"t2(p1) ::= <<\n"+ "<p1>\n"+ ">>\n"+ "\n"+ "main() ::= <<\n" +"START-<t1()>-END\n"+"\n"+"START-<t2(p1=\"Some\\nText\")>-END\n"+">>\n"; String tmpdir = System.getProperty("java.io.tmpdir"); writeFile(tmpdir, "t.stg", templates); STGroup group = new STGroupFile(tmpdir+"/"+"t.stg"); ST st = group.getInstanceOf("main"); STViz viz = st.inspect(); }
Example #28
Source File: Page.java From cs601 with BSD 3-Clause "New" or "Revised" License | 5 votes |
public void generate() { ST pageST = templates.getInstanceOf("page"); ST bodyST = generateBody(); pageST.add("body", bodyST); pageST.add("title", getTitle()); pageST.inspect(); System.out.println(pageST); }
Example #29
Source File: Compiler.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static CompiledST defineBlankRegion(CompiledST outermostImpl, Token nameToken) { String outermostTemplateName = outermostImpl.name; String mangled = STGroup.getMangledRegionName(outermostTemplateName, nameToken.getText()); CompiledST blank = new CompiledST(); blank.isRegion = true; blank.templateDefStartToken = nameToken; blank.regionDefType = ST.RegionType.IMPLICIT; blank.name = mangled; outermostImpl.addImplicitlyDefinedTemplate(blank); return blank; }
Example #30
Source File: STViz.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static void test2() throws IOException { // test rig String templates = "t1(q1=\"Some\\nText\") ::= <<\n"+"<q1>\n"+">>\n"+"\n"+"t2(p1) ::= <<\n"+"<p1>\n"+">>\n"+"\n"+"main() ::= <<\n"+"START-<t1()>-END\n"+"\n"+"START-<t2(p1=\"Some\\nText\")>-END\n"+">>\n"; String tmpdir = System.getProperty("java.io.tmpdir"); writeFile(tmpdir, "t.stg", templates); STGroup group = new STGroupFile(tmpdir+"/"+"t.stg"); ST st = group.getInstanceOf("main"); STViz viz = st.inspect(); }