Пример #1
0
  public static Map<String, Object> convertOrderIdListToHeaders(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();

    List<GenericValue> orderHeaderList = UtilGenerics.checkList(context.get("orderHeaderList"));
    List<String> orderIdList = UtilGenerics.checkList(context.get("orderIdList"));

    // we don't want to process if there is already a header list
    if (orderHeaderList == null) {
      // convert the ID list to headers
      if (orderIdList != null) {
        List<EntityCondition> conditionList1 = FastList.newInstance();
        List<EntityCondition> conditionList2 = FastList.newInstance();

        // we are only concerned about approved sales orders
        conditionList2.add(
            EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED"));
        conditionList2.add(
            EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"));

        // build the expression list from the IDs
        for (String orderId : orderIdList) {
          conditionList1.add(
              EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
        }

        // create the conditions
        EntityCondition idCond = EntityCondition.makeCondition(conditionList1, EntityOperator.OR);
        conditionList2.add(idCond);

        EntityCondition cond = EntityCondition.makeCondition(conditionList2, EntityOperator.AND);

        // run the query
        try {
          orderHeaderList =
              delegator.findList(
                  "OrderHeader", cond, null, UtilMisc.toList("+orderDate"), null, false);
        } catch (GenericEntityException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
        Debug.logInfo("Recieved orderIdList  - " + orderIdList, module);
        Debug.logInfo("Found orderHeaderList - " + orderHeaderList, module);
      }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("orderHeaderList", orderHeaderList);
    return result;
  }
Пример #2
0
 public List<Map<String, Object>> getAdItemTemplates(String temGroupId) {
   List<Map<String, Object>> themes = FastList.newInstance();
   for (Map<String, Object> temp : this.adItemTemplates) {
     if (temp.get("TemplateGroupId").equals(temGroupId)) {
       themes = UtilGenerics.checkList(temp.get("Templates"));
       break;
     }
   }
   return themes;
 }
 public static List<String> getTrail(ServletRequest request) {
   HttpSession session = ((HttpServletRequest) request).getSession();
   List<String> crumb = UtilGenerics.checkList(session.getAttribute("_BREAD_CRUMB_TRAIL_"));
   return crumb;
 }
Пример #4
0
  public List<Map<String, Object>> syncAdItemTemplates()
      throws ApiException, SdkSoapException, SdkException {
    GetDescriptionTemplatesRequestType req = null;
    GetDescriptionTemplatesResponseType resp = null;
    List<Map<String, Object>> temGroupList = FastList.newInstance();

    GetDescriptionTemplatesCall call = new GetDescriptionTemplatesCall(this.apiContext);
    req = new GetDescriptionTemplatesRequestType();
    req.setCategoryID(this.catId);
    resp = (GetDescriptionTemplatesResponseType) call.execute(req);
    if (resp != null && "SUCCESS".equals(resp.getAck().toString())) {
      DescriptionTemplateType[] descriptionTemplateTypeList = resp.getDescriptionTemplate();
      Debug.logInfo("layout of category " + this.catId + ":" + resp.getLayoutTotal(), module);
      for (DescriptionTemplateType descTemplateType : descriptionTemplateTypeList) {
        List<Map<String, Object>> templateList = null;
        Map<String, Object> templateGroup = null;
        if ("THEME".equals(String.valueOf(descTemplateType.getType()))) {
          Map<String, Object> template = FastMap.newInstance();
          template.put("TemplateId", String.valueOf(descTemplateType.getID()));
          template.put("TemplateImageURL", descTemplateType.getImageURL());
          template.put("TemplateName", descTemplateType.getName());
          template.put("TemplateType", descTemplateType.getType());

          // check group template by groupId
          for (Map<String, Object> temGroup : temGroupList) {
            if (temGroup.get("TemplateGroupId").equals(descTemplateType.getGroupID().toString())) {
              templateGroup = temGroup;
              break;
            }
          }
          if (templateGroup == null) {
            templateGroup = FastMap.newInstance();
            templateList = FastList.newInstance();
            templateGroup.put("TemplateGroupId", descTemplateType.getGroupID().toString());
            templateList.add(template);
            templateGroup.put("Templates", templateList);
            temGroupList.add(templateGroup);
          } else {
            if (templateGroup.get("Templates") != null) {
              templateList = UtilGenerics.checkList(templateGroup.get("Templates"));
              templateList.add(template);
            }
          }
        } else if ("Layout".equals(String.valueOf(descTemplateType.getType()))) {
        }
      }
      ThemeGroupType[] themes = resp.getThemeGroup();
      if (themes != null && temGroupList != null) {
        for (Map<String, Object> temGroup : temGroupList) {
          for (ThemeGroupType theme : themes) {
            if (theme.getGroupID()
                == Integer.parseInt(temGroup.get("TemplateGroupId").toString())) {
              if (theme != null) temGroup.put("TemplateGroupName", theme.getGroupName());
              break;
            } else {
              if (theme != null) temGroup.put("TemplateGroupName", "_NA_");
            }
          }
        }
      }
    }
    return adItemTemplates = temGroupList;
  }
Пример #5
0
  /**
   * Basic JavaMail Service
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMail(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    String communicationEventId = (String) context.get("communicationEventId");
    String orderId = (String) context.get("orderId");
    Locale locale = (Locale) context.get("locale");
    if (communicationEventId != null) {
      Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module);
    }
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String subject = (String) context.get("subject");
    subject = FlexibleStringExpander.expandString(subject, context);

    String partyId = (String) context.get("partyId");
    String body = (String) context.get("body");
    List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts"));
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    results.put("communicationEventId", communicationEventId);
    results.put("partyId", partyId);
    results.put("subject", subject);

    if (UtilValidate.isNotEmpty(orderId)) {
      results.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(body)) {
      body = FlexibleStringExpander.expandString(body, context);
      results.put("body", body);
    }
    if (UtilValidate.isNotEmpty(bodyParts)) {
      results.put("bodyParts", bodyParts);
    }
    results.put("userLogin", userLogin);

    String sendTo = (String) context.get("sendTo");
    String sendCc = (String) context.get("sendCc");
    String sendBcc = (String) context.get("sendBcc");

    // check to see if we should redirect all mail for testing
    String redirectAddress =
        UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo");
    if (UtilValidate.isNotEmpty(redirectAddress)) {
      String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]";
      subject += originalRecipients;
      sendTo = redirectAddress;
      sendCc = null;
      sendBcc = null;
    }

    String sendFrom = (String) context.get("sendFrom");
    String sendType = (String) context.get("sendType");
    String port = (String) context.get("port");
    String socketFactoryClass = (String) context.get("socketFactoryClass");
    String socketFactoryPort = (String) context.get("socketFactoryPort");
    String socketFactoryFallback = (String) context.get("socketFactoryFallback");
    String sendVia = (String) context.get("sendVia");
    String authUser = (String) context.get("authUser");
    String authPass = (String) context.get("authPass");
    String messageId = (String) context.get("messageId");
    String contentType = (String) context.get("contentType");
    Boolean sendPartial = (Boolean) context.get("sendPartial");
    Boolean isStartTLSEnabled = (Boolean) context.get("startTLSEnabled");

    boolean useSmtpAuth = false;

    // define some default
    if (sendType == null || sendType.equals("mail.smtp.host")) {
      sendType = "mail.smtp.host";
      if (UtilValidate.isEmpty(sendVia)) {
        sendVia =
            UtilProperties.getPropertyValue(
                "general.properties", "mail.smtp.relay.host", "localhost");
      }
      if (UtilValidate.isEmpty(authUser)) {
        authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user");
      }
      if (UtilValidate.isEmpty(authPass)) {
        authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password");
      }
      if (UtilValidate.isNotEmpty(authUser)) {
        useSmtpAuth = true;
      }
      if (UtilValidate.isEmpty(port)) {
        port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port");
      }
      if (UtilValidate.isEmpty(socketFactoryPort)) {
        socketFactoryPort =
            UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port");
      }
      if (UtilValidate.isEmpty(socketFactoryClass)) {
        socketFactoryClass =
            UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class");
      }
      if (UtilValidate.isEmpty(socketFactoryFallback)) {
        socketFactoryFallback =
            UtilProperties.getPropertyValue(
                "general.properties", "mail.smtp.socketFactory.fallback", "false");
      }
      if (sendPartial == null) {
        sendPartial =
            UtilProperties.propertyValueEqualsIgnoreCase(
                    "general.properties", "mail.smtp.sendpartial", "true")
                ? true
                : false;
      }
      if (isStartTLSEnabled == null) {
        isStartTLSEnabled =
            UtilProperties.propertyValueEqualsIgnoreCase(
                "general.properties", "mail.smtp.starttls.enable", "true");
      }
    } else if (sendVia == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonEmailSendMissingParameterSendVia", locale));
    }

    if (contentType == null) {
      contentType = "text/html";
    }

    if (UtilValidate.isNotEmpty(bodyParts)) {
      contentType = "multipart/mixed";
    }
    results.put("contentType", contentType);

    Session session;
    MimeMessage mail;
    try {
      Properties props = System.getProperties();
      props.put(sendType, sendVia);
      if (UtilValidate.isNotEmpty(port)) {
        props.put("mail.smtp.port", port);
      }
      if (UtilValidate.isNotEmpty(socketFactoryPort)) {
        props.put("mail.smtp.socketFactory.port", socketFactoryPort);
      }
      if (UtilValidate.isNotEmpty(socketFactoryClass)) {
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      }
      if (UtilValidate.isNotEmpty(socketFactoryFallback)) {
        props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
      }
      if (useSmtpAuth) {
        props.put("mail.smtp.auth", "true");
      }
      if (sendPartial != null) {
        props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false");
      }
      if (isStartTLSEnabled) {
        props.put("mail.smtp.starttls.enable", "true");
      }

      session = Session.getInstance(props);
      boolean debug =
          UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y");
      session.setDebug(debug);

      mail = new MimeMessage(session);
      if (messageId != null) {
        mail.setHeader("In-Reply-To", messageId);
        mail.setHeader("References", messageId);
      }
      mail.setFrom(new InternetAddress(sendFrom));
      mail.setSubject(subject, "UTF-8");
      mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project");
      mail.setSentDate(new Date());
      mail.addRecipients(Message.RecipientType.TO, sendTo);

      if (UtilValidate.isNotEmpty(sendCc)) {
        mail.addRecipients(Message.RecipientType.CC, sendCc);
      }
      if (UtilValidate.isNotEmpty(sendBcc)) {
        mail.addRecipients(Message.RecipientType.BCC, sendBcc);
      }

      if (UtilValidate.isNotEmpty(bodyParts)) {
        // check for multipart message (with attachments)
        // BodyParts contain a list of Maps items containing content(String) and type(String) of the
        // attachement
        MimeMultipart mp = new MimeMultipart();
        Debug.logInfo(bodyParts.size() + " multiparts found", module);
        for (Map<String, Object> bodyPart : bodyParts) {
          Object bodyPartContent = bodyPart.get("content");
          MimeBodyPart mbp = new MimeBodyPart();

          if (bodyPartContent instanceof String) {
            Debug.logInfo(
                "part of type: "
                    + bodyPart.get("type")
                    + " and size: "
                    + bodyPart.get("content").toString().length(),
                module);
            mbp.setText(
                (String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5));
          } else if (bodyPartContent instanceof byte[]) {
            ByteArrayDataSource bads =
                new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type"));
            Debug.logInfo(
                "part of type: "
                    + bodyPart.get("type")
                    + " and size: "
                    + ((byte[]) bodyPartContent).length,
                module);
            mbp.setDataHandler(new DataHandler(bads));
          } else if (bodyPartContent instanceof DataHandler) {
            mbp.setDataHandler((DataHandler) bodyPartContent);
          } else {
            mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type")));
          }

          String fileName = (String) bodyPart.get("filename");
          if (fileName != null) {
            mbp.setFileName(fileName);
          }
          mp.addBodyPart(mbp);
        }
        mail.setContent(mp);
        mail.saveChanges();
      } else {
        // create the singelpart message
        if (contentType.startsWith("text")) {
          mail.setText(body, "UTF-8", contentType.substring(5));
        } else {
          mail.setContent(body, contentType);
        }
        mail.saveChanges();
      }
    } catch (MessagingException e) {
      Debug.logError(
          e,
          "MessagingException when creating message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be created to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendMessagingException",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    } catch (IOException e) {
      Debug.logError(
          e,
          "IOExcepton when creating message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be created to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendIOException",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    }

    // check to see if sending mail is enabled
    String mailEnabled =
        UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N");
    if (!"Y".equalsIgnoreCase(mailEnabled)) {
      // no error; just return as if we already processed
      Debug.logImportant(
          "Mail notifications disabled in general.properties; mail with subject ["
              + subject
              + "] not sent to addressee ["
              + sendTo
              + "]",
          module);
      Debug.logVerbose(
          "What would have been sent, the addressee: "
              + sendTo
              + " subject: "
              + subject
              + " context: "
              + context,
          module);
      results.put("messageWrapper", new MimeMessageWrapper(session, mail));
      return results;
    }

    Transport trans = null;
    try {
      trans = session.getTransport("smtp");
      if (!useSmtpAuth) {
        trans.connect();
      } else {
        trans.connect(sendVia, authUser, authPass);
      }
      trans.sendMessage(mail, mail.getAllRecipients());
      results.put("messageWrapper", new MimeMessageWrapper(session, mail));
      results.put("messageId", mail.getMessageID());
      trans.close();
    } catch (SendFailedException e) {
      // message code prefix may be used by calling services to determine the cause of the failure
      Debug.logError(
          e,
          "[ADDRERR] Address error when sending message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      List<SMTPAddressFailedException> failedAddresses = FastList.newInstance();
      Exception nestedException = null;
      while ((nestedException = e.getNextException()) != null
          && nestedException instanceof MessagingException) {
        if (nestedException instanceof SMTPAddressFailedException) {
          SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException;
          Debug.logError(
              "Failed to send message to ["
                  + safe.getAddress()
                  + "], return code ["
                  + safe.getReturnCode()
                  + "], return message ["
                  + safe.getMessage()
                  + "]",
              module);
          failedAddresses.add(safe);
          break;
        }
      }
      Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification");
      if (sendFailureNotification == null || sendFailureNotification) {
        sendFailureNotification(ctx, context, mail, failedAddresses);
        results.put("messageWrapper", new MimeMessageWrapper(session, mail));
        try {
          results.put("messageId", mail.getMessageID());
          trans.close();
        } catch (MessagingException e1) {
          Debug.logError(e1, module);
        }
      } else {
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendAddressError",
                UtilMisc.toMap(
                    "sendTo",
                    sendTo,
                    "sendFrom",
                    sendFrom,
                    "sendCc",
                    sendCc,
                    "sendBcc",
                    sendBcc,
                    "subject",
                    subject),
                locale));
      }
    } catch (MessagingException e) {
      // message code prefix may be used by calling services to determine the cause of the failure
      Debug.logError(
          e,
          "[CON] Connection error when sending message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be sent to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendConnectionError",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    }
    return results;
  }
Пример #6
0
  /**
   * 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"));

    List<String> xslfoAttachScreenLocationList = FastList.newInstance();
    List<String> attachmentNameList = FastList.newInstance();
    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);

    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 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);
    ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer);
    screens.populateContextForService(dctx, bodyParameters);
    screenContext.putAll(bodyParameters);

    if (bodyScreenUri != null) {
      try {
        screens.render(bodyScreenUri);
      } catch (GeneralException 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));
      } catch (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));
      } catch (SAXException 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));
      } catch (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 = FastList.newInstance();
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html"));
      } else {
        bodyParts.add(
            UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "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);
        }
        isMultiPart = true;
        // start processing fo pdf attachment
        try {
          Writer writer = new StringWriter();
          MapStack<String> screenContextAtt = MapStack.create();
          // substitute the freemarker variables...
          ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenRenderer);
          screensAtt.populateContextForService(dctx, bodyParameters);
          screenContextAtt.putAll(bodyParameters);
          screensAtt.render(xslfoAttachScreenLocation);

          /*
          try { // save generated fo file for debugging
              String buf = writer.toString();
              java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml"));
              fw.write(buf.toString());
              fw.close();
          } catch (IOException e) {
              Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module);
          }
          */

          // create the input stream for the generation
          StreamSource src = new StreamSource(new StringReader(writer.toString()));

          // create the output stream for the generation
          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
          ApacheFopWorker.transform(src, null, fop);

          // and generate the PDF
          baos.flush();
          baos.close();

          // store in the list of maps for sendmail....
          bodyParts.add(
              UtilMisc.<String, Object>toMap(
                  "content",
                  baos.toByteArray(),
                  "type",
                  "application/pdf",
                  "filename",
                  attachmentName));
        } catch (GeneralException 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));
        } catch (IOException ie) {
          Debug.logError(ie, "Error rendering PDF attachment for email: " + ie.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ie.toString()),
                  locale));
        } catch (FOPException fe) {
          Debug.logError(fe, "Error rendering PDF attachment for email: " + fe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", fe.toString()),
                  locale));
        } catch (SAXException se) {
          Debug.logError(se, "Error rendering PDF attachment for email: " + se.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", se.toString()),
                  locale));
        } catch (ParserConfigurationException pe) {
          Debug.logError(pe, "Error rendering PDF attachment for email: " + pe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", pe.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());
      }

      // Only override the default contentType in case of plaintext, since other contentTypes may be
      // multipart
      //    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);
    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(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;
    try {
      if (isMultiPart) {
        sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
      } else {
        sendMailResult = dispatcher.runSync("sendMail", 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(custRequestId)) {
      result.put("custRequestId", custRequestId);
    }
    return result;
  }
Пример #7
0
  public static Map<String, Object> rateProductTaxCalc(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String productStoreId = (String) context.get("productStoreId");
    String facilityId = (String) context.get("facilityId");
    String payToPartyId = (String) context.get("payToPartyId");
    String billToPartyId = (String) context.get("billToPartyId");
    List<GenericValue> itemProductList = UtilGenerics.checkList(context.get("itemProductList"));
    List<BigDecimal> itemAmountList = UtilGenerics.checkList(context.get("itemAmountList"));
    List<BigDecimal> itemPriceList = UtilGenerics.checkList(context.get("itemPriceList"));
    List<BigDecimal> itemQuantityList = UtilGenerics.checkList(context.get("itemQuantityList"));
    List<BigDecimal> itemShippingList = UtilGenerics.checkList(context.get("itemShippingList"));
    BigDecimal orderShippingAmount = (BigDecimal) context.get("orderShippingAmount");
    BigDecimal orderPromotionsAmount = (BigDecimal) context.get("orderPromotionsAmount");
    GenericValue shippingAddress = (GenericValue) context.get("shippingAddress");
    Locale locale = (Locale) context.get("locale");
    GenericValue productStore = null;
    GenericValue facility = null;
    try {
      if (productStoreId != null) {
        productStore =
            delegator.findByPrimaryKey(
                "ProductStore", UtilMisc.toMap("productStoreId", productStoreId));
      }
      if (facilityId != null) {
        facility = delegator.findByPrimaryKey("Facility", UtilMisc.toMap("facilityId", facilityId));
      }
    } catch (GenericEntityException e) {
      Debug.logError(e, "Data error getting tax settings: " + e.toString(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "AccountingTaxSettingError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }

    if (productStore == null && payToPartyId == null) {
      throw new IllegalArgumentException(
          "Could not find payToPartyId ["
              + payToPartyId
              + "] or ProductStore ["
              + productStoreId
              + "] for tax calculation");
    }

    if (shippingAddress == null && facility != null) {
      // if there is no shippingAddress and there is a facility it means it is a face-to-face sale
      // so get facility's address
      try {
        GenericValue facilityContactMech =
            ContactMechWorker.getFacilityContactMechByPurpose(
                delegator, facilityId, UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
        if (facilityContactMech != null) {
          shippingAddress =
              delegator.findByPrimaryKey(
                  "PostalAddress",
                  UtilMisc.toMap("contactMechId", facilityContactMech.getString("contactMechId")));
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, "Data error getting tax settings: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "AccountingTaxSettingError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      }
    }
    if (shippingAddress == null
        || (shippingAddress.get("countryGeoId") == null
            && shippingAddress.get("stateProvinceGeoId") == null
            && shippingAddress.get("postalCodeGeoId") == null)) {
      String errMsg =
          UtilProperties.getMessage(resource, "AccountingTaxNoAddressSpecified", locale);
      if (shippingAddress != null) {
        errMsg +=
            UtilProperties.getMessage(
                resource,
                "AccountingTaxNoAddressSpecifiedDetails",
                UtilMisc.toMap(
                    "contactMechId",
                    shippingAddress.getString("contactMechId"),
                    "address1",
                    shippingAddress.get("address1"),
                    "postalCodeGeoId",
                    shippingAddress.get("postalCodeGeoId"),
                    "stateProvinceGeoId",
                    shippingAddress.get("stateProvinceGeoId"),
                    "countryGeoId",
                    shippingAddress.get("countryGeoId")),
                locale);
        Debug.logError(errMsg, module);
      }
      return ServiceUtil.returnError(errMsg);
    }

    // without knowing the TaxAuthority parties, just find all TaxAuthories for the set of IDs...
    Set<GenericValue> taxAuthoritySet = FastSet.newInstance();
    try {
      getTaxAuthorities(delegator, shippingAddress, taxAuthoritySet);
    } catch (GenericEntityException e) {
      Debug.logError(e, "Data error getting tax settings: " + e.toString(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "AccountingTaxSettingError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }

    // Setup the return lists.
    List<GenericValue> orderAdjustments = FastList.newInstance();
    List<List<GenericValue>> itemAdjustments = FastList.newInstance();

    // Loop through the products; get the taxCategory; and lookup each in the cache.
    for (int i = 0; i < itemProductList.size(); i++) {
      GenericValue product = itemProductList.get(i);
      BigDecimal itemAmount = itemAmountList.get(i);
      BigDecimal itemPrice = itemPriceList.get(i);
      BigDecimal itemQuantity = itemQuantityList != null ? itemQuantityList.get(i) : null;
      BigDecimal shippingAmount = itemShippingList.get(i);
      List<GenericValue> taxList = null;
      if (shippingAddress != null) {
        taxList =
            getTaxAdjustments(
                delegator,
                product,
                productStore,
                payToPartyId,
                billToPartyId,
                taxAuthoritySet,
                itemPrice,
                itemQuantity,
                itemAmount,
                shippingAmount,
                ZERO_BASE);
      }
      // this is an add and not an addAll because we want a List of Lists of GenericValues, one List
      // of Adjustments per item
      itemAdjustments.add(taxList);
    }
    if (orderShippingAmount != null && orderShippingAmount.compareTo(BigDecimal.ZERO) > 0) {
      List<GenericValue> taxList =
          getTaxAdjustments(
              delegator,
              null,
              productStore,
              payToPartyId,
              billToPartyId,
              taxAuthoritySet,
              ZERO_BASE,
              ZERO_BASE,
              ZERO_BASE,
              orderShippingAmount,
              ZERO_BASE);
      orderAdjustments.addAll(taxList);
    }
    if (orderPromotionsAmount != null && orderPromotionsAmount.compareTo(BigDecimal.ZERO) != 0) {
      List<GenericValue> taxList =
          getTaxAdjustments(
              delegator,
              null,
              productStore,
              payToPartyId,
              billToPartyId,
              taxAuthoritySet,
              ZERO_BASE,
              ZERO_BASE,
              ZERO_BASE,
              ZERO_BASE,
              orderPromotionsAmount);
      orderAdjustments.addAll(taxList);
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("orderAdjustments", orderAdjustments);
    result.put("itemAdjustments", itemAdjustments);

    return result;
  }
Пример #8
0
  public boolean runAction(
      String selfService,
      DispatchContext dctx,
      Map<String, Object> context,
      Map<String, Object> result)
      throws GenericServiceException {
    if (serviceName.equals(selfService)) {
      throw new GenericServiceException("Cannot invoke self on ECA.");
    }

    // pull out context parameters needed for this service.
    Map<String, Object> actionContext =
        dctx.getModelService(serviceName).makeValid(context, ModelService.IN_PARAM);

    // set the userLogin object in the context
    actionContext.put("userLogin", ServiceUtil.getUserLogin(dctx, actionContext, runAsUser));

    Map<String, Object> actionResult = null;
    LocalDispatcher dispatcher = dctx.getDispatcher();
    // if SECAs have been turned off, then just return true which has same effect as if secas ran
    // successfully
    if (dispatcher.isEcasDisabled()) {
      Debug.logWarning(
          "SECAs have been disabled on purpose and will not be run for [" + serviceName + "]",
          module);
      return true;
    }

    if (eventName.startsWith("global-")) {
      // XA resource ECA
      ServiceXaWrapper xaw = new ServiceXaWrapper(dctx);
      if (eventName.equals("global-rollback")) {
        xaw.setRollbackService(
            serviceName,
            context,
            "async".equals(serviceMode),
            persist); // using the actual context so we get updates
      } else if (eventName.equals("global-commit")) {
        xaw.setCommitService(
            serviceName,
            context,
            "async".equals(serviceMode),
            persist); // using the actual context so we get updates
      } else if (eventName.equals("global-commit-post-run")) {
        xaw.setCommitService(
            serviceName,
            context,
            "async".equals(serviceMode),
            persist); // using the actual context so we get updates
      }
      try {
        xaw.enlist();
      } catch (XAException e) {
        throw new GenericServiceException("Unable to enlist ServiceXaWrapper with transaction", e);
      }
    } else {
      // standard ECA
      if (this.serviceMode.equals("sync")) {
        if (newTransaction) {
          actionResult = dispatcher.runSync(this.serviceName, actionContext, -1, true);
        } else {
          actionResult = dispatcher.runSync(this.serviceName, actionContext);
        }
      } else if (this.serviceMode.equals("async")) {
        dispatcher.runAsync(serviceName, actionContext, persist);
      }
    }

    // put the results in to the defined map
    if (UtilValidate.isNotEmpty(resultMapName)) {
      Map<String, Object> resultMap = UtilGenerics.checkMap(context.get(resultMapName));
      if (resultMap == null) {
        resultMap = FastMap.newInstance();
      }
      resultMap.putAll(
          dctx.getModelService(this.serviceName)
              .makeValid(actionResult, ModelService.OUT_PARAM, false, null));
      context.put(resultMapName, resultMap);
    }

    // use the result to update the context fields.
    if (resultToContext) {
      context.putAll(
          dctx.getModelService(this.serviceName)
              .makeValid(actionResult, ModelService.OUT_PARAM, false, null));
    }

    // use the result to update the result fields
    if (resultToResult) {
      Map<String, Object> normalizedActionResult =
          dctx.getModelService(selfService)
              .makeValid(actionResult, ModelService.OUT_PARAM, false, null);
      // don't copy over the error messages, use the combining code to do that later
      normalizedActionResult.remove(ModelService.ERROR_MESSAGE);
      normalizedActionResult.remove(ModelService.ERROR_MESSAGE_LIST);
      normalizedActionResult.remove(ModelService.ERROR_MESSAGE_MAP);
      normalizedActionResult.remove("failMessage");
      result.putAll(normalizedActionResult);
    }

    // if we aren't ignoring errors check it here...
    boolean success = true;
    // don't do this if resultToResult, will already be copied over
    if (actionResult != null && !resultToResult) {
      if (!ignoreFailure) {
        if (ModelService.RESPOND_FAIL.equals(actionResult.get(ModelService.RESPONSE_MESSAGE))) {
          if (result != null) {
            result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_FAIL);
          }
          success = false;
        }
      }
      if (!ignoreError) {
        if (ModelService.RESPOND_ERROR.equals(actionResult.get(ModelService.RESPONSE_MESSAGE))) {
          if (result != null) {
            result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
          }
          success = false;
        }
      }
    }

    // copy/combine error messages on error/failure (!success) or on resultToResult to combine any
    // error info coming out, regardless of success status
    if (!success || resultToResult) {
      String errorMessage = (String) actionResult.get(ModelService.ERROR_MESSAGE);
      String failMessage = (String) actionResult.get("failMessage");
      List<? extends Object> errorMessageList =
          UtilGenerics.checkList(actionResult.get(ModelService.ERROR_MESSAGE_LIST));
      Map<String, ? extends Object> errorMessageMap =
          UtilGenerics.checkMap(actionResult.get(ModelService.ERROR_MESSAGE_MAP));

      // do something with the errorMessage
      if (UtilValidate.isNotEmpty(errorMessage)) {
        if (UtilValidate.isEmpty(result.get(ModelService.ERROR_MESSAGE))) {
          result.put(ModelService.ERROR_MESSAGE, errorMessage);
        } else {
          List<Object> origErrorMessageList =
              UtilGenerics.checkList(result.get(ModelService.ERROR_MESSAGE_LIST));
          if (origErrorMessageList == null) {
            origErrorMessageList = new LinkedList<Object>();
            result.put(ModelService.ERROR_MESSAGE_LIST, origErrorMessageList);
          }
          origErrorMessageList.add(0, errorMessage);
        }
      }
      // do something with the errorMessageList
      if (UtilValidate.isNotEmpty(errorMessageList)) {
        List<Object> origErrorMessageList =
            UtilGenerics.checkList(result.get(ModelService.ERROR_MESSAGE_LIST));
        if (origErrorMessageList == null) {
          result.put(ModelService.ERROR_MESSAGE_LIST, errorMessageList);
        } else {
          origErrorMessageList.addAll(errorMessageList);
        }
      }
      // do something with the errorMessageMap
      if (UtilValidate.isNotEmpty(errorMessageMap)) {
        Map<String, Object> origErrorMessageMap =
            UtilGenerics.checkMap(result.get(ModelService.ERROR_MESSAGE_MAP));
        if (origErrorMessageMap == null) {
          result.put(ModelService.ERROR_MESSAGE_MAP, errorMessageMap);
        } else {
          origErrorMessageMap.putAll(errorMessageMap);
        }
      }
      // do something with the fail message
      if (UtilValidate.isNotEmpty(failMessage)) {
        String origFailMessage = (String) result.get("failMessage");
        if (UtilValidate.isEmpty(origFailMessage)) {
          result.put("failMessage", failMessage);
        } else {
          result.put("failMessage", origFailMessage + ", " + failMessage);
        }
      }
    }

    return success;
  }