Search in sources :

Example 1 with NodeModel

use of freemarker.ext.dom.NodeModel in project freemarker by apache.

the class TemplateTestCase method setUp.

/*
     * 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"))));
    BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_0).build();
    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<Object, Object> tmap = new HashMap<Object, Object>();
        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.getStaticModels());
        dataModel.put("enums", beansWrapper.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") || simpleTestName.equals("listhash")) {
        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<String, String> mStringC = new HashMap<String, String>();
        mStringC.put("c", "string");
        dataModel.put("mStringC", mStringC);
        HashMap<String, String> mStringCNull = new HashMap<String, String>();
        mStringCNull.put("c", null);
        dataModel.put("mStringCNull", mStringCNull);
        HashMap<Character, String> mCharC = new HashMap<Character, String>();
        mCharC.put(Character.valueOf('c'), "char");
        dataModel.put("mCharC", mCharC);
        HashMap<String, String> mCharCNull = new HashMap<String, String>();
        mCharCNull.put("c", null);
        dataModel.put("mCharCNull", mCharCNull);
        HashMap<Object, String> mMixed = new HashMap<Object, String>();
        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<Object>()));
        dataModel.put("testcollectionEx", DefaultNonListCollectionAdapter.adapt(new HashSet<Object>(), 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<String> abcSet = new TreeSet<String>();
        abcSet.add("a");
        abcSet.add("b");
        abcSet.add("c");
        dataModel.put("abcSet", abcSet);
        dataModel.put("abcSetNonSeq", DefaultNonListCollectionAdapter.adapt(abcSet, beansWrapper));
        List<String> listWithNull = new ArrayList<String>();
        listWithNull.add("a");
        listWithNull.add(null);
        listWithNull.add("c");
        dataModel.put("listWithNull", listWithNull);
        List<String> listWithNullsOnly = new ArrayList<String>();
        listWithNull.add(null);
        listWithNull.add(null);
        listWithNull.add(null);
        dataModel.put("listWithNullsOnly", listWithNullsOnly);
        dataModel.put("abcCollection", new SimpleCollection(abcSet));
        Set<String> set = new HashSet<String>();
        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", beansWrapper.wrap(new String[] { "a", "b", "c" }));
        dataModel.put("beanTrue", beansWrapper.wrap(Boolean.TRUE));
        dataModel.put("beanFalse", 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);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NodeModel(freemarker.ext.dom.NodeModel) TemplateNodeModel(freemarker.template.TemplateNodeModel) BooleanVsStringMethods(freemarker.test.templatesuite.models.BooleanVsStringMethods) SimpleNumber(freemarker.template.SimpleNumber) TreeSet(java.util.TreeSet) VarArgTestModel(freemarker.test.templatesuite.models.VarArgTestModel) BeansWrapperBuilder(freemarker.ext.beans.BeansWrapperBuilder) HashSet(java.util.HashSet) BooleanHash1(freemarker.test.templatesuite.models.BooleanHash1) BooleanHash2(freemarker.test.templatesuite.models.BooleanHash2) GregorianCalendar(java.util.GregorianCalendar) BooleanAndStringTemplateModel(freemarker.test.templatesuite.models.BooleanAndStringTemplateModel) SimpleCollection(freemarker.template.SimpleCollection) BigInteger(java.math.BigInteger) File(java.io.File) OverloadedMethods(freemarker.test.templatesuite.models.OverloadedMethods) CopyrightCommentRemoverTemplateLoader(freemarker.test.CopyrightCommentRemoverTemplateLoader) MultiModel1(freemarker.test.templatesuite.models.MultiModel1) BeansWrapper(freemarker.ext.beans.BeansWrapper) Java7MembersOnlyBeansWrapper(freemarker.ext.beans.Java7MembersOnlyBeansWrapper) Listables(freemarker.test.templatesuite.models.Listables) SimpleDate(freemarker.template.SimpleDate) Java7MembersOnlyBeansWrapper(freemarker.ext.beans.Java7MembersOnlyBeansWrapper) OverloadedMethods2(freemarker.test.templatesuite.models.OverloadedMethods2) BooleanModel(freemarker.ext.beans.BooleanModel) TemplateBooleanModel(freemarker.template.TemplateBooleanModel) DefaultObjectWrapper(freemarker.template.DefaultObjectWrapper) Date(java.util.Date) SimpleDate(freemarker.template.SimpleDate) BigDecimal(java.math.BigDecimal) ResourceBundleModel(freemarker.ext.beans.ResourceBundleModel) DocumentBuilder(javax.xml.parsers.DocumentBuilder) BooleanList2(freemarker.test.templatesuite.models.BooleanList2) FileTemplateLoader(freemarker.cache.FileTemplateLoader) BooleanList1(freemarker.test.templatesuite.models.BooleanList1)

Example 2 with NodeModel

use of freemarker.ext.dom.NodeModel in project ofbiz-framework by apache.

the class ContentWorker method renderContentAsText.

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);
                if (ServiceUtil.isError(serviceRes)) {
                    String errorMessage = ServiceUtil.getErrorMessage(serviceRes);
                    Debug.logError(errorMessage, module);
                    throw new GeneralException(errorMessage);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                throw e;
            }
            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);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) InputSource(org.xml.sax.InputSource) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashMap(java.util.HashMap) ModelService(org.apache.ofbiz.service.ModelService) SAXException(org.xml.sax.SAXException) DispatchContext(org.apache.ofbiz.service.DispatchContext) NodeModel(freemarker.ext.dom.NodeModel) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) StringReader(java.io.StringReader) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 3 with NodeModel

use of freemarker.ext.dom.NodeModel in project ofbiz-framework by apache.

the class EntitySaxReader method endElement.

public void endElement(String namespaceURI, String localName, String fullNameString) throws SAXException {
    if (Debug.verboseOn())
        Debug.logVerbose("endElement: localName=" + localName + ", fullName=" + fullNameString + ", numberRead=" + numberRead, module);
    if ("entity-engine-xml".equals(fullNameString)) {
        return;
    }
    if ("entity-engine-transform-xml".equals(fullNameString)) {
        // transform file & parse it, then return
        URL templateUrl = null;
        try {
            templateUrl = FlexibleLocation.resolveLocation(templatePath.toString());
        } catch (MalformedURLException e) {
            throw new SAXException("Could not find transform template with resource path [" + templatePath + "]; error was: " + e.toString());
        }
        if (templateUrl == null) {
            throw new SAXException("Could not find transform template with resource path: " + templatePath);
        } else {
            try {
                BufferedReader templateReader = new BufferedReader(new InputStreamReader(templateUrl.openStream(), UtilIO.getUtf8()));
                StringWriter outWriter = new StringWriter();
                Configuration config = FreeMarkerWorker.newConfiguration();
                config.setObjectWrapper(FreeMarkerWorker.getDefaultOfbizWrapper());
                config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS");
                Template template = new Template("FMImportFilter", templateReader, config);
                NodeModel nodeModel = NodeModel.wrap(this.rootNodeForTemplate);
                Map<String, Object> context = new HashMap<String, Object>();
                TemplateHashModel staticModels = FreeMarkerWorker.getDefaultOfbizWrapper().getStaticModels();
                context.put("Static", staticModels);
                context.put("doc", nodeModel);
                template.process(context, outWriter);
                String s = outWriter.toString();
                if (Debug.verboseOn())
                    Debug.logVerbose("transformed xml: " + s, module);
                EntitySaxReader reader = new EntitySaxReader(delegator);
                reader.setUseTryInsertMethod(this.useTryInsertMethod);
                try {
                    reader.setTransactionTimeout(this.transactionTimeout);
                } catch (GenericTransactionException e1) {
                    Debug.logWarning("couldn't set tx timeout, hopefully shouldn't be a big deal", module);
                }
                numberRead += reader.parse(s);
            } catch (TemplateException | IOException e) {
                throw new SAXException("Error storing value", e);
            }
        }
        return;
    }
    if (isParseForTemplate) {
        this.currentNodeForTemplate = this.currentNodeForTemplate.getParentNode();
        return;
    }
    // Test if end action tag, set action to default
    if (actionTags.contains(fullNameString)) {
        setAction(Action.CREATE_UPDATE);
        return;
    }
    if (currentValue != null) {
        if (currentFieldName != null) {
            if (UtilValidate.isNotEmpty(currentFieldValue)) {
                if (currentValue.getModelEntity().isField(currentFieldName.toString())) {
                    ModelEntity modelEntity = currentValue.getModelEntity();
                    ModelField modelField = modelEntity.getField(currentFieldName.toString());
                    String type = modelField.getType();
                    if (type != null && "blob".equals(type)) {
                        byte[] binData = Base64.base64Decode((new String(currentFieldValue)).getBytes());
                        currentValue.setBytes(currentFieldName.toString(), binData);
                    } else {
                        currentValue.setString(currentFieldName.toString(), new String(currentFieldValue));
                    }
                } else {
                    Debug.logWarning("Ignoring invalid field name [" + currentFieldName + "] found for the entity: " + currentValue.getEntityName() + " with value=" + currentFieldValue, module);
                }
                currentFieldValue = null;
            }
            currentFieldName = null;
        } else {
            // before we write currentValue check to see if PK is there, if not and it is one field, generate it from a sequence using the entity name
            if (!currentValue.containsPrimaryKey()) {
                if (currentValue.getModelEntity().getPksSize() == 1) {
                    ModelField modelField = currentValue.getModelEntity().getOnlyPk();
                    String newSeq = delegator.getNextSeqId(currentValue.getEntityName());
                    currentValue.setString(modelField.getName(), newSeq);
                } else {
                    throw new SAXException("Cannot store value with incomplete primary key with more than 1 primary key field: " + currentValue);
                }
            }
            try {
                boolean exist = true;
                boolean skip = false;
                // It's necessary to check also for specific action CREATE and DELETE to ensure it's OK
                if (Action.CREATE == currentAction || Action.DELETE == currentAction || Debug.verboseOn()) {
                    GenericHelper helper = delegator.getEntityHelper(currentValue.getEntityName());
                    if (currentValue.containsPrimaryKey()) {
                        try {
                            helper.findByPrimaryKey(currentValue.getPrimaryKey());
                        } catch (GenericEntityNotFoundException e) {
                            exist = false;
                        }
                    }
                    if (Action.CREATE == currentAction && exist) {
                        skip = true;
                    } else if (Action.DELETE == currentAction && !exist) {
                        skip = true;
                    }
                }
                if (!skip) {
                    if (this.useTryInsertMethod && !this.checkDataOnly) {
                        if (Action.DELETE == currentAction) {
                            currentValue.remove();
                        } else {
                            currentValue.create();
                        }
                    } else {
                        if (Action.DELETE == currentAction) {
                            valuesToDelete.add(currentValue);
                            if (valuesToDelete.size() >= valuesPerWrite) {
                                delegator.removeAll(valuesToDelete);
                                valuesToDelete.clear();
                            }
                        } else {
                            valuesToWrite.add(currentValue);
                            if (valuesToWrite.size() >= valuesPerWrite) {
                                writeValues(valuesToWrite);
                                valuesToWrite.clear();
                            }
                        }
                    }
                }
                numberRead++;
                if (Debug.verboseOn())
                    countValue(skip, exist);
                if ((numberRead % valuesPerMessage) == 0) {
                    Debug.logImportant("Another " + valuesPerMessage + " values imported: now up to " + numberRead, module);
                }
                currentValue = null;
            } catch (GenericEntityException e) {
                String errMsg = "Error performing action " + currentAction;
                Debug.logError(e, errMsg, module);
                throw new SAXException(errMsg, e);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) URL(java.net.URL) SAXException(org.xml.sax.SAXException) Template(freemarker.template.Template) NodeModel(freemarker.ext.dom.NodeModel) StringWriter(java.io.StringWriter) TemplateHashModel(freemarker.template.TemplateHashModel) ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) InputStreamReader(java.io.InputStreamReader) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) GenericHelper(org.apache.ofbiz.entity.datasource.GenericHelper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BufferedReader(java.io.BufferedReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException)

Aggregations

NodeModel (freemarker.ext.dom.NodeModel)3 HashMap (java.util.HashMap)3 StringWriter (java.io.StringWriter)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 InputSource (org.xml.sax.InputSource)2 SAXException (org.xml.sax.SAXException)2 FileTemplateLoader (freemarker.cache.FileTemplateLoader)1 BeansWrapper (freemarker.ext.beans.BeansWrapper)1 BeansWrapperBuilder (freemarker.ext.beans.BeansWrapperBuilder)1 BooleanModel (freemarker.ext.beans.BooleanModel)1 Java7MembersOnlyBeansWrapper (freemarker.ext.beans.Java7MembersOnlyBeansWrapper)1 ResourceBundleModel (freemarker.ext.beans.ResourceBundleModel)1 Configuration (freemarker.template.Configuration)1 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)1 SimpleCollection (freemarker.template.SimpleCollection)1 SimpleDate (freemarker.template.SimpleDate)1 SimpleNumber (freemarker.template.SimpleNumber)1 Template (freemarker.template.Template)1 TemplateBooleanModel (freemarker.template.TemplateBooleanModel)1 TemplateException (freemarker.template.TemplateException)1