Example #1
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();
  }
  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;
    }
  }
Example #3
0
  public static GenericValue getPaymentAddress(Delegator delegator, String partyId) {
    List<GenericValue> paymentAddresses = null;
    try {
      paymentAddresses =
          delegator.findByAnd(
              "PartyContactMechPurpose",
              UtilMisc.toMap("partyId", partyId, "contactMechPurposeTypeId", "PAYMENT_LOCATION"),
              UtilMisc.toList("-fromDate"));
      paymentAddresses = EntityUtil.filterByDate(paymentAddresses);
    } catch (GenericEntityException e) {
      Debug.logError(e, "Trouble getting PartyContactMechPurpose entity list", module);
    }

    // get the address for the primary contact mech
    GenericValue purpose = EntityUtil.getFirst(paymentAddresses);
    GenericValue postalAddress = null;
    if (purpose != null) {
      try {
        postalAddress =
            delegator.findByPrimaryKey(
                "PostalAddress",
                UtilMisc.toMap("contactMechId", purpose.getString("contactMechId")));
      } catch (GenericEntityException e) {
        Debug.logError(
            e,
            "Trouble getting PostalAddress record for contactMechId: "
                + purpose.getString("contactMechId"),
            module);
      }
    }

    return postalAddress;
  }
Example #4
0
  public static Map<String, Object> makeALotOfVisits(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    int count = ((Integer) context.get("count")).intValue();

    for (int i = 0; i < count; i++) {
      GenericValue v = delegator.makeValue("Visit");
      String seqId = delegator.getNextSeqId("Visit");

      v.set("visitId", seqId);
      v.set("userCreated", "N");
      v.set("sessionId", "NA-" + seqId);
      v.set("serverIpAddress", "127.0.0.1");
      v.set("serverHostName", "localhost");
      v.set("webappName", "webtools");
      v.set("initialLocale", "en_US");
      v.set("initialRequest", "http://localhost:8080/webtools/control/main");
      v.set("initialReferrer", "http://localhost:8080/webtools/control/main");
      v.set(
          "initialUserAgent",
          "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1");
      v.set("clientIpAddress", "127.0.0.1");
      v.set("clientHostName", "localhost");
      v.set("fromDate", UtilDateTime.nowTimestamp());

      try {
        delegator.create(v);
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }

    return ServiceUtil.returnSuccess();
  }
Example #5
0
  /** Cause a Referential Integrity Error */
  public static Map<String, Object> entityFailTest(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

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

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

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

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

    if (count > 0) {
      Map<String, Object> result = ServiceUtil.returnSuccess();
      result.put("message", message);
      return result;
    } else {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonPingDatasourceInvalidCount", locale));
    }
  }
Example #7
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;
 }
Example #8
0
  /**
   * Performs a cascade delete on a party.
   *
   * <p>One reason this method can fail is that there were relationships with entities that are not
   * being deleted. If a party is not being deleted like it should, the developer should take a look
   * at the exception thrown by this method to see if any relations were violated. If there were
   * violations, consider adding the entities to the CASCADE array above.
   *
   * <p>XXX Warning, this method is very brittle. It is essentially emulating the ON DELETE CASCADE
   * functionality of well featured databases, but very poorly. As the datamodel evolves, this
   * method would have to be updated.
   */
  public static void deleteCrmParty(String partyId, Delegator delegator)
      throws GenericEntityException {
    // remove related entities from constant list
    for (int i = 0; i < CRM_PARTY_DELETE_CASCADE.length; i++) {
      String entityName = CRM_PARTY_DELETE_CASCADE[i][0];
      String fieldName = CRM_PARTY_DELETE_CASCADE[i][1];

      Map<String, Object> input = UtilMisc.<String, Object>toMap(fieldName, partyId);
      delegator.removeByAnd(entityName, input);
    }

    // remove communication events
    GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));
    List<GenericValue> commEvnts = FastList.<GenericValue>newInstance();
    commEvnts.addAll(party.getRelated("ToCommunicationEvent"));
    commEvnts.addAll(party.getRelated("FromCommunicationEvent"));
    for (GenericValue commEvnt : commEvnts) {
      commEvnt.removeRelated("CommunicationEventRole");
      commEvnt.removeRelated("CommunicationEventWorkEff");
      commEvnt.removeRelated("CommEventContentAssoc");
      delegator.removeValue(commEvnt);
    }

    // finally remove party
    delegator.removeValue(party);
  }
Example #9
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;
  }
Example #10
0
 /** Checks if the given party with role is assigned to the user login. */
 public static boolean isAssignedToUserLogin(
     String partyId, String roleTypeId, GenericValue userLogin) throws GenericEntityException {
   Delegator delegator = userLogin.getDelegator();
   String roleTypeIdTo =
       getFirstValidTeamMemberRoleTypeId(userLogin.getString("partyId"), delegator);
   if (roleTypeIdTo == null) {
     return false;
   }
   List<GenericValue> activeRelationships =
       EntityUtil.filterByDate(
           delegator.findByAnd(
               "PartyRelationship",
               UtilMisc.toMap(
                   "partyIdFrom",
                   partyId,
                   "roleTypeIdFrom",
                   roleTypeId,
                   "partyIdTo",
                   userLogin.get("partyId"),
                   "roleTypeIdTo",
                   roleTypeIdTo,
                   "partyRelationshipTypeId",
                   "ASSIGNED_TO")));
   return activeRelationships.size() > 0;
 }
  public static RecurrenceRule makeRule(
      Delegator delegator, int frequency, int interval, int count, long endTime)
      throws RecurrenceRuleException {
    String freq[] = {"", "SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};

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

    String freqStr = freq[frequency];

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

      value.set("frequency", freqStr);
      value.set("intervalNumber", Long.valueOf(interval));
      value.set("countNumber", Long.valueOf(count));
      if (endTime > 0) {
        value.set("untilDateTime", new java.sql.Timestamp(endTime));
      }
      delegator.createSetNextSeqId(value);
      RecurrenceRule newRule = new RecurrenceRule(value);
      return newRule;
    } catch (GenericEntityException ee) {
      throw new RecurrenceRuleException(ee.getMessage(), ee);
    } catch (RecurrenceRuleException re) {
      throw re;
    }
  }
Example #12
0
  public static Map<String, Object> updateContact(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

    String contactPartyId = (String) context.get("partyId");

    // make sure userLogin has CRMSFA_CONTACT_UPDATE permission for this contact
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_CONTACT", "_UPDATE", userLogin, contactPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }
    try {
      // update the Party and Person
      Map<String, Object> input =
          UtilMisc.<String, Object>toMap(
              "partyId",
              contactPartyId,
              "firstName",
              context.get("firstName"),
              "lastName",
              context.get("lastName"));
      input.put("firstNameLocal", context.get("firstNameLocal"));
      input.put("lastNameLocal", context.get("lastNameLocal"));
      input.put("personalTitle", context.get("personalTitle"));
      input.put("preferredCurrencyUomId", context.get("preferredCurrencyUomId"));
      input.put("description", context.get("description"));
      input.put("birthDate", context.get("birthDate"));
      input.put("userLogin", userLogin);
      Map<String, Object> serviceResults = dispatcher.runSync("updatePerson", input);
      if (ServiceUtil.isError(serviceResults)) {
        return UtilMessage.createAndLogServiceError(
            serviceResults, "CrmErrorUpdateContactFail", locale, MODULE);
      }

      // update PartySupplementalData
      GenericValue partyData =
          delegator.findByPrimaryKey(
              "PartySupplementalData", UtilMisc.toMap("partyId", contactPartyId));
      if (partyData == null) {
        // create a new one
        partyData =
            delegator.makeValue("PartySupplementalData", UtilMisc.toMap("partyId", contactPartyId));
        partyData.create();
      }
      partyData.setNonPKFields(context);
      partyData.store();

    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorUpdateContactFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorUpdateContactFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Example #13
0
  public static Map<String, Object> assignContactToAccount(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

    String contactPartyId = (String) context.get("contactPartyId");
    String accountPartyId = (String) context.get("accountPartyId");

    try {
      // check if this contact is already a contact of this account
      EntityCondition searchConditions =
          EntityCondition.makeCondition(
              EntityOperator.AND,
              EntityCondition.makeCondition("partyIdFrom", EntityOperator.EQUALS, contactPartyId),
              EntityCondition.makeCondition("partyIdTo", EntityOperator.EQUALS, accountPartyId),
              EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.EQUALS, "CONTACT"),
              EntityCondition.makeCondition("roleTypeIdTo", EntityOperator.EQUALS, "ACCOUNT"),
              EntityCondition.makeCondition(
                  "partyRelationshipTypeId", EntityOperator.EQUALS, "CONTACT_REL_INV"),
              EntityUtil.getFilterByDateExpr());
      List<GenericValue> existingRelationships =
          delegator.findByCondition("PartyRelationship", searchConditions, null, null);
      if (existingRelationships.size() > 0) {
        return UtilMessage.createAndLogServiceError(
            "CrmErrorContactAlreadyAssociatedToAccount", locale, MODULE);
      }

      // check if userLogin has CRMSFA_ACCOUNT_UPDATE permission for this account
      if (!CrmsfaSecurity.hasPartyRelationSecurity(
          security, "CRMSFA_ACCOUNT", "_UPDATE", userLogin, accountPartyId)) {
        return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
      }
      // create the party relationship between the Contact and the Account
      PartyHelper.createNewPartyToRelationship(
          accountPartyId,
          contactPartyId,
          "CONTACT",
          "CONTACT_REL_INV",
          null,
          UtilMisc.toList("ACCOUNT"),
          false,
          userLogin,
          delegator,
          dispatcher);

    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorAssignContactToAccountFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorAssignContactToAccountFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Example #14
0
  /** Remove all items from the given list. */
  public static int clearListInfo(Delegator delegator, String shoppingListId)
      throws GenericEntityException {
    // remove the survey responses first
    delegator.removeByAnd(
        "ShoppingListItemSurvey", UtilMisc.toMap("shoppingListId", shoppingListId));

    // next remove the items
    return delegator.removeByAnd(
        "ShoppingListItem", UtilMisc.toMap("shoppingListId", shoppingListId));
  }
 public static Map<String, Object> deleteCmsCatalog(
     DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
   Delegator delegator = dctx.getDelegator();
   String catalogId = (String) context.get("catalogId");
   GenericValue gv =
       delegator.findByPrimaryKey("CmsCatalog", UtilMisc.toMap("catalogId", catalogId));
   if (UtilValidate.isNotEmpty(gv)) {
     gv.remove();
   }
   return ServiceUtil.returnSuccess();
 }
 public static Map<String, Object> createCmsCatalog(
     DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
   Map result = ServiceUtil.returnSuccess();
   Delegator delegator = dctx.getDelegator();
   String catalogId = delegator.getNextSeqId("CmsCatalog");
   GenericValue gv = delegator.makeValue("CmsCatalog", UtilMisc.toMap("catalogId", catalogId));
   gv.setNonPKFields(context);
   gv.create();
   result.put("catalogId", catalogId);
   return result;
 }
Example #17
0
  public static Map<String, Object> deactivateContact(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

    // what contact we're expiring
    String contactPartyId = (String) context.get("partyId");

    // check that userLogin has CRMSFA_CONTACT_DEACTIVATE permission for this contact
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_CONTACT", "_DEACTIVATE", userLogin, contactPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }

    // when to expire the contact
    Timestamp expireDate = (Timestamp) context.get("expireDate");
    if (expireDate == null) {
      expireDate = UtilDateTime.nowTimestamp();
    }

    // in order to deactivate a contact, we expire all party relationships on the expire date
    try {
      List<GenericValue> partyRelationships =
          delegator.findByAnd(
              "PartyRelationship",
              UtilMisc.toMap("partyIdFrom", contactPartyId, "roleTypeIdFrom", "CONTACT"));
      PartyHelper.expirePartyRelationships(partyRelationships, expireDate, dispatcher, userLogin);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateContactFail", locale, MODULE);
    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateContactFail", locale, MODULE);
    }

    // set the party statusId to PARTY_DISABLED and register the PartyDeactivation
    try {
      GenericValue contactParty =
          delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", contactPartyId));
      contactParty.put("statusId", "PARTY_DISABLED");
      contactParty.store();

      delegator.create(
          "PartyDeactivation",
          UtilMisc.toMap("partyId", contactPartyId, "deactivationTimestamp", expireDate));
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateAccountFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Example #18
0
  /**
   * Retrieves a group of user preferences from persistent storage. Call with userPrefGroupTypeId
   * and optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in
   * user's userLoginId will be used. The retrieved preferences group is contained in the
   * <b>userPrefMap</b> element.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> getUserPreferenceGroup(
      DispatchContext ctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    if (!PreferenceWorker.isValidGetId(ctx, context)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
    }
    Delegator delegator = ctx.getDelegator();

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

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

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("userPrefMap", userPrefMap);
    return result;
  }
Example #19
0
 /**
  * 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 dctx The DispatchContext that this service is operating in
  * @param context Map containing the input parameters
  * @return Map 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();
   Delegator delegator = dctx.getDelegator();
   List<String> trailElements = FastList.newInstance();
   trailElements.add(productCategoryId);
   String parentProductCategoryId = productCategoryId;
   while (UtilValidate.isNotEmpty(parentProductCategoryId)) {
     // find product category rollup
     try {
       List<EntityCondition> rolllupConds = FastList.newInstance();
       rolllupConds.add(
           EntityCondition.makeCondition("productCategoryId", parentProductCategoryId));
       rolllupConds.add(EntityUtil.getFilterByDateExpr());
       List<GenericValue> productCategoryRollups =
           delegator.findList(
               "ProductCategoryRollup",
               EntityCondition.makeCondition(rolllupConds),
               null,
               UtilMisc.toList("sequenceNum"),
               null,
               true);
       if (UtilValidate.isNotEmpty(productCategoryRollups)) {
         // add only categories that belong to the top category to trail
         for (GenericValue productCategoryRollup : productCategoryRollups) {
           String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId");
           parentProductCategoryId = trailCategoryId;
           if (trailElements.contains(trailCategoryId)) {
             break;
           } else {
             trailElements.add(trailCategoryId);
           }
         }
       } else {
         parentProductCategoryId = null;
       }
     } catch (GenericEntityException e) {
       Map<String, String> messageMap =
           UtilMisc.toMap("errMessage", ". Cannot generate trail from product category. ");
       String errMsg =
           UtilProperties.getMessage(
               "CommonUiLabels",
               "CommonDatabaseProblem",
               messageMap,
               (Locale) context.get("locale"));
       Debug.logError(e, errMsg, module);
       return ServiceUtil.returnError(errMsg);
     }
   }
   Collections.reverse(trailElements);
   results.put("trail", trailElements);
   return results;
 }
Example #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;
  }
 public static Map<String, Object> deleteEPaketConfig(
     DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
   Delegator delegator = dctx.getDelegator();
   String epaketConfigId = (String) context.get("epaketConfigId");
   GenericValue gv =
       delegator.findByPrimaryKey(
           "EPaketConfig", UtilMisc.toMap("epaketConfigId", epaketConfigId));
   if (UtilValidate.isNotEmpty(gv)) {
     gv.remove();
     createEPaketConfigStatus(delegator, gv, "deleteEPaketConfig");
   }
   return ServiceUtil.returnSuccess();
 }
Example #22
0
  /**
   * Retrieves a single user preference from persistent storage. Call with userPrefTypeId and
   * optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in
   * user's userLoginId will be used. The retrieved preference is contained in the
   * <b>userPrefMap</b> element.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> getUserPreference(DispatchContext ctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    if (!PreferenceWorker.isValidGetId(ctx, context)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "getPreference.permissionError", locale));
    }
    Delegator delegator = ctx.getDelegator();

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

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

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("userPrefMap", userPrefMap);
    if (userPrefMap != null) {
      // Put the value in the result Map too, makes access easier for calling methods.
      Object userPrefValue = userPrefMap.get(userPrefTypeId);
      if (userPrefValue != null) {
        result.put("userPrefValue", userPrefValue);
      }
    }
    return result;
  }
Example #23
0
  /**
   * Create Note Record
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp noteDate = (Timestamp) context.get("noteDate");
    String partyId = (String) context.get("partyId");
    String noteName = (String) context.get("noteName");
    String note = (String) context.get("note");
    String noteId = delegator.getNextSeqId("NoteData");
    Locale locale = (Locale) context.get("locale");
    if (noteDate == null) {
      noteDate = UtilDateTime.nowTimestamp();
    }

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

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

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

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

    result.put("noteId", noteId);
    result.put("partyId", partyId);
    return result;
  }
  public static Map<String, Object> createEPaketConfigStatus(
      Delegator delegator, Map<String, ? extends Object> context, String Action)
      throws GenericEntityException {

    String epaketConfigStatusId = delegator.getNextSeqId("EPaketConfigStatus");
    GenericValue ePaketConfigStatus =
        delegator.makeValue(
            "EPaketConfigStatus", UtilMisc.toMap("epaketConfigStatusId", epaketConfigStatusId));

    ePaketConfigStatus.setNonPKFields(context);
    ePaketConfigStatus.set("action", Action);
    ePaketConfigStatus.create();
    return ServiceUtil.returnSuccess();
  }
Example #25
0
  public static Map<String, Object> convertOrderIdListToHeaders(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();

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

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

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

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

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

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

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

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("orderHeaderList", orderHeaderList);
    return result;
  }
Example #26
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"));
    }
  }
Example #27
0
  public static Map<String, Object> reassignContactResponsibleParty(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

    String contactPartyId = (String) context.get("contactPartyId");
    String newPartyId = (String) context.get("newPartyId");

    // ensure reassign permission on this contact
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_CONTACT", "_REASSIGN", userLogin, contactPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }
    try {
      // we need to expire all the active ASSIGNED_TO relationships from the contact party to the
      // new owner party
      List<GenericValue> activeAssignedToRelationships =
          EntityUtil.filterByDate(
              delegator.findByAnd(
                  "PartyRelationship",
                  UtilMisc.toMap(
                      "partyIdFrom",
                      contactPartyId,
                      "roleTypeIdFrom",
                      "CONTACT",
                      "partyIdTo",
                      newPartyId,
                      "partyRelationshipTypeId",
                      "ASSIGNED_TO")));
      PartyHelper.expirePartyRelationships(
          activeAssignedToRelationships, UtilDateTime.nowTimestamp(), dispatcher, userLogin);

      // reassign relationship using a helper method
      boolean result =
          createResponsibleContactRelationshipForParty(
              newPartyId, contactPartyId, userLogin, delegator, dispatcher);
      if (!result) {
        return UtilMessage.createAndLogServiceError("CrmErrorReassignFail", locale, MODULE);
      }
    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorReassignFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorReassignFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Example #28
0
  /**
   * Generic Test SOAP Service
   *
   * @param dctx 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> testSOAPService(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> response = ServiceUtil.returnSuccess();

    List<GenericValue> testingNodes = FastList.newInstance();
    for (int i = 0; i < 3; i++) {
      GenericValue testingNode = delegator.makeValue("TestingNode");
      testingNode.put("testingNodeId", "TESTING_NODE" + i);
      testingNode.put("description", "Testing Node " + i);
      testingNode.put("createdStamp", UtilDateTime.nowTimestamp());
      testingNodes.add(testingNode);
    }
    response.put("testingNodes", testingNodes);
    return response;
  }
 public static long categoryMemberCount(GenericValue category) {
   if (category == null) return 0;
   Delegator delegator = category.getDelegator();
   long count = 0;
   try {
     count =
         delegator.findCountByCondition(
             "ProductCategoryMember",
             buildCountCondition("productCategoryId", category.getString("productCategoryId")),
             null,
             null);
   } catch (GenericEntityException e) {
     Debug.logError(e, module);
   }
   return count;
 }
Example #30
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;
  }