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

The following examples show how to use org.stringtemplate.v4.ST#render() . 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: UmbrellaHeaderModuleMap.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public String render() {
  if (this.generatedModule == null) {
    ST st =
        new ST(template)
            .add("module_name", moduleName)
            .add("include_swift_header", false)
            .add("exclude_swift_header", false);
    switch (swiftMode) {
      case INCLUDE_SWIFT_HEADER:
        st.add("include_swift_header", true);
        break;
      case EXCLUDE_SWIFT_HEADER:
        st.add("exclude_swift_header", true);
        break;
      default:
      case NO_SWIFT:
    }
    this.generatedModule = st.render();
  }
  return this.generatedModule;
}
 
Example 2
Source File: ShExGenerator.java    From org.hl7.fhir.core with 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 File: ShExGenerator.java    From org.hl7.fhir.core with 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 4
Source File: GenDOT.java    From cs652 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 5
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 6
Source File: Utils.java    From AudioBookConverter with GNU General Public License v2.0 5 votes vote down vote up
public static String getOuputFilenameSuggestion(AudioBookInfo bookInfo) {
        String filenameFormat = AppProperties.getProperty("filename_format");
        if (filenameFormat == null) {
            filenameFormat = "<WRITER> <if(SERIES)>- [<SERIES><if(BOOK_NUMBER)> -<BOOK_NUMBER><endif>] <endif>- <TITLE><if(NARRATOR)> (<NARRATOR>)<endif>";
            AppProperties.setProperty("filename_format", filenameFormat);
        }

        ST filenameTemplate = new ST(filenameFormat);
        filenameTemplate.add("WRITER", bookInfo.writer().trimToNull());
        filenameTemplate.add("TITLE", bookInfo.title().trimToNull());
        filenameTemplate.add("SERIES", bookInfo.series().trimToNull());
        filenameTemplate.add("NARRATOR", bookInfo.narrator().trimToNull());
        filenameTemplate.add("BOOK_NUMBER", bookInfo.bookNumber().zeroToNull());

        String result = filenameTemplate.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;
//        return mp3Filename.replaceFirst("\\.\\w*$", ".m4b");
    }
 
Example 7
Source File: NotificationComposer.java    From eas-ddd with Apache License 2.0 5 votes vote down vote up
private String renderBody() {
    List<TemplateVariable> variables = registerVariables();
    ST st = new ST(template, BEGIN_VARIABLE, END_VARIABLE);
    for (TemplateVariable variable : variables) {
        st.add(variable.name(), variable.value());
    }
    return st.render();
}
 
Example 8
Source File: ShExGenerator.java    From org.hl7.fhir.core with 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 9
Source File: StCompiler.java    From protostuff-compiler with Apache License 2.0 5 votes vote down vote up
protected void compile(String templateName, String templateArgName, Object templateArgValue, Writer writer) {
    ST st = stGroup.getInstanceOf(templateName);
    if (st == null) {
        throw new GeneratorException("Template %s is not defined", templateName);
    }
    st.add(templateArgName, templateArgValue);
    String result = st.render();
    try {
        writer.append(result);
    } catch (IOException e) {
        throw new GeneratorException("Could not write file: %s", e.getMessage(), e);
    }
}
 
Example 10
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an entry in a choice list
 * @param base base identifier
 * @param typ type/discriminant
 * @return ShEx fragment for choice entry
 */
private String genChoiceEntry(StructureDefinition sd, ElementDefinition ed, String id, String base, ElementDefinition.TypeRefComponent typ) {
  ST shex_choice_entry = tmplt(ELEMENT_TEMPLATE);

  String ext = typ.getWorkingCode();
  shex_choice_entry.add("id", "fhir:" + base+Character.toUpperCase(ext.charAt(0)) + ext.substring(1) + " ");
  shex_choice_entry.add("card", "");
  shex_choice_entry.add("defn", genTypeRef(sd, ed, id, typ));
  shex_choice_entry.add("comment", " ");
  return shex_choice_entry.render();
}
 
Example 11
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 12
Source File: CypherQueryGraphHelper.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * getVerticesRequest gets all vertices with a label.
 * @param labelId labelId
 * @return pair (query, parameterMap)
 */
public Pair<String, Map<String, Object>> getVerticesRequest(String labelId) {
  ST getVertex = new ST(getVerticesLabelIdStatementTemplate);
  getVertex.add("type", labelId);

  Pair<String, Map<String, Object>> queryPlusParameters = new Pair(getVertex.render(), null);

  LOGGER.debug("getVertexRequest", queryPlusParameters.toString());

  return queryPlusParameters;
}
 
Example 13
Source File: STTemplateProcessorImpl.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String process(String templateName, Map<String, Object> variables)
    throws TemplateException {
  ST st = new ST(resolve(templateName));
  variables.forEach(st::add);
  return st.render();
}
 
Example 14
Source File: TypeScriptDtoDTSGenerator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String execute() {
  init();
  ST template = getTemplate();
  template.add("dtoNamespaces", this.dtoNamespaces.values());
  String output = template.render();
  return output;
}
 
Example 15
Source File: GeneratorST.java    From cs652 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public String toString(TableSep table, String templateFile) {
	STGroup templates = new STGroupFile(templateFile);
	ST tableST = templates.getInstanceOf("table");
	tableST.add("t", table);
	return tableST.render();
}
 
Example 16
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
/**
   * Emit a ShEx definition for the supplied StructureDefinition
   * @param sd Structure definition to emit
   * @param top_level True means outermost type, False means recursively called
   * @return ShEx definition
   */
  private String genShapeDefinition(StructureDefinition sd, boolean top_level) {
    // xhtml is treated as an atom
    if("xhtml".equals(sd.getName()) || (completeModel && "Resource".equals(sd.getName())))
      return "";

    ST shape_defn;
    // Resources are either incomplete items or consist of everything that is defined as a resource (completeModel)
    if("Resource".equals(sd.getName())) {
      shape_defn = tmplt(RESOURCE_SHAPE_TEMPLATE);
      known_resources.add(sd.getName());
    } else {
      shape_defn = tmplt(SHAPE_DEFINITION_TEMPLATE).add("id", sd.getId());
      if (sd.getKind().equals(StructureDefinition.StructureDefinitionKind.RESOURCE)) {
//              || sd.getKind().equals(StructureDefinition.StructureDefinitionKind.COMPLEXTYPE)) {
        known_resources.add(sd.getName());
        ST resource_decl = tmplt(RESOURCE_DECL_TEMPLATE).
                add("id", sd.getId()).
                add("root", tmplt(ROOT_TEMPLATE));
//                add("root", top_level ? tmplt(ROOT_TEMPLATE) : "");
        shape_defn.add("resourceDecl", resource_decl.render());
      } else {
        shape_defn.add("resourceDecl", "");
      }
    }

    // Generate the defining elements
    List<String> elements = new ArrayList<String>();

    // Add the additional entries for special types
    String sdn = sd.getName();
    if (sdn.equals("Coding"))
      elements.add(tmplt(CONCEPT_REFERENCE_TEMPLATE).render());
    else if (sdn.equals("CodeableConcept"))
      elements.add(tmplt(CONCEPT_REFERENCES_TEMPLATE).render());
    else if (sdn.equals("Reference"))
      elements.add(tmplt(RESOURCE_LINK_TEMPLATE).render());
//    else if (sdn.equals("Extension"))
//      return tmplt(EXTENSION_TEMPLATE).render();

    String root_comment = null;
    for (ElementDefinition ed : sd.getSnapshot().getElement()) {
      if(!ed.getPath().contains("."))
        root_comment = ed.getShort();
      else if (StringUtils.countMatches(ed.getPath(), ".") == 1 && !"0".equals(ed.getMax())) {
        elements.add(genElementDefinition(sd, ed));
      }
    }
    shape_defn.add("elements", StringUtils.join(elements, "\n"));
    shape_defn.add("comment", root_comment == null? " " : "# " + root_comment);
    return shape_defn.render();
  }
 
Example 17
Source File: Target.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public String getImplicitSetLabel(String id) {
	ST st = getTemplates().getInstanceOf("ImplicitSetLabel");
	st.add("id", id);
	return st.render();
}
 
Example 18
Source File: Target.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public String getListLabel(String label) {
	ST st = getTemplates().getInstanceOf("ListLabelName");
	st.add("label", label);
	return st.render();
}
 
Example 19
Source File: ShExGenerator.java    From org.hl7.fhir.core with Apache License 2.0 4 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) {
  String id = ed.hasBase() ? ed.getBase().getPath() : ed.getPath();
  String shortId = id.substring(id.lastIndexOf(".") + 1);
  String defn;
  ST element_def;
  String card = ("*".equals(ed.getMax()) ? (ed.getMin() == 0 ? "*" : "+") : (ed.getMin() == 0 ? "?" : "")) + ";";

  if(id.endsWith("[x]")) {
    element_def = ed.getType().size() > 1? tmplt(INNER_SHAPE_TEMPLATE) : tmplt(ELEMENT_TEMPLATE);
    element_def.add("id", "");
  } else {
    element_def = tmplt(ELEMENT_TEMPLATE);
    element_def.add("id", "fhir:" + (id.charAt(0) == id.toLowerCase().charAt(0)? shortId : id) + " ");
  }

  List<ElementDefinition> children = profileUtilities.getChildList(sd, ed);
  if (children.size() > 0) {
    innerTypes.add(new ImmutablePair<StructureDefinition, ElementDefinition>(sd, ed));
    defn = simpleElement(sd, ed, id);
  } else if(id.endsWith("[x]")) {
    defn = genChoiceTypes(sd, ed, id);
  }
  else if (ed.getType().size() == 1) {
    // Single entry
    defn = genTypeRef(sd, ed, id, ed.getType().get(0));
  } else if (ed.getContentReference() != null) {
    // Reference to another element
    String ref = ed.getContentReference();
    if(!ref.startsWith("#"))
      throw new AssertionError("Not equipped to deal with absolute path references: " + ref);
    String refPath = null;
    for(ElementDefinition ed1: sd.getSnapshot().getElement()) {
      if(ed1.getId() != null && ed1.getId().equals(ref.substring(1))) {
        refPath = ed1.getPath();
        break;
      }
    }
    if(refPath == null)
      throw new AssertionError("Reference path not found: " + ref);
    // String typ = id.substring(0, id.indexOf(".") + 1) + ed.getContentReference().substring(1);
    defn = simpleElement(sd, ed, refPath);
  } else if(id.endsWith("[x]")) {
    defn = genChoiceTypes(sd, ed, id);
  } else {
    // TODO: Refactoring required here
    element_def = genAlternativeTypes(ed, id, shortId);
    element_def.add("id", id.charAt(0) == id.toLowerCase().charAt(0)? shortId : id);
    element_def.add("card", card);
    addComment(element_def, ed);
    return element_def.render();
  }
  element_def.add("defn", defn);
  element_def.add("card", card);
  addComment(element_def, ed);
  return element_def.render();
}
 
Example 20
Source File: CypherQueryGraphHelper.java    From streams with Apache License 2.0 3 votes vote down vote up
/**
 * createVertexRequest.
 * @param activityObject activityObject
 * @return pair (query, parameterMap)
 */
public Pair<String, Map<String, Object>> createVertexRequest(ActivityObject activityObject) {

  Objects.requireNonNull(activityObject.getObjectType());

  List<String> labels = getLabels(activityObject);

  ST createVertex = new ST(createVertexStatementTemplate);
  createVertex.add("id", activityObject.getId());
  createVertex.add("type", activityObject.getObjectType());

  if ( labels.size() > 0 ) {
    createVertex.add("labels", String.join(" ", labels));
  }

  String query = createVertex.render();

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

  Pair<String, Map<String, Object>> queryPlusParameters = new Pair(createVertex.render(), props);

  LOGGER.debug("createVertexRequest: ({},{})", query, props);

  return queryPlusParameters;
}