コード例 #1
0
ファイル: CommonServices.java プロジェクト: zzj1213/BIGITWEB
  public static Map<String, Object> uploadTest(DispatchContext dctx, Map<String, ?> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    byte[] array = (byte[]) context.get("uploadFile");
    String fileName = (String) context.get("_uploadFile_fileName");
    String contentType = (String) context.get("_uploadFile_contentType");

    Map<String, Object> createCtx = FastMap.newInstance();
    createCtx.put("binData", array);
    createCtx.put("dataResourceTypeId", "OFBIZ_FILE");
    createCtx.put("dataResourceName", fileName);
    createCtx.put("dataCategoryId", "PERSONAL");
    createCtx.put("statusId", "CTNT_PUBLISHED");
    createCtx.put("mimeTypeId", contentType);
    createCtx.put("userLogin", userLogin);

    Map<String, Object> createResp = null;
    try {
      createResp = dispatcher.runSync("createFile", createCtx);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(createResp)) {
      return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResp));
    }

    GenericValue dataResource = (GenericValue) createResp.get("dataResource");
    if (dataResource != null) {
      Map<String, Object> contentCtx = FastMap.newInstance();
      contentCtx.put("dataResourceId", dataResource.getString("dataResourceId"));
      contentCtx.put("localeString", ((Locale) context.get("locale")).toString());
      contentCtx.put("contentTypeId", "DOCUMENT");
      contentCtx.put("mimeTypeId", contentType);
      contentCtx.put("contentName", fileName);
      contentCtx.put("statusId", "CTNT_PUBLISHED");
      contentCtx.put("userLogin", userLogin);

      Map<String, Object> contentResp = null;
      try {
        contentResp = dispatcher.runSync("createContent", contentCtx);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
      if (ServiceUtil.isError(contentResp)) {
        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(contentResp));
      }
    }

    return ServiceUtil.returnSuccess();
  }
コード例 #2
0
ファイル: PartyHelper.java プロジェクト: yuri0x7c1/opentaps-1
  private static EntityCondition getActiveClientPartiesCondition(
      LocalDispatcher dispatcher, Map<String, ?> parameters, List<String> roles, EntityCondition ec)
      throws GeneralException {
    Map<String, Object> results =
        dispatcher.runSync(
            "prepareFind",
            UtilMisc.toMap(
                "entityName",
                "PartyFromSummaryByRelationship",
                "inputFields",
                parameters,
                "filterByDate",
                "Y",
                "noConditionFind",
                "N"));
    if (ServiceUtil.isError(results)) {
      throw new GenericServiceException(ServiceUtil.getErrorMessage(results));
    }
    EntityCondition findConditions = (EntityCondition) results.get("entityConditionList");
    if (findConditions == null) {
      return null;
    }

    List<String> conditionRoles = (roles == null || roles.size() == 0 ? CLIENT_PARTY_ROLES : roles);
    List<EntityCondition> combinedConditions =
        UtilMisc.<EntityCondition>toList(
            findConditions,
            EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.IN, conditionRoles));
    if (ec != null) {
      combinedConditions.add(ec);
    }

    return EntityCondition.makeCondition(combinedConditions, EntityOperator.AND);
  }
コード例 #3
0
    public Object execute(XmlRpcRequest xmlRpcReq) throws XmlRpcException {
      DispatchContext dctx = dispatcher.getDispatchContext();
      String serviceName = xmlRpcReq.getMethodName();
      ModelService model = null;
      try {
        model = dctx.getModelService(serviceName);
      } catch (GenericServiceException e) {
        throw new XmlRpcException(e.getMessage(), e);
      }

      // check remote invocation security
      if (model == null || !model.export) {
        throw new XmlRpcException("Unknown method");
      }

      // prepare the context -- single parameter type struct (map)
      Map<String, Object> context = this.getContext(xmlRpcReq, serviceName);

      // add in auth parameters
      XmlRpcHttpRequestConfig config = (XmlRpcHttpRequestConfig) xmlRpcReq.getConfig();
      String username = config.getBasicUserName();
      String password = config.getBasicPassword();
      if (UtilValidate.isNotEmpty(username)) {
        context.put("login.username", username);
        context.put("login.password", password);
      }

      // add the locale to the context
      context.put("locale", Locale.getDefault());

      // invoke the service
      Map<String, Object> resp;
      try {
        resp = dispatcher.runSync(serviceName, context);
      } catch (GenericServiceException e) {
        throw new XmlRpcException(e.getMessage(), e);
      }
      if (ServiceUtil.isError(resp)) {
        Debug.logError(ServiceUtil.getErrorMessage(resp), module);
        throw new XmlRpcException(ServiceUtil.getErrorMessage(resp));
      }

      // return only definied parameters
      return model.makeValid(resp, ModelService.OUT_PARAM, false, null);
    }
コード例 #4
0
  protected void applyLineToPackage(
      String shipmentId, GenericValue userLogin, LocalDispatcher dispatcher, int shipPackSeqId)
      throws GeneralException {
    String shipmentPackageSeqId = UtilFormatOut.formatPaddedNumber(shipPackSeqId, 5);

    Map<String, Object> packageMap = new HashMap<String, Object>();
    packageMap.put("shipmentId", shipmentId);
    packageMap.put("shipmentItemSeqId", this.getShipmentItemSeqId());
    // quanity given, by defult one because it is a required field
    packageMap.put("quantity", BigDecimal.ONE);
    packageMap.put("shipmentPackageSeqId", shipmentPackageSeqId);
    packageMap.put("userLogin", userLogin);
    Map<String, Object> packageResp = dispatcher.runSync("addShipmentContentToPackage", packageMap);

    if (ServiceUtil.isError(packageResp)) {
      throw new GeneralException(ServiceUtil.getErrorMessage(packageResp));
    }
  }
コード例 #5
0
  public static Map<String, Object> finAccountReleaseAuth(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    Locale locale = (Locale) context.get("locale");

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

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

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

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

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

      return result;
    } catch (GenericServiceException e) {
      Debug.logError(e, e.getMessage(), module);
      return ServiceUtil.returnError(err + e.getMessage());
    }
  }
コード例 #6
0
ファイル: EmailServices.java プロジェクト: rbingfeng/GreenTea
  /**
   * JavaMail Service that gets body content from a Screen Widget defined in the product store
   * record and if available as attachment also.
   *
   * @param dctx The DispatchContext that this service is operating in
   * @param rServiceContext Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMailFromScreen(
      DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
    Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String webSiteId = (String) serviceContext.remove("webSiteId");
    String bodyText = (String) serviceContext.remove("bodyText");
    String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
    String xslfoAttachScreenLocationParam =
        (String) serviceContext.remove("xslfoAttachScreenLocation");
    String attachmentNameParam = (String) serviceContext.remove("attachmentName");
    List<String> xslfoAttachScreenLocationListParam =
        UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList"));
    List<String> attachmentNameListParam =
        UtilGenerics.checkList(serviceContext.remove("attachmentNameList"));

    List<String> xslfoAttachScreenLocationList = FastList.newInstance();
    List<String> attachmentNameList = FastList.newInstance();
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam))
      xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam);
    if (UtilValidate.isNotEmpty(attachmentNameParam)) attachmentNameList.add(attachmentNameParam);
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam))
      xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam);
    if (UtilValidate.isNotEmpty(attachmentNameListParam))
      attachmentNameList.addAll(attachmentNameListParam);

    Locale locale = (Locale) serviceContext.get("locale");
    Map<String, Object> bodyParameters =
        UtilGenerics.checkMap(serviceContext.remove("bodyParameters"));
    if (bodyParameters == null) {
      bodyParameters = MapStack.create();
    }
    if (!bodyParameters.containsKey("locale")) {
      bodyParameters.put("locale", locale);
    } else {
      locale = (Locale) bodyParameters.get("locale");
    }
    String partyId = (String) serviceContext.get("partyId");
    if (partyId == null) {
      partyId = (String) bodyParameters.get("partyId");
    }
    String orderId = (String) bodyParameters.get("orderId");
    String custRequestId = (String) bodyParameters.get("custRequestId");

    bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId"));
    NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters);
    String contentType = (String) serviceContext.remove("contentType");

    StringWriter bodyWriter = new StringWriter();

    MapStack<String> screenContext = MapStack.create();
    screenContext.put("locale", locale);
    ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer);
    screens.populateContextForService(dctx, bodyParameters);
    screenContext.putAll(bodyParameters);

    if (bodyScreenUri != null) {
      try {
        screens.render(bodyScreenUri);
      } catch (GeneralException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (IOException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (SAXException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (ParserConfigurationException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      }
    }

    boolean isMultiPart = false;

    // check if attachment screen location passed in
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) {
      List<Map<String, ? extends Object>> bodyParts = FastList.newInstance();
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html"));
      } else {
        bodyParts.add(
            UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "text/html"));
      }

      for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) {
        String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i);
        String attachmentName = "Details.pdf";
        if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) {
          attachmentName = attachmentNameList.get(i);
        }
        isMultiPart = true;
        // start processing fo pdf attachment
        try {
          Writer writer = new StringWriter();
          MapStack<String> screenContextAtt = MapStack.create();
          // substitute the freemarker variables...
          ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenRenderer);
          screensAtt.populateContextForService(dctx, bodyParameters);
          screenContextAtt.putAll(bodyParameters);
          screensAtt.render(xslfoAttachScreenLocation);

          /*
          try { // save generated fo file for debugging
              String buf = writer.toString();
              java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml"));
              fw.write(buf.toString());
              fw.close();
          } catch (IOException e) {
              Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module);
          }
          */

          // create the input stream for the generation
          StreamSource src = new StreamSource(new StringReader(writer.toString()));

          // create the output stream for the generation
          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
          ApacheFopWorker.transform(src, null, fop);

          // and generate the PDF
          baos.flush();
          baos.close();

          // store in the list of maps for sendmail....
          bodyParts.add(
              UtilMisc.<String, Object>toMap(
                  "content",
                  baos.toByteArray(),
                  "type",
                  "application/pdf",
                  "filename",
                  attachmentName));
        } catch (GeneralException ge) {
          Debug.logError(ge, "Error rendering PDF attachment for email: " + ge.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ge.toString()),
                  locale));
        } catch (IOException ie) {
          Debug.logError(ie, "Error rendering PDF attachment for email: " + ie.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ie.toString()),
                  locale));
        } catch (FOPException fe) {
          Debug.logError(fe, "Error rendering PDF attachment for email: " + fe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", fe.toString()),
                  locale));
        } catch (SAXException se) {
          Debug.logError(se, "Error rendering PDF attachment for email: " + se.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", se.toString()),
                  locale));
        } catch (ParserConfigurationException pe) {
          Debug.logError(pe, "Error rendering PDF attachment for email: " + pe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", pe.toString()),
                  locale));
        }

        serviceContext.put("bodyParts", bodyParts);
      }
    } else {
      isMultiPart = false;
      // store body and type for single part message in the context.
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        serviceContext.put("body", bodyText);
      } else {
        serviceContext.put("body", bodyWriter.toString());
      }

      // Only override the default contentType in case of plaintext, since other contentTypes may be
      // multipart
      //    and would require specific handling.
      if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
        serviceContext.put("contentType", "text/plain");
      } else {
        serviceContext.put("contentType", "text/html");
      }
    }

    // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax
    // in it...
    String subject = (String) serviceContext.remove("subject");
    subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
    Debug.logInfo("Expanded email subject to: " + subject, module);
    serviceContext.put("subject", subject);
    serviceContext.put("partyId", partyId);
    if (UtilValidate.isNotEmpty(orderId)) {
      serviceContext.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
      serviceContext.put("custRequestId", custRequestId);
    }

    if (Debug.verboseOn())
      Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, Object> sendMailResult;
    try {
      if (isMultiPart) {
        sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
      } else {
        sendMailResult = dispatcher.runSync("sendMail", serviceContext);
      }
    } catch (Exception e) {
      Debug.logError(e, "Error send email:" + e.toString(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }
    if (ServiceUtil.isError(sendMailResult)) {
      return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult));
    }

    result.put("messageWrapper", sendMailResult.get("messageWrapper"));
    result.put("body", bodyWriter.toString());
    result.put("subject", subject);
    result.put("communicationEventId", sendMailResult.get("communicationEventId"));
    if (UtilValidate.isNotEmpty(orderId)) {
      result.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
      result.put("custRequestId", custRequestId);
    }
    return result;
  }
コード例 #7
0
  public static String addBulkFromCart(
      Delegator delegator,
      LocalDispatcher dispatcher,
      ShoppingCart cart,
      GenericValue userLogin,
      String shoppingListId,
      String shoppingListTypeId,
      String[] items,
      boolean allowPromo,
      boolean append)
      throws IllegalArgumentException {
    String errMsg = null;

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

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

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

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

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

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

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

    // return the shoppinglist id
    return shoppingListId;
  }
コード例 #8
0
    @Override
    public boolean eval(Map<String, Object> context) {
      // if no user is logged in, treat as if the user does not have permission
      GenericValue userLogin = (GenericValue) context.get("userLogin");
      if (userLogin != null) {
        String serviceName = serviceExdr.expandString(context);
        String mainAction = actionExdr.expandString(context);
        String contextMap = ctxMapExdr.expandString(context);
        String resource = resExdr.expandString(context);
        if (UtilValidate.isEmpty(resource)) {
          resource = serviceName;
        }

        if (UtilValidate.isEmpty(serviceName)) {
          Debug.logWarning("No permission service-name specified!", module);
          return false;
        }

        Map<String, Object> serviceContext = UtilGenerics.toMap(context.get(contextMap));
        if (serviceContext != null) {
          // copy the required internal fields
          serviceContext.put("userLogin", context.get("userLogin"));
          serviceContext.put("locale", context.get("locale"));
        } else {
          serviceContext = context;
        }

        // get the service objects
        LocalDispatcher dispatcher = this.modelScreen.getDispatcher(context);
        DispatchContext dctx = dispatcher.getDispatchContext();

        // get the service
        ModelService permService;
        try {
          permService = dctx.getModelService(serviceName);
        } catch (GenericServiceException e) {
          Debug.logError(e, module);
          return false;
        }

        if (permService != null) {
          // build the context
          Map<String, Object> svcCtx = permService.makeValid(serviceContext, ModelService.IN_PARAM);
          svcCtx.put("resourceDescription", resource);
          if (UtilValidate.isNotEmpty(mainAction)) {
            svcCtx.put("mainAction", mainAction);
          }

          // invoke the service
          Map<String, Object> resp;
          try {
            resp = dispatcher.runSync(permService.name, svcCtx, 300, true);
          } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return false;
          }
          if (ServiceUtil.isError(resp) || ServiceUtil.isFailure(resp)) {
            Debug.logError(ServiceUtil.getErrorMessage(resp), module);
            return false;
          }
          Boolean hasPermission = (Boolean) resp.get("hasPermission");
          if (hasPermission != null) {
            return hasPermission.booleanValue();
          }
        }
      }
      return false;
    }
コード例 #9
0
ファイル: PayPalServices.java プロジェクト: yan96in/GreenTea
  // Note we're not doing a lot of error checking here as this method is really only used
  // to confirm the order with PayPal, the subsequent authorizations will handle any errors
  // that may occur.
  public static Map<String, Object> doExpressCheckout(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");

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

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

    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

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

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

    Map<String, Object> outMap = null;
    try {
      outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
      Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
      return outMap;
    }
    return ServiceUtil.returnSuccess();
  }
コード例 #10
0
  private static String createFinAcctPaymentTransaction(
      Delegator delegator,
      LocalDispatcher dispatcher,
      GenericValue userLogin,
      BigDecimal amount,
      String productStoreId,
      String partyId,
      String orderId,
      String orderItemSeqId,
      String currencyUom,
      String txType,
      String finAccountId,
      String reasonEnumId)
      throws GeneralException {

    final String coParty =
        ProductStoreWorker.getProductStorePayToPartyId(productStoreId, delegator);
    final String paymentMethodType = "FIN_ACCOUNT";

    if (UtilValidate.isEmpty(partyId)) {
      partyId = "_NA_";
    }

    String paymentType;
    String partyIdFrom;
    String partyIdTo;
    BigDecimal paymentAmount;

    // determine the payment type and which direction the parties should go
    if ("DEPOSIT".equals(txType)) {
      paymentType = "RECEIPT";
      partyIdFrom = partyId;
      partyIdTo = coParty;
      paymentAmount = amount;
    } else if ("WITHDRAWAL".equals(txType)) {
      paymentType = "DISBURSEMENT";
      partyIdFrom = coParty;
      partyIdTo = partyId;
      paymentAmount = amount;
    } else if ("ADJUSTMENT".equals(txType)) {
      if (amount.compareTo(BigDecimal.ZERO) < 0) {
        paymentType = "DISBURSEMENT";
        partyIdFrom = coParty;
        partyIdTo = partyId;
        paymentAmount = amount.negate(); // must be positive
      } else {
        paymentType = "RECEIPT";
        partyIdFrom = partyId;
        partyIdTo = coParty;
        paymentAmount = amount;
      }
    } else {
      throw new GeneralException("Unable to create financial account transaction!");
    }

    // payment amount should always be positive; adjustments may
    // create the payment for the transaction
    Map<String, Object> paymentCtx = UtilMisc.<String, Object>toMap("paymentTypeId", paymentType);
    paymentCtx.put("paymentMethodTypeId", paymentMethodType);
    paymentCtx.put("partyIdTo", partyIdTo);
    paymentCtx.put("partyIdFrom", partyIdFrom);
    paymentCtx.put("statusId", "PMNT_RECEIVED");
    paymentCtx.put("currencyUomId", currencyUom);
    paymentCtx.put("amount", paymentAmount);
    paymentCtx.put("userLogin", userLogin);
    paymentCtx.put("paymentRefNum", Long.toString(UtilDateTime.nowTimestamp().getTime()));

    String paymentId;
    Map<String, Object> payResult;
    try {
      payResult = dispatcher.runSync("createPayment", paymentCtx);
    } catch (GenericServiceException e) {
      throw new GeneralException(e);
    }
    if (payResult == null) {
      throw new GeneralException("Unknow error in creating financial account transaction!");
    }
    if (ServiceUtil.isError(payResult)) {
      throw new GeneralException(ServiceUtil.getErrorMessage(payResult));
    }
    paymentId = (String) payResult.get("paymentId");

    // create the initial transaction
    Map<String, Object> transCtx = UtilMisc.<String, Object>toMap("finAccountTransTypeId", txType);
    transCtx.put("finAccountId", finAccountId);
    transCtx.put("partyId", partyId);
    transCtx.put("orderId", orderId);
    transCtx.put("orderItemSeqId", orderItemSeqId);
    transCtx.put("reasonEnumId", reasonEnumId);
    transCtx.put("amount", amount);
    transCtx.put("userLogin", userLogin);
    transCtx.put("paymentId", paymentId);

    Map<String, Object> transResult;
    try {
      transResult = dispatcher.runSync("createFinAccountTrans", transCtx);
    } catch (GenericServiceException e) {
      throw new GeneralException(e);
    }
    if (transResult == null) {
      throw new GeneralException("Unknown error in creating financial account transaction!");
    }
    if (ServiceUtil.isError(transResult)) {
      throw new GeneralException(ServiceUtil.getErrorMessage(transResult));
    }

    return (String) transResult.get("finAccountTransId");
  }