Ejemplo n.º 1
0
  @Override
  public boolean exec(MethodContext methodContext) {
    // if anything but false it will be true
    boolean setIfNull = !"false".equals(methodContext.expandString(setIfNullStr));

    GenericValue value = valueAcsr.get(methodContext);
    if (value == null) {
      String errMsg =
          "In set-pk-fields a value was not found with the specified valueAcsr: "
              + valueAcsr
              + ", not setting fields";

      Debug.logWarning(errMsg, module);
      if (methodContext.getMethodType() == MethodContext.EVENT) {
        methodContext.putEnv(simpleMethod.getEventErrorMessageName(), errMsg);
        methodContext.putEnv(
            simpleMethod.getEventResponseCodeName(), simpleMethod.getDefaultErrorCode());
      } else if (methodContext.getMethodType() == MethodContext.SERVICE) {
        methodContext.putEnv(simpleMethod.getServiceErrorMessageName(), errMsg);
        methodContext.putEnv(
            simpleMethod.getServiceResponseMessageName(), simpleMethod.getDefaultErrorCode());
      }
      return false;
    }

    Map<String, ? extends Object> theMap = mapAcsr.get(methodContext);
    if (theMap == null) {
      Debug.logWarning(
          "In set-pk-fields could not find map with name " + mapAcsr + ", not setting any fields",
          module);
    } else {
      value.setPKFields(theMap, setIfNull);
    }
    return true;
  }
Ejemplo n.º 2
0
  public static Map<String, GenericValue> getPartyOtherValues(
      ServletRequest request,
      String partyId,
      String partyAttr,
      String personAttr,
      String partyGroupAttr) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Map<String, GenericValue> result = FastMap.newInstance();
    try {
      GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));

      if (party != null) result.put(partyAttr, party);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting Party entity", module);
    }

    try {
      GenericValue person =
          delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", partyId));

      if (person != null) result.put(personAttr, person);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting Person entity", module);
    }

    try {
      GenericValue partyGroup =
          delegator.findByPrimaryKey("PartyGroup", UtilMisc.toMap("partyId", partyId));

      if (partyGroup != null) result.put(partyGroupAttr, partyGroup);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting PartyGroup entity", module);
    }
    return result;
  }
Ejemplo n.º 3
0
  /**
   * 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;
  }
 private boolean evalEntityPermission(Security security, GenericValue userLogin) {
   if (nameOrRole == null) {
     Debug.logWarning("Null permission name passed for evaluation", module);
     return false;
   }
   if (action == null) {
     Debug.logWarning("Null action passed for evaluation", module);
   }
   return security.hasEntityPermission(nameOrRole, action, userLogin);
 }
Ejemplo n.º 5
0
 @Override
 public boolean exec(MethodContext methodContext) throws MiniLangException {
   List<Object> messages = errorListFma.get(methodContext.getEnvMap());
   if (messages == null) {
     messages = new LinkedList<Object>();
     errorListFma.put(methodContext.getEnvMap(), messages);
   }
   String location = this.locationFse.expandString(methodContext.getEnvMap());
   Delegator delegator = getDelegator(methodContext);
   URL dataUrl = null;
   try {
     dataUrl = FlexibleLocation.resolveLocation(location, methodContext.getLoader());
   } catch (MalformedURLException e) {
     messages.add(
         "Could not find Entity Data document in resource: "
             + location
             + "; error was: "
             + e.toString());
   }
   if (dataUrl == null) {
     messages.add("Could not find Entity Data document in resource: " + location);
   }
   if ("assert".equals(mode)) {
     try {
       EntityDataAssert.assertData(dataUrl, delegator, messages);
     } catch (Exception e) {
       String xmlError =
           "Error checking/asserting XML Resource \""
               + dataUrl.toExternalForm()
               + "\"; Error was: "
               + e.getMessage();
       messages.add(xmlError);
       Debug.logWarning(e, xmlError, module);
     }
   } else {
     try {
       EntitySaxReader reader = null;
       if (timeout > 0) {
         reader = new EntitySaxReader(delegator, timeout);
       } else {
         reader = new EntitySaxReader(delegator);
       }
       reader.parse(dataUrl);
     } catch (Exception e) {
       String xmlError =
           "Error loading XML Resource \""
               + dataUrl.toExternalForm()
               + "\"; Error was: "
               + e.getMessage();
       messages.add(xmlError);
       Debug.logWarning(e, xmlError, module);
     }
   }
   return true;
 }
Ejemplo n.º 6
0
  public static void checkPathAlias(
      ServletRequest request, ServletResponse response, Delegator delegator, String pathInfo) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String webSiteId = WebSiteWorker.getWebSiteId(request);
    // check path alias
    GenericValue pathAlias = null;
    try {
      pathAlias =
          EntityQuery.use(delegator)
              .from("WebSitePathAlias")
              .where("webSiteId", webSiteId, "pathAlias", pathInfo)
              .cache()
              .queryOne();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    if (pathAlias != null) {
      String alias = pathAlias.getString("aliasTo");
      String contentId = pathAlias.getString("contentId");
      if (contentId == null && UtilValidate.isNotEmpty(alias)) {
        if (!alias.startsWith("/")) {
          alias = "/" + alias;
        }

        RequestDispatcher rd = request.getRequestDispatcher(alias);
        try {
          rd.forward(request, response);
          return;
        } catch (ServletException e) {
          Debug.logWarning(e, module);
        } catch (IOException e) {
          Debug.logWarning(e, module);
        }
      }
    } else {
      // send 404 error if a URI is alias TO
      try {
        List<GenericValue> aliasTos =
            EntityQuery.use(delegator)
                .from("WebSitePathAlias")
                .where("webSiteId", webSiteId, "aliasTo", httpRequest.getRequestURI())
                .queryList();
        if (UtilValidate.isNotEmpty(aliasTos)) {
          httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
          return;
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      } catch (IOException e) {
        Debug.logError(e, module);
      }
    }
  }
Ejemplo n.º 7
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;
  }
Ejemplo n.º 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;
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
0
  public static List<Map<String, GenericValue>> getPartyPaymentMethodValueMaps(
      Delegator delegator, String partyId, Boolean showOld) {
    List<Map<String, GenericValue>> paymentMethodValueMaps = FastList.newInstance();
    try {
      List<GenericValue> paymentMethods =
          delegator.findByAnd("PaymentMethod", UtilMisc.toMap("partyId", partyId));

      if (!showOld) paymentMethods = EntityUtil.filterByDate(paymentMethods, true);

      for (GenericValue paymentMethod : paymentMethods) {
        Map<String, GenericValue> valueMap = FastMap.newInstance();

        paymentMethodValueMaps.add(valueMap);
        valueMap.put("paymentMethod", paymentMethod);
        if ("CREDIT_CARD".equals(paymentMethod.getString("paymentMethodTypeId"))) {
          GenericValue creditCard = paymentMethod.getRelatedOne("CreditCard");
          if (creditCard != null) valueMap.put("creditCard", creditCard);
        } else if ("GIFT_CARD".equals(paymentMethod.getString("paymentMethodTypeId"))) {
          GenericValue giftCard = paymentMethod.getRelatedOne("GiftCard");
          if (giftCard != null) valueMap.put("giftCard", giftCard);
        } else if ("EFT_ACCOUNT".equals(paymentMethod.getString("paymentMethodTypeId"))) {
          GenericValue eftAccount = paymentMethod.getRelatedOne("EftAccount");
          if (eftAccount != null) valueMap.put("eftAccount", eftAccount);
        }
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e, module);
    }
    return paymentMethodValueMaps;
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         BshUtil.eval(
             new String(this.chars, this.parseStart, this.parseLength),
             UtilMisc.makeMapWritable(context));
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "BSH scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (EvalError e) {
     Debug.logWarning(
         e,
         "Error evaluating BSH scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
 public boolean evalPermission(DispatchContext dctx, Map<String, ? extends Object> context) {
   GenericValue userLogin = (GenericValue) context.get("userLogin");
   Authorization authz = dctx.getAuthorization();
   Security security = dctx.getSecurity();
   if (userLogin == null) {
     Debug.logInfo("Secure service requested with no userLogin object", module);
     return false;
   }
   switch (permissionType) {
     case PERMISSION:
       return evalAuthzPermission(authz, userLogin, context);
     case ENTITY_PERMISSION:
       return evalEntityPermission(security, userLogin);
     case ROLE_MEMBER:
       return evalRoleMember(userLogin);
     case PERMISSION_SERVICE:
       return evalPermissionService(serviceModel, dctx, context);
     default:
       Debug.logWarning(
           "Invalid permission type ["
               + permissionType
               + "] for permission named : "
               + nameOrRole
               + " on service : "
               + serviceModel.name,
           module);
       return false;
   }
 }
Ejemplo n.º 13
0
  /** Simple event to set the users per-session currency uom value */
  public static String setSessionCurrencyUom(
      HttpServletRequest request, HttpServletResponse response) {
    String currencyUom = request.getParameter("currencyUom");
    if (UtilValidate.isNotEmpty(currencyUom)) {
      // update the session
      UtilHttp.setCurrencyUom(request.getSession(), currencyUom);

      // update the UserLogin object
      GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
      if (userLogin == null) {
        userLogin = (GenericValue) request.getSession().getAttribute("autoUserLogin");
      }

      if (userLogin != null) {
        GenericValue ulUpdate = GenericValue.create(userLogin);
        ulUpdate.set("lastCurrencyUom", currencyUom);
        try {
          ulUpdate.store();
          userLogin.refreshFromCache();
        } catch (GenericEntityException e) {
          Debug.logWarning(e, module);
        }
      }
    }
    return "success";
  }
Ejemplo n.º 14
0
  @Override
  public T getObject(MethodContext methodContext) {
    T fieldVal = null;

    if (!mapAcsr.isEmpty()) {
      Map<String, ? extends Object> fromMap = mapAcsr.get(methodContext);
      if (fromMap == null) {
        Debug.logWarning(
            "Map not found with name " + mapAcsr + ", not getting Object value, returning null.",
            module);
        return null;
      }
      fieldVal = fieldAcsr.get(fromMap, methodContext);
    } else {
      // no map name, try the env
      fieldVal = fieldAcsr.get(methodContext);
    }

    if (fieldVal == null) {
      if (Debug.infoOn())
        Debug.logInfo(
            "Field value not found with name "
                + fieldAcsr
                + " in Map with name "
                + mapAcsr
                + ", not getting Object value, returning null.",
            module);
      return null;
    }

    return fieldVal;
  }
Ejemplo n.º 15
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();
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         InvokerHelper.createScript(this.parsedScript, GroovyUtil.getBinding(context)).run();
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "Groovy scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (Exception e) {
     // handle other things, like the groovy.lang.MissingPropertyException
     Debug.logWarning(
         e,
         "Error evaluating Groovy scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
Ejemplo n.º 17
0
 @Override
 public boolean exec(MethodContext methodContext) throws MiniLangException {
   try {
     Delegator delegator = getDelegator(methodContext);
     String entityName = this.entityNameFse.expandString(methodContext.getEnvMap());
     ModelEntity modelEntity = delegator.getModelEntity(entityName);
     EntityCondition whereEntityCondition = null;
     if (this.whereCondition != null) {
       whereEntityCondition =
           this.whereCondition.createCondition(
               methodContext.getEnvMap(),
               modelEntity,
               delegator.getModelFieldTypeReader(modelEntity));
     }
     EntityCondition havingEntityCondition = null;
     if (this.havingCondition != null) {
       havingEntityCondition =
           this.havingCondition.createCondition(
               methodContext.getEnvMap(),
               modelEntity,
               delegator.getModelFieldTypeReader(modelEntity));
     }
     long count =
         delegator.findCountByCondition(
             entityName, whereEntityCondition, havingEntityCondition, null);
     this.countFma.put(methodContext.getEnvMap(), count);
   } catch (GeneralException e) {
     String errMsg = "Exception thrown while performing entity count: " + e.getMessage();
     Debug.logWarning(e, errMsg, module);
     simpleMethod.addErrorMessage(methodContext, errMsg);
     return false;
   }
   return true;
 }
Ejemplo n.º 18
0
  /**
   * Retrieve the last deactivation date if the party is currently deactivated.
   *
   * @param partyId
   * @param delegator
   * @return the timestamp of last deactivation, null if the party is not deactivated
   * @throws GenericEntityNotFoundException
   */
  public static Timestamp getDeactivationDate(String partyId, Delegator delegator)
      throws GenericEntityException {
    // check party current status:
    if (isActive(partyId, delegator)) {
      return null;
    }

    // party is currently deactivated, get the deactivation date
    try {

      List<GenericValue> deactivationDates =
          delegator.findByAnd(
              "PartyDeactivation",
              UtilMisc.toMap("partyId", partyId),
              UtilMisc.toList("-deactivationTimestamp"));
      if (UtilValidate.isNotEmpty(deactivationDates)) {
        return (Timestamp) deactivationDates.get(0).get("deactivationTimestamp");
      } else {
        Debug.logWarning(
            "The party ["
                + partyId
                + "] status is disabled but there is no registered deactivation date.",
            MODULE);
      }

    } catch (GenericEntityException e) {
      Debug.logError(e, MODULE);
    }
    return null;
  }
Ejemplo n.º 19
0
  public static String getPartyName(GenericValue partyObject, boolean lastNameFirst) {
    if (partyObject == null) {
      return "";
    }
    if ("PartyGroup".equals(partyObject.getEntityName())
        || "Person".equals(partyObject.getEntityName())) {
      return formatPartyNameObject(partyObject, lastNameFirst);
    } else {
      String partyId = null;
      try {
        partyId = partyObject.getString("partyId");
      } catch (IllegalArgumentException e) {
        Debug.logError(e, "Party object does not contain a party ID", module);
      }

      if (partyId == null) {
        Debug.logWarning(
            "No party ID found; cannot get name based on entity: " + partyObject.getEntityName(),
            module);
        return "";
      } else {
        return getPartyName(partyObject.getDelegator(), partyId, lastNameFirst);
      }
    }
  }
 public Object eval(String source, int lineNo, int columnNo, Object expr) throws BSFException {
   if (!(expr instanceof String))
     throw new BSFException("simple-method expression must be a string");
   // right now only supports one method per file, so get all methods and just run the first...
   Map<String, SimpleMethod> simpleMethods = null;
   try {
     simpleMethods = SimpleMethod.getDirectSimpleMethods(source, (String) expr, "<bsf source>");
   } catch (MiniLangException e) {
     throw new BSFException("Error loading/parsing simple-method XML source: " + e.getMessage());
   }
   Set<String> smNames = simpleMethods.keySet();
   if (smNames.size() == 0) throw new BSFException("Did not find any simple-methods in the file");
   String methodName = smNames.iterator().next();
   if (smNames.size() > 1)
     Debug.logWarning(
         "Found more than one simple-method in the file, running the ["
             + methodName
             + "] method, you should remove all but one method from this file",
         module);
   SimpleMethod simpleMethod = simpleMethods.get(methodName);
   MethodContext methodContext = new MethodContext(context, null, MethodContext.EVENT);
   try {
     return simpleMethod.exec(methodContext);
   } catch (MiniLangException e) {
     throw new BSFException(e.getMessage());
   }
 }
Ejemplo n.º 21
0
 public LabelReferences(Delegator delegator, LabelManagerFactory factory) {
   this.delegator = delegator;
   this.labels = factory.getLabels();
   DelegatorElement delegatorInfo = null;
   try {
     delegatorInfo = EntityConfigUtil.getDelegator(delegator.getDelegatorBaseName());
   } catch (GenericEntityConfException e) {
     Debug.logWarning(e, "Exception thrown while getting delegator config: ", module);
   }
   String modelName;
   if (delegatorInfo != null) {
     modelName = delegatorInfo.getEntityModelReader();
   } else {
     modelName = "main";
   }
   // since we do not associate a dispatcher to this DispatchContext, it is important to set a name
   // of an existing entity model reader:
   // in this way it will be possible to retrieve the service models from the cache
   this.dispatchContext = new DispatchContext(modelName, this.getClass().getClassLoader(), null);
   Collection<LabelInfo> infoList = this.labels.values();
   for (LabelInfo labelInfo : infoList) {
     this.labelSet.add(labelInfo.getLabelKey());
   }
   Collection<ComponentConfig> componentConfigs = ComponentConfig.getAllComponents();
   for (ComponentConfig config : componentConfigs) {
     String rootFolder = config.getRootLocation();
     rootFolder = rootFolder.replace('\\', '/');
     if (!rootFolder.endsWith("/")) {
       rootFolder = rootFolder + "/";
     }
     this.rootFolders.add(rootFolder);
   }
 }
Ejemplo n.º 22
0
  public void renderPortalPageBegin(
      Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage)
      throws GeneralException, IOException {
    String portalPageId = portalPage.getActualPortalPageId();
    String originalPortalPageId = portalPage.getOriginalPortalPageId();
    String confMode = portalPage.getConfMode(context);

    Map<String, String> uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap"));
    String addColumnLabel = "";
    String addColumnHint = "";
    if (uiLabelMap == null) {
      Debug.logWarning("Could not find uiLabelMap in context", module);
    } else {
      addColumnLabel = uiLabelMap.get("CommonAddColumn");
      addColumnHint = uiLabelMap.get("CommonAddAColumnToThisPortalPage");
    }

    StringWriter sr = new StringWriter();
    sr.append("<@renderPortalPageBegin ");
    sr.append("originalPortalPageId=\"");
    sr.append(originalPortalPageId);
    sr.append("\" portalPageId=\"");
    sr.append(portalPageId);
    sr.append("\" confMode=\"");
    sr.append(confMode);
    sr.append("\" addColumnLabel=\"");
    sr.append(addColumnLabel);
    sr.append("\" addColumnHint=\"");
    sr.append(addColumnHint);
    sr.append("\" />");
    executeMacro(writer, sr.toString());
  }
Ejemplo n.º 23
0
 public static String makeProductUrl(
     HttpServletRequest request,
     String previousCategoryId,
     String productCategoryId,
     String productId) {
   Delegator delegator = (Delegator) request.getAttribute("delegator");
   String url = null;
   try {
     GenericValue product =
         EntityQuery.use(delegator)
             .from("Product")
             .where("productId", productId)
             .cache()
             .queryOne();
     ProductContentWrapper wrapper = new ProductContentWrapper(product, request);
     List<String> trail = CategoryWorker.getTrail(request);
     url =
         makeProductUrl(
             delegator,
             wrapper,
             trail,
             request.getContextPath(),
             previousCategoryId,
             productCategoryId,
             productId);
   } catch (GenericEntityException e) {
     Debug.logWarning(e, "Cannot create product's URL for: " + productId, module);
     return redirectUrl;
   }
   return url;
 }
  /**
   * 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;
  }
 private boolean evalAuthzPermission(
     Authorization authz, GenericValue userLogin, Map<String, ? extends Object> context) {
   if (nameOrRole == null) {
     Debug.logWarning("Null permission name passed for evaluation", module);
     return false;
   }
   return authz.hasPermission(userLogin.getString("userLoginId"), nameOrRole, context);
 }
Ejemplo n.º 26
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();
  }
Ejemplo n.º 27
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   ModelFieldVisitor visitor = new XmlWidgetFieldVisitor(sb);
   try {
     accept(visitor);
   } catch (Exception e) {
     Debug.logWarning(e, "Exception thrown in XmlWidgetFieldVisitor: ", module);
   }
   return sb.toString();
 }
Ejemplo n.º 28
0
 /**
  * Returns an appropriate <code>Converter</code> instance for <code>sourceClass</code> and <code>
  * targetClass</code>. If no matching <code>Converter</code> is found, the method throws <code>
  * ClassNotFoundException</code>.
  *
  * <p>This method is intended to be used when the source or target <code>Object</code> types are
  * unknown at compile time. If the source and target <code>Object</code> types are known at
  * compile time, then one of the "ready made" converters should be used.
  *
  * @param sourceClass The object class to convert from
  * @param targetClass The object class to convert to
  * @return A matching <code>Converter</code> instance
  * @throws ClassNotFoundException
  */
 public static <S, T> Converter<S, T> getConverter(Class<S> sourceClass, Class<T> targetClass)
     throws ClassNotFoundException {
   String key = sourceClass.getName().concat(DELIMITER).concat(targetClass.getName());
   if (Debug.verboseOn()) {
     Debug.logVerbose("Getting converter: " + key, module);
   }
   OUTER:
   do {
     Converter<?, ?> result = converterMap.get(key);
     if (result != null) {
       return UtilGenerics.cast(result);
     }
     if (noConversions.contains(key)) {
       throw new ClassNotFoundException("No converter found for " + key);
     }
     Class<?> foundSourceClass = null;
     Converter<?, ?> foundConverter = null;
     for (Converter<?, ?> value : converterMap.values()) {
       if (value.canConvert(sourceClass, targetClass)) {
         // this converter can deal with the source/target pair
         if (foundSourceClass == null
             || foundSourceClass.isAssignableFrom(value.getSourceClass())) {
           // remember the current target source class; if we find another converter, check
           // to see if it's source class is assignable to this one, and if so, it means it's
           // a child class, so we'll then take that converter.
           foundSourceClass = value.getSourceClass();
           foundConverter = value;
         }
       }
     }
     if (foundConverter != null) {
       converterMap.putIfAbsent(key, foundConverter);
       continue OUTER;
     }
     for (ConverterCreator value : creators) {
       result = createConverter(value, sourceClass, targetClass);
       if (result != null) {
         converterMap.putIfAbsent(key, result);
         continue OUTER;
       }
     }
     if (noConversions.add(key)) {
       Debug.logWarning(
           "*** No converter found, converting from "
               + sourceClass.getName()
               + " to "
               + targetClass.getName()
               + ". Please report this message to the developer community so "
               + "a suitable converter can be created. ***",
           module);
     }
     throw new ClassNotFoundException("No converter found for " + key);
   } while (true);
 }
Ejemplo n.º 29
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();
  }
Ejemplo n.º 30
0
 private static String translateAccountNumber(GenericValue eftAccount) {
   String accountNumber = eftAccount.getString("accountNumber").replaceAll("\\D", "");
   if (accountNumber.length() > 20) {
     Debug.logWarning(
         "EftAccount with paymentMethodId ["
             + eftAccount.get("paymentMethodId")
             + "] has a accountNumber larger than 20 digits.  Truncating to 20.",
         module);
     return accountNumber.substring(0, 20);
   }
   return accountNumber;
 }