Search in sources :

Example 31 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher 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 32 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class EmailServices method sendMailFromUrl.

/**
 * JavaMail Service that gets body content from a URL
 *@param ctx The DispatchContext that this service is operating in
 *@param rcontext Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> sendMailFromUrl(DispatchContext ctx, Map<String, ? extends Object> rcontext) {
    // pretty simple, get the content and then call the sendMail method below
    Map<String, Object> sendMailContext = UtilMisc.makeMapWritable(rcontext);
    String bodyUrl = (String) sendMailContext.remove("bodyUrl");
    Map<String, Object> bodyUrlParameters = UtilGenerics.checkMap(sendMailContext.remove("bodyUrlParameters"));
    Locale locale = (Locale) rcontext.get("locale");
    LocalDispatcher dispatcher = ctx.getDispatcher();
    URL url = null;
    try {
        url = new URL(bodyUrl);
    } catch (MalformedURLException e) {
        Debug.logWarning(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendMalformedUrl", UtilMisc.toMap("bodyUrl", bodyUrl, "errorString", e.toString()), locale));
    }
    HttpClient httpClient = new HttpClient(url, bodyUrlParameters);
    String body = null;
    try {
        body = httpClient.post();
    } catch (HttpClientException e) {
        Debug.logWarning(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendGettingError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    sendMailContext.put("body", body);
    Map<String, Object> sendMailResult;
    try {
        sendMailResult = dispatcher.runSync("sendMail", sendMailContext);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // just return the same result; it contains all necessary information
    return sendMailResult;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) MalformedURLException(java.net.MalformedURLException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) HttpClient(org.apache.ofbiz.base.util.HttpClient) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) URL(java.net.URL)

Example 33 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class EmailServices method sendMailFromScreen.

/**
 * JavaMail Service that gets body content from a Screen Widget
 * defined in the product store record and if available as attachment also.
 *@param dctx The DispatchContext that this service is operating in
 *@param rServiceContext Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> sendMailFromScreen(DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
    Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String webSiteId = (String) serviceContext.remove("webSiteId");
    String bodyText = (String) serviceContext.remove("bodyText");
    String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
    String xslfoAttachScreenLocationParam = (String) serviceContext.remove("xslfoAttachScreenLocation");
    String attachmentNameParam = (String) serviceContext.remove("attachmentName");
    List<String> xslfoAttachScreenLocationListParam = UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList"));
    List<String> attachmentNameListParam = UtilGenerics.checkList(serviceContext.remove("attachmentNameList"));
    VisualTheme visualTheme = (VisualTheme) rServiceContext.get("visualTheme");
    if (visualTheme == null) {
        visualTheme = ThemeFactory.resolveVisualTheme(null);
    }
    List<String> xslfoAttachScreenLocationList = new LinkedList<>();
    List<String> attachmentNameList = new LinkedList<>();
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam)) {
        xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam);
    }
    if (UtilValidate.isNotEmpty(attachmentNameParam)) {
        attachmentNameList.add(attachmentNameParam);
    }
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam)) {
        xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam);
    }
    if (UtilValidate.isNotEmpty(attachmentNameListParam)) {
        attachmentNameList.addAll(attachmentNameListParam);
    }
    List<String> attachmentTypeList = new LinkedList<>();
    String attachmentTypeParam = (String) serviceContext.remove("attachmentType");
    List<String> attachmentTypeListParam = UtilGenerics.checkList(serviceContext.remove("attachmentTypeList"));
    if (UtilValidate.isNotEmpty(attachmentTypeParam)) {
        attachmentTypeList.add(attachmentTypeParam);
    }
    if (UtilValidate.isNotEmpty(attachmentTypeListParam)) {
        attachmentTypeList.addAll(attachmentTypeListParam);
    }
    Locale locale = (Locale) serviceContext.get("locale");
    Map<String, Object> bodyParameters = UtilGenerics.checkMap(serviceContext.remove("bodyParameters"));
    if (bodyParameters == null) {
        bodyParameters = MapStack.create();
    }
    if (!bodyParameters.containsKey("locale")) {
        bodyParameters.put("locale", locale);
    } else {
        locale = (Locale) bodyParameters.get("locale");
    }
    String partyId = (String) serviceContext.get("partyId");
    if (partyId == null) {
        partyId = (String) bodyParameters.get("partyId");
    }
    String orderId = (String) bodyParameters.get("orderId");
    String returnId = (String) serviceContext.get("returnId");
    String custRequestId = (String) bodyParameters.get("custRequestId");
    bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId"));
    NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters);
    String contentType = (String) serviceContext.remove("contentType");
    StringWriter bodyWriter = new StringWriter();
    MapStack<String> screenContext = MapStack.create();
    screenContext.put("locale", locale);
    ScreenStringRenderer screenStringRenderer = null;
    try {
        screenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme(), "screen");
    } catch (TemplateException | IOException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, screenStringRenderer);
    screens.populateContextForService(dctx, bodyParameters);
    screenContext.putAll(bodyParameters);
    if (bodyScreenUri != null) {
        try {
            screens.render(bodyScreenUri);
        } catch (GeneralException | IOException | SAXException | ParserConfigurationException e) {
            Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    boolean isMultiPart = false;
    // check if attachment screen location passed in
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) {
        List<Map<String, ? extends Object>> bodyParts = new LinkedList<Map<String, ? extends Object>>();
        if (bodyText != null) {
            bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
            bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", UtilValidate.isNotEmpty(contentType) ? contentType : "text/html"));
        } else {
            bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", UtilValidate.isNotEmpty(contentType) ? contentType : "text/html"));
        }
        for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) {
            String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i);
            String attachmentName = "Details.pdf";
            if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) {
                attachmentName = attachmentNameList.get(i);
            }
            String attachmentType = MimeConstants.MIME_PDF;
            if (UtilValidate.isNotEmpty(attachmentTypeList) && attachmentTypeList.size() >= i) {
                attachmentType = attachmentTypeList.get(i);
            }
            isMultiPart = true;
            // start processing fo pdf attachment
            try {
                Writer writer = new StringWriter();
                // substitute the freemarker variables...
                ScreenStringRenderer foScreenStringRenderer = null;
                if (MimeConstants.MIME_PLAIN_TEXT.equals(attachmentType)) {
                    foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme(), "screentext");
                } else {
                    foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme(), "screenfop");
                }
                ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenStringRenderer);
                screensAtt.populateContextForService(dctx, bodyParameters);
                screensAtt.render(xslfoAttachScreenLocation);
                // create the output stream for the generation
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (MimeConstants.MIME_PLAIN_TEXT.equals(attachmentType)) {
                    baos.write(writer.toString().getBytes("UTF-8"));
                } else {
                    // create the input stream for the generation
                    StreamSource src = new StreamSource(new StringReader(writer.toString()));
                    Fop fop = ApacheFopWorker.createFopInstance(baos, attachmentType);
                    ApacheFopWorker.transform(src, null, fop);
                }
                // and generate the attachment
                baos.flush();
                baos.close();
                // store in the list of maps for sendmail....
                bodyParts.add(UtilMisc.<String, Object>toMap("content", baos.toByteArray(), "type", attachmentType, "filename", attachmentName));
            } catch (GeneralException | IOException | SAXException | ParserConfigurationException | TemplateException ge) {
                Debug.logError(ge, "Error rendering PDF attachment for email: " + ge.toString(), module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", ge.toString()), locale));
            }
            serviceContext.put("bodyParts", bodyParts);
        }
    } else {
        isMultiPart = false;
        // store body and type for single part message in the context.
        if (bodyText != null) {
            bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
            serviceContext.put("body", bodyText);
        } else {
            serviceContext.put("body", bodyWriter.toString());
        }
        // and would require specific handling.
        if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
            serviceContext.put("contentType", "text/plain");
        } else {
            serviceContext.put("contentType", "text/html");
        }
    }
    // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax in it...
    String subject = (String) serviceContext.remove("subject");
    subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
    if (Debug.infoOn()) {
        Debug.logInfo("Expanded email subject to: " + subject, module);
    }
    serviceContext.put("subject", subject);
    serviceContext.put("partyId", partyId);
    if (UtilValidate.isNotEmpty(orderId)) {
        serviceContext.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(returnId)) {
        serviceContext.put("returnId", returnId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
        serviceContext.put("custRequestId", custRequestId);
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, Object> sendMailResult;
    Boolean hideInLog = (Boolean) serviceContext.get("hideInLog");
    try {
        if (!Boolean.TRUE.equals(hideInLog)) {
            if (isMultiPart) {
                sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
            } else {
                sendMailResult = dispatcher.runSync("sendMail", serviceContext);
            }
        } else {
            if (isMultiPart) {
                sendMailResult = dispatcher.runSync("sendMailMultiPartHiddenInLog", serviceContext);
            } else {
                sendMailResult = dispatcher.runSync("sendMailHiddenInLog", serviceContext);
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Error send email:" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    if (ServiceUtil.isError(sendMailResult)) {
        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult));
    }
    result.put("messageWrapper", sendMailResult.get("messageWrapper"));
    result.put("body", bodyWriter.toString());
    result.put("subject", subject);
    result.put("communicationEventId", sendMailResult.get("communicationEventId"));
    if (UtilValidate.isNotEmpty(orderId)) {
        result.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(returnId)) {
        result.put("returnId", returnId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
        result.put("custRequestId", custRequestId);
    }
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) 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) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) LinkedList(java.util.LinkedList) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) MessagingException(javax.mail.MessagingException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) SendFailedException(javax.mail.SendFailedException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 34 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class QRCodeEvents method serveQRCodeImage.

/**
 * Streams QR Code to the output.
 */
public static String serveQRCodeImage(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Map<String, Object> parameters = UtilHttp.getParameterMap(request);
    String message = (String) parameters.get("message");
    GenericValue userLogin = (GenericValue) request.getAttribute("userLogin");
    if (userLogin == null) {
        userLogin = (GenericValue) session.getAttribute("userLogin");
    }
    if (userLogin == null) {
        userLogin = (GenericValue) session.getAttribute("autoUserLogin");
    }
    Locale locale = UtilHttp.getLocale(request);
    if (UtilValidate.isEmpty(message)) {
        message = "Error get message parameter.";
    }
    String format = (String) parameters.get("format");
    if (UtilValidate.isEmpty(format)) {
        format = "jpg";
    }
    String mimeType = "image/" + format;
    String width = (String) parameters.get("width");
    String height = (String) parameters.get("height");
    String encoding = (String) parameters.get("encoding");
    Boolean verifyOutput = Boolean.valueOf((String) parameters.get("verifyOutput"));
    String logoImageMaxWidth = (String) parameters.get("logoImageMaxWidth");
    String logoImageMaxHeight = (String) parameters.get("logoImageMaxHeight");
    try {
        response.setContentType(mimeType);
        OutputStream os = response.getOutputStream();
        Map<String, Object> context = UtilMisc.<String, Object>toMap("message", message, "format", format, "userLogin", userLogin, "locale", locale);
        if (UtilValidate.isNotEmpty(width)) {
            try {
                context.put("width", Integer.parseInt(width));
            } catch (NumberFormatException e) {
                Debug.logWarning(e, e.getMessage(), module);
            }
            if (UtilValidate.isEmpty(height)) {
                try {
                    context.put("height", Integer.parseInt(width));
                } catch (NumberFormatException e) {
                    Debug.logWarning(e, e.getMessage(), module);
                }
            }
        }
        if (UtilValidate.isNotEmpty(height)) {
            try {
                context.put("height", Integer.parseInt(height));
            } catch (NumberFormatException e) {
                Debug.logWarning(e, e.getMessage(), module);
            }
            if (UtilValidate.isEmpty(width)) {
                try {
                    context.put("width", Integer.parseInt(height));
                } catch (NumberFormatException e) {
                    Debug.logWarning(e, e.getMessage(), module);
                }
            }
        }
        if (UtilValidate.isNotEmpty(encoding)) {
            context.put("encoding", encoding);
        }
        if (UtilValidate.isNotEmpty(verifyOutput) && verifyOutput.booleanValue()) {
            context.put("verifyOutput", verifyOutput);
        }
        if (UtilValidate.isNotEmpty(logoImageMaxWidth)) {
            try {
                context.put("logoImageMaxWidth", Integer.parseInt(logoImageMaxWidth));
            } catch (NumberFormatException e) {
                Debug.logWarning(e, e.getMessage(), module);
            }
        }
        if (UtilValidate.isNotEmpty(logoImageMaxHeight)) {
            try {
                context.put("logoImageMaxHeight", Integer.parseInt(logoImageMaxHeight));
            } catch (NumberFormatException e) {
                Debug.logWarning(e, e.getMessage(), module);
            }
        }
        Map<String, Object> results = dispatcher.runSync("generateQRCodeImage", context);
        if (ServiceUtil.isSuccess(results)) {
            BufferedImage bufferedImage = (BufferedImage) results.get("bufferedImage");
            if (!ImageIO.write(bufferedImage, format, os)) {
                String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorWriteFormatToFile", new Object[] { format }, locale);
                request.setAttribute("_ERROR_MESSAGE_", errMsg);
                return "error";
            }
            os.flush();
        } else {
            String errMsg = ServiceUtil.getErrorMessage(results);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (IOException | GenericServiceException e) {
        String errMsg = UtilProperties.getMessage("QRCodeUiLabels", "ErrorGenerateQRCode", new Object[] { e.getMessage() }, locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HttpSession(javax.servlet.http.HttpSession) OutputStream(java.io.OutputStream) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 35 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class EntitySyncServices method loadOfflineSyncData.

public static Map<String, Object> loadOfflineSyncData(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String fileName = (String) context.get("xmlFileName");
    Locale locale = (Locale) context.get("locale");
    URL xmlFile = UtilURL.fromResource(fileName);
    if (xmlFile != null) {
        Document xmlSyncDoc = null;
        try {
            xmlSyncDoc = UtilXml.readXmlDocument(xmlFile, false);
        } catch (SAXException e) {
            Debug.logError(e, module);
        } catch (ParserConfigurationException e) {
            Debug.logError(e, module);
        } catch (IOException e) {
            Debug.logError(e, module);
        }
        if (xmlSyncDoc == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtEntitySyncXMLDocumentIsNotValid", UtilMisc.toMap("fileName", fileName), locale));
        }
        List<? extends Element> syncElements = UtilXml.childElementList(xmlSyncDoc.getDocumentElement());
        if (syncElements != null) {
            for (Element entitySync : syncElements) {
                String entitySyncId = entitySync.getAttribute("entitySyncId");
                String startTime = entitySync.getAttribute("lastSuccessfulSynchTime");
                String createString = UtilXml.childElementValue(entitySync, "values-to-create");
                String storeString = UtilXml.childElementValue(entitySync, "values-to-store");
                String removeString = UtilXml.childElementValue(entitySync, "keys-to-remove");
                // de-serialize the value lists
                try {
                    List<GenericValue> valuesToCreate = checkList(XmlSerializer.deserialize(createString, delegator), GenericValue.class);
                    List<GenericValue> valuesToStore = checkList(XmlSerializer.deserialize(storeString, delegator), GenericValue.class);
                    List<GenericEntity> keysToRemove = checkList(XmlSerializer.deserialize(removeString, delegator), GenericEntity.class);
                    Map<String, Object> storeContext = UtilMisc.toMap("entitySyncId", entitySyncId, "valuesToCreate", valuesToCreate, "valuesToStore", valuesToStore, "keysToRemove", keysToRemove, "userLogin", userLogin);
                    // store the value(s)
                    Map<String, Object> storeResult = dispatcher.runSync("storeEntitySyncData", storeContext);
                    if (ServiceUtil.isError(storeResult)) {
                        throw new Exception(ServiceUtil.getErrorMessage(storeResult));
                    }
                // TODO create a response document to send back to the initial sync machine
                } catch (GenericServiceException gse) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", gse.getMessage()), locale));
                } catch (Exception e) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", e.getMessage()), locale));
                }
            }
        }
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtOfflineXMLFileNotFound", UtilMisc.toMap("fileName", fileName), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) URL(java.net.URL) UtilURL(org.apache.ofbiz.base.util.UtilURL) SyncAbortException(org.apache.ofbiz.entityext.synchronization.EntitySyncContext.SyncAbortException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) SerializeException(org.apache.ofbiz.entity.serialize.SerializeException) SyncErrorException(org.apache.ofbiz.entityext.synchronization.EntitySyncContext.SyncErrorException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntity(org.apache.ofbiz.entity.GenericEntity) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)427 GenericValue (org.apache.ofbiz.entity.GenericValue)356 Delegator (org.apache.ofbiz.entity.Delegator)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)321 Locale (java.util.Locale)296 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)270 HashMap (java.util.HashMap)214 BigDecimal (java.math.BigDecimal)135 GeneralException (org.apache.ofbiz.base.util.GeneralException)87 Timestamp (java.sql.Timestamp)81 LinkedList (java.util.LinkedList)79 IOException (java.io.IOException)59 Map (java.util.Map)51 HttpSession (javax.servlet.http.HttpSession)49 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)28 ModelService (org.apache.ofbiz.service.ModelService)28 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)24 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)23 Security (org.apache.ofbiz.security.Security)20 ByteBuffer (java.nio.ByteBuffer)19