Java Code Examples for org.stringtemplate.v4.ST#add()

The following examples show how to use org.stringtemplate.v4.ST#add() . 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: CypherQueryGraphHelper.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * createActorObjectEdge.
 * @param activity activity
 * @return pair (query, parameterMap)
 */
public Pair<String, Map<String, Object>> createActorObjectEdge(Activity activity) {

  Pair queryPlusParameters = new Pair(null, new HashMap<>());

  ObjectNode object = MAPPER.convertValue(activity, ObjectNode.class);
  object = PropertyUtil.getInstance(MAPPER).cleanProperties(object);
  Map<String, Object> props = PropertyUtil.getInstance(MAPPER).flattenToMap(object);

  ST mergeEdge = new ST(createEdgeStatementTemplate);
  mergeEdge.add("s_id", activity.getActor().getId());
  mergeEdge.add("s_type", activity.getActor().getObjectType());
  mergeEdge.add("d_id", activity.getObject().getId());
  mergeEdge.add("d_type", activity.getObject().getObjectType());
  mergeEdge.add("r_id", activity.getId());
  mergeEdge.add("r_type", activity.getVerb());
  mergeEdge.add("r_props", getActorObjectEdgePropertyCreater(props));

  String statement = mergeEdge.render();
  queryPlusParameters = queryPlusParameters.setAt0(statement);
  queryPlusParameters = queryPlusParameters.setAt1(props);

  LOGGER.debug("createActorObjectEdge: ({},{})", statement, props);

  return queryPlusParameters;
}
 
Example 2
Source File: PersistTestModuleBuilder.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** Creates or overrides META-INF/persistence.xml. */
public Path savePersistenceXml() throws IOException, URISyntaxException {
  Path persistenceXmlPath = getOrCreateMetaInf().resolve("persistence.xml");
  URL url =
      Thread.currentThread()
          .getContextClassLoader()
          .getResource(PERSISTENCE_XML_TEMPLATE_RESOURCE_PATH);
  if (url == null) {
    throw new IOException(
        "Resource '" + PERSISTENCE_XML_TEMPLATE_RESOURCE_PATH + "' doesn't exist");
  }
  ST st = new ST(Resources.toString(url, UTF_8), '$', '$');
  if (persistenceUnit != null) {
    st.add("unit", persistenceUnit);
  }
  if (!entityFqnSet.isEmpty()) {
    st.add("entity_classes", entityFqnSet);
  }
  if (!properties.isEmpty()) {
    st.add("properties", properties);
  }
  Files.write(persistenceXmlPath, st.render().getBytes(UTF_8));
  return persistenceXmlPath;
}
 
Example 3
Source File: TestGenerator.java    From fix-orchestra with Apache License 2.0 6 votes vote down vote up
private void generateFeature(AutoIndentWriter writer, Repository repository, FlowType flow,
    ActorType actor) {
  final STGroupFile stFeatureGroup = new STGroupFile("templates/feature.stg");

  ST st = stFeatureGroup.getInstanceOf("feature");
  st.add("repository", repository);
  st.add("flow", flow);
  st.add("actor", actor);
  st.write(writer, errorListener);
  
  repository.getMessages().getMessage().stream()
  .filter(m -> flow.getName().equals(m.getFlow())).forEach(message -> {
    Responses responses = message.getResponses();
    if (responses != null)
      responses.getResponse().forEach(response -> generateFeatureScenario(writer, stFeatureGroup, repository, actor, message, response));
  });
}
 
Example 4
Source File: StateGenerator.java    From fix-orchestra with Apache License 2.0 6 votes vote down vote up
private void generateTransitionsEnum(StateMachineType stateMachine, StateType state)
    throws Exception {
  String stateMachineName = stateMachine.getName();
  String stateName = state.getName();
  List<TransitionType> transitions = state.getTransition();
  if (!transitions.isEmpty()) {
    try (final STWriterWrapper writer = getWriter(
        srcPath.resolve(String.format("%s%sTransition.java", stateMachineName, stateName)))) {
      final ST stInterface = stGroup.getInstanceOf("transition_enum");
      stInterface.add("stateMachine", stateMachine);
      stInterface.add("state", state);
      stInterface.add("package", this.srcPackage);
      stInterface.write(writer, templateErrorListener);
    }
  }
}
 
Example 5
Source File: STViz.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void test1() throws IOException
{ // test rig
    String templates = "method(type,name,locals,args,stats) ::= <<\n"+"public <type> <name>(<args:{a| int <a>}; separator=\", \">) {\n"+"    <if(locals)>int locals[<locals>];<endif>\n"+"    <stats;separator=\"\\n\">\n"+"}\n"+">>\n"+"assign(a,b) ::= \"<a> = <b>;\"\n"+"return(x) ::= <<return <x>;>>\n"+"paren(x) ::= \"(<x>)\"\n";
    String tmpdir = System.getProperty("java.io.tmpdir");
    writeFile(tmpdir, "t.stg", templates);
    STGroup group = new STGroupFile(tmpdir+"/"+"t.stg");
    ST st = group.getInstanceOf("method");
    st.impl.dump();
    st.add("type", "float");
    st.add("name", "foo");
    st.add("locals", 3);
    st.add("args", new String[] {"x",
                                 "y",
                                 "z"});
    ST s1 = group.getInstanceOf("assign");
    ST paren = group.getInstanceOf("paren");
    paren.add("x", "x");
    s1.add("a", paren);
    s1.add("b", "y");
    ST s2 = group.getInstanceOf("assign");
    s2.add("a", "y");
    s2.add("b", "z");
    ST s3 = group.getInstanceOf("return");
    s3.add("x", "3.14159");
    st.add("stats", s1);
    st.add("stats", s2);
    st.add("stats", s3);
    STViz viz = st.inspect();
    System.out.println(st.render()); // should not mess up ST event lists
}
 
Example 6
Source File: STViz.java    From codebuff with 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 7
Source File: GenerateMultiPatternMatcherBenchmarkTest.java    From stringbench with Apache License 2.0 5 votes vote down vote up
public static void generate(String pkg, String algorithm) throws IOException {
	ST st = new ST(new String(Files.readAllBytes(Paths.get("src/test/resources/TemplateMultiPatternMatcherBenchmarkTest.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/multipattern", pkg);
	Files.createDirectories(dir);
	Files.write(dir.resolve(algorithm + "BenchmarkTest.java"), text.getBytes(StandardCharsets.UTF_8));
}
 
Example 8
Source File: PySnippetExecutor.java    From bookish with MIT License 5 votes vote down vote up
public void createNotebooksIndexFile() {
	ST indexFile = tool.artifact.templates.getInstanceOf("NotebooksIndexFile");
	indexFile.add("file", tool.artifact);
	indexFile.add("booktitle", tool.artifact.title);

	for (ChapDocInfo doc : tool.artifact.docs) {
		String basename = doc.getSourceBaseName();

		MultiMap<String, ExecutableCodeDef> labelToDefs = collectSnippetsByLabel(doc);
		for (String label : labelToDefs.keySet()) {
			indexFile.add("names", basename+"/"+label);
		}
	}
	ParrtIO.save(tool.outputDir+"/notebooks/index.html", indexFile.render());
}
 
Example 9
Source File: STViz.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void test1() throws IOException
{ // test rig
    String templates = "method(type,name,locals,args,stats) ::= <<\n"+"public <type> <name>(<args:{a| int <a>}; separator=\", \">) {\n"+"    <if(locals)>int locals[<locals>];<endif>\n"+"    <stats;separator=\"\\n\">\n"+"}\n"+">>\n"+"assign(a,b) ::= \"<a> = <b>;\"\n"+"return(x) ::= <<return <x>;>>\n"+"paren(x) ::= \"(<x>)\"\n";
    String tmpdir = System.getProperty("java.io.tmpdir");
    writeFile(tmpdir, "t.stg", templates);
    STGroup group = new STGroupFile(tmpdir+"/"+"t.stg");
    ST st = group.getInstanceOf("method");
    st.impl.dump();
    st.add("type", "float");
    st.add("name", "foo");
    st.add("locals", 3);
    st.add("args", new String[] {"x",
                                 "y",
                                 "z"});
    ST s1 = group.getInstanceOf("assign");
    ST paren = group.getInstanceOf("paren");
    paren.add("x", "x");
    s1.add("a", paren);
    s1.add("b", "y");
    ST s2 = group.getInstanceOf("assign");
    s2.add("a", "y");
    s2.add("b", "z");
    ST s3 = group.getInstanceOf("return");
    s3.add("x", "3.14159");
    st.add("stats", s1);
    st.add("stats", s2);
    st.add("stats", s3);
    STViz viz = st.inspect();
    System.out.println(st.render()); // should not mess up ST event lists
}
 
Example 10
Source File: STViz.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void test1() throws IOException
{ // test rig
    String templates = "method(type,name,locals,args,stats) ::= <<\n"+"public <type> <name>(<args:{a| int <a>}; separator=\", \">) {\n"+"    <if(locals)>int locals[<locals>];<endif>\n"+"    <stats;separator=\"\\n\">\n"+"}\n"+">>\n"+"assign(a,b) ::= \"<a> = <b>;\"\n"+"return(x) ::= <<return <x>;>>\n"+"paren(x) ::= \"(<x>)\"\n";
    String tmpdir = System.getProperty("java.io.tmpdir");
    writeFile(tmpdir, "t.stg", templates);
    STGroup group = new STGroupFile(tmpdir+"/"+"t.stg");
    ST st = group.getInstanceOf("method");
    st.impl.dump();
    st.add("type", "float");
    st.add("name", "foo");
    st.add("locals", 3);
    st.add("args", new String[] {"x",
                                 "y",
                                 "z"});
    ST s1 = group.getInstanceOf("assign");
    ST paren = group.getInstanceOf("paren");
    paren.add("x", "x");
    s1.add("a", paren);
    s1.add("b", "y");
    ST s2 = group.getInstanceOf("assign");
    s2.add("a", "y");
    s2.add("b", "z");
    ST s3 = group.getInstanceOf("return");
    s3.add("x", "3.14159");
    st.add("stats", s1);
    st.add("stats", s2);
    st.add("stats", s3);
    STViz viz = st.inspect();
    System.out.println(st.render()); // should not mess up ST event lists
}
 
Example 11
Source File: GenerateSinglePatternMatcherBenchmarkTest.java    From stringbench with Apache License 2.0 5 votes vote down vote up
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 12
Source File: TestArraysStringTemplate.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
		int[] nums =  {3,9,20,2,1,4,6,32,5,6,77,885};
//		ST array = new ST("int <name>[] = { <data; wrap, anchor, separator=\", \"> };");
		ST array = new ST(
			"int <name>[] = {<data:{d |  [<d>]}> }"
		);
		array.add("name", "a");
		array.add("data", nums);
		System.out.println(array.render());
	}
 
Example 13
Source File: CodeGeneratingVisitor.java    From compiler with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void visit(final ReturnStatement n) {
	final ST st = stg.getInstanceOf("Return");

	if (n.hasExpr()) {
		n.getExpr().accept(this);
		st.add("expr", code.removeLast());
	}

	code.add(st.render());
}
 
Example 14
Source File: ShExGenerator.java    From org.hl7.fhir.core with 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 15
Source File: IjProjectWriter.java    From buck with Apache License 2.0 5 votes vote down vote up
private void writeModulesIndex(ImmutableSortedSet<ModuleIndexEntry> moduleEntries)
    throws IOException {
  ST moduleIndexContents = StringTemplateFile.MODULE_INDEX_TEMPLATE.getST();
  moduleIndexContents.add("modules", moduleEntries);

  writeTemplate(moduleIndexContents, getIdeaConfigDir().resolve("modules.xml"));
}
 
Example 16
Source File: PySnippetExecutor.java    From bookish with MIT License 5 votes vote down vote up
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 17
Source File: CodeGeneratingVisitor.java    From compiler with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void visit(final DoStatement n) {
	final ST st = stg.getInstanceOf("DoWhile");

	n.getCondition().accept(this);
	st.add("condition", code.removeLast());

	n.getBody().accept(this);
	st.add("stmt", code.removeLast());

	code.add(st.render());
}
 
Example 18
Source File: CodeGeneratingVisitor.java    From compiler with Apache License 2.0 4 votes vote down vote up
protected void generateQuantifier(final Node n, final Component c, final Expression e, final Block b, final String kind, final ST st) {
	final BoaType type = c.getType().type;

	final String id = c.getIdentifier().getToken();

	n.env.set(id, type);
	st.add("type", type.toJavaType());
	st.add("index", id);

	this.indexeeFinder.start(e, id);
	final Set<Node> indexees = this.indexeeFinder.getIndexees();

	if (indexees.size() > 0) {
		final List<Node> array = new ArrayList<Node>(indexees);
		final Set<String> seen = new LinkedHashSet<String>();
		String src = "";
		for (int i = 0; i < array.size(); i++) {
			final Factor indexee = (Factor)array.get(i);

			this.skipIndex = id;
			indexee.accept(this);
			final String src2 = code.removeLast();
			this.skipIndex = "";

			if (seen.contains(src2)) continue;
			seen.add(src2);

			final BoaType indexeeType = this.indexeeFinder.getFactors().get(indexee).type;
			final String func = (indexeeType instanceof BoaArray) ? ".length" : ".size()";

			if (src.length() > 0)
				src = "java.lang.Math.min(" + src2 + func + ", " + src + ")";
			else
				src = src2 + func;
		}

		st.add("len", src);
	} else {
		throw new TypeCheckException(e, "quantifier variable '" + id + "' must be used in the " + kind + " condition expression");
	}

	e.accept(this);
	st.add("expression", code.removeLast());

	b.accept(this);
	st.add("statement", code.removeLast());

	code.add(st.render());
}
 
Example 19
Source File: SubsetValidator.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
		LangDescriptor[] languages = new LangDescriptor[] {
//			QUORUM_DESCR,
			ANTLR4_DESCR,
			JAVA_DESCR,
			JAVA8_DESCR,
			JAVA_GUAVA_DESCR,
			JAVA8_GUAVA_DESCR,
			SQLITE_CLEAN_DESCR,
			TSQL_CLEAN_DESCR,
		};

		int maxNumFiles = 30;
		int trials = 50;
		Map<String,float[]> results = new HashMap<>();
		for (LangDescriptor language : languages) {
			float[] medians = getMedianErrorRates(language, maxNumFiles, trials);
			results.put(language.name, medians);
		}
		String python =
			"#\n"+
			"# AUTO-GENERATED FILE. DO NOT EDIT\n" +
			"# CodeBuff <version> '<date>'\n" +
			"#\n"+
			"import numpy as np\n"+
			"import matplotlib.pyplot as plt\n\n" +
			"fig = plt.figure()\n"+
			"ax = plt.subplot(111)\n"+
			"N = <maxNumFiles>\n" +
			"sizes = range(1,N+1)\n" +
			"<results:{r |\n" +
			"<r> = [<rest(results.(r)); separator={,}>]\n"+
			"ax.plot(range(1,len(<r>)+1), <r>, label=\"<r>\", marker='<markers.(r)>', color='<colors.(r)>')\n" +
			"}>\n" +
			"ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)\n" +
			"ax.set_xlabel(\"Number of training files in sample corpus subset\", fontsize=14)\n"+
			"ax.set_ylabel(\"Median Error rate for <trials> trials\", fontsize=14)\n" +
			"ax.set_title(\"Effect of Corpus size on Median Leave-one-out Validation Error Rate\")\n"+
			"plt.legend()\n" +
			"plt.tight_layout()\n" +
			"fig.savefig('images/subset_validator.pdf', format='pdf')\n"+
			"plt.show()\n";
		ST pythonST = new ST(python);
		pythonST.add("results", results);
		pythonST.add("markers", LeaveOneOutValidator.nameToGraphMarker);
		pythonST.add("colors", LeaveOneOutValidator.nameToGraphColor);
		pythonST.add("version", version);
		pythonST.add("date", new Date());
		pythonST.add("trials", trials);
		pythonST.add("maxNumFiles", maxNumFiles);
		List<String> corpusDirs = map(languages, l -> l.corpusDir);
		String[] dirs = corpusDirs.toArray(new String[languages.length]);
		String fileName = "python/src/subset_validator.py";
		Utils.writeFile(fileName, pythonST.render());
		System.out.println("wrote python code to "+fileName);
	}
 
Example 20
Source File: OutputModelObject.java    From cs652 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public ST getTemplate() {
	String className = getClass().getSimpleName();
	ST st = Gen.templates.getInstanceOf(className);
	st.add("model", this);
	return st;
}