Пример #1
0
  /**
   * Generate a new MWK
   *
   * @return Hex String of the new encrypted MWK ready for transmission to ValueLink
   */
  public byte[] generateMwk() {
    KeyGenerator keyGen = null;
    try {
      keyGen = KeyGenerator.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      Debug.logError(e, module);
    }

    // generate the DES key 1
    SecretKey des1 = keyGen.generateKey();
    SecretKey des2 = keyGen.generateKey();

    if (des1 != null && des2 != null) {
      byte[] desByte1 = des1.getEncoded();
      byte[] desByte2 = des2.getEncoded();
      byte[] desByte3 = des1.getEncoded();

      // check for weak keys
      try {
        if (DESKeySpec.isWeak(des1.getEncoded(), 0) || DESKeySpec.isWeak(des2.getEncoded(), 0)) {
          return generateMwk();
        }
      } catch (Exception e) {
        Debug.logError(e, module);
      }

      byte[] des3 = copyBytes(desByte1, copyBytes(desByte2, desByte3, 0), 0);
      return generateMwk(des3);
    } else {
      Debug.logInfo("Null DES keys returned", module);
    }

    return null;
  }
Пример #2
0
  protected SecretKey getDesEdeKey(byte[] rawKey) {
    SecretKeyFactory skf = null;
    try {
      skf = SecretKeyFactory.getInstance("DESede");
    } catch (NoSuchAlgorithmException e) {
      // should never happen since DESede is a standard algorithm
      Debug.logError(e, module);
      return null;
    }

    // load the raw key
    if (rawKey.length > 0) {
      DESedeKeySpec desedeSpec1 = null;
      try {
        desedeSpec1 = new DESedeKeySpec(rawKey);
      } catch (InvalidKeyException e) {
        Debug.logError(e, "Not a valid DESede key", module);
        return null;
      }

      // create the SecretKey Object
      SecretKey key = null;
      try {
        key = skf.generateSecret(desedeSpec1);
      } catch (InvalidKeySpecException e) {
        Debug.logError(e, module);
      }
      return key;
    } else {
      throw new RuntimeException("No valid DESede key available");
    }
  }
Пример #3
0
 /**
  * Generate a new MWK
  *
  * @param desBytes byte array of the DES key (24 bytes)
  * @return Hex String of the new encrypted MWK ready for transmission to ValueLink
  */
 public byte[] generateMwk(byte[] desBytes) {
   if (debug) {
     Debug.logInfo(
         "DES Key : " + StringUtil.toHexString(desBytes) + " / " + desBytes.length, module);
   }
   SecretKeyFactory skf1 = null;
   SecretKey mwk = null;
   try {
     skf1 = SecretKeyFactory.getInstance("DESede");
   } catch (NoSuchAlgorithmException e) {
     Debug.logError(e, module);
   }
   DESedeKeySpec desedeSpec2 = null;
   try {
     desedeSpec2 = new DESedeKeySpec(desBytes);
   } catch (InvalidKeyException e) {
     Debug.logError(e, module);
   }
   if (skf1 != null && desedeSpec2 != null) {
     try {
       mwk = skf1.generateSecret(desedeSpec2);
     } catch (InvalidKeySpecException e) {
       Debug.logError(e, module);
     }
   }
   if (mwk != null) {
     return generateMwk(mwk);
   } else {
     return null;
   }
 }
  public void setMessage(MimeMessage message) {
    if (message != null) {
      // serialize the message
      this.message = message;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try {
        message.writeTo(baos);
        baos.flush();
        serializedBytes = baos.toByteArray();
        this.contentType = message.getContentType();

        // see if this is a multi-part message
        Object content = message.getContent();
        if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          this.parts = mp.getCount();
        } else {
          this.parts = 0;
        }
      } catch (MessagingException e) {
        Debug.logError(e, module);
      } catch (IOException e) {
        Debug.logError(e, module);
      } finally {
        try {
          baos.close();
        } catch (IOException e) {
          Debug.logError(e, module);
        }
      }
    }
  }
  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);
  }
Пример #6
0
  private static NVPDecoder sendNVPRequest(GenericValue payPalConfig, NVPEncoder encoder)
      throws PayPalException {
    NVPCallerServices caller = new NVPCallerServices();
    try {
      APIProfile profile = ProfileFactory.createSignatureAPIProfile();
      profile.setAPIUsername(payPalConfig.getString("apiUserName"));
      profile.setAPIPassword(payPalConfig.getString("apiPassword"));
      profile.setSignature(payPalConfig.getString("apiSignature"));
      profile.setEnvironment(payPalConfig.getString("apiEnvironment"));
      caller.setAPIProfile(profile);
    } catch (PayPalException e) {
      Debug.logError(e.getMessage(), module);
    }

    String requestMessage = encoder.encode();
    String responseMessage = caller.call(requestMessage);

    NVPDecoder decoder = new NVPDecoder();
    decoder.decode(responseMessage);
    if (!"Success".equals(decoder.get("ACK"))) {
      Debug.logError(
          "A response other than success was received from PayPal: " + responseMessage, module);
    }

    return decoder;
  }
Пример #7
0
  private static String getLastProductStoreId(Delegator delegator, String finAccountId) {
    GenericValue trans = null;
    try {
      trans =
          EntityQuery.use(delegator)
              .from("FinAccountTrans")
              .where(
                  EntityCondition.makeCondition(
                      "finAccountTransTypeId", EntityOperator.EQUALS, "DEPOSIT"),
                  EntityCondition.makeCondition(
                      "finAccountId", EntityOperator.EQUALS, finAccountId),
                  EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null))
              .orderBy("-transactionDate")
              .queryFirst();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    if (trans != null) {
      String orderId = trans.getString("orderId");
      OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
      return orh.getProductStoreId();
    }

    // none found; pick one from our set stores
    try {
      GenericValue store =
          EntityQuery.use(delegator).from("ProductStore").orderBy("productStoreId").queryFirst();
      if (store != null) return store.getString("productStoreId");
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    return null;
  }
    @Override
    public boolean eval(Map<String, Object> context) {
      Object fieldVal = this.fieldAcsr.get(context);
      String expr = this.exprExdr.expandString(context);
      Pattern pattern;
      try {
        pattern = compiler.compile(expr);
      } catch (MalformedPatternException e) {
        String errMsg = "Error in evaluation in if-regexp in screen: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new IllegalArgumentException(errMsg);
      }

      String fieldString = null;
      try {
        fieldString =
            (String)
                ObjectType.simpleTypeConvert(
                    fieldVal,
                    "String",
                    null,
                    (TimeZone) context.get("timeZone"),
                    (Locale) context.get("locale"),
                    true);
      } catch (GeneralException e) {
        Debug.logError(e, "Could not convert object to String, using empty String", module);
      }
      // always use an empty string by default
      if (fieldString == null) fieldString = "";

      return matcher.matches(fieldString, pattern);
    }
Пример #9
0
  public static Map<String, Object> streamTest(DispatchContext dctx, Map<String, ?> context) {
    InputStream in = (InputStream) context.get("inputStream");
    OutputStream out = (OutputStream) context.get("outputStream");

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    Writer writer = new OutputStreamWriter(out);
    String line;

    try {
      while ((line = reader.readLine()) != null) {
        Debug.log("Read line: " + line, module);
        writer.write(line);
      }
    } catch (IOException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    } finally {
      try {
        writer.close();
      } catch (Exception e) {
        Debug.logError(e, module);
      }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("contentType", "text/plain");
    return result;
  }
Пример #10
0
  private static void writeJSONtoResponse(JSON json, HttpServletResponse response) {
    String jsonStr = json.toString();
    if (jsonStr == null) {
      Debug.logError("JSON Object was empty; fatal error!", module);
      return;
    }

    // set the X-JSON content type
    response.setContentType("application/x-json");
    // jsonStr.length is not reliable for unicode characters
    try {
      response.setContentLength(jsonStr.getBytes("UTF8").length);
    } catch (UnsupportedEncodingException e) {
      Debug.logError("Problems with Json encoding: " + e, module);
    }

    // return the JSON String
    Writer out;
    try {
      out = response.getWriter();
      out.write(jsonStr);
      out.flush();
    } catch (IOException e) {
      Debug.logError(e, module);
    }
  }
Пример #11
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;
  }
Пример #12
0
  /**
   * Authorizes and captures an EFT transaction. If the authorization or capture fails due to
   * problems with the transaction, this service will result in a failure.
   *
   * <p>If this service results in an error, it means that the service is not propery configured and
   * will not work until the issues are resolved.
   */
  public static Map authorizeAndCaptureEft(DispatchContext dctx, Map context) {
    Delegator delegator = dctx.getDelegator();
    String resource = getResource(context);
    Double amount = (Double) context.get("processAmount");
    GenericValue eftAccount = (GenericValue) context.get("eftAccount");
    String currencyUomId = (String) context.get("currency");

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

      AuthorizeResponse response = processRequest(request, resource);

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

      if (isTestMode(resource)) {
        Debug.logInfo("eCheck.NET AUTH_CAPTURE results: " + results, module);
      }
      return results;
    } catch (GenericEntityException e) {
      String message =
          "Entity engine error when attempting to authorize and capture EFT via eCheck.net: "
              + e.getMessage();
      Debug.logError(e, message, module);
      return ServiceUtil.returnError(message);
    } catch (GenericServiceException e) {
      String message =
          "Service error when attempting to authorize and capture EFT via eCheck.net.  This is a configuration problem that must be fixed before this service can work properly: "
              + e.getMessage();
      Debug.logError(e, message, module);
      return ServiceUtil.returnError(message);
    }
  }
Пример #13
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);
      }
    }
  }
Пример #14
0
  /*
   * Returns the value of a given ShipmentPackageContent record.  Calculated by working out the total value (from the OrderItems) of all ItemIssuances
   * for the ShipmentItem then dividing that by the total quantity issued for the same to get an average item value then multiplying that by the package
   * content quantity.
   * Note: No rounding of the calculation is performed so you will need to round it to the accuracy that you require
   */
  public static BigDecimal getShipmentPackageContentValue(GenericValue shipmentPackageContent) {
    BigDecimal quantity = shipmentPackageContent.getBigDecimal("quantity");

    BigDecimal value = new BigDecimal("0");

    // lookup the issuance to find the order
    List<GenericValue> issuances = null;
    try {
      GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem");
      issuances = shipmentItem.getRelated("ItemIssuance");
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    BigDecimal totalIssued = BigDecimal.ZERO;
    BigDecimal totalValue = BigDecimal.ZERO;
    if (UtilValidate.isNotEmpty(issuances)) {
      for (GenericValue issuance : issuances) {
        // we only need one
        BigDecimal issuanceQuantity = issuance.getBigDecimal("quantity");
        BigDecimal issuanceCancelQuantity = issuance.getBigDecimal("cancelQuantity");
        if (issuanceCancelQuantity != null) {
          issuanceQuantity = issuanceQuantity.subtract(issuanceCancelQuantity);
        }
        // get the order item
        GenericValue orderItem = null;
        try {
          orderItem = issuance.getRelatedOne("OrderItem");
        } catch (GenericEntityException e) {
          Debug.logError(e, module);
        }

        if (orderItem != null) {
          // get the value per unit - (base price * amount)
          BigDecimal selectedAmount = orderItem.getBigDecimal("selectedAmount");
          if (selectedAmount == null || selectedAmount.compareTo(BigDecimal.ZERO) <= 0) {
            selectedAmount = BigDecimal.ONE;
          }

          BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
          BigDecimal itemValue = unitPrice.multiply(selectedAmount);

          // total value for package (per unit * quantity)
          totalIssued = totalIssued.add(issuanceQuantity);
          totalValue = totalValue.add(itemValue.multiply(issuanceQuantity));
        }
      }
    }
    // take the average value of the issuances and multiply it by the shipment package content
    // quantity
    value = totalValue.divide(totalIssued, 10, BigDecimal.ROUND_HALF_EVEN).multiply(quantity);
    return value;
  }
Пример #15
0
  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();
  }
Пример #16
0
  private static List<Map<Object, Object>> getListMapsFromXmlFile(String XmlFilePath) {
    List<Map<Object, Object>> listMaps = FastList.newInstance();
    InputStream ins = null;
    URL xmlFileUrl = null;
    Document xmlDocument = null;
    try {
      if (UtilValidate.isNotEmpty(XmlFilePath)) {
        xmlFileUrl = UtilURL.fromFilename(XmlFilePath);
        if (xmlFileUrl != null) ins = xmlFileUrl.openStream();
        if (ins != null) {
          xmlDocument = UtilXml.readXmlDocument(ins, xmlFileUrl.toString());
          List<? extends Node> nodeList =
              UtilXml.childNodeList(xmlDocument.getDocumentElement().getFirstChild());
          for (Node node : nodeList) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
              Map<Object, Object> fields = FastMap.newInstance();
              fields.put(node.getNodeName(), UtilXml.elementValue((Element) node));
              Map<Object, Object> attrFields = getAttributeNameValueMap(node);
              Set<Object> keys = attrFields.keySet();
              Iterator<Object> attrFieldsIter = keys.iterator();
              while (attrFieldsIter.hasNext()) {
                Object key = attrFieldsIter.next();
                fields.put(key, attrFields.get(key));
              }

              List<? extends Node> childNodeList = UtilXml.childNodeList(node.getFirstChild());
              for (Node childNode : childNodeList) {
                fields.put(childNode.getNodeName(), UtilXml.elementValue((Element) childNode));
                attrFields = getAttributeNameValueMap(childNode);
                keys = attrFields.keySet();
                attrFieldsIter = keys.iterator();
                while (attrFieldsIter.hasNext()) {
                  Object key = attrFieldsIter.next();
                  fields.put(key, attrFields.get(key));
                }
              }
              listMaps.add(fields);
            }
          }
        }
      }
    } catch (Exception exc) {
      Debug.logError(exc, "Error reading xml file", module);
    } finally {
      try {
        if (ins != null) ins.close();
      } catch (Exception exc) {
        Debug.logError(exc, "Error reading xml file", module);
      }
    }
    return listMaps;
  }
Пример #17
0
 public static <F> List<F> getAllFutures(Collection<Future<F>> futureList) {
   List<F> result = FastList.newInstance();
   for (Future<F> future : futureList) {
     try {
       result.add(future.get());
     } catch (ExecutionException e) {
       Debug.logError(e, module);
     } catch (InterruptedException e) {
       Debug.logError(e, module);
     }
   }
   return result;
 }
 public AssignmentEventAudit(EntityAuditMgr mgr, Delegator delegator, String eventAuditId) {
   super(mgr, delegator, eventAuditId);
   if (this.delegator != null) {
     try {
       this.assignmentEventAudit =
           delegator.findByPrimaryKey(
               "WfAssignmentEventAudit", UtilMisc.toMap("eventAuditId", eventAuditId));
     } catch (GenericEntityException e) {
       Debug.logError(e, module);
     }
   } else {
     Debug.logError("Invalid delegator object passed", module);
   }
 }
Пример #19
0
 // actual kek encryption/decryption code
 protected byte[] cryptoViaKek(byte[] content, int mode) {
   // open a cipher using the kek for transport
   Cipher cipher = this.getCipher(this.getKekKey(), mode);
   byte[] dec = new byte[0];
   try {
     dec = cipher.doFinal(content);
   } catch (IllegalStateException e) {
     Debug.logError(e, module);
   } catch (IllegalBlockSizeException e) {
     Debug.logError(e, module);
   } catch (BadPaddingException e) {
     Debug.logError(e, module);
   }
   return dec;
 }
Пример #20
0
  public static Delegator getDelegator(String delegatorName) {
    if (delegatorName == null) {
      delegatorName = "default";
      // Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a
      // getGenericDelegator call with a null delegatorName, assuming default for the name.",
      // module);
    }
    do {
      Delegator delegator = delegatorCache.get(delegatorName);

      if (delegator != null) {
        // setup the Entity ECA Handler
        delegator.initEntityEcaHandler();
        // Debug.logInfo("got delegator(" + delegatorName + ") from cache", module);

        // setup the distributed CacheClear
        delegator.initDistributedCacheClear();

        return delegator;
      }
      try {
        delegator = UtilObject.getObjectFromFactory(DelegatorFactory.class, delegatorName);
      } catch (ClassNotFoundException e) {
        Debug.logError(e, module);
      }
      // Debug.logInfo("putting delegator(" + delegatorName + ") into cache", module);
      delegatorCache.putIfAbsent(delegatorName, delegator);
    } while (true);
  }
Пример #21
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;
  }
Пример #22
0
  /**
   * Gets a partial list of a given size starting from a cursor index. Note that although the
   * arguments are longs, the EntityListIterator must accept ints.
   *
   * @param viewSize a <code>long</code> value
   * @param cursorIndex a <code>long</code> value
   * @return a <code>List</code> value
   * @exception ListBuilderException if an error occurs
   */
  public List getPartialList(long viewSize, long cursorIndex) throws ListBuilderException {
    if (!isInitialized()) {
      initialize();
    }
    try {
      // XXX Note:  EntityListIterator is a 1 based list, so we must add 1 to index
      List<GenericValue> results = iterator.getPartialList((int) cursorIndex + 1, (int) viewSize);
      close();
      // convert to domain entities if needed
      if (repository != null && entityClass != null) {
        List domainResults = null;
        try {
          domainResults = Repository.loadFromGeneric(entityClass, results, repository);
        } catch (RepositoryException e) {
          Debug.logError(e, module);
        }
        if (domainResults != null) {
          return domainResults;
        }
      }

      return results;
    } catch (GenericEntityException e) {
      throw new ListBuilderException(e);
    }
  }
Пример #23
0
  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;
  }
Пример #24
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();
  }
Пример #25
0
  /**
   * Converts the supplied String into a String suitable for address line matching. Performs the
   * following transformations on the supplied String: - Converts to upper case - Retrieves all
   * records from the AddressMatchMap table and replaces all occurrences of addressMatchMap.mapKey
   * with addressMatchMap.mapValue using upper case matching. - Removes all non-word characters from
   * the String i.e. everything except A-Z, 0-9 and _
   *
   * @param delegator A Delegator instance
   * @param address The address String to convert
   * @return The converted Address
   */
  public static String makeMatchingString(Delegator delegator, String address) {
    if (address == null) {
      return null;
    }

    // upper case the address
    String str = address.trim().toUpperCase();

    // replace mapped words
    List<GenericValue> addressMap = null;
    try {
      addressMap =
          delegator.findList(
              "AddressMatchMap", null, null, UtilMisc.toList("sequenceNum"), null, false);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    if (addressMap != null) {
      for (GenericValue v : addressMap) {
        str =
            str.replaceAll(
                v.getString("mapKey").toUpperCase(), v.getString("mapValue").toUpperCase());
      }
    }

    // remove all non-word characters
    return str.replaceAll("\\W", "");
  }
Пример #26
0
  public static Map<String, Object> doAuthorization(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig =
        getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
      currency = orh.getCurrency();
    }
    encoder.add("CURRENCYCODE", currency);

    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalConfig, 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, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("authResult", false);
      result.put("authRefNum", "N/A");
      result.put("processAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("authCode", error.getKey());
        result.put("authMessage", error.getValue());
      } else {
        result.put(
            "authMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("authResult", true);
      result.put("processAmount", new BigDecimal(decoder.get("AMT")));
      result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what
    // should be checked for this type of transaction
    return result;
  }
Пример #27
0
  private static String parseStateProvinceGeoId(
      String payPalShipToState, String countryGeoId, Delegator delegator) {
    String lookupField = "geoName";
    List<EntityCondition> conditionList = FastList.newInstance();
    conditionList.add(EntityCondition.makeCondition("geoAssocTypeId", "REGIONS"));
    if ("USA".equals(countryGeoId) || "CAN".equals(countryGeoId)) {
      // PayPal returns two letter code for US and Canadian States/Provinces
      String geoTypeId = "USA".equals(countryGeoId) ? "STATE" : "PROVINCE";
      conditionList.add(EntityCondition.makeCondition("geoTypeId", geoTypeId));
      lookupField = "geoCode";
    }
    conditionList.add(EntityCondition.makeCondition("geoIdFrom", countryGeoId));
    conditionList.add(EntityCondition.makeCondition(lookupField, payPalShipToState));
    EntityCondition cond = EntityCondition.makeCondition(conditionList);
    GenericValue geoAssocAndGeoTo = null;
    try {
      geoAssocAndGeoTo =
          EntityQuery.use(delegator).from("GeoAssocAndGeoTo").where(cond).cache().queryFirst();

    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    if (geoAssocAndGeoTo != null) {
      return geoAssocAndGeoTo.getString("geoId");
    }
    return null;
  }
Пример #28
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));
    }
  }
Пример #29
0
  /**
   * Transmit a request to ValueLink
   *
   * @param url override URL from what is defined in the properties
   * @param request request Map of request parameters
   * @return Map of response parameters
   * @throws HttpClientException
   */
  public Map<String, Object> send(String url, Map<String, Object> request)
      throws HttpClientException {
    if (debug) {
      Debug.logInfo("Request : " + url + " / " + request, module);
    }

    // read the timeout value
    String timeoutString = (String) props.get("payment.valuelink.timeout");
    int timeout = 34;
    try {
      timeout = Integer.parseInt(timeoutString);
    } catch (NumberFormatException e) {
      Debug.logError(e, "Unable to set timeout to " + timeoutString + " using default " + timeout);
    }

    // create the HTTP client
    HttpClient client = new HttpClient(url, request);
    client.setTimeout(timeout * 1000);
    client.setDebug(debug);

    client.setClientCertificateAlias((String) props.get("payment.valuelink.certificateAlias"));
    String response = client.post();

    // parse the response and return a map
    return this.parseResponse(response);
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   Object obj = null;
   try {
     obj = UelUtil.evaluate(context, new String(this.bracketedOriginal));
   } catch (PropertyNotFoundException e) {
     if (Debug.verboseOn()) {
       Debug.logVerbose("Error evaluating expression " + this + ": " + e, module);
     }
   } catch (Exception e) {
     Debug.logError("Error evaluating expression " + this + ": " + e, module);
   }
   if (obj != null) {
     try {
       // Check for runtime nesting
       String str = (String) obj;
       if (str.contains(openBracket)) {
         FlexibleStringExpander fse = FlexibleStringExpander.getInstance(str);
         return fse.get(context, timeZone, locale);
       }
     } catch (ClassCastException e) {
     }
   }
   return obj;
 }