public static RecurrenceRule makeRule(
      Delegator delegator, int frequency, int interval, int count, long endTime)
      throws RecurrenceRuleException {
    String freq[] = {"", "SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};

    if (frequency < 1 || frequency > 7) throw new RecurrenceRuleException("Invalid frequency");
    if (interval < 0) throw new RecurrenceRuleException("Invalid interval");

    String freqStr = freq[frequency];

    try {
      GenericValue value = delegator.makeValue("RecurrenceRule");

      value.set("frequency", freqStr);
      value.set("intervalNumber", Long.valueOf(interval));
      value.set("countNumber", Long.valueOf(count));
      if (endTime > 0) {
        value.set("untilDateTime", new java.sql.Timestamp(endTime));
      }
      delegator.createSetNextSeqId(value);
      RecurrenceRule newRule = new RecurrenceRule(value);
      return newRule;
    } catch (GenericEntityException ee) {
      throw new RecurrenceRuleException(ee.getMessage(), ee);
    } catch (RecurrenceRuleException re) {
      throw re;
    }
  }
  /**
   * 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();
  }
Beispiel #3
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));
    }
  }
 /**
  * Removes this rule from the persistant store.
  *
  * @throws RecurrenceRuleException
  */
 public void remove() throws RecurrenceRuleException {
   try {
     rule.remove();
   } catch (GenericEntityException e) {
     throw new RecurrenceRuleException(e.getMessage(), e);
   }
 }
  /**
   * Authorizes and captures an EFT transaction. If the authorization or capture fails due to
   * problems with the transaction, this service will result in a failure.
   *
   * <p>If this service results in an error, it means that the service is not propery configured and
   * will not work until the issues are resolved.
   */
  public static Map authorizeAndCaptureEft(DispatchContext dctx, Map context) {
    Delegator delegator = dctx.getDelegator();
    String resource = getResource(context);
    Double amount = (Double) context.get("processAmount");
    GenericValue eftAccount = (GenericValue) context.get("eftAccount");
    String currencyUomId = (String) context.get("currency");

    try {
      Map request = buildRequestHeader(resource);
      request.putAll(buildRequest(eftAccount, amount, currencyUomId, "AUTH_CAPTURE"));
      request.putAll(buildCustomerRequest(delegator, context));
      request.putAll(buildOrderRequest(context));

      AuthorizeResponse response = processRequest(request, resource);

      // process the response
      Map results = ServiceUtil.returnSuccess();
      if (response == null) {
        results.put("authResult", Boolean.FALSE);
        results.put("authRefNum", AuthorizeResponse.ERROR);
        results.put("processAmount", new Double(0.0));
      } else if (AuthorizeResponse.APPROVED.equals(response.getResponseCode())) {
        results.put("authResult", Boolean.TRUE);
        results.put("authFlag", response.getReasonCode());
        results.put("authMessage", response.getReasonText());
        results.put("authCode", response.getResponseField(AuthorizeResponse.AUTHORIZATION_CODE));
        results.put("authRefNum", response.getResponseField(AuthorizeResponse.TRANSACTION_ID));
        results.put(
            "processAmount", new Double(response.getResponseField(AuthorizeResponse.AMOUNT)));
      } else {
        results.put("authResult", Boolean.FALSE);
        results.put("authFlag", response.getReasonCode());
        results.put("authMessage", response.getReasonText());
        results.put("authCode", response.getResponseField(AuthorizeResponse.AUTHORIZATION_CODE));
        results.put("authRefNum", AuthorizeResponse.ERROR);
        results.put("processAmount", new Double(0.0));
      }

      if (isTestMode(resource)) {
        Debug.logInfo("eCheck.NET AUTH_CAPTURE results: " + results, module);
      }
      return results;
    } catch (GenericEntityException e) {
      String message =
          "Entity engine error when attempting to authorize and capture EFT via eCheck.net: "
              + e.getMessage();
      Debug.logError(e, message, module);
      return ServiceUtil.returnError(message);
    } catch (GenericServiceException e) {
      String message =
          "Service error when attempting to authorize and capture EFT via eCheck.net.  This is a configuration problem that must be fixed before this service can work properly: "
              + e.getMessage();
      Debug.logError(e, message, module);
      return ServiceUtil.returnError(message);
    }
  }
  /**
   * 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;
  }
  protected List<GenericValue> getAssignedRequsetType(GenericDelegator delegator, String partyId)
      throws GenericEntityException {

    List<GenericValue> assignedRequestType = null;
    try {
      assignedRequestType =
          delegator.findByAnd("PartyRequestView", UtilMisc.toMap("asignedPartyId", partyId));
    } catch (GenericEntityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return assignedRequestType;
  }
  /**
   * 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;
  }
  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;
  }
Beispiel #10
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;
  }
  /**
   * Creates a PartyRelationshipType
   *
   * @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> createPartyRelationshipType(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = FastMap.newInstance();
    Delegator delegator = ctx.getDelegator();
    Security security = ctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    ServiceUtil.getPartyIdCheckSecurity(
        userLogin, security, context, result, "PARTYMGR", "_CREATE");

    if (result.size() > 0) return result;

    GenericValue partyRelationshipType =
        delegator.makeValue(
            "PartyRelationshipType",
            UtilMisc.toMap("partyRelationshipTypeId", context.get("partyRelationshipTypeId")));

    partyRelationshipType.set("parentTypeId", context.get("parentTypeId"), true);
    partyRelationshipType.set("hasTable", context.get("hasTable"), true);
    partyRelationshipType.set("roleTypeIdValidFrom", context.get("roleTypeIdValidFrom"), true);
    partyRelationshipType.set("roleTypeIdValidTo", context.get("roleTypeIdValidTo"), false);
    partyRelationshipType.set("description", context.get("description"), true);
    partyRelationshipType.set("partyRelationshipName", context.get("partyRelationshipName"), true);

    try {
      if (delegator.findOne(
              partyRelationshipType.getEntityName(), partyRelationshipType.getPrimaryKey(), false)
          != null) {
        return ServiceUtil.returnError("Could not create party relationship type: already exists");
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e, module);
      return ServiceUtil.returnError(
          "Could not create party relationship type (read failure): " + e.getMessage());
    }

    try {
      partyRelationshipType.create();
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          "Could not create party relationship type (write failure): " + e.getMessage());
    }

    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    return result;
  }
Beispiel #12
0
 public static GenericValue findPartyLatestTelecomNumber(String partyId, Delegator delegator) {
   GenericValue pcm = findPartyLatestContactMech(partyId, "TELECOM_NUMBER", delegator);
   if (pcm != null) {
     try {
       return pcm.getRelatedOne("TelecomNumber");
     } catch (GenericEntityException e) {
       Debug.logError(
           e,
           "Error while finding latest TelecomNumber for party with ID ["
               + partyId
               + "]: "
               + e.toString(),
           module);
     }
   }
   return null;
 }
Beispiel #13
0
 public static GenericValue findPartyLatestPostalAddress(String partyId, Delegator delegator) {
   GenericValue pcm = findPartyLatestContactMech(partyId, "POSTAL_ADDRESS", delegator);
   if (pcm != null) {
     try {
       return pcm.getRelatedOne("PostalAddress");
     } catch (GenericEntityException e) {
       Debug.logError(
           e,
           "Error while finding latest PostalAddress for party with ID ["
               + partyId
               + "]: "
               + e.toString(),
           module);
     }
   }
   return null;
 }
 protected Process(EntityPersistentMgr mgr, Delegator delegator, String processId)
     throws PersistenceException {
   super(mgr, delegator);
   if (this.delegator != null) {
     try {
       this.process =
           delegator.findByPrimaryKey(
               org.ofbiz.shark.SharkConstants.WfProcess,
               UtilMisc.toMap(org.ofbiz.shark.SharkConstants.processId, processId));
     } catch (GenericEntityException e) {
       Debug.logError("Invalid delegator object passed", module);
       e.printStackTrace();
       throw new PersistenceException(e);
     }
   } else {
     Debug.logError("Invalid delegator object passed", module);
   }
 }
Beispiel #15
0
 public static GenericValue findPartyLatestUserLogin(String partyId, Delegator delegator) {
   try {
     List<GenericValue> userLoginList =
         delegator.findByAnd(
             "UserLogin",
             UtilMisc.toMap("partyId", partyId),
             UtilMisc.toList("-" + ModelEntity.STAMP_FIELD));
     return EntityUtil.getFirst(userLoginList);
   } catch (GenericEntityException e) {
     Debug.logError(
         e,
         "Error while finding latest UserLogin for party with ID ["
             + partyId
             + "]: "
             + e.toString(),
         module);
     return null;
   }
 }
  /**
   * 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();
  }
Beispiel #17
0
 @Override
 public boolean exec(MethodContext methodContext) throws MiniLangException {
   String entityName = entityNameFse.expandString(methodContext.getEnvMap());
   boolean useCache = "true".equals(useCacheFse.expandString(methodContext.getEnvMap()));
   boolean useIterator = "true".equals(useIteratorFse.expandString(methodContext.getEnvMap()));
   List<String> orderByNames = orderByListFma.get(methodContext.getEnvMap());
   Collection<String> fieldsToSelectList = fieldsToSelectListFma.get(methodContext.getEnvMap());
   Delegator delegator = getDelegator(methodContext);
   try {
     EntityCondition whereCond = null;
     Map<String, ? extends Object> fieldMap = mapFma.get(methodContext.getEnvMap());
     if (fieldMap != null) {
       whereCond = EntityCondition.makeCondition(fieldMap);
     }
     if (useIterator) {
       listFma.put(
           methodContext.getEnvMap(),
           delegator.find(
               entityName,
               whereCond,
               null,
               UtilMisc.toSet(fieldsToSelectList),
               orderByNames,
               null));
     } else {
       listFma.put(
           methodContext.getEnvMap(),
           delegator.findList(
               entityName,
               whereCond,
               UtilMisc.toSet(fieldsToSelectList),
               orderByNames,
               null,
               useCache));
     }
   } catch (GenericEntityException e) {
     String errMsg = "Exception thrown while performing entity find: " + e.getMessage();
     Debug.logWarning(e, errMsg, module);
     simpleMethod.addErrorMessage(methodContext, errMsg);
     return false;
   }
   return true;
 }
  /**
   * 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();
  }
Beispiel #19
0
 public static GenericValue findPartyLatestPostalAddressGeoPoint(
     String partyId, Delegator delegator) {
   GenericValue latestPostalAddress = findPartyLatestPostalAddress(partyId, delegator);
   if (latestPostalAddress != null) {
     try {
       GenericValue latestGeoPoint = latestPostalAddress.getRelatedOne("GeoPoint");
       if (latestGeoPoint != null) {
         return latestGeoPoint;
       }
       return null;
     } catch (GenericEntityException e) {
       Debug.logError(
           e,
           "Error while finding latest GeoPoint for party with ID ["
               + partyId
               + "]: "
               + e.toString(),
           module);
     }
   }
   return null;
 }
Beispiel #20
0
 public static Timestamp findPartyLastLoginTime(String partyId, Delegator delegator) {
   try {
     List<GenericValue> loginHistory =
         delegator.findByAnd(
             "UserLoginHistory", UtilMisc.toMap("partyId", partyId), UtilMisc.toList("-fromDate"));
     GenericValue v = EntityUtil.getFirst(loginHistory);
     if (v != null) {
       return v.getTimestamp("fromDate");
     } else {
       return null;
     }
   } catch (GenericEntityException e) {
     Debug.logError(
         e,
         "Error while finding latest login time for party with ID ["
             + partyId
             + "]: "
             + e.toString(),
         module);
     return null;
   }
 }
Beispiel #21
0
 public static GenericValue findPartyLatestContactMech(
     String partyId, String contactMechTypeId, Delegator delegator) {
   try {
     List<GenericValue> cmList =
         delegator.findByAnd(
             "PartyAndContactMech",
             UtilMisc.toMap("partyId", partyId, "contactMechTypeId", contactMechTypeId),
             UtilMisc.toList("-fromDate"));
     cmList = EntityUtil.filterByDate(cmList);
     return EntityUtil.getFirst(cmList);
   } catch (GenericEntityException e) {
     Debug.logError(
         e,
         "Error while finding latest ContactMech for party with ID ["
             + partyId
             + "] TYPE ["
             + contactMechTypeId
             + "]: "
             + e.toString(),
         module);
     return null;
   }
 }
  public static List<GenericValue> getRelatedCategoriesRet(
      Delegator delegator,
      String attributeName,
      String parentId,
      boolean limitView,
      boolean excludeEmpty,
      boolean recursive) {
    List<GenericValue> categories = FastList.newInstance();

    if (Debug.verboseOn())
      Debug.logVerbose("[CategoryWorker.getRelatedCategories] ParentID: " + parentId, module);

    List<GenericValue> rollups = null;

    try {
      rollups =
          delegator.findByAndCache(
              "ProductCategoryRollup",
              UtilMisc.toMap("parentProductCategoryId", parentId),
              UtilMisc.toList("sequenceNum"));
      if (limitView) {
        rollups = EntityUtil.filterByDate(rollups, true);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
    }
    if (rollups != null) {
      // Debug.logInfo("Rollup size: " + rollups.size(), module);
      for (GenericValue parent : rollups) {
        // Debug.logInfo("Adding child of: " + parent.getString("parentProductCategoryId"), module);
        GenericValue cv = null;

        try {
          cv = parent.getRelatedOneCache("CurrentProductCategory");
        } catch (GenericEntityException e) {
          Debug.logWarning(e.getMessage(), module);
        }
        if (cv != null) {
          if (excludeEmpty) {
            if (!isCategoryEmpty(cv)) {
              // Debug.logInfo("Child : " + cv.getString("productCategoryId") + " is not empty.",
              // module);
              categories.add(cv);
              if (recursive) {
                categories.addAll(
                    getRelatedCategoriesRet(
                        delegator,
                        attributeName,
                        cv.getString("productCategoryId"),
                        limitView,
                        excludeEmpty,
                        recursive));
              }
            }
          } else {
            categories.add(cv);
            if (recursive) {
              categories.addAll(
                  getRelatedCategoriesRet(
                      delegator,
                      attributeName,
                      cv.getString("productCategoryId"),
                      limitView,
                      excludeEmpty,
                      recursive));
            }
          }
        }
      }
    }
    return categories;
  }
  @SuppressWarnings("unchecked")
  public Writer getWriter(final Writer out, Map args) {
    final StringBuilder buf = new StringBuilder();
    final Environment env = Environment.getCurrentEnvironment();
    final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
    // FreeMarkerWorker.convertContext(templateCtx);
    final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    /*
            final String editTemplate = FreeMarkerWorker.getArg(args, "editTemplate", ctx);
            final String wrapTemplateId = FreeMarkerWorker.getArg(args, "wrapTemplateId", ctx);
            //final String mapKey = FreeMarkerWorker.getArg(args, "mapKey", ctx);
            final String templateContentId = FreeMarkerWorker.getArg(args, "templateContentId", ctx);
            final String subDataResourceTypeId = FreeMarkerWorker.getArg(args, "subDataResourceTypeId", ctx);
            final String contentId = FreeMarkerWorker.getArg(args, "contentId", ctx);
            final String subContentId = FreeMarkerWorker.getArg(args, "subContentId", ctx);
            final String rootDir = FreeMarkerWorker.getArg(args, "rootDir", ctx);
            final String webSiteId = FreeMarkerWorker.getArg(args, "webSiteId", ctx);
            final String https = FreeMarkerWorker.getArg(args, "https", ctx);
            final String viewSize = FreeMarkerWorker.getArg(args, "viewSize", ctx);
            final String viewIndex = FreeMarkerWorker.getArg(args, "viewIndex", ctx);
            final String listSize = FreeMarkerWorker.getArg(args, "listSize", ctx);
            final String highIndex = FreeMarkerWorker.getArg(args, "highIndex", ctx);
            final String lowIndex = FreeMarkerWorker.getArg(args, "lowIndex", ctx);
            final String queryString = FreeMarkerWorker.getArg(args, "queryString", ctx);
            final Locale locale = FreeMarkerWorker.getWrappedObject("locale", env);
            final String mimeTypeId = FreeMarkerWorker.getArg(args, "mimeTypeId", ctx);
    */
    final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
    // final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
    GenericValue view = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env);
    final Integer indent =
        (templateCtx.get("indent") == null)
            ? Integer.valueOf(0)
            : (Integer) templateCtx.get("indent");

    String contentId = (String) templateCtx.get("contentId");
    String subContentId = (String) templateCtx.get("subContentId");
    if (view == null) {
      String thisContentId = subContentId;
      if (UtilValidate.isEmpty(thisContentId)) {
        thisContentId = contentId;
      }
      if (UtilValidate.isNotEmpty(thisContentId)) {
        try {
          view = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", thisContentId));
        } catch (GenericEntityException e) {
          Debug.logError(e, "Error getting sub-content", module);
          throw new RuntimeException(e.getMessage());
        }
      }
    }

    final GenericValue subContentDataResourceView = view;
    final Map<String, Object> traverseContext = FastMap.newInstance();
    traverseContext.put("delegator", delegator);
    Map<String, Object> whenMap = FastMap.newInstance();
    whenMap.put("followWhen", templateCtx.get("followWhen"));
    whenMap.put("pickWhen", templateCtx.get("pickWhen"));
    whenMap.put("returnBeforePickWhen", templateCtx.get("returnBeforePickWhen"));
    whenMap.put("returnAfterPickWhen", templateCtx.get("returnAfterPickWhen"));
    traverseContext.put("whenMap", whenMap);
    String fromDateStr = (String) templateCtx.get("fromDateStr");
    String thruDateStr = (String) templateCtx.get("thruDateStr");
    Timestamp fromDate = null;
    if (UtilValidate.isNotEmpty(fromDateStr)) {
      fromDate = UtilDateTime.toTimestamp(fromDateStr);
    }
    traverseContext.put("fromDate", fromDate);
    Timestamp thruDate = null;
    if (UtilValidate.isNotEmpty(thruDateStr)) {
      thruDate = UtilDateTime.toTimestamp(thruDateStr);
    }
    traverseContext.put("thruDate", thruDate);
    String startContentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
    if (startContentAssocTypeId != null) startContentAssocTypeId = "SUB_CONTENT";
    traverseContext.put("contentAssocTypeId", startContentAssocTypeId);
    String direction = (String) templateCtx.get("direction");
    if (UtilValidate.isEmpty(direction)) direction = "From";
    traverseContext.put("direction", direction);

    return new LoopWriter(out) {

      @Override
      public void write(char cbuf[], int off, int len) {
        // StringBuilder ctxBuf = (StringBuilder) templateContext.get("buf");
        // ctxBuf.append(cbuf, off, len);
        buf.append(cbuf, off, len);
      }

      @Override
      public void flush() throws IOException {
        out.flush();
      }

      @Override
      public int onStart() throws TemplateModelException, IOException {
        // templateContext.put("buf", new StringBuilder());
        List<Map<String, Object>> nodeTrail = FastList.newInstance();
        traverseContext.put("nodeTrail", nodeTrail);
        // GenericValue content = null;
        /*
                        if (UtilValidate.isNotEmpty(contentId)) {
                            try {
                                content = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
                            } catch (GenericEntityException e) {
                                // TODO: Not sure what to put here.
                                throw new RuntimeException(e.getMessage());
                            }
                        }
        */
        Map<String, Object> rootNode = ContentWorker.makeNode(subContentDataResourceView);
        ContentWorker.traceNodeTrail("1", nodeTrail);
        ContentWorker.selectKids(rootNode, traverseContext);
        ContentWorker.traceNodeTrail("2", nodeTrail);
        nodeTrail.add(rootNode);
        boolean isPick =
            checkWhen(
                subContentDataResourceView, (String) traverseContext.get("contentAssocTypeId"));
        rootNode.put("isPick", Boolean.valueOf(isPick));
        if (!isPick) {
          ContentWorker.traceNodeTrail("3", nodeTrail);
          isPick = ContentWorker.traverseSubContent(traverseContext);
          ContentWorker.traceNodeTrail("4", nodeTrail);
        }
        if (isPick) {
          populateContext(traverseContext, templateCtx);
          ContentWorker.traceNodeTrail("5", nodeTrail);
          return TransformControl.EVALUATE_BODY;
        } else {
          return TransformControl.SKIP_BODY;
        }
      }

      @Override
      public int afterBody() throws TemplateModelException, IOException {
        // out.write(buf.toString());
        // buf.setLength(0);
        // templateContext.put("buf", new StringBuilder());
        List<Map<String, Object>> nodeTrail =
            UtilGenerics.checkList(traverseContext.get("nodeTrail"));
        ContentWorker.traceNodeTrail("6", nodeTrail);
        boolean inProgress = ContentWorker.traverseSubContent(traverseContext);
        ContentWorker.traceNodeTrail("7", nodeTrail);
        if (inProgress) {
          populateContext(traverseContext, templateCtx);
          ContentWorker.traceNodeTrail("8", nodeTrail);
          return TransformControl.REPEAT_EVALUATION;
        } else return TransformControl.END_EVALUATION;
      }

      @Override
      public void close() throws IOException {
        String wrappedFTL = buf.toString();
        String encloseWrappedText = (String) templateCtx.get("encloseWrappedText");
        if (UtilValidate.isEmpty(encloseWrappedText)
            || encloseWrappedText.equalsIgnoreCase("false")) {
          out.write(wrappedFTL);
          wrappedFTL = null; // So it won't get written again below.
        }
        String wrapTemplateId = (String) templateCtx.get("wrapTemplateId");
        if (UtilValidate.isNotEmpty(wrapTemplateId)) {
          templateCtx.put("wrappedFTL", wrappedFTL);
          Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
          /*
                              templateRoot.put("viewSize", viewSize);
                              templateRoot.put("viewIndex", viewIndex);
                              templateRoot.put("listSize", listSize);
                              templateRoot.put("highIndex", highIndex);
                              templateRoot.put("lowIndex", lowIndex);
                              templateRoot.put("queryString", queryString);
                              templateRoot.put("wrapDataResourceTypeId", subDataResourceTypeId);
                              templateRoot.put("wrapContentIdTo", contentId);
                              templateRoot.put("wrapMimeTypeId", mimeTypeId);
                              //templateRoot.put("wrapMapKey", mapKey);

          */
          templateRoot.put("context", templateCtx);
          String mimeTypeId = (String) templateCtx.get("mimeTypeId");
          Locale locale = (Locale) templateCtx.get("locale");
          if (locale == null) locale = Locale.getDefault();
          try {
            ContentWorker.renderContentAsText(
                dispatcher,
                delegator,
                wrapTemplateId,
                out,
                templateRoot,
                locale,
                mimeTypeId,
                null,
                null,
                true);
          } catch (GeneralException e) {
            Debug.logError(e, "Error rendering content", module);
            throw new IOException("Error rendering content" + e.toString());
          }
          /*
                              Map resultsCtx = FreeMarkerWorker.getWrappedObject("context", env);
                              templateContext.put("contentId", contentId);
                              templateContext.put("locale", locale);
                              templateContext.put("mapKey", null);
                              templateContext.put("subContentId", null);
                              templateContext.put("templateContentId", null);
                              templateContext.put("subDataResourceTypeId", null);
                              templateContext.put("mimeTypeId", null);
          */
        } else {
          if (UtilValidate.isNotEmpty(wrappedFTL)) out.write(wrappedFTL);
        }
        FreeMarkerWorker.removeValues(templateCtx, removeKeyNames);
        FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
      }

      private boolean checkWhen(GenericValue thisContent, String contentAssocTypeId) {
        boolean isPick = false;
        Map<String, Object> assocContext = FastMap.newInstance();
        if (UtilValidate.isEmpty(contentAssocTypeId)) {
          contentAssocTypeId = "";
        }
        assocContext.put("contentAssocTypeId", contentAssocTypeId);
        // assocContext.put("contentTypeId", assocValue.get("contentTypeId"));
        // String assocRelation = null;
        String thisDirection = (String) templateCtx.get("direction");
        String thisContentId = (String) templateCtx.get("thisContentId");
        // String relatedDirection = null;
        if (thisDirection != null && thisDirection.equalsIgnoreCase("From")) {
          assocContext.put("contentIdFrom", thisContentId);
          // assocRelation = "FromContent";
          // relatedDirection = "From";
        } else {
          assocContext.put("contentIdTo", thisContentId);
          // assocRelation = "ToContent";
          // relatedDirection = "To";
        }
        assocContext.put("content", thisContent);
        List<Object> purposes = ContentWorker.getPurposes(thisContent);
        assocContext.put("purposes", purposes);
        List<String> contentTypeAncestry = FastList.newInstance();
        String contentTypeId = (String) thisContent.get("contentTypeId");
        try {
          ContentWorker.getContentTypeAncestry(delegator, contentTypeId, contentTypeAncestry);
        } catch (GenericEntityException e) {
          return false;
        }
        assocContext.put("typeAncestry", contentTypeAncestry);
        Map<String, Object> whenMap = UtilGenerics.checkMap(traverseContext.get("whenMap"));
        // String pickWhen = (String)whenMap.get("pickWhen");
        List<Map<String, ? extends Object>> nodeTrail =
            UtilGenerics.checkList(traverseContext.get("nodeTrail"));
        int indentSz = indent.intValue() + nodeTrail.size();
        assocContext.put("indentObj", Integer.valueOf(indentSz));
        isPick = ContentWorker.checkWhen(assocContext, (String) whenMap.get("pickWhen"));
        return isPick;
      }

      public void populateContext(
          Map<String, Object> traverseContext, Map<String, Object> templateContext) {
        List<Map<String, Object>> nodeTrail =
            UtilGenerics.checkList(traverseContext.get("nodeTrail"));
        int sz = nodeTrail.size();
        Map<String, Object> node = nodeTrail.get(sz - 1);
        // GenericValue content = (GenericValue)node.get("value");
        String contentId = (String) node.get("contentId");
        // String subContentId = (String)node.get("subContentId");
        templateContext.put("subContentId", contentId);
        templateContext.put("subContentDataResourceView", null);
        int indentSz = indent.intValue() + nodeTrail.size();
        templateContext.put("indent", Integer.valueOf(indentSz));
        if (sz >= 2) {
          Map<String, Object> parentNode = nodeTrail.get(sz - 2);
          GenericValue parentContent = (GenericValue) parentNode.get("value");
          String parentContentId = (String) parentNode.get("contentId");
          templateContext.put("parentContentId", parentContentId);
          templateContext.put("parentContent", parentContent);
          templateContext.put("nodeTrail", nodeTrail);
        }
      }
    };
  }
Beispiel #24
0
  /**
   * Renders this screen to a String, i.e. in a text format, as defined with the
   * ScreenStringRenderer implementation.
   *
   * @param writer The Writer that the screen text will be written to
   * @param context Map containing the screen context; the following are reserved words in this
   *     context: - parameters (contains any special initial parameters coming in) - userLogin (if a
   *     user is logged in) - autoUserLogin (if a user is automatically logged in, ie no password
   *     has been entered) - formStringRenderer - request, response, session, application (special
   *     case, only in HTML contexts, etc) - delegator, dispatcher, authz, security - null
   *     (represents a null field value for entity operations) - sections (used for decorators to
   *     reference the sections to be decorated and render them)
   * @param screenStringRenderer An implementation of the ScreenStringRenderer interface that is
   *     responsible for the actual text generation for different screen elements; implementing your
   *     own makes it possible to use the same screen definitions for many types of screen UIs
   */
  public void renderScreenString(
      Appendable writer, Map<String, Object> context, ScreenStringRenderer screenStringRenderer)
      throws ScreenRenderException {
    // make sure the "nullField" object is in there for entity ops
    context.put("nullField", GenericEntity.NULL_FIELD);

    // wrap the whole screen rendering in a transaction, should improve performance in querying and
    // such
    Map<String, String> parameters = UtilGenerics.cast(context.get("parameters"));
    boolean beganTransaction = false;
    int transactionTimeout = -1;
    if (parameters != null) {
      String transactionTimeoutPar = parameters.get("TRANSACTION_TIMEOUT");
      if (transactionTimeoutPar != null) {
        try {
          transactionTimeout = Integer.parseInt(transactionTimeoutPar);
        } catch (NumberFormatException nfe) {
          String msg =
              "TRANSACTION_TIMEOUT parameter for screen ["
                  + this.sourceLocation
                  + "#"
                  + this.name
                  + "] is invalid and it will be ignored: "
                  + nfe.toString();
          Debug.logWarning(msg, module);
        }
      }
    }

    if (transactionTimeout < 0 && !transactionTimeoutExdr.isEmpty()) {
      // no TRANSACTION_TIMEOUT parameter, check screen attribute
      String transactionTimeoutStr = transactionTimeoutExdr.expandString(context);
      if (UtilValidate.isNotEmpty(transactionTimeoutStr)) {
        try {
          transactionTimeout = Integer.parseInt(transactionTimeoutStr);
        } catch (NumberFormatException e) {
          Debug.logWarning(
              e,
              "Could not parse transaction-timeout value, original=["
                  + transactionTimeoutExdr
                  + "], expanded=["
                  + transactionTimeoutStr
                  + "]",
              module);
        }
      }
    }

    try {
      // If transaction timeout is not present (i.e. is equal to -1), the default transaction
      // timeout is used
      // If transaction timeout is present, use it to start the transaction
      // If transaction timeout is set to zero, no transaction is started
      if (useTransaction) {
        if (transactionTimeout < 0) {
          beganTransaction = TransactionUtil.begin();
        }
        if (transactionTimeout > 0) {
          beganTransaction = TransactionUtil.begin(transactionTimeout);
        }
      }

      // render the screen, starting with the top-level section
      this.section.renderWidgetString(writer, context, screenStringRenderer);
    } catch (ScreenRenderException e) {
      throw e;
    } catch (RuntimeException e) {
      String errMsg =
          "Error rendering screen [" + this.sourceLocation + "#" + this.name + "]: " + e.toString();
      Debug.logError(errMsg + ". Rolling back transaction.", module);
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(beganTransaction, errMsg, e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }
      // after rolling back, rethrow the exception
      throw new ScreenRenderException(errMsg, e);
    } catch (Exception e) {
      String errMsg =
          "Error rendering screen [" + this.sourceLocation + "#" + this.name + "]: " + e.toString();
      Debug.logError(errMsg + ". Rolling back transaction.", module);
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(beganTransaction, errMsg, e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }

      // throw nested exception, don't need to log details here: Debug.logError(e, errMsg, module);

      // after rolling back, rethrow the exception
      throw new ScreenRenderException(errMsg, e);
    } finally {
      // only commit the transaction if we started one... this will throw an exception if it fails
      try {
        TransactionUtil.commit(beganTransaction);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not commit transaction: " + e2.toString(), module);
      }
    }
  }
  /**
   * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Delegator delegator = (Delegator) getServletContext().getAttribute("delegator");

    String pathInfo = request.getPathInfo();
    List<String> pathElements = StringUtil.split(pathInfo, "/");

    // look for productId
    String productId = null;
    try {
      String lastPathElement = pathElements.get(pathElements.size() - 1);
      if (lastPathElement.startsWith("p_")
          || delegator.findOne("Product", UtilMisc.toMap("productId", lastPathElement), true)
              != null) {
        if (lastPathElement.startsWith("p_")) {
          productId = lastPathElement.substring(2);
        } else {
          productId = lastPathElement;
        }
        pathElements.remove(pathElements.size() - 1);
      }
    } catch (GenericEntityException e) {
      Debug.logError(
          e,
          "Error looking up product info for ProductUrl with path info ["
              + pathInfo
              + "]: "
              + e.toString(),
          module);
    }

    // get category info going with the IDs that remain
    String categoryId = null;
    if (pathElements.size() == 1) {
      CategoryWorker.setTrail(request, pathElements.get(0), null);
      categoryId = pathElements.get(0);
    } else if (pathElements.size() == 2) {
      CategoryWorker.setTrail(request, pathElements.get(1), pathElements.get(0));
      categoryId = pathElements.get(1);
    } else if (pathElements.size() > 2) {
      List<String> trail = CategoryWorker.getTrail(request);
      if (trail == null) {
        trail = FastList.newInstance();
      }

      if (trail.contains(pathElements.get(0))) {
        // first category is in the trail, so remove it everything after that and fill it in with
        // the list from the pathInfo
        int firstElementIndex = trail.indexOf(pathElements.get(0));
        while (trail.size() > firstElementIndex) {
          trail.remove(firstElementIndex);
        }
        trail.addAll(pathElements);
      } else {
        // first category is NOT in the trail, so clear out the trail and use the pathElements list
        trail.clear();
        trail.addAll(pathElements);
      }
      CategoryWorker.setTrail(request, trail);
      categoryId = pathElements.get(pathElements.size() - 1);
    }
    if (categoryId != null) {
      request.setAttribute("productCategoryId", categoryId);
    }

    String rootCategoryId = null;
    if (pathElements.size() >= 1) {
      rootCategoryId = pathElements.get(0);
    }
    if (rootCategoryId != null) {
      request.setAttribute("rootCategoryId", rootCategoryId);
    }

    if (productId != null) {
      request.setAttribute("product_id", productId);
      request.setAttribute("productId", productId);
    }

    RequestDispatcher rd =
        request.getRequestDispatcher(
            "/"
                + CONTROL_MOUNT_POINT
                + "/"
                + (productId != null ? PRODUCT_REQUEST : CATEGORY_REQUEST));
    rd.forward(request, response);
  }
  public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();

    // Finalize the Visit
    boolean beganTransaction = false;
    try {
      beganTransaction = TransactionUtil.begin();

      // instead of using this message, get directly from session attribute so it won't create a new
      // one: GenericValue visit = VisitHandler.getVisit(session);
      GenericValue visit = (GenericValue) session.getAttribute("visit");
      if (visit != null) {
        visit.set("thruDate", new Timestamp(session.getLastAccessedTime()));
        visit.store();
      } else {
        Debug.logWarning(
            "Could not find visit value object in session ["
                + session.getId()
                + "] that is being destroyed",
            module);
      }

      // Store the UserLoginSession
      String userLoginSessionString = getUserLoginSession(session);
      GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
      if (userLogin != null && userLoginSessionString != null) {
        GenericValue userLoginSession = null;
        userLoginSession = userLogin.getRelatedOne("UserLoginSession");

        if (userLoginSession == null) {
          userLoginSession =
              userLogin
                  .getDelegator()
                  .makeValue(
                      "UserLoginSession",
                      UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId")));
          userLogin.getDelegator().create(userLoginSession);
        }
        userLoginSession.set("savedDate", UtilDateTime.nowTimestamp());
        userLoginSession.set("sessionData", userLoginSessionString);
        userLoginSession.store();
      }

      countDestroySession();
      Debug.logInfo("Destroying session: " + session.getId(), module);
      this.logStats(session, visit);
    } catch (GenericEntityException e) {
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(
            beganTransaction, "Error saving information about closed HttpSession", e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }

      Debug.logError(e, "Error in session destuction information persistence", module);
    } finally {
      // only commit the transaction if we started one... this will throw an exception if it fails
      try {
        TransactionUtil.commit(beganTransaction);
      } catch (GenericEntityException e) {
        Debug.logError(
            e, "Could not commit transaction for update visit for session destuction", module);
      }
    }
  }
Beispiel #27
0
  public static Map<String, Object> getExpressCheckout(
      DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
      encoder.add("TOKEN", token);
    } else {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }

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

    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
      cart.addOrderNote(decoder.get("NOTE"));
    }

    if (cart.getUserLogin() == null) {
      try {
        GenericValue userLogin =
            EntityQuery.use(delegator)
                .from("UserLogin")
                .where("userLoginId", "anonymous")
                .queryOne();
        try {
          cart.setUserLogin(userLogin, dispatcher);
        } catch (CartItemModifyException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
      // Check nothing has been set on the anon userLogin either
      partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
      cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
      GenericValue party = null;
      try {
        party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
      if (party == null) {
        partyId = null;
      }
    }

    Map<String, Object> inMap = FastMap.newInstance();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
      newParty = true;
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("personalTitle", decoder.get("SALUTATION"));
      inMap.put("firstName", decoder.get("FIRSTNAME"));
      inMap.put("middleName", decoder.get("MIDDLENAME"));
      inMap.put("lastName", decoder.get("LASTNAME"));
      inMap.put("suffix", decoder.get("SUFFIX"));
      try {
        outMap = dispatcher.runSync("createPerson", inMap);
        partyId = (String) outMap.get("partyId");
        cart.setOrderPartyId(partyId);
        cart.getUserLogin().setString("partyId", partyId);
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        dispatcher.runSync("createPartyRole", inMap);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
      EntityCondition cond =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition(
                      UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")),
                  EntityCondition.makeCondition(
                      EntityFunction.UPPER_FIELD("infoString"),
                      EntityComparisonOperator.EQUALS,
                      EntityFunction.UPPER(emailAddress))));

      try {
        GenericValue matchingEmail =
            EntityQuery.use(delegator)
                .from("PartyAndContactMech")
                .where(cond)
                .orderBy("fromDate")
                .filterByDate()
                .queryFirst();
        if (matchingEmail != null) {
          emailContactMechId = matchingEmail.getString("contactMechId");
        } else {
          // No email found so we'll need to create one but first check if it should be PRIMARY or
          // just BILLING
          long primaryEmails =
              EntityQuery.use(delegator)
                  .from("PartyContactWithPurpose")
                  .where(
                      "partyId",
                      partyId,
                      "contactMechTypeId",
                      "EMAIL_ADDRESS",
                      "contactMechPurposeTypeId",
                      "PRIMARY_EMAIL")
                  .filterByDate(
                      "contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate")
                  .queryCount();
          if (primaryEmails > 0) emailContactPurposeTypeId = "BILLING_EMAIL";
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    if (emailContactMechId == null) {
      inMap.clear();
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
      inMap.put("emailAddress", emailAddress);
      inMap.put("partyId", partyId);
      inMap.put("roleTypeId", "CUSTOMER");
      inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us
      inMap.put("fromDate", UtilDateTime.nowTimestamp());
      try {
        outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
        emailContactMechId = (String) outMap.get("contactMechId");
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);

    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
      inMap.clear();
      if (phoneNumber.startsWith("+")) {
        // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
        String[] phoneNumbers = phoneNumber.split(" ");
        inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
        inMap.put("contactNumber", phoneNumbers[1]);
      } else {
        // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
        inMap.put("countryCode", "1");
        String[] phoneNumbers = phoneNumber.split("-");
        inMap.put("areaCode", phoneNumbers[0]);
        inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
      }
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("partyId", partyId);
      try {
        outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
        phoneContactId = (String) outMap.get("contactMechId");
        cart.addContactMech("PHONE_BILLING", phoneContactId);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
      }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = FastMap.newInstance();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId =
        PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put(
        "stateProvinceGeoId",
        parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
      // We want an exact match only
      EntityCondition cond =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition(postalMap),
                  EntityCondition.makeCondition(
                      UtilMisc.toMap(
                          "attnName",
                          null,
                          "directions",
                          null,
                          "postalCodeExt",
                          null,
                          "postalCodeGeoId",
                          null)),
                  EntityCondition.makeCondition("partyId", partyId)));
      try {
        GenericValue postalMatch =
            EntityQuery.use(delegator)
                .from("PartyAndPostalAddress")
                .where(cond)
                .orderBy("fromDate")
                .filterByDate()
                .queryFirst();
        if (postalMatch != null) {
          postalContactId = postalMatch.getString("contactMechId");
          List<GenericValue> postalPurposes =
              EntityQuery.use(delegator)
                  .from("PartyContactMechPurpose")
                  .where("partyId", partyId, "contactMechId", postalContactId)
                  .filterByDate()
                  .queryList();
          List<Object> purposeStrings =
              EntityUtil.getFieldListFromEntityList(
                  postalPurposes, "contactMechPurposeTypeId", false);
          if (UtilValidate.isNotEmpty(purposeStrings)
              && purposeStrings.contains("SHIPPING_LOCATION")) {
            needsShippingPurpose = false;
          }
          if (needsBillingPurpose
              && UtilValidate.isNotEmpty(purposeStrings)
              && purposeStrings.contains("BILLING_LOCATION")) {
            needsBillingPurpose = false;
          }
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    if (postalContactId == null) {
      postalMap.put("userLogin", cart.getUserLogin());
      postalMap.put("fromDate", UtilDateTime.nowTimestamp());
      try {
        outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
        postalContactId = (String) outMap.get("contactMechId");
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
      inMap.clear();
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("contactMechId", postalContactId);
      inMap.put("partyId", partyId);
      try {
        if (needsShippingPurpose) {
          inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
          dispatcher.runSync("createPartyContactMechPurpose", inMap);
        }
        if (needsBillingPurpose) {
          inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
          dispatcher.runSync("createPartyContactMechPurpose", inMap);
        }
      } catch (GenericServiceException e) {
        // Not the end of the world, we'll carry on
        Debug.logInfo(e.getMessage(), module);
      }
    }

    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work
    // with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
      cart.setAllCarrierPartyId("_NA_");
      cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
      String[] shipMethodSplit = shipMethod.split(" - ");
      cart.setAllCarrierPartyId(shipMethodSplit[0]);
      String shippingMethodTypeDesc =
          StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
      try {
        GenericValue shipmentMethod =
            EntityQuery.use(delegator)
                .from("ProductStoreShipmentMethView")
                .where(
                    "productStoreId",
                    cart.getProductStoreId(),
                    "partyId",
                    shipMethodSplit[0],
                    "roleTypeId",
                    "CARRIER",
                    "description",
                    shippingMethodTypeDesc)
                .queryFirst();
        cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
      } catch (GenericEntityException e1) {
        Debug.logError(e1, module);
      }
    }
    // Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
      Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
      for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
        cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
      }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result =
        ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
      return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }

    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
      shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
      cho.calcAndAddTax();
    } catch (GeneralException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));

    try {
      outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");

    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);

    return ServiceUtil.returnSuccess();
  }
  public static String addBulkFromCart(
      Delegator delegator,
      LocalDispatcher dispatcher,
      ShoppingCart cart,
      GenericValue userLogin,
      String shoppingListId,
      String shoppingListTypeId,
      String[] items,
      boolean allowPromo,
      boolean append)
      throws IllegalArgumentException {
    String errMsg = null;

    if (items == null || items.length == 0) {
      errMsg =
          UtilProperties.getMessage(
              resource_error, "shoppinglistevents.select_items_to_add_to_list", cart.getLocale());
      throw new IllegalArgumentException(errMsg);
    }

    if (UtilValidate.isEmpty(shoppingListId)) {
      // create a new shopping list
      Map<String, Object> newListResult = null;
      try {
        newListResult =
            dispatcher.runSync(
                "createShoppingList",
                UtilMisc.<String, Object>toMap(
                    "userLogin",
                    userLogin,
                    "productStoreId",
                    cart.getProductStoreId(),
                    "partyId",
                    cart.getOrderPartyId(),
                    "shoppingListTypeId",
                    shoppingListTypeId,
                    "currencyUom",
                    cart.getCurrency()));
      } catch (GenericServiceException e) {
        Debug.logError(e, "Problems creating new ShoppingList", module);
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.cannot_create_new_shopping_list",
                cart.getLocale());
        throw new IllegalArgumentException(errMsg);
      }

      // check for errors
      if (ServiceUtil.isError(newListResult)) {
        throw new IllegalArgumentException(ServiceUtil.getErrorMessage(newListResult));
      }

      // get the new list id
      if (newListResult != null) {
        shoppingListId = (String) newListResult.get("shoppingListId");
      }

      // if no list was created throw an error
      if (shoppingListId == null || shoppingListId.equals("")) {
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.shoppingListId_is_required_parameter",
                cart.getLocale());
        throw new IllegalArgumentException(errMsg);
      }
    } else if (!append) {
      try {
        clearListInfo(delegator, shoppingListId);
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new IllegalArgumentException(
            "Could not clear current shopping list: " + e.toString());
      }
    }

    for (int i = 0; i < items.length; i++) {
      Integer cartIdInt = null;
      try {
        cartIdInt = Integer.valueOf(items[i]);
      } catch (Exception e) {
        Debug.logWarning(
            e,
            UtilProperties.getMessage(
                resource_error, "OrderIllegalCharacterInSelectedItemField", cart.getLocale()),
            module);
      }
      if (cartIdInt != null) {
        ShoppingCartItem item = cart.findCartItem(cartIdInt.intValue());
        if (allowPromo || !item.getIsPromo()) {
          Debug.logInfo(
              "Adding cart item to shopping list ["
                  + shoppingListId
                  + "], allowPromo="
                  + allowPromo
                  + ", item.getIsPromo()="
                  + item.getIsPromo()
                  + ", item.getProductId()="
                  + item.getProductId()
                  + ", item.getQuantity()="
                  + item.getQuantity(),
              module);
          Map<String, Object> serviceResult = null;
          try {
            Map<String, Object> ctx =
                UtilMisc.<String, Object>toMap(
                    "userLogin",
                    userLogin,
                    "shoppingListId",
                    shoppingListId,
                    "productId",
                    item.getProductId(),
                    "quantity",
                    item.getQuantity());
            ctx.put("reservStart", item.getReservStart());
            ctx.put("reservLength", item.getReservLength());
            ctx.put("reservPersons", item.getReservPersons());
            //    ctx.put("accommodationMapId", item.getAccommodationMapId());
            //    ctx.put("accommodationSpotId", item.getAccommodationSpotId());
            if (item.getConfigWrapper() != null) {
              ctx.put("configId", item.getConfigWrapper().getConfigId());
            }
            serviceResult = dispatcher.runSync("createShoppingListItem", ctx);
          } catch (GenericServiceException e) {
            Debug.logError(e, "Problems creating ShoppingList item entity", module);
            errMsg =
                UtilProperties.getMessage(
                    resource_error,
                    "shoppinglistevents.error_adding_item_to_shopping_list",
                    cart.getLocale());
            throw new IllegalArgumentException(errMsg);
          }

          // check for errors
          if (ServiceUtil.isError(serviceResult)) {
            throw new IllegalArgumentException(ServiceUtil.getErrorMessage(serviceResult));
          }
        }
      }
    }

    // return the shoppinglist id
    return shoppingListId;
  }
Beispiel #29
0
  // Note we're not doing a lot of error checking here as this method is really only used
  // to confirm the order with PayPal, the subsequent authorizations will handle any errors
  // that may occur.
  public static Map<String, Object> doExpressCheckout(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {
      payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
      payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal =
        grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2, BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalPaymentSetting, 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, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
      if (errorMessages.containsKey("10417")) {
        // "The transaction cannot complete successfully,  Instruct the customer to use an
        // alternative payment method"
        // I've only encountered this once and there's no indication of the cause so the temporary
        // solution is to try again
        boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
        if (retry) {
          context.put("_RETRY_", false);
          return PayPalServices.doExpressCheckout(dctx, context);
        }
      }
      return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    Map<String, Object> outMap = null;
    try {
      outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
      Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
      return outMap;
    }
    return ServiceUtil.returnSuccess();
  }
  /**
   * Creates and updates a PartyRelationship creating related PartyRoles if needed. A side of the
   * relationship is checked to maintain history
   *
   * @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> createUpdatePartyRelationshipAndRoles(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = FastMap.newInstance();
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();

    try {
      List<GenericValue> partyRelationShipList =
          PartyRelationshipHelper.getActivePartyRelationships(delegator, context);
      if (UtilValidate.isEmpty(
          partyRelationShipList)) { // If already exists and active nothing to do: keep the current
                                    // one
        String partyId = (String) context.get("partyId");
        String partyIdFrom = (String) context.get("partyIdFrom");
        String partyIdTo = (String) context.get("partyIdTo");
        String roleTypeIdFrom = (String) context.get("roleTypeIdFrom");
        String roleTypeIdTo = (String) context.get("roleTypeIdTo");
        String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId");

        // Before creating the partyRelationShip, create the partyRoles if they don't exist
        GenericValue partyToRole = null;
        partyToRole =
            delegator.findOne(
                "PartyRole",
                UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo),
                false);
        if (partyToRole == null) {
          partyToRole =
              delegator.makeValue(
                  "PartyRole", UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo));
          partyToRole.create();
        }

        GenericValue partyFromRole = null;
        partyFromRole =
            delegator.findOne(
                "PartyRole",
                UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom),
                false);
        if (partyFromRole == null) {
          partyFromRole =
              delegator.makeValue(
                  "PartyRole",
                  UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom));
          partyFromRole.create();
        }

        // Check if there is already a partyRelationship of that type with another party from the
        // side indicated
        String sideChecked = partyIdFrom.equals(partyId) ? "partyIdFrom" : "partyIdTo";
        partyRelationShipList =
            delegator.findByAnd(
                "PartyRelationship",
                UtilMisc.toMap(
                    sideChecked,
                    partyId,
                    "roleTypeIdFrom",
                    roleTypeIdFrom,
                    "roleTypeIdTo",
                    roleTypeIdTo,
                    "partyRelationshipTypeId",
                    partyRelationshipTypeId));
        // We consider the last one (in time) as sole active (we try to maintain a unique
        // relationship and keep changes history)
        partyRelationShipList = EntityUtil.filterByDate(partyRelationShipList);
        GenericValue oldPartyRelationShip = EntityUtil.getFirst(partyRelationShipList);
        if (UtilValidate.isNotEmpty(oldPartyRelationShip)) {
          oldPartyRelationShip.setFields(
              UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp())); // Current becomes inactive
          oldPartyRelationShip.store();
        }
        try {
          dispatcher.runSync("createPartyRelationship", context); // Create new one
        } catch (GenericServiceException e) {
          Debug.logWarning(e.getMessage(), module);
          return ServiceUtil.returnError(
              "Could not create party relationship (write failure): " + e.getMessage());
        }
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          "Could not create party relationship (write failure): " + e.getMessage());
    }
    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    return result;
  }