Java Examples for freemarker.ext.dom.NodeModel
The following java examples will help you to understand the usage of freemarker.ext.dom.NodeModel. These source code samples are taken from different open source projects.
Example 1
Project: codehaus-mojo-master File: XMLDataModelLoader.java View source code |
public TemplateModel getModel(File inputFile) throws MojoExecutionException { try { this.log.info("creating xml data model from file: " + inputFile); NodeModel nm = freemarker.ext.dom.NodeModel.parse(inputFile); return nm; } catch (Exception ex) { throw new MojoExecutionException("Unable to create xml model from file: " + inputFile, ex); } }
Example 2
Project: smooks-master File: FreeMarkerUtils.java View source code |
/**
* Get a "merged" model for FreeMarker templating.
* <p/>
* This utility merges the current set of beans being managed by the
* {@link BeanContext} associated with the
* current {@link ExecutionContext}, with the contents of the {@link DOMModel}
* associated with the current {@link ExecutionContext}. This is very useful
* for templating with FreeMarker.
*
* @param executionContext The current execution context.
* @return A merged templating model.
*/
public static Map<String, Object> getMergedModel(ExecutionContext executionContext) {
Map<String, Object> beans = executionContext.getBeanContext().getBeanMap();
Map<String, Object> model = beans;
DOMModel domModel = DOMModel.getModel(executionContext);
if (!domModel.getModels().isEmpty()) {
Map<String, ElementToNodeModel> elementToNodeModelMap = getElementToNodeModelMap(executionContext);
model = new HashMap<String, Object>();
model.putAll(beans);
Set<Map.Entry<String, Element>> models = domModel.getModels().entrySet();
for (Map.Entry<String, Element> entry : models) {
NodeModel nodeModel = getNodeModel(entry.getKey(), entry.getValue(), elementToNodeModelMap);
model.put(entry.getKey(), nodeModel);
}
}
return model;
}
Example 3
Project: nsesa-editor-an-master File: GWTAmendmentServiceImpl.java View source code |
private String toHTML(byte[] bytes) { try { final InputSource inputSource = new InputSource(new ByteArrayInputStream(bytes)); final NodeModel model = NodeModel.parse(inputSource); final Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); configuration.setDirectoryForTemplateLoading(documentTemplate.getFile().getParentFile()); final StringWriter sw = new StringWriter(); Map<String, Object> root = new HashMap<String, Object>(); root.put("doc", model); configuration.getTemplate(documentTemplate.getFile().getName()).process(root, sw); return sw.toString(); } catch (IOException e) { throw new RuntimeException("Could not read file.", e); } catch (SAXException e) { throw new RuntimeException("Could not parse file.", e); } catch (ParserConfigurationException e) { throw new RuntimeException("Could not parse file.", e); } catch (TemplateException e) { throw new RuntimeException("Could not load template.", e); } }
Example 4
Project: AT4AMParlamentoElettronicoEdition-master File: GWTAmendmentServiceImpl.java View source code |
private String toHTML(byte[] bytes) { try { final InputSource inputSource = new InputSource(new ByteArrayInputStream(bytes)); final NodeModel model = NodeModel.parse(inputSource); final Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); configuration.setDirectoryForTemplateLoading(documentTemplate.getFile().getParentFile()); final StringWriter sw = new StringWriter(); Map<String, Object> root = new HashMap<String, Object>(); root.put("doc", model); configuration.getTemplate(documentTemplate.getFile().getName()).process(root, sw); return sw.toString(); } catch (IOException e) { throw new RuntimeException("Could not read file.", e); } catch (SAXException e) { throw new RuntimeException("Could not parse file.", e); } catch (ParserConfigurationException e) { throw new RuntimeException("Could not parse file.", e); } catch (TemplateException e) { throw new RuntimeException("Could not load template.", e); } }
Example 5
Project: xdocreport.samples-master File: DocxXMLProjectWithFreemarkerList.java View source code |
public static void main(String[] args) { try { // 1) Load Docx file by filling Freemarker template engine and cache // it to the registry InputStream in = DocxXMLProjectWithFreemarkerList.class.getResourceAsStream("DocxXMLProjectWithFreemarkerList.docx"); IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Freemarker); // 2) Create fields metadata to manage lazy loop (#forech velocity) // for table row. // FieldsMetadata metadata = report.createFieldsMetadata(); // metadata.addFieldAsList( "doc.project.developer.@name" ); // metadata.addFieldAsList( "developers.lastName" ); // metadata.addFieldAsList( "developers.mail" ); // 3) Create context Java model IContext context = report.createContext(); InputStream projectInputStream = DocxXMLProjectWithFreemarkerList.class.getResourceAsStream("project.xml"); InputSource projectInputSource = new InputSource(projectInputStream); freemarker.ext.dom.NodeModel project = freemarker.ext.dom.NodeModel.parse(projectInputSource); context.put("doc", project); // 4) Generate report by merging Java model with the Docx OutputStream out = new FileOutputStream(new File("DocxXMLProjectWithFreemarkerList_Out.docx")); report.process(context, out); } catch (IOException e) { e.printStackTrace(); } catch (XDocReportException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
Example 6
Project: MyFramework-master File: GeneratorControl.java View source code |
/** load xml data */ public NodeModel loadXml(String file, boolean removeXmlNamespace) { try { if (removeXmlNamespace) { InputStream forEncodingInput = FileHelper.getInputStream(file); String encoding = XMLHelper.getXMLEncoding(forEncodingInput); forEncodingInput.close(); InputStream input = FileHelper.getInputStream(file); String xml = IOHelper.toString(encoding, input); xml = XMLHelper.removeXmlns(xml); input.close(); return NodeModel.parse(new InputSource(new StringReader(xml.trim()))); } else { return NodeModel.parse(new InputSource(FileHelper.getInputStream(file))); } } catch (Exception e) { throw new IllegalArgumentException("loadXml error,file:" + file, e); } }
Example 7
Project: jinhe-tss-master File: TestFreeMarkerParser.java View source code |
public static void test2() throws Exception {
String div = "<DIV id=span_div_27 style=\"FONT-SIZE: 1px; Z-INDEX: 10; LEFT: 0px; VISIBILITY: hidden;" + " POSITION: relative; TOP: 7px; HEIGHT: 1px\"></DIV>";
String templateStr = "" + "<#assign manager = statics[\"com.jinhe.tss.portal.engine.FreeMarkerParserTest.StaticManager\"] />" + "<#assign data = manager.getNavigatorService().getMenuXML(21) />" + "<#assign doc = statics[\"freemarker.ext.dom.NodeModel\"].parse(manager.translateValue(data)) />" + "<#assign menu = doc.Menu>" + "<TABLE height=33 cellSpacing=0 cellPadding=0 width=\"90%\" align=center><TBODY><TR> \n" + "<#list menu.MenuItem as item>" + "<TD class=mainTd id=td_${item.@id}><SPAN class=menuSpan id=manegeMenu_${item.@id}>" + "<a href='${item.@url}'>${item.@name}</a>" + "</SPAN>" + div + "</TD> \n" + "</#list>" + "</TR></TBODY></TABLE>";
FreemarkerParser parser = new FreemarkerParser(null);
parser.parseTemplateTwice(templateStr, new OutputStreamWriter(System.out));
}
Example 8
Project: Vega-master File: AlertRenderer.java View source code |
public String render(IScanAlert alert) { final int maxAlertString = Activator.getDefault().getPreferenceStore().getInt("MaxAlertString"); Map<String, Object> root = new HashMap<String, Object>(); try { Template t = configuration.getTemplate("main.ftl"); Document xmlRoot = getAlertDocument(alert.getName()); if (xmlRoot == null) return ""; NodeModel nodeModel = NodeModel.wrap(xmlRoot); root.put("doc", nodeModel); Map<String, Object> vars = new HashMap<String, Object>(); for (String k : alert.propertyKeys()) { Object value = alert.getProperty(k); if (value instanceof String) { String s = (String) value; if (s.length() > maxAlertString) { s = s.substring(0, maxAlertString) + "..."; } vars.put(k, s); } else { vars.put(k, alert.getProperty(k)); } } String severityVar = severityToString(alert.getSeverity()); if (severityVar != null) { vars.put("severity", severityVar); } String severityCSSVar = severityToSeverityCSSClass(alert.getSeverity()); if (severityCSSVar != null) { vars.put("severityCSS", severityCSSVar); } if (imageURL != null) vars.put("imageURL", imageURL); if (bulletPointURL != null) vars.put("bulletPointURL", bulletPointURL); if (bannerPatternURL != null) vars.put("bannerPatternURL", bannerPatternURL); if (bannerLogoURL != null) vars.put("bannerLogoURL", bannerLogoURL); if (titlePatternURL != null) vars.put("titlePatternURL", titlePatternURL); if (redArrowURL != null) vars.put("redArrowURL", redArrowURL); if (redArrowURL != null) vars.put("sectionGradientURL", sectionGradientURL); if (linkArrowURL != null) vars.put("linkArrowURL", linkArrowURL); if (alert.getRequestId() >= 0 && requestLog != null) { final IRequestLogRecord record = requestLog.lookupRecord(alert.getRequestId()); if (record != null) { if (record.getRequest() instanceof HttpEntityEnclosingRequest) { vars.put("requestText", renderEntityEnclosingRequest((HttpEntityEnclosingRequest) record.getRequest())); } else { vars.put("requestText", renderBasicRequest(record.getRequest())); } vars.put("requestId", Long.toString(alert.getRequestId())); } } root.put("vars", vars); StringWriter out = new StringWriter(); t.process(root, out); out.flush(); return out.toString(); } catch (IOException e) { return "I/O error reading alert template file alerts/" + alert.getName() + ".xml :<br><br>" + e.getMessage(); } catch (TemplateException e) { return "Error processing alert template file alerts/" + alert.getName() + ".xml :<br><br>" + e.getMessage(); } }
Example 9
Project: incubator-freemarker-master File: TemplateTestCase.java View source code |
/* * This method just contains all the code to seed the data model * ported over from the individual classes. This seems ugly and unnecessary. * We really might as well just expose pretty much * the same tree to all our tests. (JR) */ @Override @SuppressWarnings("boxing") public void setUp() throws Exception { conf.setTemplateLoader(new CopyrightCommentRemoverTemplateLoader(new FileTemplateLoader(new File(getTestClassDirectory(), "templates")))); dataModel.put(ASSERT_VAR_NAME, AssertDirective.INSTANCE); dataModel.put(ASSERT_EQUALS_VAR_NAME, AssertEqualsDirective.INSTANCE); dataModel.put(ASSERT_FAILS_VAR_NAME, AssertFailsDirective.INSTANCE); dataModel.put(NO_OUTPUT_VAR_NAME, NoOutputDirective.INSTANCE); dataModel.put(JAVA_OBJECT_INFO_VAR_NAME, JavaObjectInfo.INSTANCE); dataModel.put(TEST_NAME_VAR_NAME, simpleTestName); dataModel.put(ICI_INT_VALUE_VAR_NAME, conf.getIncompatibleImprovements().intValue()); dataModel.put("message", "Hello, world!"); if (simpleTestName.startsWith("api-builtin")) { dataModel.put("map", ImmutableMap.of(1, "a", 2, "b", 3, "c")); dataModel.put("list", ImmutableList.of(1, 2, 3)); dataModel.put("set", ImmutableSet.of("a", "b", "c")); dataModel.put("s", "test"); } else if (simpleTestName.equals("bean-maps")) { BeansWrapper w1 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w2 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w3 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w4 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w5 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w6 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w7 = new Java7MembersOnlyBeansWrapper(); w1.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY); w2.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY); w3.setExposureLevel(BeansWrapper.EXPOSE_NOTHING); w4.setExposureLevel(BeansWrapper.EXPOSE_NOTHING); w5.setExposureLevel(BeansWrapper.EXPOSE_ALL); w6.setExposureLevel(BeansWrapper.EXPOSE_ALL); w1.setMethodsShadowItems(true); w2.setMethodsShadowItems(false); w3.setMethodsShadowItems(true); w4.setMethodsShadowItems(false); w5.setMethodsShadowItems(true); w6.setMethodsShadowItems(false); w7.setSimpleMapWrapper(true); Object test = getTestMapBean(); dataModel.put("m1", w1.wrap(test)); dataModel.put("m2", w2.wrap(test)); dataModel.put("m3", w3.wrap(test)); dataModel.put("m4", w4.wrap(test)); dataModel.put("m5", w5.wrap(test)); dataModel.put("m6", w6.wrap(test)); dataModel.put("m7", w7.wrap(test)); dataModel.put("s1", w1.wrap("hello")); dataModel.put("s2", w1.wrap("world")); dataModel.put("s3", w5.wrap("hello")); dataModel.put("s4", w5.wrap("world")); } else if (simpleTestName.equals("beans")) { dataModel.put("array", new String[] { "array-0", "array-1" }); dataModel.put("list", Arrays.asList(new String[] { "list-0", "list-1", "list-2" })); Map tmap = new HashMap(); tmap.put("key", "value"); Object objKey = new Object(); tmap.put(objKey, "objValue"); dataModel.put("map", tmap); dataModel.put("objKey", objKey); dataModel.put("obj", new freemarker.test.templatesuite.models.BeanTestClass()); dataModel.put("resourceBundle", new ResourceBundleModel(ResourceBundle.getBundle("freemarker.test.templatesuite.models.BeansTestResources"), BeansWrapper.getDefaultInstance())); dataModel.put("date", new GregorianCalendar(1974, 10, 14).getTime()); dataModel.put("statics", BeansWrapper.getDefaultInstance().getStaticModels()); dataModel.put("enums", BeansWrapper.getDefaultInstance().getEnumModels()); } else if (simpleTestName.equals("boolean")) { dataModel.put("boolean1", TemplateBooleanModel.FALSE); dataModel.put("boolean2", TemplateBooleanModel.TRUE); dataModel.put("boolean3", TemplateBooleanModel.TRUE); dataModel.put("boolean4", TemplateBooleanModel.TRUE); dataModel.put("boolean5", TemplateBooleanModel.FALSE); dataModel.put("list1", new BooleanList1()); dataModel.put("list2", new BooleanList2()); dataModel.put("hash1", new BooleanHash1()); dataModel.put("hash2", new BooleanHash2()); } else if (simpleTestName.startsWith("dateformat")) { GregorianCalendar cal = new GregorianCalendar(2002, 10, 15, 14, 54, 13); cal.setTimeZone(TimeZone.getTimeZone("GMT")); dataModel.put("date", new SimpleDate(cal.getTime(), TemplateDateModel.DATETIME)); dataModel.put("unknownDate", new SimpleDate(cal.getTime(), TemplateDateModel.UNKNOWN)); dataModel.put("javaGMT02", TimeZone.getTimeZone("GMT+02")); dataModel.put("javaUTC", TimeZone.getTimeZone("UTC")); dataModel.put("adaptedToStringScalar", new Object() { @Override public String toString() { return "GMT+02"; } }); dataModel.put("sqlDate", new java.sql.Date(1273955885023L)); dataModel.put("sqlTime", new java.sql.Time(74285023L)); } else if (templateName.equals("list.ftl") || templateName.equals("list2.ftl") || templateName.equals("list3.ftl")) { dataModel.put("listables", new Listables()); } else if (simpleTestName.startsWith("number-format")) { dataModel.put("int", new SimpleNumber(Integer.valueOf(1))); dataModel.put("double", new SimpleNumber(Double.valueOf(1.0))); dataModel.put("double2", new SimpleNumber(Double.valueOf(1 + 1e-15))); dataModel.put("double3", new SimpleNumber(Double.valueOf(1e-16))); dataModel.put("double4", new SimpleNumber(Double.valueOf(-1e-16))); dataModel.put("bigDecimal", new SimpleNumber(java.math.BigDecimal.valueOf(1))); dataModel.put("bigDecimal2", new SimpleNumber(java.math.BigDecimal.valueOf(1, 16))); } else if (simpleTestName.equals("simplehash-char-key")) { HashMap mStringC = new HashMap(); mStringC.put("c", "string"); dataModel.put("mStringC", mStringC); HashMap mStringCNull = new HashMap(); mStringCNull.put("c", null); dataModel.put("mStringCNull", mStringCNull); HashMap mCharC = new HashMap(); mCharC.put(Character.valueOf('c'), "char"); dataModel.put("mCharC", mCharC); HashMap mCharCNull = new HashMap(); mCharCNull.put("c", null); dataModel.put("mCharCNull", mCharCNull); HashMap mMixed = new HashMap(); mMixed.put(Character.valueOf('c'), "char"); mMixed.put("s", "string"); mMixed.put("s2", "string2"); mMixed.put("s2n", null); dataModel.put("mMixed", mMixed); } else if (simpleTestName.equals("default-xmlns")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/defaultxmlns1.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("multimodels")) { dataModel.put("test", "selftest"); dataModel.put("self", "self"); dataModel.put("zero", Integer.valueOf(0)); dataModel.put("data", new MultiModel1()); } else if (simpleTestName.equals("stringbimethods")) { dataModel.put("multi", new TestBoolean()); } else if (simpleTestName.startsWith("type-builtins")) { dataModel.put("testmethod", new TestMethod()); dataModel.put("testnode", new TestNode()); dataModel.put("testcollection", new SimpleCollection(new ArrayList())); dataModel.put("testcollectionEx", DefaultNonListCollectionAdapter.adapt(new HashSet(), null)); dataModel.put("bean", new TestBean()); } else if (simpleTestName.equals("date-type-builtins")) { GregorianCalendar cal = new GregorianCalendar(2003, 4 - 1, 5, 6, 7, 8); cal.setTimeZone(TimeZone.getTimeZone("UTC")); Date d = cal.getTime(); dataModel.put("unknown", d); dataModel.put("timeOnly", new java.sql.Time(d.getTime())); dataModel.put("dateOnly", new java.sql.Date(d.getTime())); dataModel.put("dateTime", new java.sql.Timestamp(d.getTime())); } else if (simpleTestName.equals("var-layers")) { dataModel.put("x", Integer.valueOf(4)); dataModel.put("z", Integer.valueOf(4)); conf.setSharedVariable("y", Integer.valueOf(7)); } else if (simpleTestName.equals("xml-fragment")) { DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); DocumentBuilder db = f.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new InputSource(getClass().getResourceAsStream("models/xmlfragment.xml"))); NodeModel.simplify(doc); dataModel.put("node", NodeModel.wrap(doc.getDocumentElement().getFirstChild().getFirstChild())); } else if (simpleTestName.equals("xmlns1")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xmlns2")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns2.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xmlns3") || simpleTestName.equals("xmlns4")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns3.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xmlns5")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/defaultxmlns1.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xml-ns_prefix-scope")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xml-ns_prefix-scope.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.startsWith("sequence-builtins")) { Set abcSet = new TreeSet(); abcSet.add("a"); abcSet.add("b"); abcSet.add("c"); dataModel.put("abcSet", abcSet); List listWithNull = new ArrayList(); listWithNull.add("a"); listWithNull.add(null); listWithNull.add("c"); dataModel.put("listWithNull", listWithNull); List listWithNullsOnly = new ArrayList(); listWithNull.add(null); listWithNull.add(null); listWithNull.add(null); dataModel.put("listWithNullsOnly", listWithNullsOnly); dataModel.put("abcCollection", new SimpleCollection(abcSet)); Set set = new HashSet(); set.add("a"); set.add("b"); set.add("c"); dataModel.put("set", set); } else if (simpleTestName.equals("number-to-date")) { dataModel.put("bigInteger", new BigInteger("1305575275540")); dataModel.put("bigDecimal", new BigDecimal("1305575275539.5")); } else if (simpleTestName.equals("varargs")) { dataModel.put("m", new VarArgTestModel()); } else if (simpleTestName.startsWith("overloaded-methods-") && !simpleTestName.startsWith("overloaded-methods-2-")) { dataModel.put("obj", new OverloadedMethods()); } else if (simpleTestName.startsWith("boolean-formatting")) { dataModel.put("beansBoolean", new BooleanModel(Boolean.TRUE, (BeansWrapper) conf.getObjectWrapper())); dataModel.put("booleanAndString", new BooleanAndStringTemplateModel()); dataModel.put("booleanVsStringMethods", new BooleanVsStringMethods()); } else if (simpleTestName.startsWith("number-math-builtins")) { dataModel.put("fNan", Float.valueOf(Float.NaN)); dataModel.put("dNan", Double.valueOf(Double.NaN)); dataModel.put("fNinf", Float.valueOf(Float.NEGATIVE_INFINITY)); dataModel.put("dPinf", Double.valueOf(Double.POSITIVE_INFINITY)); dataModel.put("fn", Float.valueOf(-0.05f)); dataModel.put("dn", Double.valueOf(-0.05)); dataModel.put("ineg", Integer.valueOf(-5)); dataModel.put("ln", Long.valueOf(-5)); dataModel.put("sn", Short.valueOf((short) -5)); dataModel.put("bn", Byte.valueOf((byte) -5)); dataModel.put("bin", BigInteger.valueOf(5)); dataModel.put("bdn", BigDecimal.valueOf(-0.05)); dataModel.put("fp", Float.valueOf(0.05f)); dataModel.put("dp", Double.valueOf(0.05)); dataModel.put("ip", Integer.valueOf(5)); dataModel.put("lp", Long.valueOf(5)); dataModel.put("sp", Short.valueOf((short) 5)); dataModel.put("bp", Byte.valueOf((byte) 5)); dataModel.put("bip", BigInteger.valueOf(5)); dataModel.put("bdp", BigDecimal.valueOf(0.05)); } else if (simpleTestName.startsWith("classic-compatible")) { dataModel.put("array", new String[] { "a", "b", "c" }); dataModel.put("beansArray", new BeansWrapper().wrap(new String[] { "a", "b", "c" })); dataModel.put("beanTrue", new BeansWrapper().wrap(Boolean.TRUE)); dataModel.put("beanFalse", new BeansWrapper().wrap(Boolean.FALSE)); } else if (simpleTestName.startsWith("overloaded-methods-2-")) { dataModel.put("obj", new OverloadedMethods2()); final boolean dow = conf.getObjectWrapper() instanceof DefaultObjectWrapper; dataModel.put("dow", dow); dataModel.put("dowPre22", dow && ((DefaultObjectWrapper) conf.getObjectWrapper()).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22); } }
Example 10
Project: freemarker-online-master File: DataModelParser.java View source code |
private static Object parseValue(String value, TimeZone timeZone) throws DataModelParsingException { if (value.endsWith(";")) { // Tolerate this habit of Java and JavaScript programmers value = value.substring(value.length() - 1).trim(); } if (NUMBER_LIKE.matcher(value).matches()) { try { return new BigDecimal(value); } catch (NumberFormatException e) { CalendarFieldsToDateConverter calToDateConverter = new TrivialCalendarFieldsToDateConverter(); DateParseException attemptedTemportalPExc = null; String attemptedTemporalType = null; final int dashIdx = value.indexOf('-'); final int colonIdx = value.indexOf(':'); if (value.indexOf('T') > 1 || (dashIdx > 1 && colonIdx > dashIdx)) { try { return new Timestamp(DateUtil.parseISO8601DateTime(value, timeZone, calToDateConverter).getTime()); } catch (DateParseException pExc) { attemptedTemporalType = "date-time"; attemptedTemportalPExc = pExc; } } else if (dashIdx > 1) { try { return new java.sql.Date(DateUtil.parseISO8601Date(value, timeZone, calToDateConverter).getTime()); } catch (DateParseException pExc) { attemptedTemporalType = "date"; attemptedTemportalPExc = pExc; } } else if (colonIdx > 1) { try { return new Time(DateUtil.parseISO8601Time(value, timeZone, calToDateConverter).getTime()); } catch (DateParseException pExc) { attemptedTemporalType = "time"; attemptedTemportalPExc = pExc; } } if (attemptedTemportalPExc == null) { throw new DataModelParsingException("Malformed number: " + value, e); } else { throw new DataModelParsingException("Malformed ISO 8601 " + attemptedTemporalType + " (or malformed number): " + attemptedTemportalPExc.getMessage(), e.getCause()); } } } else if (value.startsWith("\"")) { try { return JSON_MAPPER.readValue(value, String.class); } catch (IOException e) { throw new DataModelParsingException("Malformed quoted string (using JSON syntax): " + getMessageWithoutLocation(e), e); } } else if (value.startsWith("\'")) { throw new DataModelParsingException("Malformed quoted string (using JSON syntax): Use \" character for quotation, not \' character."); } else if (value.startsWith("[")) { try { return JSON_MAPPER.readValue(value, List.class); } catch (IOException e) { throw new DataModelParsingException("Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e); } } else if (value.startsWith("{")) { try { return JSON_MAPPER.readValue(value, LinkedHashMap.class); } catch (IOException e) { throw new DataModelParsingException("Malformed list (using JSON syntax): " + getMessageWithoutLocation(e), e); } } else if (value.startsWith("<")) { try { DocumentBuilder builder = NodeModel.getDocumentBuilderFactory().newDocumentBuilder(); ErrorHandler errorHandler = NodeModel.getErrorHandler(); if (errorHandler != null) builder.setErrorHandler(errorHandler); final Document doc = builder.parse(new InputSource(new StringReader(value))); NodeModel.simplify(doc); return doc; } catch (SAXException e) { final String saxMsg = e.getMessage(); throw new DataModelParsingException("Malformed XML: " + (saxMsg != null ? saxMsg : e), e); } catch (Exception e) { throw new DataModelParsingException("XML parsing has failed with internal error: " + e, e); } } else if (value.equalsIgnoreCase(KEYWORD_TRUE)) { checkKeywordCase(value, KEYWORD_TRUE); return Boolean.TRUE; } else if (value.equalsIgnoreCase(KEYWORD_FALSE)) { checkKeywordCase(value, KEYWORD_FALSE); return Boolean.FALSE; } else if (value.equalsIgnoreCase(KEYWORD_NULL)) { checkKeywordCase(value, KEYWORD_NULL); return null; } else if (value.equalsIgnoreCase(KEYWORD_NAN)) { checkKeywordCase(value, KEYWORD_NAN); return Double.NaN; } else if (value.equalsIgnoreCase(KEYWORD_INFINITY)) { checkKeywordCase(value, KEYWORD_INFINITY); return Double.POSITIVE_INFINITY; } else if (value.equalsIgnoreCase(KEYWORD_POSITIVE_INFINITY)) { checkKeywordCase(value, KEYWORD_POSITIVE_INFINITY); return Double.POSITIVE_INFINITY; } else if (value.equalsIgnoreCase(KEYWORD_NEGATIVE_INFINITY)) { checkKeywordCase(value, KEYWORD_NEGATIVE_INFINITY); return Double.NEGATIVE_INFINITY; } else if (value.length() == 0) { throw new DataModelParsingException("Empty value. (If you indeed wanted a 0 length string, quote it, like \"\".)"); } else { return value; } }
Example 11
Project: cougar-master File: IDLReader.java View source code |
// TODO this arg list is getting out of hand and could be rationalised public void init(Document iddDoc, Document extensionDoc, final String service, String packageName, final String basedir, final String genSrcDir, final Log log, final String outputDir, boolean client, boolean server) throws Exception { try { output = new File(basedir, genSrcDir); if (outputDir != null) { iDDOutputDir = new File(basedir + "/" + outputDir); if (!iDDOutputDir.exists()) { if (!iDDOutputDir.mkdirs()) { throw new IllegalArgumentException("IDD Output Directory " + iDDOutputDir + " could not be created"); } } if (!iDDOutputDir.isDirectory() || (!iDDOutputDir.canWrite())) { throw new IllegalArgumentException("IDD Output Directory " + iDDOutputDir + " is not a directory or cannot be written to."); } } config = new Configuration(); config.setClassForTemplateLoading(IDLReader.class, "/templates"); config.setStrictSyntaxMode(true); this.log = log; this.packageName = packageName; this.service = service; this.client = client; // server must be true if client if false. this.server = server || !client; dataModel = NodeModel.wrap(iddDoc.cloneNode(true)); if (extensionDoc != null) { NodeModel extensionModel = NodeModel.wrap(extensionDoc); mergeExtensionsIntoDocument(getRootNode(dataModel), getRootNode(extensionModel)); removeUndefinedOperations(getRootNode(dataModel), getRootNode(extensionModel)); } if (log.isDebugEnabled()) { log.debug(serialize()); } } catch (final Exception e) { log.error("Failed to initialise FTL", e); throw e; } }
Example 12
Project: ofbiz-master File: ContentWorker.java View source code |
public static void renderContentAsText(LocalDispatcher dispatcher, GenericValue content, Appendable out, Map<String, Object> templateContext, Locale locale, String mimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException { // if the content has a service attached run the service Delegator delegator = dispatcher.getDelegator(); //Kept for backward compatibility String serviceName = content.getString("serviceName"); GenericValue custMethod = null; if (UtilValidate.isNotEmpty(content.getString("customMethodId"))) { custMethod = EntityQuery.use(delegator).from("CustomMethod").where("customMethodId", content.get("customMethodId")).cache().queryOne(); } if (custMethod != null) serviceName = custMethod.getString("customMethodName"); if (dispatcher != null && UtilValidate.isNotEmpty(serviceName)) { DispatchContext dctx = dispatcher.getDispatchContext(); ModelService service = dctx.getModelService(serviceName); if (service != null) { //put all requestParameters into templateContext to use them as IN service parameters Map<String, Object> tempTemplateContext = new HashMap<String, Object>(); tempTemplateContext.putAll(UtilGenerics.<String, Object>checkMap(templateContext.get("requestParameters"))); tempTemplateContext.putAll(templateContext); Map<String, Object> serviceCtx = service.makeValid(tempTemplateContext, ModelService.IN_PARAM); Map<String, Object> serviceRes; try { serviceRes = dispatcher.runSync(serviceName, serviceCtx); } catch (GenericServiceException e) { Debug.logError(e, module); throw e; } if (ServiceUtil.isError(serviceRes)) { throw new GeneralException(ServiceUtil.getErrorMessage(serviceRes)); } else { templateContext.putAll(serviceRes); } } } String contentId = content.getString("contentId"); if (templateContext == null) { templateContext = new HashMap<String, Object>(); } // create the content facade ContentMapFacade facade = new ContentMapFacade(dispatcher, content, templateContext, locale, mimeTypeId, cache); // If this content is decorating something then tell the facade about it in order to maintain the chain of decoration ContentMapFacade decoratedContent = (ContentMapFacade) templateContext.get("decoratedContent"); if (decoratedContent != null) { facade.setDecoratedContent(decoratedContent); } // look for a content decorator String contentDecoratorId = content.getString("decoratorContentId"); // Check that the decoratorContent is not the same as the current content if (contentId.equals(contentDecoratorId)) { Debug.logError("[" + contentId + "] decoratorContentId is the same as contentId, ignoring.", module); contentDecoratorId = null; } // check to see if the decorator has already been run boolean isDecorated = Boolean.TRUE.equals(templateContext.get("_IS_DECORATED_")); if (!isDecorated && UtilValidate.isNotEmpty(contentDecoratorId)) { // if there is a decorator content; do not render this content; // instead render the decorator GenericValue decorator = EntityQuery.use(delegator).from("Content").where("contentId", contentDecoratorId).cache(cache).queryOne(); if (decorator == null) { throw new GeneralException("No decorator content found for decorator contentId [" + contentDecoratorId + "]"); } // render the decorator ContentMapFacade decFacade = new ContentMapFacade(dispatcher, decorator, templateContext, locale, mimeTypeId, cache); decFacade.setDecoratedContent(facade); facade.setIsDecorated(true); // decorated content templateContext.put("decoratedContent", facade); // decorator content templateContext.put("thisContent", decFacade); ContentWorker.renderContentAsText(dispatcher, contentDecoratorId, out, templateContext, locale, mimeTypeId, null, null, cache); } else { // get the data resource info String templateDataResourceId = content.getString("templateDataResourceId"); String dataResourceId = content.getString("dataResourceId"); if (UtilValidate.isEmpty(dataResourceId)) { Debug.logError("No dataResourceId found for contentId: " + content.getString("contentId"), module); return; } // set this content facade in the context templateContext.put("thisContent", facade); templateContext.put("contentId", contentId); // now if no template; just render the data if (UtilValidate.isEmpty(templateDataResourceId) || templateContext.containsKey("ignoreTemplate")) { if (UtilValidate.isEmpty(contentId)) { Debug.logError("No content ID found.", module); return; } if (UtilValidate.isNotEmpty(webAnalytics)) { DataResourceWorker.renderDataResourceAsText(dispatcher, delegator, dataResourceId, out, templateContext, locale, mimeTypeId, cache, webAnalytics); } else { DataResourceWorker.renderDataResourceAsText(dispatcher, dataResourceId, out, templateContext, locale, mimeTypeId, cache); } // there is a template; render the data and then the template } else { Writer dataWriter = new StringWriter(); DataResourceWorker.renderDataResourceAsText(dispatcher, dataResourceId, dataWriter, templateContext, locale, mimeTypeId, cache); String textData = dataWriter.toString(); if (textData != null) { textData = textData.trim(); } String mimeType; try { mimeType = DataResourceWorker.getDataResourceMimeType(delegator, dataResourceId, null); } catch (GenericEntityException e) { throw new GeneralException(e.getMessage()); } // This part is using an xml file as the input data and an ftl or xsl file to present it. if (UtilValidate.isNotEmpty(mimeType)) { if (mimeType.toLowerCase().indexOf("xml") >= 0) { GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne(); GenericValue templateDataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", templateDataResourceId).cache().queryOne(); if ("FTL".equals(templateDataResource.getString("dataTemplateTypeId"))) { StringReader sr = new StringReader(textData); try { NodeModel nodeModel = NodeModel.parse(new InputSource(sr)); templateContext.put("doc", nodeModel); } catch (SAXException e) { throw new GeneralException(e.getMessage()); } catch (ParserConfigurationException e2) { throw new GeneralException(e2.getMessage()); } } else { templateContext.put("docFile", DataResourceWorker.getContentFile(dataResource.getString("dataResourceTypeId"), dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot")).getAbsoluteFile().toString()); } } else { // must be text templateContext.put("textData", textData); } } else { templateContext.put("textData", textData); } // render the template DataResourceWorker.renderDataResourceAsText(dispatcher, templateDataResourceId, out, templateContext, locale, mimeTypeId, cache); } } }
Example 13
Project: docgen-old-master File: Transform.java View source code |
// ------------------------------------------------------------------------- // Methods: /** * Loads the source XML and generates the output in the destination * directory. Don't forget to set JavaBean properties first. * * @throws DocgenException If a docgen-specific error occurs * @throws IOException If a file or other resource is missing or otherwise * can't be read/written. * @throws SAXException If the XML is not well-formed and valid, or the * SAX XML parsing has other problems. */ public void execute() throws DocgenException, IOException, SAXException { if (executed) { throw new DocgenException("This transformation was alrady executed; " + "use a new " + Transform.class.getName() + "."); } executed = true; if (srcDir == null) { throw new DocgenException("The source directory (the DocBook XML) wasn't specified."); } if (!srcDir.isDirectory()) { throw new IOException("Source directory doesn't exist: " + srcDir.getAbsolutePath()); } if (destDir == null) { throw new DocgenException("The destination directory wasn't specified."); } // Note: This directory will be created automatically if missing. // Load configuration file: File templatesDir = null; String eclipseLinkTo = null; File cfgFile = new File(srcDir, FILE_SETTINGS); if (cfgFile.exists()) { Map<String, Object> cfg; try { cfg = CJSONInterpreter.evalAsMap(cfgFile); } catch (CJSONInterpreter.EvaluationException e) { throw new DocgenException(e.getMessage(), e.getCause()); } for (Entry<String, Object> cfgEnt : cfg.entrySet()) { final String settingName = cfgEnt.getKey(); final Object settingValue = cfgEnt.getValue(); if (settingName.equals(SETTING_IGNORED_FILES)) { List<String> patterns = castSettingToStringList(cfgFile, settingName, settingValue); for (String pattern : patterns) { ignoredFilePathPatterns.add(FileUtil.globToRegexp(pattern)); } } else if (settingName.equals(SETTING_OLINKS)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); for (Entry<String, Object> ent : m.entrySet()) { String name = ent.getKey(); String target = castSettingValueMapValueToString(cfgFile, settingName, ent.getValue()); olinks.put(name, target); } } else if (settingName.equals(SETTING_INTERNAL_BOOKMARKS)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); for (Entry<String, Object> ent : m.entrySet()) { String name = ent.getKey(); String target = castSettingValueMapValueToString(cfgFile, settingName, ent.getValue()); internalBookmarks.put(name, target); } // Book-mark targets will be checked later, when the XML // document is already loaded. } else if (settingName.equals(SETTING_EXTERNAL_BOOKMARKS)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); for (Entry<String, Object> ent : m.entrySet()) { String name = ent.getKey(); String target = castSettingValueMapValueToString(cfgFile, settingName, ent.getValue()); externalBookmarks.put(name, target); } } else if (settingName.equals(SETTING_LOGO)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); logo = new HashMap<>(); for (Entry<String, Object> ent : m.entrySet()) { String k = ent.getKey(); String v = castSettingValueMapValueToString(cfgFile, settingName, ent.getValue()); if (!(k.equals(SETTING_LOGO_KEY_SRC) || k.equals(SETTING_LOGO_KEY_ALT) || k.equals(SETTING_LOGO_KEY_HREF))) { throw newCfgFileException(cfgFile, SETTING_LOGO, "Unknown logo option: " + k); } logo.put(k, v); } if (!logo.containsKey(SETTING_LOGO_KEY_SRC)) { throw newCfgFileException(cfgFile, SETTING_LOGO, "Missing logo option: " + SETTING_LOGO_KEY_SRC); } if (!logo.containsKey(SETTING_LOGO_KEY_ALT)) { throw newCfgFileException(cfgFile, SETTING_LOGO, "Missing logo option: " + SETTING_LOGO_KEY_ALT); } if (!logo.containsKey(SETTING_LOGO_KEY_HREF)) { throw newCfgFileException(cfgFile, SETTING_LOGO, "Missing logo option: " + SETTING_LOGO_KEY_HREF); } } else if (settingName.equals(SETTING_COPYRIGHT_HOLDER)) { copyrightHolder = castSettingToString(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_COPYRIGHT_START_YEAR)) { copyrightStartYear = castSettingToInt(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_SEO_META)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); seoMeta = new LinkedHashMap<>(); for (Entry<String, Object> ent : m.entrySet()) { String k = ent.getKey(); Map<String, String> v = castSettingValueMapValueToMapOfStringString(cfgFile, settingName, ent.getValue(), null, SETTING_SEO_META_KEYS); seoMeta.put(k, v); } } else if (settingName.equals(SETTING_TABS)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); for (Entry<String, Object> ent : m.entrySet()) { String k = ent.getKey(); String v = castSettingValueMapValueToString(cfgFile, settingName, ent.getValue()); tabs.put(k, v); } } else if (settingName.equals(SETTING_SECONDARY_TABS)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); secondaryTabs = new LinkedHashMap<>(); for (Entry<String, Object> ent : m.entrySet()) { String k = ent.getKey(); Map<String, String> v = castSettingValueMapValueToMapOfStringString(cfgFile, settingName, ent.getValue(), COMMON_LINK_KEYS, null); secondaryTabs.put(k, v); } } else if (settingName.equals(SETTING_SOCIAL_LINKS)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); socialLinks = new LinkedHashMap<>(); for (Entry<String, Object> ent : m.entrySet()) { String entName = ent.getKey(); Map<String, String> entValue = castSettingValueMapValueToMapOfStringString(cfgFile, settingName, ent.getValue(), COMMON_LINK_KEYS, null); socialLinks.put(entName, entValue); } } else if (settingName.equals(SETTING_FOOTER_SITEMAP)) { // TODO Check value in more details footerSiteMap = (Map) castSettingToMap(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_VALIDATION)) { Map<String, Object> m = castSettingToMap(cfgFile, SETTING_VALIDATION, settingValue); for (Entry<String, Object> ent : m.entrySet()) { String name = ent.getKey(); if (name.equals(SETTING_VALIDATION_PROGRAMLISTINGS_REQ_ROLE)) { validationOps.setProgramlistingRequiresRole(caseSettingToBoolean(cfgFile, settingName + "." + name, ent.getValue())); } else if (name.equals(SETTING_VALIDATION_PROGRAMLISTINGS_REQ_LANG)) { validationOps.setProgramlistingRequiresLanguage(caseSettingToBoolean(cfgFile, settingName + "." + name, ent.getValue())); } else if (name.equals(SETTING_VALIDATION_OUTPUT_FILES_CAN_USE_AUTOID)) { validationOps.setOutputFilesCanUseAutoID(caseSettingToBoolean(cfgFile, settingName + "." + name, ent.getValue())); } else if (name.equals(SETTING_VALIDATION_MAXIMUM_PROGRAMLISTING_WIDTH)) { validationOps.setMaximumProgramlistingWidth(castSettingToInt(cfgFile, settingName + "." + name, ent.getValue())); } else { throw newCfgFileException(cfgFile, SETTING_VALIDATION, "Unknown validation option: " + name); } } } else if (settingName.equals(SETTING_OFFLINE)) { if (offline == null) { // Ignore if the caller has already set this offline = caseSettingToBoolean(cfgFile, settingName, settingValue); } } else if (settingName.equals(SETTING_SIMPLE_NAVIGATION_MODE)) { simpleNavigationMode = caseSettingToBoolean(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_DEPLOY_URL)) { deployUrl = castSettingToString(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_ONLINE_TRACKER_HTML)) { String onlineTrackerHtmlPath = castSettingToString(cfgFile, settingName, settingValue); File f = new File(getSourceDirectory(), onlineTrackerHtmlPath); if (!f.exists()) { throw newCfgFileException(cfgFile, SETTING_ONLINE_TRACKER_HTML, "File not found: " + f.toPath()); } onlineTrackerHTML = FileUtil.loadString(f, UTF_8); } else if (settingName.equals(SETTING_REMOVE_NODES_WHEN_ONLINE)) { removeNodesWhenOnline = Collections.unmodifiableSet(new HashSet<String>(castSettingToStringList(cfgFile, settingName, settingValue))); } else if (settingName.equals(SETTING_ECLIPSE)) { Map<String, Object> m = castSettingToMap(cfgFile, settingName, settingValue); for (Entry<String, Object> ent : m.entrySet()) { String name = ent.getKey(); if (name.equals(SETTING_ECLIPSE_LINK_TO)) { String value = castSettingToString(cfgFile, settingName + "." + name, ent.getValue()); eclipseLinkTo = value; } else { throw newCfgFileException(cfgFile, settingName, "Unknown Eclipse option: " + name); } } } else if (settingName.equals(SETTING_LOCALE)) { String s = castSettingToString(cfgFile, settingName, settingValue); locale = StringUtil.deduceLocale(s); } else if (settingName.equals(SETTING_TIME_ZONE)) { String s = castSettingToString(cfgFile, settingName, settingValue); timeZone = TimeZone.getTimeZone(s); } else if (settingName.equals(SETTING_GENERATE_ECLIPSE_TOC)) { generateEclipseTOC = caseSettingToBoolean(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_SHOW_EDITORAL_NOTES)) { showEditoralNotes = caseSettingToBoolean(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_SHOW_XXE_LOGO)) { showXXELogo = caseSettingToBoolean(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_SEARCH_KEY)) { searchKey = castSettingToString(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_DISABLE_JAVASCRIPT)) { disableJavaScript = caseSettingToBoolean(cfgFile, settingName, settingValue); } else if (settingName.equals(SETTING_CONTENT_DIRECTORY)) { String s = castSettingToString(cfgFile, settingName, settingValue); contentDir = new File(srcDir, s); if (!contentDir.isDirectory()) { throw newCfgFileException(cfgFile, settingName, "It's not an existing directory: " + contentDir.getAbsolutePath()); } } else if (settingName.equals(SETTING_LOWEST_FILE_ELEMENT_RANK) || settingName.equals(SETTING_LOWEST_PAGE_TOC_ELEMENT_RANK)) { DocumentStructureRank rank; String strRank = castSettingToString(cfgFile, settingName, settingValue); try { rank = DocumentStructureRank.valueOf(strRank.toUpperCase()); } catch (IllegalArgumentException e) { String msg; if (strRank.equalsIgnoreCase("article")) { msg = "\"article\" is not a rank, since articles " + "can have various ranks depending on their " + "context. (Hint: if the article is the " + "top-level element then it has \"chapter\" " + "rank.)"; } else { msg = "Unknown rank: " + strRank; } throw newCfgFileException(cfgFile, settingName, msg); } if (settingName.equals(SETTING_LOWEST_FILE_ELEMENT_RANK)) { lowestFileElemenRank = rank; } else if (settingName.equals(SETTING_LOWEST_PAGE_TOC_ELEMENT_RANK)) { lowestPageTOCElemenRank = rank; } else { throw new BugException("Unexpected setting name."); } } else if (settingName.equals(SETTING_MAX_TOF_DISPLAY_DEPTH)) { maxTOFDisplayDepth = castSettingToInt(cfgFile, settingName, settingValue); if (maxTOFDisplayDepth < 1) { throw newCfgFileException(cfgFile, settingName, "Value must be at least 1."); } } else if (settingName.equals(SETTING_MAX_MAIN_TOF_DISPLAY_DEPTH)) { maxMainTOFDisplayDepth = castSettingToInt(cfgFile, settingName, settingValue); if (maxTOFDisplayDepth < 1) { throw newCfgFileException(cfgFile, settingName, "Value must be at least 1."); } } else if (settingName.equals(SETTING_NUMBERED_SECTIONS)) { numberedSections = caseSettingToBoolean(cfgFile, settingName, settingValue); } else { throw newCfgFileException(cfgFile, "Unknown setting: \"" + settingName + "\". (Hint: See the list of available " + "settings in the Java API documentation of " + Transform.class.getName() + ". Also, note that " + "setting names are case-sensitive.)"); } } if (offline == null) { throw new DocgenException("The \"" + SETTING_OFFLINE + "\" setting wasn't specified; it must be set to true or false"); } if (logo == null) { throw new DocgenException("The \"" + SETTING_LOGO + "\" setting wasn't specified; it must be set currently, as the layout reserves space for it."); } if (copyrightHolder == null) { throw new DocgenException("The \"" + SETTING_COPYRIGHT_HOLDER + "\" setting wasn't specified."); } if (copyrightStartYear == null) { throw new DocgenException("The \"" + SETTING_COPYRIGHT_START_YEAR + "\" setting wasn't specified."); } } // Ensure proper rank relations: if (lowestPageTOCElemenRank.compareTo(lowestFileElemenRank) > 0) { lowestPageTOCElemenRank = lowestFileElemenRank; } // Ensure {@link #maxMainTOFDisplayDepth} is set: if (maxMainTOFDisplayDepth == 0) { maxMainTOFDisplayDepth = maxTOFDisplayDepth; } templatesDir = new File(srcDir, DIR_TEMPLATES); if (!templatesDir.exists()) { templatesDir = null; } if (contentDir == null) { contentDir = srcDir; } // Initialize state fields primaryIndexTermLookup = new HashMap<String, List<NodeModel>>(); secondaryIndexTermLookup = new HashMap<String, SortedMap<String, List<NodeModel>>>(); elementsById = new HashMap<String, Element>(); tocNodes = new ArrayList<TOCNode>(); indexEntries = new ArrayList<String>(); try { Logger.selectLoggerLibrary(Logger.LIBRARY_NONE); } catch (ClassNotFoundException e) { throw new BugException(e); } fmConfig = new Configuration(Configuration.VERSION_2_3_24); TemplateLoader templateLoader = new ClassTemplateLoader(Transform.class, "templates"); if (templatesDir != null) { templateLoader = new MultiTemplateLoader(new TemplateLoader[] { new FileTemplateLoader(templatesDir), templateLoader }); } fmConfig.setTemplateLoader(templateLoader); fmConfig.setLocale(locale); fmConfig.setTimeZone(timeZone); fmConfig.setDefaultEncoding(UTF_8.name()); fmConfig.setOutputEncoding(UTF_8.name()); // Do the actual job: // - Load and validate the book XML final File docFile; { final File docFile1 = new File(contentDir, FILE_BOOK); if (docFile1.isFile()) { docFile = docFile1; } else { final File docFile2 = new File(contentDir, FILE_ARTICLE); if (docFile2.isFile()) { docFile = docFile2; } else { throw new DocgenException("The book file is missing: " + docFile1.getAbsolutePath() + " or " + docFile2.getAbsolutePath()); } } } Document doc = XMLUtil.loadDocBook5XML(docFile, validate, validationOps, logger); ignoredFilePathPatterns.add(FileUtil.globToRegexp(docFile.getName())); // - Post-edit and examine the DOM: preprocessDOM(doc); // Resolve Docgen URL schemes in setting values: if (tabs != null) { for (Entry<String, String> tabEnt : tabs.entrySet()) { tabEnt.setValue(resolveDocgenURL(SETTING_TABS, tabEnt.getValue())); } } if (secondaryTabs != null) { for (Map<String, String> tab : secondaryTabs.values()) { tab.put("href", resolveDocgenURL(SETTING_SECONDARY_TABS, tab.get("href"))); } } if (externalBookmarks != null) { for (Entry<String, String> bookmarkEnt : externalBookmarks.entrySet()) { bookmarkEnt.setValue(resolveDocgenURL(SETTING_EXTERNAL_BOOKMARKS, bookmarkEnt.getValue())); } } if (socialLinks != null) { for (Map<String, String> tab : socialLinks.values()) { tab.put("href", resolveDocgenURL(SETTING_SOCIAL_LINKS, tab.get("href"))); } } if (footerSiteMap != null) { for (Map<String, String> links : footerSiteMap.values()) { for (Map.Entry<String, String> link : links.entrySet()) { link.setValue(resolveDocgenURL(SETTING_FOOTER_SITEMAP, link.getValue())); } } } if (logo != null) { String logoHref = logo.get(SETTING_LOGO_KEY_HREF); if (logoHref != null) { logo.put(SETTING_LOGO_KEY_HREF, resolveDocgenURL(SETTING_LOGO, logoHref)); } } // - Create destination directory: if (!destDir.isDirectory() && !destDir.mkdirs()) { throw new IOException("Failed to create destination directory: " + destDir.getAbsolutePath()); } // - Check internal book-marks: for (Entry<String, String> ent : internalBookmarks.entrySet()) { String id = ent.getValue(); if (!elementsById.containsKey(id)) { throw newCfgFileException(cfgFile, SETTING_INTERNAL_BOOKMARKS, "No element with id \"" + id + "\" exists in the book."); } } // - Setup common data-model variables: try { // Settings: fmConfig.setSharedVariable(VAR_OFFLINE, offline); fmConfig.setSharedVariable(VAR_SIMPLE_NAVIGATION_MODE, simpleNavigationMode); fmConfig.setSharedVariable(VAR_DEPLOY_URL, deployUrl); fmConfig.setSharedVariable(VAR_ONLINE_TRACKER_HTML, onlineTrackerHTML); fmConfig.setSharedVariable(VAR_SHOW_EDITORAL_NOTES, showEditoralNotes); fmConfig.setSharedVariable(VAR_SHOW_XXE_LOGO, showXXELogo); fmConfig.setSharedVariable(VAR_SEARCH_KEY, searchKey); fmConfig.setSharedVariable(VAR_DISABLE_JAVASCRIPT, disableJavaScript); fmConfig.setSharedVariable(VAR_OLINKS, olinks); fmConfig.setSharedVariable(VAR_NUMBERED_SECTIONS, numberedSections); fmConfig.setSharedVariable(VAR_LOGO, logo); fmConfig.setSharedVariable(VAR_COPYRIGHT_HOLDER, copyrightHolder); fmConfig.setSharedVariable(VAR_COPYRIGHT_START_YEAR, copyrightStartYear); fmConfig.setSharedVariable(VAR_TABS, tabs); fmConfig.setSharedVariable(VAR_SECONDARY_TABS, secondaryTabs); fmConfig.setSharedVariable(VAR_SOCIAL_LINKS, socialLinks); fmConfig.setSharedVariable(VAR_FOOTER_SITEMAP, footerSiteMap); fmConfig.setSharedVariable(VAR_EXTERNAL_BOOKMARDS, externalBookmarks); fmConfig.setSharedVariable(VAR_INTERNAL_BOOKMARDS, internalBookmarks); fmConfig.setSharedVariable(VAR_ROOT_ELEMENT, doc.getDocumentElement()); // Calculated data: { Date generationTime; String generationTimeStr = System.getProperty(SYSPROP_GENERATION_TIME); if (generationTimeStr == null) { generationTime = new Date(); } else { try { generationTime = DateUtil.parseISO8601DateTime(generationTimeStr, DateUtil.UTC, new DateUtil.TrivialCalendarFieldsToDateConverter()); } catch (DateParseException e) { throw new DocgenException("Malformed \"" + SYSPROP_GENERATION_TIME + "\" system property value: " + generationTimeStr, e); } } fmConfig.setSharedVariable(VAR_TRANSFORM_START_TIME, generationTime); } fmConfig.setSharedVariable(VAR_INDEX_ENTRIES, indexEntries); int tofCntLv1 = countTOFEntries(tocNodes.get(0), 1); int tofCntLv2 = countTOFEntries(tocNodes.get(0), 2); fmConfig.setSharedVariable(VAR_SHOW_NAVIGATION_BAR, tofCntLv1 != 0 || internalBookmarks.size() != 0 || externalBookmarks.size() != 0); fmConfig.setSharedVariable(VAR_SHOW_BREADCRUMB, tofCntLv1 != tofCntLv2); // Helper methods and directives: fmConfig.setSharedVariable("NodeFromID", nodeFromID); fmConfig.setSharedVariable("CreateLinkFromID", createLinkFromID); fmConfig.setSharedVariable("primaryIndexTermLookup", primaryIndexTermLookup); fmConfig.setSharedVariable("secondaryIndexTermLookup", secondaryIndexTermLookup); fmConfig.setSharedVariable("CreateLinkFromNode", createLinkFromNode); } catch (TemplateModelException e) { throw new BugException(e); } // - Generate ToC JSON-s: { logger.info("Generating ToC JSON..."); Template template = fmConfig.getTemplate(FILE_TOC_JSON_TEMPLATE); try (Writer wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(destDir, FILE_TOC_JSON_OUTPUT)), UTF_8))) { try { SimpleHash dataModel = new SimpleHash(fmConfig.getObjectWrapper()); dataModel.put(VAR_JSON_TOC_ROOT, tocNodes.get(0)); template.process(dataModel, wr, null, NodeModel.wrap(doc)); } catch (TemplateException e) { throw new BugException("Failed to generate ToC JSON " + "(see cause exception).", e); } } } // - Generate Sitemap XML: { logger.info("Generating Sitemap XML..."); Template template = fmConfig.getTemplate(FILE_SITEMAP_XML_TEMPLATE); try (Writer wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(destDir, FILE_SITEMAP_XML_OUTPUT)), UTF_8))) { try { SimpleHash dataModel = new SimpleHash(fmConfig.getObjectWrapper()); dataModel.put(VAR_JSON_TOC_ROOT, tocNodes.get(0)); template.process(dataModel, wr, null, NodeModel.wrap(doc)); } catch (TemplateException e) { throw new BugException("Failed to generate Sitemap XML" + "(see cause exception).", e); } } } // - Generate the HTML-s: logger.info("Generating HTML files..."); int htmlFileCounter = 0; for (TOCNode tocNode : tocNodes) { if (tocNode.getOutputFileName() != null) { try { currentFileTOCNode = tocNode; try { // All output-file-specific processing comes here. htmlFileCounter += generateHTMLFile(); } finally { currentFileTOCNode = null; } } catch (freemarker.core.StopException e) { throw new DocgenException(e.getMessage()); } catch (TemplateException e) { throw new BugException(e); } } } if (!offline && searchKey != null) { try { generateSearchResultsHTMLFile(doc); htmlFileCounter++; } catch (freemarker.core.StopException e) { throw new DocgenException(e.getMessage()); } catch (TemplateException e) { throw new BugException(e); } } // - Copy the standard statics: logger.info("Copying common static files..."); copyCommonStatic("docgen.css"); copyCommonStatic("docgen.min.css"); copyCommonStatic("img/patterned-bg.png"); copyCommonStatic("fonts/icomoon.eot"); copyCommonStatic("fonts/icomoon.svg"); copyCommonStatic("fonts/icomoon.ttf"); copyCommonStatic("fonts/icomoon.woff"); for (int i = 1; i < 15; i++) { copyCommonStatic("img/callouts/" + i + ".gif"); } if (showXXELogo) { copyCommonStatic("img/xxe.png"); } if (!disableJavaScript) { copyCommonStatic("main.js"); copyCommonStatic("main.min.js"); } // - Copy the custom statics: logger.info("Copying custom static files..."); int bookSpecStaticFileCounter = FileUtil.copyDir(contentDir, destDir, ignoredFilePathPatterns); // - Eclipse ToC: if (generateEclipseTOC) { if (simpleNavigationMode) { throw new DocgenException("Eclipse ToC generation is untested/unsupported with simpleNavigationMode=true."); } logger.info("Generating Eclipse ToC..."); Template template = fmConfig.getTemplate(FILE_ECLIPSE_TOC_TEMPLATE); try (Writer wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(destDir, FILE_ECLIPSE_TOC_OUTPUT)), UTF_8))) { try { SimpleHash dataModel = new SimpleHash(fmConfig.getObjectWrapper()); if (eclipseLinkTo != null) { dataModel.put(VAR_ECLIPSE_LINK_TO, eclipseLinkTo); } template.process(dataModel, wr, null, NodeModel.wrap(doc)); } catch (TemplateException e) { throw new BugException("Failed to generate Eclipse ToC " + "(see cause exception).", e); } } } // - Report summary: logger.info("Done: " + htmlFileCounter + " HTML-s + " + bookSpecStaticFileCounter + " custom statics + commons" + (generateEclipseTOC ? " + Eclipse ToC" : "")); }
Example 14
Project: rapid-framework-master File: GeneratorControl.java View source code |
/** load xml data */ public NodeModel loadXml(String file, boolean removeXmlNamespace) { try { if (removeXmlNamespace) { InputStream forEncodingInput = FileHelper.getInputStream(file); String encoding = XMLHelper.getXMLEncoding(forEncodingInput); forEncodingInput.close(); InputStream input = FileHelper.getInputStream(file); String xml = IOHelper.toString(encoding, input); xml = XMLHelper.removeXmlns(xml); input.close(); return NodeModel.parse(new InputSource(new StringReader(xml.trim()))); } else { return NodeModel.parse(new InputSource(FileHelper.getInputStream(file))); } } catch (Exception e) { throw new IllegalArgumentException("loadXml error,file:" + file, e); } }
Example 15
Project: rg-master File: GeneratorControl.java View source code |
/** load xml data */ public NodeModel loadXml(String file, boolean removeXmlNamespace) { try { if (removeXmlNamespace) { InputStream forEncodingInput = FileHelper.getInputStream(file); String encoding = XMLHelper.getXMLEncoding(forEncodingInput); forEncodingInput.close(); InputStream input = FileHelper.getInputStream(file); String xml = IOHelper.toString(encoding, input); xml = XMLHelper.removeXmlns(xml); input.close(); return NodeModel.parse(new InputSource(new StringReader(xml.trim()))); } else { return NodeModel.parse(new InputSource(FileHelper.getInputStream(file))); } } catch (Exception e) { throw new IllegalArgumentException("loadXml error,file:" + file, e); } }
Example 16
Project: freemarker-old-master File: TemplateTestCase.java View source code |
/* * This method just contains all the code to seed the data model * ported over from the individual classes. This seems ugly and unnecessary. * We really might as well just expose pretty much * the same tree to all our tests. (JR) */ @Override @SuppressWarnings("boxing") public void setUp() throws Exception { conf.setDirectoryForTemplateLoading(new File(getTestClassDirectory(), "templates")); dataModel.put(ASSERT_VAR_NAME, AssertDirective.INSTANCE); dataModel.put(ASSERT_EQUALS_VAR_NAME, AssertEqualsDirective.INSTANCE); dataModel.put(ASSERT_FAILS_VAR_NAME, AssertFailsDirective.INSTANCE); dataModel.put(NO_OUTPUT_VAR_NAME, NoOutputDirective.INSTANCE); dataModel.put(JAVA_OBJECT_INFO_VAR_NAME, JavaObjectInfo.INSTANCE); dataModel.put(TEST_NAME_VAR_NAME, simpleTestName); dataModel.put(ICI_INT_VALUE_VAR_NAME, conf.getIncompatibleImprovements().intValue()); dataModel.put("message", "Hello, world!"); if (simpleTestName.startsWith("api-builtin")) { dataModel.put("map", ImmutableMap.of(1, "a", 2, "b", 3, "c")); dataModel.put("list", ImmutableList.of(1, 2, 3)); dataModel.put("set", ImmutableSet.of("a", "b", "c")); dataModel.put("s", "test"); } else if (simpleTestName.equals("bean-maps")) { BeansWrapper w1 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w2 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w3 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w4 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w5 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w6 = new Java7MembersOnlyBeansWrapper(); BeansWrapper w7 = new Java7MembersOnlyBeansWrapper(); w1.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY); w2.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY); w3.setExposureLevel(BeansWrapper.EXPOSE_NOTHING); w4.setExposureLevel(BeansWrapper.EXPOSE_NOTHING); w5.setExposureLevel(BeansWrapper.EXPOSE_ALL); w6.setExposureLevel(BeansWrapper.EXPOSE_ALL); w1.setMethodsShadowItems(true); w2.setMethodsShadowItems(false); w3.setMethodsShadowItems(true); w4.setMethodsShadowItems(false); w5.setMethodsShadowItems(true); w6.setMethodsShadowItems(false); w7.setSimpleMapWrapper(true); Object test = getTestMapBean(); dataModel.put("m1", w1.wrap(test)); dataModel.put("m2", w2.wrap(test)); dataModel.put("m3", w3.wrap(test)); dataModel.put("m4", w4.wrap(test)); dataModel.put("m5", w5.wrap(test)); dataModel.put("m6", w6.wrap(test)); dataModel.put("m7", w7.wrap(test)); dataModel.put("s1", w1.wrap("hello")); dataModel.put("s2", w1.wrap("world")); dataModel.put("s3", w5.wrap("hello")); dataModel.put("s4", w5.wrap("world")); } else if (simpleTestName.equals("beans")) { dataModel.put("array", new String[] { "array-0", "array-1" }); dataModel.put("list", Arrays.asList(new String[] { "list-0", "list-1", "list-2" })); Map tmap = new HashMap(); tmap.put("key", "value"); Object objKey = new Object(); tmap.put(objKey, "objValue"); dataModel.put("map", tmap); dataModel.put("objKey", objKey); dataModel.put("obj", new freemarker.test.templatesuite.models.BeanTestClass()); dataModel.put("resourceBundle", new ResourceBundleModel(ResourceBundle.getBundle("freemarker.test.templatesuite.models.BeansTestResources"), BeansWrapper.getDefaultInstance())); dataModel.put("date", new GregorianCalendar(1974, 10, 14).getTime()); dataModel.put("statics", BeansWrapper.getDefaultInstance().getStaticModels()); dataModel.put("enums", BeansWrapper.getDefaultInstance().getEnumModels()); } else if (simpleTestName.equals("boolean")) { dataModel.put("boolean1", TemplateBooleanModel.FALSE); dataModel.put("boolean2", TemplateBooleanModel.TRUE); dataModel.put("boolean3", TemplateBooleanModel.TRUE); dataModel.put("boolean4", TemplateBooleanModel.TRUE); dataModel.put("boolean5", TemplateBooleanModel.FALSE); dataModel.put("list1", new BooleanList1()); dataModel.put("list2", new BooleanList2()); dataModel.put("hash1", new BooleanHash1()); dataModel.put("hash2", new BooleanHash2()); } else if (simpleTestName.startsWith("dateformat")) { GregorianCalendar cal = new GregorianCalendar(2002, 10, 15, 14, 54, 13); cal.setTimeZone(TimeZone.getTimeZone("GMT")); dataModel.put("date", new SimpleDate(cal.getTime(), TemplateDateModel.DATETIME)); dataModel.put("unknownDate", new SimpleDate(cal.getTime(), TemplateDateModel.UNKNOWN)); dataModel.put("javaGMT02", TimeZone.getTimeZone("GMT+02")); dataModel.put("javaUTC", TimeZone.getTimeZone("UTC")); dataModel.put("adaptedToStringScalar", new Object() { @Override public String toString() { return "GMT+02"; } }); dataModel.put("sqlDate", new java.sql.Date(1273955885023L)); dataModel.put("sqlTime", new java.sql.Time(74285023L)); } else if (templateName.equals("list.ftl") || templateName.equals("list2.ftl") || templateName.equals("list3.ftl")) { dataModel.put("listables", new Listables()); } else if (simpleTestName.startsWith("number-format")) { dataModel.put("int", new SimpleNumber(Integer.valueOf(1))); dataModel.put("double", new SimpleNumber(Double.valueOf(1.0))); dataModel.put("double2", new SimpleNumber(Double.valueOf(1 + 1e-15))); dataModel.put("double3", new SimpleNumber(Double.valueOf(1e-16))); dataModel.put("double4", new SimpleNumber(Double.valueOf(-1e-16))); dataModel.put("bigDecimal", new SimpleNumber(java.math.BigDecimal.valueOf(1))); dataModel.put("bigDecimal2", new SimpleNumber(java.math.BigDecimal.valueOf(1, 16))); } else if (simpleTestName.equals("simplehash-char-key")) { HashMap mStringC = new HashMap(); mStringC.put("c", "string"); dataModel.put("mStringC", mStringC); HashMap mStringCNull = new HashMap(); mStringCNull.put("c", null); dataModel.put("mStringCNull", mStringCNull); HashMap mCharC = new HashMap(); mCharC.put(Character.valueOf('c'), "char"); dataModel.put("mCharC", mCharC); HashMap mCharCNull = new HashMap(); mCharCNull.put("c", null); dataModel.put("mCharCNull", mCharCNull); HashMap mMixed = new HashMap(); mMixed.put(Character.valueOf('c'), "char"); mMixed.put("s", "string"); mMixed.put("s2", "string2"); mMixed.put("s2n", null); dataModel.put("mMixed", mMixed); } else if (simpleTestName.equals("default-xmlns")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/defaultxmlns1.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("multimodels")) { dataModel.put("test", "selftest"); dataModel.put("self", "self"); dataModel.put("zero", Integer.valueOf(0)); dataModel.put("data", new MultiModel1()); } else if (simpleTestName.equals("stringbimethods")) { dataModel.put("multi", new TestBoolean()); } else if (simpleTestName.startsWith("type-builtins")) { dataModel.put("testmethod", new TestMethod()); dataModel.put("testnode", new TestNode()); dataModel.put("testcollection", new SimpleCollection(new ArrayList())); dataModel.put("testcollectionEx", DefaultNonListCollectionAdapter.adapt(new HashSet(), null)); dataModel.put("bean", new TestBean()); } else if (simpleTestName.equals("date-type-builtins")) { GregorianCalendar cal = new GregorianCalendar(2003, 4 - 1, 5, 6, 7, 8); cal.setTimeZone(TimeZone.getTimeZone("UTC")); Date d = cal.getTime(); dataModel.put("unknown", d); dataModel.put("timeOnly", new java.sql.Time(d.getTime())); dataModel.put("dateOnly", new java.sql.Date(d.getTime())); dataModel.put("dateTime", new java.sql.Timestamp(d.getTime())); } else if (simpleTestName.equals("var-layers")) { dataModel.put("x", Integer.valueOf(4)); dataModel.put("z", Integer.valueOf(4)); conf.setSharedVariable("y", Integer.valueOf(7)); } else if (simpleTestName.equals("xml-fragment")) { DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); DocumentBuilder db = f.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new InputSource(getClass().getResourceAsStream("models/xmlfragment.xml"))); dataModel.put("node", NodeModel.wrap(doc.getDocumentElement().getFirstChild().getFirstChild())); } else if (simpleTestName.equals("xmlns1")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xmlns2")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns2.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xmlns3") || simpleTestName.equals("xmlns4")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns3.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xmlns5")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/defaultxmlns1.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.equals("xml-ns_prefix-scope")) { InputSource is = new InputSource(getClass().getResourceAsStream("models/xml-ns_prefix-scope.xml")); NodeModel nm = NodeModel.parse(is); dataModel.put("doc", nm); } else if (simpleTestName.startsWith("sequence-builtins")) { Set abcSet = new TreeSet(); abcSet.add("a"); abcSet.add("b"); abcSet.add("c"); dataModel.put("abcSet", abcSet); List listWithNull = new ArrayList(); listWithNull.add("a"); listWithNull.add(null); listWithNull.add("c"); dataModel.put("listWithNull", listWithNull); List listWithNullsOnly = new ArrayList(); listWithNull.add(null); listWithNull.add(null); listWithNull.add(null); dataModel.put("listWithNullsOnly", listWithNullsOnly); dataModel.put("abcCollection", new SimpleCollection(abcSet)); Set set = new HashSet(); set.add("a"); set.add("b"); set.add("c"); dataModel.put("set", set); } else if (simpleTestName.equals("number-to-date")) { dataModel.put("bigInteger", new BigInteger("1305575275540")); dataModel.put("bigDecimal", new BigDecimal("1305575275539.5")); } else if (simpleTestName.equals("varargs")) { dataModel.put("m", new VarArgTestModel()); } else if (simpleTestName.startsWith("overloaded-methods-") && !simpleTestName.startsWith("overloaded-methods-2-")) { dataModel.put("obj", new OverloadedMethods()); } else if (simpleTestName.startsWith("boolean-formatting")) { dataModel.put("beansBoolean", new BooleanModel(Boolean.TRUE, (BeansWrapper) conf.getObjectWrapper())); dataModel.put("booleanAndString", new BooleanAndStringTemplateModel()); dataModel.put("booleanVsStringMethods", new BooleanVsStringMethods()); } else if (simpleTestName.startsWith("number-math-builtins")) { dataModel.put("fNan", Float.valueOf(Float.NaN)); dataModel.put("dNan", Double.valueOf(Double.NaN)); dataModel.put("fNinf", Float.valueOf(Float.NEGATIVE_INFINITY)); dataModel.put("dPinf", Double.valueOf(Double.POSITIVE_INFINITY)); dataModel.put("fn", Float.valueOf(-0.05f)); dataModel.put("dn", Double.valueOf(-0.05)); dataModel.put("ineg", Integer.valueOf(-5)); dataModel.put("ln", Long.valueOf(-5)); dataModel.put("sn", Short.valueOf((short) -5)); dataModel.put("bn", Byte.valueOf((byte) -5)); dataModel.put("bin", BigInteger.valueOf(5)); dataModel.put("bdn", BigDecimal.valueOf(-0.05)); dataModel.put("fp", Float.valueOf(0.05f)); dataModel.put("dp", Double.valueOf(0.05)); dataModel.put("ip", Integer.valueOf(5)); dataModel.put("lp", Long.valueOf(5)); dataModel.put("sp", Short.valueOf((short) 5)); dataModel.put("bp", Byte.valueOf((byte) 5)); dataModel.put("bip", BigInteger.valueOf(5)); dataModel.put("bdp", BigDecimal.valueOf(0.05)); } else if (simpleTestName.startsWith("classic-compatible")) { dataModel.put("array", new String[] { "a", "b", "c" }); dataModel.put("beansArray", new BeansWrapper().wrap(new String[] { "a", "b", "c" })); dataModel.put("beanTrue", new BeansWrapper().wrap(Boolean.TRUE)); dataModel.put("beanFalse", new BeansWrapper().wrap(Boolean.FALSE)); } else if (simpleTestName.startsWith("overloaded-methods-2-")) { dataModel.put("obj", new OverloadedMethods2()); final boolean dow = conf.getObjectWrapper() instanceof DefaultObjectWrapper; dataModel.put("dow", dow); dataModel.put("dowPre22", dow && ((DefaultObjectWrapper) conf.getObjectWrapper()).getIncompatibleImprovements().intValue() < _TemplateAPI.VERSION_INT_2_3_22); } }