public static String addBulkFromCart(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");

    String shoppingListId = request.getParameter("shoppingListId");
    String shoppingListTypeId = request.getParameter("shoppingListTypeId");
    String selectedCartItems[] = request.getParameterValues("selectedItem");
    if (UtilValidate.isEmpty(selectedCartItems)) {
      selectedCartItems = makeCartItemsArray(cart);
    }

    try {
      shoppingListId =
          addBulkFromCart(
              delegator,
              dispatcher,
              cart,
              userLogin,
              shoppingListId,
              shoppingListTypeId,
              selectedCartItems,
              true,
              true);
    } catch (IllegalArgumentException e) {
      request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
      return "error";
    }

    request.setAttribute("shoppingListId", shoppingListId);
    return "success";
  }
  public void renderPortalPagePortletBody(
      Appendable writer,
      Map<String, Object> context,
      ModelScreenWidget.PortalPage portalPage,
      GenericValue portalPortlet)
      throws GeneralException, IOException {
    String portalPortletId = portalPortlet.getString("portalPortletId");
    String screenName = portalPortlet.getString("screenName");
    String screenLocation = portalPortlet.getString("screenLocation");

    ModelScreen modelScreen = null;
    if (UtilValidate.isNotEmpty(screenName) && UtilValidate.isNotEmpty(screenLocation)) {
      try {
        modelScreen = ScreenFactory.getScreenFromLocation(screenLocation, screenName);
      } catch (IOException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      } catch (SAXException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      } catch (ParserConfigurationException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      }
    }
    modelScreen.renderScreenString(writer, context, this);
  }
Beispiel #3
0
  public static List<GenericValue> findParties(
      Delegator delegator, String idToFind, String partyIdentificationTypeId)
      throws GenericEntityException {
    List<GenericValue> partiesByIds =
        findPartiesById(delegator, idToFind, partyIdentificationTypeId);
    List<GenericValue> parties = null;
    if (UtilValidate.isNotEmpty(partiesByIds)) {
      for (GenericValue party : partiesByIds) {
        GenericValue partyToAdd = party;
        // retreive party GV if the actual genericValue came from viewEntity
        if (!"Party".equals(party.getEntityName())) {
          partyToAdd =
              delegator.findByPrimaryKeyCache(
                  "Party", UtilMisc.toMap("partyId", party.get("partyId")));
        }

        if (UtilValidate.isEmpty(parties)) {
          parties = UtilMisc.toList(partyToAdd);
        } else {
          parties.add(partyToAdd);
        }
      }
    }
    return parties;
  }
  private void getAutoFieldsServiceTag(Element element, Set<String> fieldNames)
      throws GenericServiceException {
    String serviceName = UtilFormatOut.checkNull(element.getAttribute("service-name"));
    String defaultFieldType = UtilFormatOut.checkNull(element.getAttribute("default-field-type"));
    if (UtilValidate.isNotEmpty(serviceName) && (!("hidden".equals(defaultFieldType)))) {
      ModelService modelService = dispatchContext.getModelService(serviceName);
      List<ModelParam> modelParams = modelService.getInModelParamList();
      Iterator<ModelParam> modelParamIter = modelParams.iterator();
      while (modelParamIter.hasNext()) {
        ModelParam modelParam = modelParamIter.next();
        // skip auto params that the service engine populates...
        if ("userLogin".equals(modelParam.name)
            || "locale".equals(modelParam.name)
            || "timeZone".equals(modelParam.name)) {
          continue;
        }
        if (modelParam.formDisplay) {
          if (UtilValidate.isNotEmpty(modelParam.entityName)
              && UtilValidate.isNotEmpty(modelParam.fieldName)) {
            ModelEntity modelEntity;
            modelEntity = delegator.getModelEntity(modelParam.entityName);

            if (modelEntity != null) {
              ModelField modelField = modelEntity.getField(modelParam.fieldName);

              if (modelField != null) {
                fieldNames.add(modelField.getName());
              }
            }
          }
        }
      }
    }
  }
  public static String makeCatalogUrl(
      String contextPath,
      List<String> crumb,
      String productId,
      String currentCategoryId,
      String previousCategoryId) {
    StringBuilder urlBuilder = new StringBuilder();
    urlBuilder.append(contextPath);
    if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
      urlBuilder.append("/");
    }
    urlBuilder.append(CATALOG_URL_MOUNT_POINT);

    if (UtilValidate.isNotEmpty(currentCategoryId)) {
      crumb = CategoryWorker.adjustTrail(crumb, currentCategoryId, previousCategoryId);
      for (String trailCategoryId : crumb) {
        if ("TOP".equals(trailCategoryId)) continue;
        urlBuilder.append("/");
        urlBuilder.append(trailCategoryId);
      }
    }

    if (UtilValidate.isNotEmpty(productId)) {
      urlBuilder.append("/p_");
      urlBuilder.append(productId);
    }

    return urlBuilder.toString();
  }
  public static String makeCatalogUrl(
      HttpServletRequest request,
      String productId,
      String currentCategoryId,
      String previousCategoryId) {
    StringBuilder urlBuilder = new StringBuilder();
    urlBuilder.append(request.getSession().getServletContext().getContextPath());
    if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
      urlBuilder.append("/");
    }
    urlBuilder.append(CATALOG_URL_MOUNT_POINT);

    if (UtilValidate.isNotEmpty(currentCategoryId)) {
      List<String> trail = CategoryWorker.getTrail(request);
      trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId);
      for (String trailCategoryId : trail) {
        if ("TOP".equals(trailCategoryId)) continue;
        urlBuilder.append("/");
        urlBuilder.append(trailCategoryId);
      }
    }

    if (UtilValidate.isNotEmpty(productId)) {
      urlBuilder.append("/p_");
      urlBuilder.append(productId);
    }

    return urlBuilder.toString();
  }
  public static boolean isProductInCategory(
      Delegator delegator, String productId, String productCategoryId)
      throws GenericEntityException {
    if (productCategoryId == null) return false;
    if (UtilValidate.isEmpty(productId)) return false;

    List<GenericValue> productCategoryMembers =
        EntityUtil.filterByDate(
            delegator.findByAndCache(
                "ProductCategoryMember",
                UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId)),
            true);
    if (UtilValidate.isEmpty(productCategoryMembers)) {
      // before giving up see if this is a variant product, and if so look up the virtual product
      // and check it...
      GenericValue product =
          delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", productId));
      List<GenericValue> productAssocs = ProductWorker.getVariantVirtualAssocs(product);
      // this does take into account that a product could be a variant of multiple products, but
      // this shouldn't ever really happen...
      if (productAssocs != null) {
        for (GenericValue productAssoc : productAssocs) {
          if (isProductInCategory(
              delegator, productAssoc.getString("productId"), productCategoryId)) {
            return true;
          }
        }
      }

      return false;
    } else {
      return true;
    }
  }
  /**
   * 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 #9
0
 public static String makeLinkHiddenFormName(
     Map<String, Object> context, ModelFormField modelFormField) {
   ModelForm modelForm = modelFormField.getModelForm();
   Integer itemIndex = (Integer) context.get("itemIndex");
   String iterateId = "";
   String formUniqueId = "";
   String formName = (String) context.get("formName");
   if (UtilValidate.isEmpty(formName)) {
     formName = modelForm.getName();
   }
   if (UtilValidate.isNotEmpty(context.get("iterateId"))) {
     iterateId = (String) context.get("iterateId");
   }
   if (UtilValidate.isNotEmpty(context.get("formUniqueId"))) {
     formUniqueId = (String) context.get("formUniqueId");
   }
   if (itemIndex != null) {
     return formName
         + modelForm.getItemIndexSeparator()
         + itemIndex.intValue()
         + iterateId
         + formUniqueId
         + modelForm.getItemIndexSeparator()
         + modelFormField.getName();
   } else {
     return formName + modelForm.getItemIndexSeparator() + modelFormField.getName();
   }
 }
Beispiel #10
0
  /**
   * Finds all matching PartyAndPostalAddress records based on the values provided. Excludes party
   * records with a statusId of PARTY_DISABLED. Results are ordered by descending
   * PartyContactMech.fromDate. The matching process is as follows: 1. Calls {@link
   * #findMatchingPartyPostalAddress(Delegator, String, String, String, String, String, String,
   * String, String)} to retrieve a list of address matched PartyAndPostalAddress records. Results
   * are limited to Parties of type PERSON. 2. For each matching PartyAndPostalAddress record, the
   * Person record for the Party is then retrieved and an upper case comparison is performed against
   * the supplied firstName, lastName and if provided, middleName.
   *
   * @param delegator Delegator instance
   * @param address1 PostalAddress.address1 to match against (Required).
   * @param address2 Optional PostalAddress.address2 to match against.
   * @param city PostalAddress.city value to match against (Required).
   * @param stateProvinceGeoId Optional PostalAddress.stateProvinceGeoId value to match against. If
   *     null or "**" is passed then the value will be ignored during matching. "NA" can be passed
   *     in place of "_NA_".
   * @param postalCode PostalAddress.postalCode value to match against. Cannot be null but can be
   *     skipped by passing a value starting with an "*". If the length of the supplied string is 10
   *     characters and the string contains a "-" then the postal code will be split at the "-" and
   *     the second half will be used as the postalCodeExt.
   * @param postalCodeExt Optional PostalAddress.postalCodeExt value to match against. Will be
   *     overridden if a postalCodeExt value is retrieved from postalCode as described above.
   * @param countryGeoId Optional PostalAddress.countryGeoId value to match against.
   * @param firstName Person.firstName to match against (Required).
   * @param middleName Optional Person.middleName to match against.
   * @param lastName Person.lastName to match against (Required).
   * @return List of PartyAndPostalAddress GenericValue objects that match the supplied criteria.
   * @throws GeneralException
   */
  public static List<GenericValue> findMatchingPersonPostalAddresses(
      Delegator delegator,
      String address1,
      String address2,
      String city,
      String stateProvinceGeoId,
      String postalCode,
      String postalCodeExt,
      String countryGeoId,
      String firstName,
      String middleName,
      String lastName)
      throws GeneralException {
    // return list
    List<GenericValue> returnList = FastList.newInstance();

    // address information
    if (firstName == null || lastName == null) {
      throw new IllegalArgumentException();
    }

    List<GenericValue> validFound =
        findMatchingPartyPostalAddress(
            delegator,
            address1,
            address2,
            city,
            stateProvinceGeoId,
            postalCode,
            postalCodeExt,
            countryGeoId,
            "PERSON");

    if (UtilValidate.isNotEmpty(validFound)) {
      for (GenericValue partyAndAddr : validFound) {
        String partyId = partyAndAddr.getString("partyId");
        if (UtilValidate.isNotEmpty(partyId)) {
          GenericValue p = delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", partyId));
          if (p != null) {
            String fName = p.getString("firstName");
            String lName = p.getString("lastName");
            String mName = p.getString("middleName");
            if (lName.toUpperCase().equals(lastName.toUpperCase())) {
              if (fName.toUpperCase().equals(firstName.toUpperCase())) {
                if (mName != null && middleName != null) {
                  if (mName.toUpperCase().equals(middleName.toUpperCase())) {
                    returnList.add(partyAndAddr);
                  }
                } else if (middleName == null) {
                  returnList.add(partyAndAddr);
                }
              }
            }
          }
        }
      }
    }

    return returnList;
  }
Beispiel #11
0
 @Override
 public void renderMenuItem(Appendable writer, Map<String, Object> context, ModelMenuItem menuItem)
     throws IOException {
   if (isHideIfSelected(menuItem, context)) return;
   Map<String, Object> parameters = new HashMap<String, Object>();
   String style = menuItem.getWidgetStyle();
   if (menuItem.isSelected(context)) {
     style = menuItem.getSelectedStyle();
     if (UtilValidate.isEmpty(style)) {
       style = "selected";
     }
   }
   if (this.isDisableIfEmpty(menuItem, context)) {
     style = menuItem.getDisabledTitleStyle();
   }
   if (style == null) {
     style = "";
   }
   String alignStyle = menuItem.getAlignStyle();
   if (UtilValidate.isNotEmpty(alignStyle)) {
     style = style.concat(" ").concat(alignStyle);
   }
   parameters.put("style", style);
   parameters.put("toolTip", menuItem.getTooltip(context));
   String linkStr = "";
   MenuLink link = menuItem.getLink();
   if (link != null) {
     StringWriter sw = new StringWriter();
     renderLink(sw, context, link);
     linkStr = sw.toString();
   } else {
     linkStr = menuItem.getTitle(context);
     UtilCodec.SimpleEncoder simpleEncoder =
         (UtilCodec.SimpleEncoder) context.get("simpleEncoder");
     if (simpleEncoder != null) {
       linkStr = simpleEncoder.encode(linkStr);
     }
   }
   parameters.put("linkStr", linkStr);
   boolean containsNestedMenus = !menuItem.getMenuItemList().isEmpty();
   parameters.put("containsNestedMenus", containsNestedMenus);
   try {
     executeMacro(writer, "renderMenuItemBegin", parameters);
   } catch (TemplateException e) {
     throw new IOException(e);
   }
   if (containsNestedMenus) {
     for (ModelMenuItem childMenuItem : menuItem.getMenuItemList()) {
       childMenuItem.renderMenuItemString(writer, context, this);
     }
   }
   parameters.clear();
   parameters.put("containsNestedMenus", containsNestedMenus);
   try {
     executeMacro(writer, "renderMenuItemEnd", parameters);
   } catch (TemplateException e) {
     throw new IOException(e);
   }
 }
Beispiel #12
0
  public static List<Map<String, BigDecimal>> getPackageSplit(
      DispatchContext dctx, List<Map<String, Object>> shippableItemInfo, BigDecimal maxWeight) {
    // create the package list w/ the first package
    List<Map<String, BigDecimal>> packages = FastList.newInstance();

    if (UtilValidate.isNotEmpty(shippableItemInfo)) {
      for (Map<String, Object> itemInfo : shippableItemInfo) {
        long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue();
        BigDecimal totalQuantity = (BigDecimal) itemInfo.get("quantity");
        BigDecimal totalWeight = (BigDecimal) itemInfo.get("weight");
        String productId = (String) itemInfo.get("productId");

        // sanity check
        if (pieces < 1) {
          pieces = 1; // can NEVER be less than one
        }
        BigDecimal weight = totalWeight.divide(BigDecimal.valueOf(pieces), generalRounding);
        for (int z = 1; z <= totalQuantity.intValue(); z++) {
          BigDecimal partialQty =
              pieces > 1
                  ? BigDecimal.ONE.divide(BigDecimal.valueOf(pieces), generalRounding)
                  : BigDecimal.ONE;
          for (long x = 0; x < pieces; x++) {
            if (weight.compareTo(maxWeight) >= 0) {
              Map<String, BigDecimal> newPackage = FastMap.newInstance();
              newPackage.put(productId, partialQty);
              packages.add(newPackage);
            } else if (totalWeight.compareTo(BigDecimal.ZERO) > 0) {
              // create the first package
              if (packages.size() == 0) {
                packages.add(FastMap.<String, BigDecimal>newInstance());
              }

              // package loop
              boolean addedToPackage = false;
              for (Map<String, BigDecimal> packageMap : packages) {
                if (!addedToPackage) {
                  BigDecimal packageWeight =
                      calcPackageWeight(dctx, packageMap, shippableItemInfo, weight);
                  if (packageWeight.compareTo(maxWeight) <= 0) {
                    BigDecimal qty = packageMap.get(productId);
                    qty = UtilValidate.isEmpty(qty) ? BigDecimal.ZERO : qty;
                    packageMap.put(productId, qty.add(partialQty));
                    addedToPackage = true;
                  }
                }
              }
              if (!addedToPackage) {
                Map<String, BigDecimal> packageMap = FastMap.newInstance();
                packageMap.put(productId, partialQty);
                packages.add(packageMap);
              }
            }
          }
        }
      }
    }
    return packages;
  }
  /**
   * 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;
  }
Beispiel #14
0
 public static String removeContextPath(String uri, String contextPath) {
   if (UtilValidate.isEmpty(contextPath) || UtilValidate.isEmpty(uri)) {
     return uri;
   }
   if (uri.length() > contextPath.length() && uri.startsWith(contextPath)) {
     return uri.substring(contextPath.length());
   }
   return uri;
 }
 private void getWebappTag(Element element, String filePath) {
   String title = UtilFormatOut.checkNull(element.getAttribute("title"));
   String appBarDisplay = UtilFormatOut.checkNull(element.getAttribute("app-bar-display"));
   // title labels
   if (UtilValidate.isNotEmpty(title)
       && UtilValidate.isNotEmpty(appBarDisplay)
       && "true".equalsIgnoreCase(appBarDisplay)) {
     setLabelReference(title, filePath);
   }
 }
Beispiel #16
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);
      }
    }
  }
Beispiel #17
0
 public Parameter(Element element) {
   this.name = element.getAttribute("param-name");
   this.value =
       UtilValidate.isNotEmpty(element.getAttribute("value"))
           ? FlexibleStringExpander.getInstance(element.getAttribute("value"))
           : null;
   this.fromField =
       UtilValidate.isNotEmpty(element.getAttribute("from-field"))
           ? FlexibleMapAccessor.getInstance(element.getAttribute("from-field"))
           : null;
 }
  /**
   * 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;
  }
 /**
  * Returns a complete category trail - can be used for exporting proper category trees. This is
  * mostly useful when used in combination with bread-crumbs, for building a faceted index tree, or
  * to export a category tree for migration to another system. Will create the tree from root point
  * to categoryId.
  *
  * <p>This method is not meant to be run on every request. Its best use is to generate the trail
  * every so often and store somewhere (a lucene/solr tree, entities, cache or so).
  *
  * @param productCategoryId id of category the trail should be generated for
  * @returns List organized trail from root point to categoryId.
  */
 public static Map getCategoryTrail(DispatchContext dctx, Map context) {
   String productCategoryId = (String) context.get("productCategoryId");
   Map<String, Object> results = ServiceUtil.returnSuccess();
   GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
   List<String> trailElements = FastList.newInstance();
   trailElements.add(productCategoryId);
   String parentProductCategoryId = productCategoryId;
   while (UtilValidate.isNotEmpty(parentProductCategoryId)) {
     // find product category rollup
     try {
       List<EntityCondition> rolllupConds = FastList.newInstance();
       rolllupConds.add(
           EntityCondition.makeCondition("productCategoryId", parentProductCategoryId));
       rolllupConds.add(EntityUtil.getFilterByDateExpr());
       List<GenericValue> productCategoryRollups =
           delegator.findList(
               "ProductCategoryRollup",
               EntityCondition.makeCondition(rolllupConds),
               null,
               UtilMisc.toList("sequenceNum"),
               null,
               true);
       if (UtilValidate.isNotEmpty(productCategoryRollups)) {
         // add only categories that belong to the top category to trail
         for (GenericValue productCategoryRollup : productCategoryRollups) {
           String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId");
           parentProductCategoryId = trailCategoryId;
           if (trailElements.contains(trailCategoryId)) {
             break;
           } else {
             trailElements.add(trailCategoryId);
           }
         }
       } else {
         parentProductCategoryId = null;
       }
     } catch (GenericEntityException e) {
       Map<String, String> messageMap =
           UtilMisc.toMap("errMessage", ". Cannot generate trail from product category. ");
       String errMsg =
           UtilProperties.getMessage(
               "CommonUiLabels",
               "CommonDatabaseProblem",
               messageMap,
               (Locale) context.get("locale"));
       Debug.logError(e, errMsg, module);
       return ServiceUtil.returnError(errMsg);
     }
   }
   Collections.reverse(trailElements);
   results.put("trail", trailElements);
   return results;
 }
Beispiel #20
0
  /**
   * Generic service to find party by id. By default return the party find by partyId but you can
   * pass searchPartyFirst at false if you want search in partyIdentification before or pass
   * searchAllId at true to find apartyuct with this id (party.partyId and
   * partyIdentification.idValue)
   *
   * @param delegator
   * @param idToFind
   * @param partyIdentificationTypeId
   * @param searchPartyFirst
   * @param searchAllId
   * @return
   * @throws GenericEntityException
   */
  public static List<GenericValue> findPartiesById(
      Delegator delegator,
      String idToFind,
      String partyIdentificationTypeId,
      boolean searchPartyFirst,
      boolean searchAllId)
      throws GenericEntityException {

    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: entered id = "
              + idToFind
              + ", partyIdentificationTypeId = "
              + partyIdentificationTypeId,
          module);

    GenericValue party = null;
    List<GenericValue> partiesFound = null;

    // 1) look if the idToFind given is a real partyId
    if (searchPartyFirst) {
      party = delegator.findByPrimaryKeyCache("Party", UtilMisc.toMap("partyId", idToFind));
    }

    if (searchAllId || (searchPartyFirst && UtilValidate.isEmpty(party))) {
      // 2) Retrieve party in PartyIdentification
      Map<String, String> conditions = UtilMisc.toMap("idValue", idToFind);
      if (UtilValidate.isNotEmpty(partyIdentificationTypeId)) {
        conditions.put("partyIdentificationTypeId", partyIdentificationTypeId);
      }
      partiesFound =
          delegator.findByAndCache(
              "PartyIdentificationAndParty", conditions, UtilMisc.toList("partyId"));
    }

    if (!searchPartyFirst) {
      party = delegator.findByPrimaryKeyCache("Party", UtilMisc.toMap("partyId", idToFind));
    }

    if (UtilValidate.isNotEmpty(party)) {
      if (UtilValidate.isNotEmpty(partiesFound)) partiesFound.add(party);
      else partiesFound = UtilMisc.toList(party);
    }
    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: found party.partyId = "
              + party
              + ", and list : "
              + partiesFound,
          module);
    return partiesFound;
  }
 private void getAutoFieldsEntityTag(Element element, Set<String> fieldNames) {
   String entityName = UtilFormatOut.checkNull(element.getAttribute("entity-name"));
   String defaultFieldType = UtilFormatOut.checkNull(element.getAttribute("default-field-type"));
   if (UtilValidate.isNotEmpty(entityName)
       && UtilValidate.isNotEmpty(defaultFieldType)
       && (!("hidden".equals(defaultFieldType)))) {
     ModelEntity entity = delegator.getModelEntity(entityName);
     for (Iterator<ModelField> f = entity.getFieldsIterator(); f.hasNext(); ) {
       ModelField field = f.next();
       fieldNames.add(field.getName());
     }
   }
 }
  /**
   * 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;
  }
 /**
  * Sets package tracking codes in an org.opentaps.warehouse.shipment.packing.PackingSession
  * object.
  *
  * @param session An org.opentaps.warehouse.shipment.packing.PackingSession
  * @param packageTrackingCodes
  */
 private static void setSessionPackageTrackingCodes(
     PackingSession session, Map<String, String> packageTrackingCodes) {
   if (!UtilValidate.isEmpty(packageTrackingCodes)) {
     Set<String> keySet = packageTrackingCodes.keySet();
     for (String packageSeqId : keySet) {
       String packageTrackingCode = packageTrackingCodes.get(packageSeqId);
       if (UtilValidate.isNotEmpty(packageTrackingCodes)) {
         session.setPackageTrackingCode(packageSeqId, packageTrackingCode);
       } else {
         session.setPackageTrackingCode(packageSeqId, null);
       }
     }
   }
 }
 /**
  * Sets package boxTypeId in an org.opentaps.warehouse.shipment.packing.PackingSession object.
  *
  * @param session An org.opentaps.warehouse.shipment.packing.PackingSession
  * @param packageBoxTypeIds
  */
 private static void setSessionPackageBoxTypeIds(
     PackingSession session, Map<String, String> packageBoxTypeIds) {
   if (UtilValidate.isNotEmpty(packageBoxTypeIds)) {
     Set<String> keySet = packageBoxTypeIds.keySet();
     for (String packageSeqId : keySet) {
       String packageBoxTypeId = packageBoxTypeIds.get(packageSeqId);
       if (UtilValidate.isNotEmpty(packageBoxTypeId)) {
         session.setPackageBoxTypeId(packageSeqId, packageBoxTypeId);
       } else {
         session.setPackageBoxTypeId(packageSeqId, null);
       }
     }
   }
 }
Beispiel #25
0
  public static void setRequestAttributes(
      ServletRequest request, Delegator delegator, ServletContext servletContext) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    // check if multi tenant is enabled
    boolean useMultitenant = EntityUtil.isMultiTenantEnabled();
    if (useMultitenant) {
      // get tenant delegator by domain name
      String serverName = request.getServerName();
      try {
        // if tenant was specified, replace delegator with the new per-tenant delegator and set
        // tenantId to session attribute
        delegator = getDelegator(servletContext);

        // Use base delegator for fetching data from entity of entityGroup org.ofbiz.tenant
        Delegator baseDelegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName());
        GenericValue tenantDomainName =
            EntityQuery.use(baseDelegator)
                .from("TenantDomainName")
                .where("domainName", serverName)
                .queryOne();

        if (UtilValidate.isNotEmpty(tenantDomainName)) {
          String tenantId = tenantDomainName.getString("tenantId");
          // make that tenant active, setup a new delegator and a new dispatcher
          String tenantDelegatorName = delegator.getDelegatorBaseName() + "#" + tenantId;
          httpRequest.getSession().setAttribute("delegatorName", tenantDelegatorName);

          // after this line the delegator is replaced with the new per-tenant delegator
          delegator = DelegatorFactory.getDelegator(tenantDelegatorName);
          servletContext.setAttribute("delegator", delegator);
        }

      } catch (GenericEntityException e) {
        Debug.logWarning(e, "Unable to get Tenant", module);
      }
    }

    // set the web context in the request for future use
    request.setAttribute("servletContext", httpRequest.getSession().getServletContext());
    request.setAttribute("delegator", delegator);

    // set the webSiteId in the session
    if (UtilValidate.isEmpty(httpRequest.getSession().getAttribute("webSiteId"))) {
      httpRequest
          .getSession()
          .setAttribute(
              "webSiteId", httpRequest.getSession().getServletContext().getAttribute("webSiteId"));
    }
  }
  public void init(ServletContext context) throws EventHandlerException {
    String delegatorName = context.getInitParameter("entityDelegatorName");
    this.delegator = DelegatorFactory.getDelegator(delegatorName);
    this.dispatcher = GenericDispatcher.getLocalDispatcher(delegator.getDelegatorName(), delegator);
    this.setHandlerMapping(new ServiceRpcHandler());

    String extensionsEnabledString = context.getInitParameter("xmlrpc.enabledForExtensions");
    if (UtilValidate.isNotEmpty(extensionsEnabledString)) {
      enabledForExtensions = Boolean.valueOf(extensionsEnabledString);
    }
    String exceptionsEnabledString = context.getInitParameter("xmlrpc.enabledForExceptions");
    if (UtilValidate.isNotEmpty(exceptionsEnabledString)) {
      enabledForExceptions = Boolean.valueOf(exceptionsEnabledString);
    }
  }
Beispiel #27
0
  private Map<String, Object> serviceInvoker(
      String localName, ModelService modelService, Map<String, Object> context)
      throws GenericServiceException {
    if (UtilValidate.isEmpty(modelService.location)) {
      throw new GenericServiceException("Cannot run Groovy service with empty location");
    }
    Map<String, Object> params = FastMap.newInstance();
    params.putAll(context);
    context.put(ScriptUtil.PARAMETERS_KEY, params);

    DispatchContext dctx = dispatcher.getLocalContext(localName);
    context.put("dctx", dctx);
    context.put("dispatcher", dctx.getDispatcher());
    context.put("delegator", dispatcher.getDelegator());
    try {
      ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys);
      ScriptHelper scriptHelper =
          (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY);
      if (scriptHelper != null) {
        context.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper);
      }
      Script script =
          InvokerHelper.createScript(
              GroovyUtil.getScriptClassFromLocation(
                  this.getLocation(modelService), groovyClassLoader),
              GroovyUtil.getBinding(context));
      Object resultObj = null;
      if (UtilValidate.isEmpty(modelService.invoke)) {
        resultObj = script.run();
      } else {
        resultObj = script.invokeMethod(modelService.invoke, EMPTY_ARGS);
      }
      if (resultObj == null) {
        resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY);
      }
      if (resultObj != null && resultObj instanceof Map<?, ?>) {
        return cast(resultObj);
      }
      Map<String, Object> result = ServiceUtil.returnSuccess();
      result.putAll(
          modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), "OUT"));
      return result;
    } catch (GeneralException ge) {
      throw new GenericServiceException(ge);
    } catch (Exception e) {
      return ServiceUtil.returnError(e.getMessage());
    }
  }
Beispiel #28
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;
  }
  public static boolean isBinComplete(Delegator delegator, String picklistBinId)
      throws GeneralException {
    // lookup the items in the bin
    List<GenericValue> items;
    try {
      items = delegator.findByAnd("PicklistItem", UtilMisc.toMap("picklistBinId", picklistBinId));
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      throw e;
    }

    if (!UtilValidate.isEmpty(items)) {
      for (GenericValue v : items) {
        String itemStatus = v.getString("itemStatusId");
        if (itemStatus != null) {
          if (!"PICKITEM_COMPLETED".equals(itemStatus)) {
            return false;
          }
        }
      }
      return true;
    }

    return false;
  }
  public static String addListToCart(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);

    String shoppingListId = request.getParameter("shoppingListId");
    String includeChild = request.getParameter("includeChild");
    String prodCatalogId = CatalogWorker.getCurrentCatalogId(request);

    String eventMessage = null;
    try {
      addListToCart(
          delegator,
          dispatcher,
          cart,
          prodCatalogId,
          shoppingListId,
          (includeChild != null),
          true,
          true);
    } catch (IllegalArgumentException e) {
      request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
      return "error";
    }

    if (UtilValidate.isNotEmpty(eventMessage)) {
      request.setAttribute("_EVENT_MESSAGE_", eventMessage);
    }

    return "success";
  }