Search in sources :

Example 16 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class MacroScreenRenderer method renderContentBody.

public void renderContentBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content) throws IOException {
    Locale locale = UtilMisc.ensureLocale(context.get("locale"));
    String mimeTypeId = "text/html";
    String expandedContentId = content.getContentId(context);
    String expandedDataResourceId = content.getDataResourceId(context);
    String renderedContent = null;
    LocalDispatcher dispatcher = (LocalDispatcher) context.get("dispatcher");
    Delegator delegator = (Delegator) context.get("delegator");
    // make a new map for content rendering; so our current map does not get clobbered
    Map<String, Object> contentContext = new HashMap<>();
    contentContext.putAll(context);
    String dataResourceId = (String) contentContext.get("dataResourceId");
    if (Debug.verboseOn()) {
        Debug.logVerbose("expandedContentId:" + expandedContentId, module);
    }
    try {
        if (UtilValidate.isNotEmpty(dataResourceId)) {
            if (WidgetDataResourceWorker.getDataresourceWorker() != null) {
                renderedContent = WidgetDataResourceWorker.getDataresourceWorker().renderDataResourceAsTextExt(delegator, dataResourceId, contentContext, locale, mimeTypeId, false);
            } else {
                Debug.logError("Not rendering content, WidgetDataResourceWorker.dataresourceWorker not found.", module);
            }
        } else if (UtilValidate.isNotEmpty(expandedContentId)) {
            if (WidgetContentWorker.getContentWorker() != null) {
                renderedContent = WidgetContentWorker.getContentWorker().renderContentAsTextExt(dispatcher, expandedContentId, contentContext, locale, mimeTypeId, true);
            } else {
                Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module);
            }
        } else if (UtilValidate.isNotEmpty(expandedDataResourceId)) {
            if (WidgetDataResourceWorker.getDataresourceWorker() != null) {
                renderedContent = WidgetDataResourceWorker.getDataresourceWorker().renderDataResourceAsTextExt(delegator, expandedDataResourceId, contentContext, locale, mimeTypeId, false);
            } else {
                Debug.logError("Not rendering content, WidgetDataResourceWorker.dataresourceWorker not found.", module);
            }
        }
        if (UtilValidate.isEmpty(renderedContent)) {
            String editRequest = content.getEditRequest(context);
            if (UtilValidate.isNotEmpty(editRequest)) {
                if (WidgetContentWorker.getContentWorker() != null) {
                    WidgetContentWorker.getContentWorker().renderContentAsTextExt(dispatcher, "NOCONTENTFOUND", writer, contentContext, locale, mimeTypeId, true);
                } else {
                    Debug.logError("Not rendering content, WidgetContentWorker.contentWorker not found.", module);
                }
            }
        } else {
            if (content.xmlEscape()) {
                renderedContent = UtilFormatOut.encodeXmlValue(renderedContent);
            }
            writer.append(renderedContent);
        }
    } catch (GeneralException | IOException e) {
        String errMsg = "Error rendering included content with id [" + expandedContentId + "] : " + e.toString();
        Debug.logError(e, errMsg, module);
    }
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) IOException(java.io.IOException)

Example 17 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ScreenFopViewHandler method render.

/**
 * @see org.apache.ofbiz.webapp.view.ViewHandler#render(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    ModelTheme modelTheme = visualTheme.getModelTheme();
    // render and obtain the XSL-FO
    Writer writer = new StringWriter();
    try {
        ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType(getName()), modelTheme.getScreenRendererLocation(getName()));
        FormStringRenderer formStringRenderer = new MacroFormRenderer(modelTheme.getFormRendererLocation(getName()), request, response);
        // TODO: uncomment these lines when the renderers are implemented
        // TreeStringRenderer treeStringRenderer = new MacroTreeRenderer(modelTheme.getTreeRendererLocation(getName()), writer);
        // MenuStringRenderer menuStringRenderer = new MacroMenuRenderer(modelTheme.getMenuRendererLocation(getName()), writer);
        ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
        screens.populateContextForRequest(request, response, servletContext);
        // this is the object used to render forms from their definitions
        screens.getContext().put("formStringRenderer", formStringRenderer);
        screens.getContext().put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder(getName())));
        screens.render(page);
    } catch (IOException | GeneralException | SAXException | ParserConfigurationException | TemplateException e) {
        renderError("Problems with the response writer/output stream", e, "[Not Yet Rendered]", request, response);
        return;
    }
    // set the input source (XSL-FO) and generate the output stream of contentType
    String screenOutString = writer.toString();
    if (!screenOutString.startsWith("<?xml")) {
        screenOutString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + screenOutString;
    }
    if (Debug.verboseOn())
        Debug.logVerbose("XSL:FO Screen Output: " + screenOutString, module);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = modelTheme.getContentType(getName());
    }
    // get encryption related parameters
    FOUserAgent foUserAgent = null;
    String userPassword = request.getParameter("userPassword");
    String ownerPassword = request.getParameter("ownerPassword");
    boolean allowPrint = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowPrint")) ? ApacheFopWorker.getAllowPrintDefault() : request.getParameter("allowPrint"));
    boolean allowCopyContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowCopyContent")) ? ApacheFopWorker.getAllowCopyContentDefault() : request.getParameter("allowCopyContent"));
    boolean allowEditContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowEditContent")) ? ApacheFopWorker.getAllowEditContentDefault() : request.getParameter("allowEditContent"));
    boolean allowEditAnnotations = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowEditAnnotations")) ? ApacheFopWorker.getAllowEditAnnotationsDefault() : request.getParameter("allowEditAnnotations"));
    if (UtilValidate.isNotEmpty(userPassword) || UtilValidate.isNotEmpty(ownerPassword) || !allowPrint || !allowCopyContent || allowEditContent || !allowEditAnnotations) {
        int encryptionLength = 128;
        try {
            encryptionLength = Integer.parseInt(request.getParameter("encryption-length"));
        } catch (NumberFormatException e) {
            try {
                encryptionLength = Integer.parseInt(ApacheFopWorker.getEncryptionLengthDefault());
            } catch (NumberFormatException e1) {
            // ignore
            }
        }
        boolean encryptMetadata = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("encrypt-metadata")) ? ApacheFopWorker.getEncryptMetadataDefault() : request.getParameter("encrypt-metadata"));
        boolean allowFillInForms = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowFillInForms")) ? ApacheFopWorker.getAllowFillInFormsDefault() : request.getParameter("allowFillInForms"));
        boolean allowAccessContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowAccessContent")) ? ApacheFopWorker.getAllowAccessContentDefault() : request.getParameter("allowAccessContent"));
        boolean allowAssembleDocument = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowAssembleDocument")) ? ApacheFopWorker.getAllowAssembleDocumentDefault() : request.getParameter("allowAssembleDocument"));
        boolean allowPrintHq = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowPrintHq")) ? ApacheFopWorker.getAllowPrintHqDefault() : request.getParameter("allowPrintHq"));
        FopFactory fopFactory = ApacheFopWorker.getFactoryInstance();
        foUserAgent = fopFactory.newFOUserAgent();
        PDFEncryptionParams pdfEncryptionParams = new PDFEncryptionParams(userPassword, ownerPassword, allowPrint, allowCopyContent, allowEditContent, allowEditAnnotations, encryptMetadata);
        pdfEncryptionParams.setAllowFillInForms(allowFillInForms);
        pdfEncryptionParams.setAllowAccessContent(allowAccessContent);
        pdfEncryptionParams.setAllowAssembleDocument(allowAssembleDocument);
        pdfEncryptionParams.setAllowPrintHq(allowPrintHq);
        pdfEncryptionParams.setEncryptionLengthInBits(encryptionLength);
        foUserAgent.getRendererOptions().put(PDFEncryptionOption.ENCRYPTION_PARAMS, pdfEncryptionParams);
    }
    Reader reader = new StringReader(screenOutString);
    StreamSource src = new StreamSource(reader);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    /* Debug area, uncomment this to view the xml file generate before analyse by fop
        try { 
                java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/temp.xsl.fo"));
                fw.write(screenOutString);
                fw.close();
            } catch (IOException e) {
                Debug.logError(e, "Couldn't save xls debug file: " + e.toString(), module);
            }
        */
    try {
        Fop fop = ApacheFopWorker.createFopInstance(out, contentType, foUserAgent);
        ApacheFopWorker.transform(src, null, fop);
    } catch (Exception e) {
        renderError("Unable to transform FO file", e, screenOutString, request, response);
        return;
    }
    // set the content type and length
    response.setContentType(contentType);
    response.setContentLength(out.size());
    // write to the browser
    try {
        out.writeTo(response.getOutputStream());
        response.getOutputStream().flush();
    } catch (IOException e) {
        renderError("Unable to write to OutputStream", e, screenOutString, request, response);
    }
}
Also used : FOUserAgent(org.apache.fop.apps.FOUserAgent) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) Reader(java.io.Reader) StringReader(java.io.StringReader) FopFactory(org.apache.fop.apps.FopFactory) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) TemplateException(freemarker.template.TemplateException) ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) FormStringRenderer(org.apache.ofbiz.widget.renderer.FormStringRenderer) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) StringWriter(java.io.StringWriter) Writer(java.io.Writer) PDFEncryptionParams(org.apache.fop.pdf.PDFEncryptionParams)

Example 18 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class ScreenFopViewHandler method renderError.

protected void renderError(String msg, Exception e, String screenOutString, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    Debug.logError(msg + ": " + e + "; Screen XSL:FO text was:\n" + screenOutString, module);
    try {
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        Writer writer = new StringWriter();
        VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
        ModelTheme modelTheme = visualTheme.getModelTheme();
        ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
        ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
        screens.populateContextForRequest(request, response, servletContext);
        screens.getContext().put("errorMessage", msg + ": " + e);
        screens.render(DEFAULT_ERROR_TEMPLATE);
        response.setContentType("text/html");
        response.getWriter().write(writer.toString());
        writer.close();
    } catch (IOException | GeneralException | SAXException | ParserConfigurationException | TemplateException x) {
        Debug.logError("Multiple errors rendering FOP", module);
        throw new ViewHandlerException("Multiple errors rendering FOP", x);
    }
}
Also used : ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) IOException(java.io.IOException) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 19 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class MacroScreenViewHandler method render.

public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    try {
        Writer writer = response.getWriter();
        VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
        ModelTheme modelTheme = visualTheme.getModelTheme();
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        // compress output if configured to do so
        if (UtilValidate.isEmpty(encoding)) {
            encoding = modelTheme.getEncoding(getName());
        }
        boolean compressOutput = "compressed".equals(encoding);
        if (!compressOutput) {
            compressOutput = "true".equals(modelTheme.getCompress(getName()));
        }
        if (!compressOutput && this.servletContext != null) {
            compressOutput = "true".equals(this.servletContext.getAttribute("compressHTML"));
        }
        if (compressOutput) {
            // StandardCompress defaults to a 2k buffer. That could be increased
            // to speed up output.
            writer = new StandardCompress().getWriter(writer, null);
        }
        MapStack<String> context = MapStack.create();
        ScreenRenderer.populateContextForRequest(context, null, request, response, servletContext);
        ScreenStringRenderer screenStringRenderer = loadRenderers(request, response, context, writer);
        ScreenRenderer screens = new ScreenRenderer(writer, context, screenStringRenderer);
        context.put("screens", screens);
        context.put("simpleEncoder", UtilCodec.getEncoder(visualTheme.getModelTheme().getEncoder(getName())));
        screenStringRenderer.renderScreenBegin(writer, context);
        screens.render(page);
        screenStringRenderer.renderScreenEnd(writer, context);
        writer.flush();
    } catch (TemplateException e) {
        Debug.logError(e, "Error initializing screen renderer", module);
        throw new ViewHandlerException(e.getMessage());
    } catch (IOException e) {
        throw new ViewHandlerException("Error in the response writer/output stream: " + e.toString(), e);
    } catch (SAXException | ParserConfigurationException e) {
        throw new ViewHandlerException("XML Error rendering page: " + e.toString(), e);
    } catch (GeneralException e) {
        throw new ViewHandlerException("Lower level error rendering page: " + e.toString(), e);
    }
}
Also used : ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) IOException(java.io.IOException) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StandardCompress(freemarker.template.utility.StandardCompress) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Writer(java.io.Writer)

Example 20 with GeneralException

use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.

the class LabelManagerFactory method findMatchingLabels.

public void findMatchingLabels(String component, String fileName, String key, String locale, boolean onlyNotUsedLabels) throws MalformedURLException, SAXException, ParserConfigurationException, IOException, GeneralException {
    if (UtilValidate.isEmpty(component) && UtilValidate.isEmpty(fileName) && UtilValidate.isEmpty(key) && UtilValidate.isEmpty(locale)) {
        // Important! Don't allow unparameterized queries - doing so will result in loading the entire project into memory
        return;
    }
    for (LabelFile fileInfo : filesFound.values()) {
        if (UtilValidate.isNotEmpty(component) && !component.equals(fileInfo.componentName)) {
            continue;
        }
        if (UtilValidate.isNotEmpty(fileName) && !fileName.equals(fileInfo.getFileName())) {
            continue;
        }
        if (Debug.infoOn()) {
            Debug.logInfo("Current file : " + fileInfo.getFileName(), module);
        }
        Document resourceDocument = UtilXml.readXmlDocument(fileInfo.file.toURI().toURL(), false);
        Element resourceElem = resourceDocument.getDocumentElement();
        String labelKeyComment = "";
        for (Node propertyNode : UtilXml.childNodeList(resourceElem.getFirstChild())) {
            if (propertyNode instanceof Element) {
                Element propertyElem = (Element) propertyNode;
                String labelKey = UtilCodec.canonicalize(propertyElem.getAttribute("key"));
                if (onlyNotUsedLabels && (labelKey.contains(".description.") || labelKey.contains(".transitionName.") || labelKey.contains(".partyRelationshipName.") || labelKey.contains(".geoName.") || labelKey.contains(".categoryName.") || labelKey.contains("FieldDescription.") || labelKey.contains("TemporalExpression_") || labelKey.contains(".portalPageName.") || labelKey.contains("ProductStoreGroup.productStoreGroupName.NA") || labelKey.contains("buildEbayConfig.") || labelKey.contains("week.") || labelKey.contains("second.") || labelKey.contains("hour.") || labelKey.contains("millisecond.") || labelKey.contains("service.") || labelKey.contains("check.") || // These are languages Ids
                (labelKey.length() == 2) || // These are languages Ids
                labelKey.contains("pt_") || // These are languages Ids
                labelKey.contains("en_"))) {
                    // OFBIZ-8154 WIP
                    continue;
                }
                String labelComment = "";
                for (Node valueNode : UtilXml.childNodeList(propertyElem.getFirstChild())) {
                    if (valueNode instanceof Element) {
                        Element valueElem = (Element) valueNode;
                        // No longer supporting old way of specifying xml:lang value.
                        // Old way: en_AU, new way: en-AU
                        String localeName = valueElem.getAttribute("xml:lang");
                        if (localeName.contains("_")) {
                            GeneralException e = new GeneralException("Confusion in labels with the separator used between languages and countries. Please use a dash instead of an underscore.");
                            throw e;
                        }
                        String labelValue = UtilCodec.canonicalize(UtilXml.nodeValue(valueElem.getFirstChild()));
                        LabelInfo label = labels.get(labelKey + keySeparator + fileInfo.getFileName());
                        if (UtilValidate.isEmpty(label)) {
                            label = new LabelInfo(labelKey, labelKeyComment, fileInfo.getFileName(), localeName, labelValue, labelComment);
                            labels.put(labelKey + keySeparator + fileInfo.getFileName(), label);
                        } else {
                            if (label.setLabelValue(localeName, labelValue, labelComment, false)) {
                                duplicatedLocalesLabelsList.add(label);
                            }
                        }
                        localesFound.add(localeName);
                        labelComment = "";
                    } else if (valueNode instanceof Comment) {
                        labelComment = labelComment + UtilCodec.canonicalize(valueNode.getNodeValue());
                    }
                }
                labelKeyComment = "";
            } else if (propertyNode instanceof Comment) {
                labelKeyComment = labelKeyComment + UtilCodec.canonicalize(propertyNode.getNodeValue());
            }
        }
    }
}
Also used : Comment(org.w3c.dom.Comment) GeneralException(org.apache.ofbiz.base.util.GeneralException) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document)

Aggregations

GeneralException (org.apache.ofbiz.base.util.GeneralException)216 GenericValue (org.apache.ofbiz.entity.GenericValue)133 Delegator (org.apache.ofbiz.entity.Delegator)101 Locale (java.util.Locale)81 HashMap (java.util.HashMap)71 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)68 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)68 IOException (java.io.IOException)65 BigDecimal (java.math.BigDecimal)55 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)54 Writer (java.io.Writer)29 LinkedList (java.util.LinkedList)29 Map (java.util.Map)29 Timestamp (java.sql.Timestamp)26 StringWriter (java.io.StringWriter)19 Environment (freemarker.core.Environment)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)14 HttpSession (javax.servlet.http.HttpSession)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)13