Java Code Examples for org.stringtemplate.v4.ST

The following examples show how to use org.stringtemplate.v4.ST. These examples are extracted from open source projects. 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
@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 Project: org.hl7.fhir.core   Source File: ShExGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: codebuff   Source File: CodeGenerator.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 Project: codebuff   Source File: MapModelAdaptor.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 Project: compiler   Source File: CodeGeneratingVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/** {@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 Project: bookish   Source File: PySnippetExecutor.java    License: MIT License 6 votes vote down vote up
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 Project: compiler   Source File: CodeGeneratingVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/** {@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 Project: bender   Source File: BenderConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: cs652   Source File: Trans.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 Project: fix-orchestra   Source File: DocGenerator.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: codebuff   Source File: STViz.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 12
Source Project: org.hl7.fhir.core   Source File: ShExGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate a reference to a resource
 * @param id attribute identifier
 * @param typ possible reference types
 * @return string that represents the result
 */
private String genReference(String id, ElementDefinition.TypeRefComponent typ) {
  ST shex_ref = tmplt(REFERENCE_DEFN_TEMPLATE);

  String ref = getTypeName(typ);
  shex_ref.add("id", id);
  shex_ref.add("ref", ref);
  references.add(ref);
  return shex_ref.render();
}
 
Example 13
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 14
Source Project: codebuff   Source File: ErrorManager.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ST getMessageTemplate(ANTLRMessage msg) {
		ST messageST = msg.getMessageTemplate(tool.longMessages);
		ST locationST = getLocationFormat();
		ST reportST = getReportFormat(msg.getErrorType().severity);
		ST messageFormatST = getMessageFormat();

		boolean locationValid = false;
		if (msg.line != -1) {
			locationST.add("line", msg.line);
			locationValid = true;
		}
		if (msg.charPosition != -1) {
			locationST.add("column", msg.charPosition);
			locationValid = true;
		}
		if (msg.fileName != null) {
			File f = new File(msg.fileName);
			// Don't show path to file in messages; too long.
			String displayFileName = msg.fileName;
			if ( f.exists() ) {
				displayFileName = f.getName();
			}
			locationST.add("file", displayFileName);
			locationValid = true;
		}

		messageFormatST.add("id", msg.getErrorType().code);
		messageFormatST.add("text", messageST);

		if (locationValid) reportST.add("location", locationST);
		reportST.add("message", messageFormatST);
		//((DebugST)reportST).inspect();
//		reportST.impl.dump();
		return reportST;
	}
 
Example 15
@Override
public void error(ANTLRMessage msg) {
	ST msgST = tool.errMgr.getMessageTemplate(msg);
       String s = msgST.render();
	if (tool.errMgr.formatWantsSingleLineMessage()) {
		s = s.replace('\n', ' ');
	}
       grammarErrorMessages.add(s);
}
 
Example 16
Source Project: cs601   Source File: UserListPage.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** This "controller" pulls from "model" and pushes to "view" */
public ST generateBody() {
	ST bodyST = templates.getInstanceOf("userlist");
	User[] list = users; // normally pull from database
	// filter list if you want here (not in template)
	bodyST.add("users", list);
	return bodyST;
}
 
Example 17
Source Project: org.hl7.fhir.core   Source File: ShExGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private String genValueSet(ValueSet vs) {
  ST vsd = tmplt(VALUE_SET_DEFINITION).add("vsuri", vsprefix(vs.getUrl())).add("comment", vs.getDescription());
  ValueSetExpander.ValueSetExpansionOutcome vse = context.expandVS(vs, true, false);
  List<String> valid_codes = new ArrayList<String>();
  if(vse != null &&
          vse.getValueset() != null &&
          vse.getValueset().hasExpansion() &&
          vse.getValueset().getExpansion().hasContains()) {
    for(ValueSet.ValueSetExpansionContainsComponent vsec : vse.getValueset().getExpansion().getContains())
      valid_codes.add("\"" + vsec.getCode() + "\"");
  }
  return vsd.add("val_list", valid_codes.size() > 0? " [" + StringUtils.join(valid_codes, " ") + ']' : " EXTERNAL").render();
}
 
Example 18
Source Project: buck   Source File: BuckModuleAdapterPluginGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void writePluginManifest() throws IOException {
  Writer writer = createResourceWriter();

  ST template =
      getStringTemplate(MANIFEST_TEMPLATE)
          .add("fullClassName", fullAdapterPluginClassName)
          .add("pluginDependencies", String.join(", ", buckModuleDescriptor.dependencies))
          .add("pluginId", buckModuleDescriptor.name);

  writeStringTemplateToWriter(writer, template);
}
 
Example 19
Source Project: org.hl7.fhir.core   Source File: ShExGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate a set of alternative shapes
 * @param ed Containing element definition
 * @param id Element definition identifier
 * @param shortId id to use in the actual definition
 * @return ShEx list of alternative anonymous shapes separated by "OR"
 */
private ST genAlternativeTypes(ElementDefinition ed, String id, String shortId) {
  ST shex_alt = tmplt(ALTERNATIVE_SHAPES_TEMPLATE);
  List<String> altEntries = new ArrayList<String>();


  for(ElementDefinition.TypeRefComponent typ : ed.getType())  {
    altEntries.add(genAltEntry(id, typ));
  }
  shex_alt.add("altEntries", StringUtils.join(altEntries, " OR\n    "));
  return shex_alt;
}
 
Example 20
Source Project: cs601   Source File: Fill.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
	String[] names = {"Terence", "Jim", "Ketaki", "Siddharth"};
	String[] phones = {"x1", "x9", "x2", "x5"};
	User[] users = {new User("Tom", "x99"), new User("Jane","x1")};

	STGroup group = new STGroupDir(".");
	ST st = group.getInstanceOf("fill");
	st.add("names", names);
	st.add("phones", phones);
	st.add("users", users);
	System.out.println(st.toString());
}
 
Example 21
Source Project: codebuff   Source File: STViz.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 22
Source Project: fix-orchestra   Source File: DocGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateAllComponentsList(final Path messagesDocPath, final List<ComponentType> componentList)
    throws Exception {
  final ST st = stGroup.getInstanceOf("components");
  st.add("components", componentList);
  st.add("title", "All Components");
  final Path path = messagesDocPath.resolve("AllComponents.html");
  try (final STWriterWrapper writer = getWriter(path)) {
    st.write(writer, templateErrorListener);
  }
}
 
Example 23
Source Project: codebuff   Source File: STViz.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 24
Source Project: org.hl7.fhir.core   Source File: ShExGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate a ShEx element definition
 * @param sd Containing structure definition
 * @param ed Containing element definition
 * @return ShEx definition
 */
private String genElementDefinition(StructureDefinition sd, ElementDefinition ed) {
  ST element_def =  tmplt(ELEMENT_TEMPLATE);

  String id = ed.hasBase() ? ed.getBase().getPath() : ed.getPath();
  String card = "*".equals(ed.getMax()) ? (ed.getMin() == 0 ? "*" : "+") : "?";
  String defn;
  element_def.add("id", id);
  element_def.add("card", card);
  
  List<ElementDefinition> children = ProfileUtilities.getChildList(sd, ed);
  if (children.size() > 0) {
    // inline anonymous type - give it a name and factor it out
    this.typeReferences.add(new ImmutablePair<StructureDefinition, ElementDefinition>(sd, ed));
    ST anon_link = tmplt(SIMPLE_ELEMENT_TEMPLATE);
    anon_link.add("typ", id);
    defn = anon_link.render();
  } else if (ed.getType().size() == 1) {
    // Single entry
    defn = genTypeRef(ed.getType().get(0));
  } else { 
    // multiple types
    // todo: figure out how to do this with the API
    if(id.endsWith("[x]")) {
      return genChoiceTypes(ed, id, card);
    } else {
      defn = genAlternativeTypes(ed, id, card);
    }
    }
  element_def.add("defn", defn);
  return element_def.render();
    }
 
Example 25
Source Project: buck   Source File: IjProjectWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void writeLibrary(IjLibrary library) throws IOException {
  ST contents = null;
  if (library.getType() == IjLibrary.Type.DEFAULT) {
    contents = StringTemplateFile.LIBRARY_TEMPLATE.getST();
  } else if (library.getType() == IjLibrary.Type.KOTLIN_JAVA_RUNTIME) {
    Optional<Path> templatePath = projectConfig.getKotlinJavaRuntimeLibraryTemplatePath();
    if (templatePath.isPresent()) {
      contents = StringTemplateFile.getST(templatePath.get());
    }
  }
  if (contents == null) {
    return;
  }
  contents.add("name", library.getName());
  contents.add(
      "binaryJars",
      library.getBinaryJars().stream()
          .map(projectPaths::getProjectRelativePath)
          .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())));
  contents.add(
      "classPaths",
      library.getClassPaths().stream()
          .map(projectPaths::getProjectRelativePath)
          .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())));
  contents.add(
      "sourceJars",
      library.getSourceJars().stream()
          .map(projectPaths::getProjectRelativePath)
          .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())));
  contents.add("javadocUrls", library.getJavadocUrls());
  // TODO(mkosiba): support res and assets for aar.

  Path path = projectPaths.getLibraryXmlFilePath(library);
  writeTemplate(contents, path);
}
 
Example 26
Source Project: org.hl7.fhir.core   Source File: ShExGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate a list of type choices for a "name[x]" style id
 * @param ed containing elmentdefinition
 * @param id choice identifier
 * @return ShEx fragment for the set of choices
 */
private String genChoiceTypes(ElementDefinition ed, String id, String card) {
  ST shex_choice = tmplt(CHOICE_TEMPLATE);
  List<String> choiceEntries = new ArrayList<String>();
  String base = id.replace("[x]", "");

  for(ElementDefinition.TypeRefComponent typ : ed.getType())  {
    choiceEntries.add(genChoiceEntry(base, typ));
  }
  shex_choice.add("choiceEntries", StringUtils.join(choiceEntries, " |\n\t\t"));
  shex_choice.add("card", card);
  return shex_choice.render();
  }
 
Example 27
Source Project: cs601   Source File: Page.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 28
Source Project: codebuff   Source File: STViz.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 29
Source Project: fix-orchestra   Source File: StateGenerator.java    License: Apache License 2.0 5 votes vote down vote up
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 30
Source Project: codebuff   Source File: STViz.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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();
}