Example #1
0
  public static Map<String, Object> ping(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    String message = (String) context.get("message");
    Locale locale = (Locale) context.get("locale");
    if (message == null) {
      message = "PONG";
    }

    long count = -1;
    try {
      count = delegator.findCountByCondition("SequenceValueItem", null, null, null);
    } catch (GenericEntityException e) {
      Debug.logError(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonPingDatasourceCannotConnect", locale));
    }

    if (count > 0) {
      Map<String, Object> result = ServiceUtil.returnSuccess();
      result.put("message", message);
      return result;
    } else {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonPingDatasourceInvalidCount", locale));
    }
  }
Example #2
0
  /**
   * Copies a user preference group. Call with fromUserLoginId, userPrefGroupTypeId and optional
   * userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in user's
   * userLoginId will be used.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> copyUserPreferenceGroup(
      DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    String userLoginId = PreferenceWorker.getUserLoginId(context, false);
    String fromUserLoginId = (String) context.get("fromUserLoginId");
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isEmpty(userLoginId)
        || UtilValidate.isEmpty(userPrefGroupTypeId)
        || UtilValidate.isEmpty(fromUserLoginId)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "copyPreference.invalidArgument", locale));
    }

    try {
      Map<String, String> fieldMap =
          UtilMisc.toMap(
              "userLoginId", fromUserLoginId, "userPrefGroupTypeId", userPrefGroupTypeId);
      List<GenericValue> resultList = delegator.findByAnd("UserPreference", fieldMap);
      if (resultList != null) {
        for (GenericValue preference : resultList) {
          preference.set("userLoginId", userLoginId);
        }
        delegator.storeAll(resultList);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "copyPreference.writeFailure", new Object[] {e.getMessage()}, locale));
    }

    return ServiceUtil.returnSuccess();
  }
Example #3
0
  public static Map<String, Object> doRefund(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }
    GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
    GenericValue captureTrans =
        PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference);
    BigDecimal refundAmount = (BigDecimal) context.get("refundAmount");
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "RefundTransaction");
    encoder.add("TRANSACTIONID", captureTrans.getString("referenceNum"));
    encoder.add("REFUNDTYPE", "Partial");
    encoder.add("CURRENCYCODE", captureTrans.getString("currencyUomId"));
    encoder.add("AMT", refundAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("NOTE", "Order #" + orderPaymentPreference.getString("orderId"));
    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("refundResult", false);
      result.put("refundRefNum", captureTrans.getString("referenceNum"));
      result.put("refundAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("refundCode", error.getKey());
        result.put("refundMessage", error.getValue());
      } else {
        result.put(
            "refundMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("refundResult", true);
      result.put("refundAmount", new BigDecimal(decoder.get("GROSSREFUNDAMT")));
      result.put("refundRefNum", decoder.get("REFUNDTRANSACTIONID"));
    }
    return result;
  }
  /**
   * Gets the request fields that are configured in the properties file, such as the merchant key
   * and password. This handles version as well. If some critical data is missing, this throws
   * GenericServiceException.
   */
  private static Map buildRequestHeader(String resource) throws GenericServiceException {
    Map request = FastMap.newInstance();

    String login = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.login");
    if (UtilValidate.isEmpty(login)) {
      Debug.logWarning(
          "Authorize.NET login not configured.  Please ensure payment.authorizedotnet.login is defined in "
              + resource,
          module);
    }

    String password = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.password");
    if (UtilValidate.isEmpty(password)) {
      Debug.logWarning(
          "Authorize.NET password not configured.  Please ensure payment.authorizedotnet.password is defined in "
              + resource,
          module);
    }

    String delimited =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.delimited");
    String delimiter =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.delimiter");
    String emailcustomer =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.emailcustomer");
    String emailmerchant =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.emailmerchant");
    String transdescription =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.transdescription");

    request.put("x_login", login);
    request.put("x_password", password);
    request.put("x_delim_data", delimited);
    request.put("x_delim_char", delimiter);
    request.put("x_email_customer", emailcustomer);
    request.put("x_email_merchant", emailmerchant);
    request.put("x_description", transdescription);
    request.put("x_relay_response", "FALSE");

    String version =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.version", "3.0");
    String tkey = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.trankey");

    // transaction key is only supported in 3.1
    if ("3.1".equals(version) && UtilValidate.isNotEmpty(tkey)) {
      Debug.logWarning(
          "Version 3.1 of Authorize.NET requires a transaction key.  Please define payment.authorizedotnet.trankey in "
              + resource,
          module);
      Debug.logWarning("Reverting to version 3.0 of Authorize.NET", module);
      version = "3.0";
    }

    request.put("x_version", version);
    request.put("x_tran_key", tkey);

    return request;
  }
Example #5
0
  public static Map<String, Object> doVoid(DispatchContext dctx, Map<String, Object> context) {
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    Locale locale = (Locale) context.get("locale");
    if (payPalConfig == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }
    GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
    GenericValue authTrans = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoVoid");
    encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum"));
    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("releaseResult", false);
      result.put("releaseRefNum", authTrans.getString("referenceNum"));
      result.put("releaseAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("releaseCode", error.getKey());
        result.put("releaseMessage", error.getValue());
      } else {
        result.put(
            "releaseMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("releaseResult", true);
      // PayPal voids the entire order amount minus any captures, that's a little difficult to
      // figure out here
      // so until further testing proves we should do otherwise I'm just going to return requested
      // void amount
      result.put("releaseAmount", context.get("releaseAmount"));
      result.put("releaseRefNum", decoder.get("AUTHORIZATIONID"));
    }
    return result;
  }
Example #6
0
  /**
   * Retrieves a group of user preferences from persistent storage. Call with userPrefGroupTypeId
   * and optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in
   * user's userLoginId will be used. The retrieved preferences group is contained in the
   * <b>userPrefMap</b> element.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> getUserPreferenceGroup(
      DispatchContext ctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    if (!PreferenceWorker.isValidGetId(ctx, context)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
    }
    Delegator delegator = ctx.getDelegator();

    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isEmpty(userPrefGroupTypeId)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale));
    }
    String userLoginId = PreferenceWorker.getUserLoginId(context, true);

    Map<String, Object> userPrefMap = null;
    try {
      Map<String, String> fieldMap =
          UtilMisc.toMap("userLoginId", "_NA_", "userPrefGroupTypeId", userPrefGroupTypeId);
      userPrefMap =
          PreferenceWorker.createUserPrefMap(delegator.findByAnd("UserPreference", fieldMap));
      fieldMap.put("userLoginId", userLoginId);
      userPrefMap.putAll(
          PreferenceWorker.createUserPrefMap(delegator.findByAnd("UserPreference", fieldMap)));
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale));
    } catch (GeneralException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale));
    }
    // for the 'DEFAULT' values find the related values in general properties and if found use
    // those.
    Iterator it = userPrefMap.entrySet().iterator();
    Map generalProperties = UtilProperties.getProperties("general");
    while (it.hasNext()) {
      Map.Entry pairs = (Map.Entry) it.next();
      if ("DEFAULT".equals(pairs.getValue())) {
        if (UtilValidate.isNotEmpty(generalProperties.get(pairs.getKey()))) {
          userPrefMap.put((String) pairs.getKey(), generalProperties.get(pairs.getKey()));
        }
      }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("userPrefMap", userPrefMap);
    return result;
  }
Example #7
0
  /**
   * 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;
  }
Example #8
0
  /**
   * Retrieves a single user preference from persistent storage. Call with userPrefTypeId and
   * optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in
   * user's userLoginId will be used. The retrieved preference is contained in the
   * <b>userPrefMap</b> element.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> getUserPreference(DispatchContext ctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    if (!PreferenceWorker.isValidGetId(ctx, context)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
    }
    Delegator delegator = ctx.getDelegator();

    String userPrefTypeId = (String) context.get("userPrefTypeId");
    if (UtilValidate.isEmpty(userPrefTypeId)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale));
    }
    String userLoginId = PreferenceWorker.getUserLoginId(context, true);
    Map<String, String> fieldMap =
        UtilMisc.toMap("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId);
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isNotEmpty(userPrefGroupTypeId)) {
      fieldMap.put("userPrefGroupTypeId", userPrefGroupTypeId);
    }

    Map<String, Object> userPrefMap = null;
    try {
      GenericValue preference =
          EntityUtil.getFirst(delegator.findByAnd("UserPreference", fieldMap));
      if (preference != null) {
        userPrefMap = PreferenceWorker.createUserPrefMap(preference);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale));
    } catch (GeneralException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("userPrefMap", userPrefMap);
    if (userPrefMap != null) {
      // Put the value in the result Map too, makes access easier for calling methods.
      Object userPrefValue = userPrefMap.get(userPrefTypeId);
      if (userPrefValue != null) {
        result.put("userPrefValue", userPrefValue);
      }
    }
    return result;
  }
Example #9
0
  /** Cause a Referential Integrity Error */
  public static Map<String, Object> entityFailTest(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    // attempt to create a DataSource entity w/ an invalid dataSourceTypeId
    GenericValue newEntity = delegator.makeValue("DataSource");
    newEntity.set("dataSourceId", "ENTITY_FAIL_TEST");
    newEntity.set("dataSourceTypeId", "ENTITY_FAIL_TEST");
    newEntity.set("description", "Entity Fail Test - Delete me if I am here");
    try {
      delegator.create(newEntity);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonEntityTestFailure", locale));
    }

    /*
    try {
        newEntity.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    */

    return ServiceUtil.returnSuccess();
  }
Example #10
0
  public static Map<String, Object> doAuthorization(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig =
        getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
      currency = orh.getCurrency();
    }
    encoder.add("CURRENCYCODE", currency);

    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("authResult", false);
      result.put("authRefNum", "N/A");
      result.put("processAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("authCode", error.getKey());
        result.put("authMessage", error.getValue());
      } else {
        result.put(
            "authMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("authResult", true);
      result.put("processAmount", new BigDecimal(decoder.get("AMT")));
      result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what
    // should be checked for this type of transaction
    return result;
  }
 // assumes production mode if the payment.authorizedotnet.test property is missing
 private static boolean isTestMode(String resource) {
   String boolValue =
       UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.test", "false");
   boolValue = boolValue.toLowerCase();
   if (boolValue.startsWith("y") || boolValue.startsWith("t")) return true;
   if (boolValue.startsWith("n") || boolValue.startsWith("f")) return false;
   return false;
 }
Example #12
0
  public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) {
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal captureAmount = (BigDecimal) context.get("captureAmount");
    GenericValue payPalConfig =
        getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    Locale locale = (Locale) context.get("locale");
    if (authTrans == null) {
      authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
    }

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoCapture");
    encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum"));
    encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId"));
    encoder.add("COMPLETETYPE", "NotComplete");

    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("captureResult", false);
      result.put("captureRefNum", "N/A");
      result.put("captureAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("captureCode", error.getKey());
        result.put("captureMessage", error.getValue());
      } else {
        result.put(
            "captureMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("captureResult", true);
      result.put("captureAmount", new BigDecimal(decoder.get("AMT")));
      result.put("captureRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what
    // should be checked for this type of transaction
    return result;
  }
Example #13
0
  /**
   * Stores a user preference group in persistent storage. Call with userPrefMap,
   * userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId isn't specified, then the
   * currently logged-in user's userLoginId will be used.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> setUserPreferenceGroup(
      DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    String userLoginId = PreferenceWorker.getUserLoginId(context, false);
    Map<String, Object> userPrefMap =
        checkMap(context.get("userPrefMap"), String.class, Object.class);
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isEmpty(userLoginId)
        || UtilValidate.isEmpty(userPrefGroupTypeId)
        || userPrefMap == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale));
    }

    try {
      for (Iterator i = userPrefMap.entrySet().iterator(); i.hasNext(); ) {
        Map.Entry mapEntry = (Map.Entry) i.next();
        GenericValue rec =
            delegator.makeValidValue(
                "UserPreference",
                PreferenceWorker.toFieldMap(
                    userLoginId,
                    (String) mapEntry.getKey(),
                    userPrefGroupTypeId,
                    (String) mapEntry.getValue()));
        delegator.createOrStore(rec);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale));
    } catch (GeneralException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale));
    }

    return ServiceUtil.returnSuccess();
  }
  public static Map<String, Object> finAccountReleaseAuth(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    Locale locale = (Locale) context.get("locale");

    String err =
        UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeExpired", locale);
    try {

      // expire the related financial authorization transaction
      GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref);
      if (authTransaction == null) {
        return ServiceUtil.returnError(
            err
                + UtilProperties.getMessage(
                    resourceError, "AccountingFinAccountCannotFindAuthorization", locale));
      }

      Map<String, Object> input =
          UtilMisc.toMap(
              "userLogin", userLogin, "finAccountAuthId", authTransaction.get("referenceNum"));
      Map<String, Object> serviceResults = dispatcher.runSync("expireFinAccountAuth", input);

      Map<String, Object> result = ServiceUtil.returnSuccess();
      result.put("releaseRefNum", authTransaction.getString("referenceNum"));
      result.put("releaseAmount", authTransaction.getBigDecimal("amount"));
      result.put("releaseResult", Boolean.TRUE);

      // if there's an error, don't release
      if (ServiceUtil.isError(serviceResults)) {
        return ServiceUtil.returnError(err + ServiceUtil.getErrorMessage(serviceResults));
      }

      return result;
    } catch (GenericServiceException e) {
      Debug.logError(e, e.getMessage(), module);
      return ServiceUtil.returnError(err + e.getMessage());
    }
  }
Example #15
0
  /**
   * Stores a single user preference in persistent storage. Call with userPrefTypeId,
   * userPrefGroupTypeId, userPrefValue and optional userPrefLoginId. If userPrefLoginId isn't
   * specified, then the currently logged-in user's userLoginId will be used.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> setUserPreference(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    String userLoginId = PreferenceWorker.getUserLoginId(context, false);
    String userPrefTypeId = (String) context.get("userPrefTypeId");
    Object userPrefValue = (String) context.get("userPrefValue");
    if (UtilValidate.isEmpty(userLoginId)
        || UtilValidate.isEmpty(userPrefTypeId)
        || userPrefValue == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale));
    }
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    String userPrefDataType = (String) context.get("userPrefDataType");

    try {
      if (UtilValidate.isNotEmpty(userPrefDataType)) {
        userPrefValue =
            ObjectType.simpleTypeConvert(userPrefValue, userPrefDataType, null, null, false);
      }
      GenericValue rec =
          delegator.makeValidValue(
              "UserPreference",
              PreferenceWorker.toFieldMap(
                  userLoginId, userPrefTypeId, userPrefGroupTypeId, userPrefValue));
      delegator.createOrStore(rec);
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale));
    } catch (GeneralException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale));
    }

    return ServiceUtil.returnSuccess();
  }
 /**
  * Returns a complete category trail - can be used for exporting proper category trees. This is
  * mostly useful when used in combination with bread-crumbs, for building a faceted index tree, or
  * to export a category tree for migration to another system. Will create the tree from root point
  * to categoryId.
  *
  * <p>This method is not meant to be run on every request. Its best use is to generate the trail
  * every so often and store somewhere (a lucene/solr tree, entities, cache or so).
  *
  * @param productCategoryId id of category the trail should be generated for
  * @returns List organized trail from root point to categoryId.
  */
 public static Map getCategoryTrail(DispatchContext dctx, Map context) {
   String productCategoryId = (String) context.get("productCategoryId");
   Map<String, Object> results = ServiceUtil.returnSuccess();
   GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
   List<String> trailElements = FastList.newInstance();
   trailElements.add(productCategoryId);
   String parentProductCategoryId = productCategoryId;
   while (UtilValidate.isNotEmpty(parentProductCategoryId)) {
     // find product category rollup
     try {
       List<EntityCondition> rolllupConds = FastList.newInstance();
       rolllupConds.add(
           EntityCondition.makeCondition("productCategoryId", parentProductCategoryId));
       rolllupConds.add(EntityUtil.getFilterByDateExpr());
       List<GenericValue> productCategoryRollups =
           delegator.findList(
               "ProductCategoryRollup",
               EntityCondition.makeCondition(rolllupConds),
               null,
               UtilMisc.toList("sequenceNum"),
               null,
               true);
       if (UtilValidate.isNotEmpty(productCategoryRollups)) {
         // add only categories that belong to the top category to trail
         for (GenericValue productCategoryRollup : productCategoryRollups) {
           String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId");
           parentProductCategoryId = trailCategoryId;
           if (trailElements.contains(trailCategoryId)) {
             break;
           } else {
             trailElements.add(trailCategoryId);
           }
         }
       } else {
         parentProductCategoryId = null;
       }
     } catch (GenericEntityException e) {
       Map<String, String> messageMap =
           UtilMisc.toMap("errMessage", ". Cannot generate trail from product category. ");
       String errMsg =
           UtilProperties.getMessage(
               "CommonUiLabels",
               "CommonDatabaseProblem",
               messageMap,
               (Locale) context.get("locale"));
       Debug.logError(e, errMsg, module);
       return ServiceUtil.returnError(errMsg);
     }
   }
   Collections.reverse(trailElements);
   results.put("trail", trailElements);
   return results;
 }
Example #17
0
 public static void sendFailureNotification(
     DispatchContext dctx,
     Map<String, ? extends Object> context,
     MimeMessage message,
     List<SMTPAddressFailedException> failures) {
   Locale locale = (Locale) context.get("locale");
   Map<String, Object> newContext = FastMap.newInstance();
   newContext.put("userLogin", context.get("userLogin"));
   newContext.put("sendFailureNotification", false);
   newContext.put("sendFrom", context.get("sendFrom"));
   newContext.put("sendTo", context.get("sendFrom"));
   newContext.put(
       "subject", UtilProperties.getMessage(resource, "CommonEmailSendUndeliveredMail", locale));
   StringBuilder sb = new StringBuilder();
   sb.append(UtilProperties.getMessage(resource, "CommonEmailDeliveryFailed", locale));
   sb.append("/n/n");
   for (SMTPAddressFailedException failure : failures) {
     sb.append(failure.getAddress());
     sb.append(": ");
     sb.append(failure.getMessage());
     sb.append("/n/n");
   }
   sb.append(UtilProperties.getMessage(resource, "CommonEmailDeliveryOriginalMessage", locale));
   sb.append("/n/n");
   List<Map<String, Object>> bodyParts = FastList.newInstance();
   bodyParts.add(UtilMisc.<String, Object>toMap("content", sb.toString(), "type", "text/plain"));
   Map<String, Object> bodyPart = FastMap.newInstance();
   bodyPart.put("content", sb.toString());
   bodyPart.put("type", "text/plain");
   try {
     bodyParts.add(UtilMisc.<String, Object>toMap("content", message.getDataHandler()));
   } catch (MessagingException e) {
     Debug.logError(e, module);
   }
   try {
     dctx.getDispatcher().runSync("sendMailMultiPart", newContext);
   } catch (GenericServiceException e) {
     Debug.logError(e, module);
   }
 }
Example #18
0
 public static Map<String, Object> testRollbackListener(
     DispatchContext dctx, Map<String, ?> context) {
   Locale locale = (Locale) context.get("locale");
   ServiceXaWrapper xar = new ServiceXaWrapper(dctx);
   xar.setRollbackService("testScv", context);
   try {
     xar.enlist();
   } catch (XAException e) {
     Debug.logError(e, module);
   }
   return ServiceUtil.returnError(
       UtilProperties.getMessage(resource, "CommonTestRollingBack", locale));
 }
Example #19
0
  /**
   * Create Note Record
   *
   * @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> createNote(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp noteDate = (Timestamp) context.get("noteDate");
    String partyId = (String) context.get("partyId");
    String noteName = (String) context.get("noteName");
    String note = (String) context.get("note");
    String noteId = delegator.getNextSeqId("NoteData");
    Locale locale = (Locale) context.get("locale");
    if (noteDate == null) {
      noteDate = UtilDateTime.nowTimestamp();
    }

    // check for a party id
    if (partyId == null) {
      if (userLogin != null && userLogin.get("partyId") != null)
        partyId = userLogin.getString("partyId");
    }

    Map<String, Object> fields =
        UtilMisc.toMap(
            "noteId",
            noteId,
            "noteName",
            noteName,
            "noteInfo",
            note,
            "noteParty",
            partyId,
            "noteDateTime",
            noteDate);

    try {
      GenericValue newValue = delegator.makeValue("NoteData", fields);

      delegator.create(newValue);
    } catch (GenericEntityException e) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonNoteCannotBeUpdated",
              UtilMisc.toMap("errorString", e.getMessage()),
              locale));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();

    result.put("noteId", noteId);
    result.put("partyId", partyId);
    return result;
  }
Example #20
0
  /**
   * getBufferedImage
   *
   * <p>Set a buffered image
   *
   * @param context
   * @param fileLocation Full file Path or URL
   * @return URL images for all different size types
   * @throws IOException Error prevents the document from being fully parsed
   * @throws JDOMException Errors occur in parsing
   */
  public static Map<String, Object> getBufferedImage(String fileLocation, Locale locale)
      throws IllegalArgumentException, IOException {

    /* VARIABLES */
    BufferedImage bufImg;
    Map<String, Object> result = FastMap.newInstance();

    /* BUFFERED IMAGE */
    try {
      bufImg = ImageIO.read(new File(fileLocation));
    } catch (IllegalArgumentException e) {
      String errMsg =
          UtilProperties.getMessage(resource, "ImageTransform.input_is_null", locale)
              + " : "
              + fileLocation
              + " ; "
              + e.toString();
      Debug.logError(errMsg, module);
      result.put("errorMessage", errMsg);
      return result;
    } catch (IOException e) {
      String errMsg =
          UtilProperties.getMessage(resource, "ImageTransform.error_occurs_during_reading", locale)
              + " : "
              + fileLocation
              + " ; "
              + e.toString();
      Debug.logError(errMsg, module);
      result.put("errorMessage", errMsg);
      return result;
    }

    result.put("responseMessage", "success");
    result.put("bufferedImage", bufImg);
    return result;
  }
Example #21
0
 private static void initConfig(URL url) throws IOException {
   try {
     if (url == null) {
       String errMsg =
           "The Java environment (-Dxxx=yyy) variable with name "
               + url.toString()
               + " is not set, cannot resolve location.";
       throw new MalformedURLException(errMsg);
     }
     props = UtilProperties.getProperties(url);
   } catch (IOException e) {
     e.printStackTrace();
     throw e;
   }
 }
Example #22
0
  public static String replaceShoppingListItem(
      HttpServletRequest request, HttpServletResponse response) {
    String quantityStr = request.getParameter("quantity");

    // just call the updateShoppingListItem service
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    Locale locale = UtilHttp.getLocale(request);

    BigDecimal quantity = null;
    try {
      quantity = new BigDecimal(quantityStr);
    } catch (Exception e) {
      // do nothing, just won't pass to service if it is null
    }

    Map<String, Object> serviceInMap = FastMap.newInstance();
    serviceInMap.put("shoppingListId", request.getParameter("shoppingListId"));
    serviceInMap.put("shoppingListItemSeqId", request.getParameter("shoppingListItemSeqId"));
    serviceInMap.put("productId", request.getParameter("add_product_id"));
    serviceInMap.put("userLogin", userLogin);
    if (quantity != null) serviceInMap.put("quantity", quantity);
    Map<String, Object> result = null;
    try {
      result = dispatcher.runSync("updateShoppingListItem", serviceInMap);
    } catch (GenericServiceException e) {
      String errMsg =
          UtilProperties.getMessage(
                  resource_error, "shoppingListEvents.error_calling_update", locale)
              + ": "
              + e.toString();
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
      String errorMsg =
          "Error calling the updateShoppingListItem in handleShoppingListItemVariant: "
              + e.toString();
      Debug.logError(e, errorMsg, module);
      return "error";
    }

    ServiceUtil.getMessages(request, result, "", "", "", "", "", "", "");
    if ("error".equals(result.get(ModelService.RESPONSE_MESSAGE))) {
      return "error";
    } else {
      return "success";
    }
  }
Example #23
0
  public static void addWeightedKeywordSourceString(
      GenericValue value, String fieldName, List<String> strings) {
    if (value.getString(fieldName) != null) {
      int weight = 1;

      try {
        weight =
            Integer.parseInt(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight." + value.getEntityName() + "." + fieldName, "1"));
      } catch (Exception e) {
        Debug.logWarning("Could not parse weight number: " + e.toString(), module);
      }

      for (int i = 0; i < weight; i++) {
        strings.add(value.getString(fieldName));
      }
    }
  }
Example #24
0
  public static String getJSONuiLabel(HttpServletRequest request, HttpServletResponse response) {
    String requiredLabels = request.getParameter("requiredLabel");

    JSONObject uiLabelObject = null;
    if (UtilValidate.isNotEmpty(requiredLabels)) {
      // Transform JSON String to Object
      uiLabelObject = (JSONObject) JSONSerializer.toJSON(requiredLabels);
    }

    JSONArray jsonUiLabel = new JSONArray();
    Locale locale = request.getLocale();
    if (!uiLabelObject.isEmpty()) {
      Set<String> resourceSet = UtilGenerics.checkSet(uiLabelObject.keySet());
      // Iterate over the resource set
      // here we need a keySet because we don't now which label resource to load
      // the key set should have the size one, if greater or empty error should returned
      if (UtilValidate.isEmpty(resourceSet)) {
        Debug.logError("No resource and labels found", module);
        return "error";
      } else if (resourceSet.size() > 1) {
        Debug.logError(
            "More than one resource found, please use the method: getJSONuiLabelArray", module);
        return "error";
      }

      for (String resource : resourceSet) {
        String label = uiLabelObject.getString(resource);
        if (UtilValidate.isEmail(label)) {
          continue;
        }

        String receivedLabel = UtilProperties.getMessage(resource, label, locale);
        jsonUiLabel.add(receivedLabel);
      }
    }

    writeJSONtoResponse(jsonUiLabel, response);
    return "success";
  }
Example #25
0
  public static String getJSONuiLabelArray(
      HttpServletRequest request, HttpServletResponse response) {
    String requiredLabels = request.getParameter("requiredLabels");

    JSONObject uiLabelObject = null;
    if (UtilValidate.isNotEmpty(requiredLabels)) {
      // Transform JSON String to Object
      uiLabelObject = (JSONObject) JSONSerializer.toJSON(requiredLabels);
    }

    JSONObject jsonUiLabel = new JSONObject();
    Locale locale = request.getLocale();
    if (!uiLabelObject.isEmpty()) {
      Set<String> resourceSet = UtilGenerics.checkSet(uiLabelObject.keySet());
      // Iterate over the resouce set
      for (String resource : resourceSet) {
        JSONArray labels = uiLabelObject.getJSONArray(resource);
        if (labels.isEmpty() || labels == null) {
          continue;
        }

        // Iterate over the uiLabel List
        Iterator<String> jsonLabelIterator = UtilGenerics.cast(labels.iterator());
        JSONArray resourceLabelList = new JSONArray();
        while (jsonLabelIterator.hasNext()) {
          String label = jsonLabelIterator.next();
          String receivedLabel = UtilProperties.getMessage(resource, label, locale);
          if (UtilValidate.isNotEmpty(receivedLabel)) {
            resourceLabelList.add(receivedLabel);
          }
        }
        jsonUiLabel.element(resource, resourceLabelList);
      }
    }

    writeJSONtoResponse(jsonUiLabel, response);
    return "success";
  }
  /**
   * Processes the request and returns an AuthorizeResponse. This service causes a
   * GenericServiceException if there is a fatal confguration error that must be addressed.
   */
  private static AuthorizeResponse processRequest(Map request, String resource)
      throws GenericServiceException {
    boolean testMode = isTestMode(resource);
    String url = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.url");
    if (UtilValidate.isEmpty(url)) {
      throw new GenericServiceException(
          "Authorize.NET transaction URL not configured.  Please ensure payment.authorizedotnet.test is defined in "
              + resource);
    }

    Debug.logInfo("Sending eCheck.NET request type " + request.get("x_type"), module);
    if (testMode) {
      Debug.logInfo("Request URL: " + url, module);
      Debug.logInfo("Request Map: " + request, module);
    }

    // post the request to the url
    String responseString = null;
    try {
      HttpClient client = new HttpClient(url, request);
      client.setClientCertificateAlias("AUTHORIZE_NET");
      responseString = client.post();
    } catch (HttpClientException e) {
      Debug.logError(
          e,
          "Failed to send eCheck.NET request due to client exception: " + e.getMessage(),
          module);
      return null;
    }

    if (testMode) {
      Debug.logInfo("Response from eCheck.NET: " + responseString, module);
    }

    return new AuthorizeResponse(responseString);
  }
Example #27
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;
  }
Example #28
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;
  }
Example #29
0
  private static String processTrackingCode(
      GenericValue trackingCode, HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String trackingCodeId = trackingCode.getString("trackingCodeId");

    // check effective dates
    java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp();
    if (trackingCode.get("fromDate") != null
        && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
      if (Debug.infoOn())
        Debug.logInfo(
            "The TrackingCode with ID ["
                + trackingCodeId
                + "] has not yet gone into effect, ignoring this trackingCodeId",
            module);
      return "success";
    }
    if (trackingCode.get("thruDate") != null
        && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
      if (Debug.infoOn())
        Debug.logInfo(
            "The TrackingCode with ID ["
                + trackingCodeId
                + "] has expired, ignoring this trackingCodeId",
            module);
      return "success";
    }

    // persist that info by associating with the current visit
    GenericValue visit = VisitHandler.getVisit(request.getSession());
    if (visit == null) {
      Debug.logWarning(
          "Could not get visit, not associating trackingCode [" + trackingCodeId + "] with visit",
          module);
    } else {
      GenericValue trackingCodeVisit =
          delegator.makeValue(
              "TrackingCodeVisit",
              UtilMisc.toMap(
                  "trackingCodeId",
                  trackingCodeId,
                  "visitId",
                  visit.get("visitId"),
                  "fromDate",
                  UtilDateTime.nowTimestamp(),
                  "sourceEnumId",
                  "TKCDSRC_URL_PARAM"));
      try {
        trackingCodeVisit.create();
      } catch (GenericEntityException e) {
        Debug.logError(e, "Error while saving TrackingCodeVisit", module);
      }
    }

    // write trackingCode cookies with the value set to the trackingCodeId
    // NOTE: just write these cookies and if others exist from other tracking codes they will be
    // overwritten, ie only keep the newest

    // load the properties from the website entity
    String cookieDomain = null;

    String webSiteId = WebSiteWorker.getWebSiteId(request);
    if (webSiteId != null) {
      try {
        GenericValue webSite =
            delegator.findByPrimaryKeyCache("WebSite", UtilMisc.toMap("webSiteId", webSiteId));
        if (webSite != null) {
          cookieDomain = webSite.getString("cookieDomain");
        }
      } catch (GenericEntityException e) {
        Debug.logWarning(
            e, "Problems with WebSite entity; using global default cookie domain", module);
      }
    }

    if (cookieDomain == null) {
      cookieDomain = UtilProperties.getPropertyValue("url", "cookie.domain", "");
    }

    // if trackingCode.trackableLifetime not null and is > 0 write a trackable cookie with name in
    // the form: TKCDT_{trackingCode.trackingCodeTypeId} and timeout will be
    // trackingCode.trackableLifetime
    Long trackableLifetime = trackingCode.getLong("trackableLifetime");
    if (trackableLifetime != null
        && (trackableLifetime.longValue() > 0 || trackableLifetime.longValue() == -1)) {
      Cookie trackableCookie =
          new Cookie(
              "TKCDT_" + trackingCode.getString("trackingCodeTypeId"),
              trackingCode.getString("trackingCodeId"));
      if (trackableLifetime.longValue() > 0)
        trackableCookie.setMaxAge(trackableLifetime.intValue());
      trackableCookie.setPath("/");
      if (cookieDomain.length() > 0) trackableCookie.setDomain(cookieDomain);
      response.addCookie(trackableCookie);
    }

    // if trackingCode.billableLifetime not null and is > 0 write a billable cookie with name in the
    // form: TKCDB_{trackingCode.trackingCodeTypeId} and timeout will be
    // trackingCode.billableLifetime
    Long billableLifetime = trackingCode.getLong("billableLifetime");
    if (billableLifetime != null
        && (billableLifetime.longValue() > 0 || billableLifetime.longValue() == -1)) {
      Cookie billableCookie =
          new Cookie(
              "TKCDB_" + trackingCode.getString("trackingCodeTypeId"),
              trackingCode.getString("trackingCodeId"));
      if (billableLifetime.longValue() > 0) billableCookie.setMaxAge(billableLifetime.intValue());
      billableCookie.setPath("/");
      if (cookieDomain.length() > 0) billableCookie.setDomain(cookieDomain);
      response.addCookie(billableCookie);
    }

    // if site id exist in cookies then it is not required to create it, if exist with different
    // site then create it
    int siteIdCookieAge = (60 * 60 * 24 * 365); // should this be configurable?
    String siteId = request.getParameter("siteId");
    if (UtilValidate.isNotEmpty(siteId)) {
      String visitorSiteIdCookieName = "Ofbiz.TKCD.SiteId";
      String visitorSiteId = null;
      // first try to get the current ID from the visitor cookie
      javax.servlet.http.Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
          if (cookies[i].getName().equals(visitorSiteIdCookieName)) {
            visitorSiteId = cookies[i].getValue();
            break;
          }
        }
      }

      if (visitorSiteId == null || (visitorSiteId != null && !visitorSiteId.equals(siteId))) {
        // if trackingCode.siteId is  not null  write a trackable cookie with name in the form:
        // Ofbiz.TKCSiteId and timeout will be 60 * 60 * 24 * 365
        Cookie siteIdCookie = new Cookie("Ofbiz.TKCD.SiteId", siteId);
        siteIdCookie.setMaxAge(siteIdCookieAge);
        siteIdCookie.setPath("/");
        if (cookieDomain.length() > 0) siteIdCookie.setDomain(cookieDomain);
        response.addCookie(siteIdCookie);
        // if trackingCode.siteId is  not null  write a trackable cookie with name in the form:
        // Ofbiz.TKCSiteId and timeout will be 60 * 60 * 24 * 365
        Cookie updatedTimeStampCookie =
            new Cookie("Ofbiz.TKCD.UpdatedTimeStamp", UtilDateTime.nowTimestamp().toString());
        updatedTimeStampCookie.setMaxAge(siteIdCookieAge);
        updatedTimeStampCookie.setPath("/");
        if (cookieDomain.length() > 0) updatedTimeStampCookie.setDomain(cookieDomain);
        response.addCookie(updatedTimeStampCookie);
      }
    }

    // if we have overridden logo, css and/or catalogId set some session attributes
    HttpSession session = request.getSession();
    String overrideLogo = trackingCode.getString("overrideLogo");
    if (overrideLogo != null) session.setAttribute("overrideLogo", overrideLogo);
    String overrideCss = trackingCode.getString("overrideCss");
    if (overrideCss != null) session.setAttribute("overrideCss", overrideCss);
    String prodCatalogId = trackingCode.getString("prodCatalogId");
    if (UtilValidate.isNotEmpty(prodCatalogId)) {
      session.setAttribute("CURRENT_CATALOG_ID", prodCatalogId);
      CategoryWorker.setTrail(request, FastList.<String>newInstance());
    }

    // if forward/redirect is needed, do a response.sendRedirect and return null to tell the control
    // servlet to not do any other requests/views
    String redirectUrl = trackingCode.getString("redirectUrl");
    if (UtilValidate.isNotEmpty(redirectUrl)) {
      try {
        response.sendRedirect(redirectUrl);
      } catch (java.io.IOException e) {
        Debug.logError(
            e, "Could not redirect as requested in the trackingCode to: " + redirectUrl, module);
      }
      return null;
    }

    return "success";
  }
Example #30
0
  /**
   * If TrackingCode monitoring is desired this event should be added to the list of events that run
   * on every request. This event looks for the parameter <code>ptc</code> and handles the value as
   * a Partner Managed Tracking Code.
   *
   * <p>If the specified trackingCodeId exists then it is used as is, otherwise a new one is created
   * with the ptc value as the trackingCodeId. The values for the fields of the new TrackingCode can
   * come from one of two places: if a <code>dtc</code> parameter is included the value will be used
   * to lookup a TrackingCode with default values, otherwise the default trackingCodeId will be
   * looked up in the <code>partner.trackingCodeId.default</code> in the <code>general.properties
   * </code> file. If that is still not found just use an empty TrackingCode.
   */
  public static String checkPartnerTrackingCodeUrlParam(
      HttpServletRequest request, HttpServletResponse response) {
    String trackingCodeId = request.getParameter("ptc");

    if (UtilValidate.isNotEmpty(trackingCodeId)) {
      // partner managed tracking code is specified on the request
      Delegator delegator = (Delegator) request.getAttribute("delegator");
      GenericValue trackingCode;
      try {
        trackingCode =
            delegator.findByPrimaryKeyCache(
                "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
      } catch (GenericEntityException e) {
        Debug.logError(
            e,
            "Error looking up TrackingCode with trackingCodeId ["
                + trackingCodeId
                + "], ignoring this trackingCodeId",
            module);
        return "error";
      }

      if (trackingCode == null) {
        // create new TrackingCode with default values from a "dtc" parameter or from a properties
        // file

        String dtc = request.getParameter("dtc");
        if (UtilValidate.isEmpty(dtc)) {
          dtc = UtilProperties.getPropertyValue("general", "partner.trackingCodeId.default");
        }
        if (UtilValidate.isNotEmpty(dtc)) {
          GenericValue defaultTrackingCode = null;
          try {
            defaultTrackingCode =
                delegator.findByPrimaryKeyCache(
                    "TrackingCode", UtilMisc.toMap("trackingCodeId", dtc));
          } catch (GenericEntityException e) {
            Debug.logError(
                e,
                "Error looking up Default values TrackingCode with trackingCodeId ["
                    + dtc
                    + "], not using the dtc value for new TrackingCode defaults",
                module);
          }

          if (defaultTrackingCode != null) {
            defaultTrackingCode.set("trackingCodeId", trackingCodeId);
            defaultTrackingCode.set("trackingCodeTypeId", "PARTNER_MGD");
            // null out userLogin fields, no use tracking to customer, or is there?; set dates to
            // current
            defaultTrackingCode.set("createdDate", UtilDateTime.nowTimestamp());
            defaultTrackingCode.set("createdByUserLogin", null);
            defaultTrackingCode.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            defaultTrackingCode.set("lastModifiedByUserLogin", null);

            trackingCode = defaultTrackingCode;
            try {
              trackingCode.create();
            } catch (GenericEntityException e) {
              Debug.logError(
                  e,
                  "Error creating new Partner TrackingCode with trackingCodeId ["
                      + trackingCodeId
                      + "], ignoring this trackingCodeId",
                  module);
              return "error";
            }
          }
        }

        // if trackingCode is still null then the defaultTrackingCode thing didn't work out, use
        // empty TrackingCode
        if (trackingCode == null) {
          trackingCode = delegator.makeValue("TrackingCode");
          trackingCode.set("trackingCodeId", trackingCodeId);
          trackingCode.set("trackingCodeTypeId", "PARTNER_MGD");
          // leave userLogin fields empty, no use tracking to customer, or is there?; set dates to
          // current
          trackingCode.set("createdDate", UtilDateTime.nowTimestamp());
          trackingCode.set("lastModifiedDate", UtilDateTime.nowTimestamp());

          // use nearly unlimited trackable lifetime: 10 billion seconds, 310 years
          trackingCode.set("trackableLifetime", Long.valueOf(10000000000L));
          // use 2592000 seconds as billable lifetime: equals 1 month
          trackingCode.set("billableLifetime", Long.valueOf(2592000));

          trackingCode.set(
              "comments",
              "This TrackingCode has default values because no default TrackingCode could be found.");

          Debug.logWarning(
              "No default TrackingCode record was found, using a TrackingCode with hard coded default values: "
                  + trackingCode,
              module);

          try {
            trackingCode.create();
          } catch (GenericEntityException e) {
            Debug.logError(
                e,
                "Error creating new Partner TrackingCode with trackingCodeId ["
                    + trackingCodeId
                    + "], ignoring this trackingCodeId",
                module);
            return "error";
          }
        }
      }

      return processTrackingCode(trackingCode, request, response);
    } else {
      return "success";
    }
  }