Ejemplo n.º 1
0
 private void executeMacro(
     Appendable writer, String macroName, Map<String, Object> macroParameters)
     throws IOException, TemplateException {
   StringBuilder sb = new StringBuilder("<@");
   sb.append(macroName);
   if (macroParameters != null) {
     for (Map.Entry<String, Object> parameter : macroParameters.entrySet()) {
       sb.append(' ');
       sb.append(parameter.getKey());
       sb.append("=");
       Object value = parameter.getValue();
       if (value instanceof String) {
         sb.append('"');
         sb.append(((String) value).replaceAll("\"", "\\\\\""));
         sb.append('"');
       } else {
         sb.append(value);
       }
     }
   }
   sb.append(" />");
   if (Debug.verboseOn()) {
     Debug.logVerbose("Executing macro: " + sb, module);
   }
   executeMacro(writer, sb.toString());
 }
Ejemplo n.º 2
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);
    }
  }
 public boolean evalPermission(DispatchContext dctx, Map<String, ? extends Object> context) {
   GenericValue userLogin = (GenericValue) context.get("userLogin");
   Authorization authz = dctx.getAuthorization();
   Security security = dctx.getSecurity();
   if (userLogin == null) {
     Debug.logInfo("Secure service requested with no userLogin object", module);
     return false;
   }
   switch (permissionType) {
     case PERMISSION:
       return evalAuthzPermission(authz, userLogin, context);
     case ENTITY_PERMISSION:
       return evalEntityPermission(security, userLogin);
     case ROLE_MEMBER:
       return evalRoleMember(userLogin);
     case PERMISSION_SERVICE:
       return evalPermissionService(serviceModel, dctx, context);
     default:
       Debug.logWarning(
           "Invalid permission type ["
               + permissionType
               + "] for permission named : "
               + nameOrRole
               + " on service : "
               + serviceModel.name,
           module);
       return false;
   }
 }
Ejemplo n.º 4
0
  @Override
  public T getObject(MethodContext methodContext) {
    T fieldVal = null;

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

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

    return fieldVal;
  }
  /**
   * Returns the next recurrence of this rule.
   *
   * @param startTime The time this recurrence first began.
   * @param fromTime The time to base the next recurrence on.
   * @param currentCount The total number of times the recurrence has run.
   * @return long The next recurrence as a long.
   */
  public long next(long startTime, long fromTime, long currentCount) {
    // Set up the values
    if (startTime == 0) startTime = RecurrenceUtil.now();
    if (fromTime == 0) fromTime = startTime;

    // Test the end time of the recurrence.
    if (getEndTime() != 0 && getEndTime() <= RecurrenceUtil.now()) return 0;
    Debug.logVerbose("Rule NOT expired by end time.", module);

    // Test the recurrence limit.
    if (getCount() != -1 && currentCount >= getCount()) return 0;
    Debug.logVerbose("Rule NOT expired by max count.", module);

    boolean isSeeking = true;
    long nextRuntime = 0;
    long seekTime = fromTime;
    int loopProtection = 0;
    int maxLoop = (10 * 10 * 10 * 10 * 10);

    while (isSeeking && loopProtection < maxLoop) {
      Date nextRun = getNextFreq(startTime, seekTime);
      seekTime = nextRun.getTime();
      if (validByRule(nextRun)) {
        isSeeking = false;
        nextRuntime = nextRun.getTime();
      }
      loopProtection++;
    }
    return nextRuntime;
  }
  public static String getCatalogTopCategory(ServletRequest request, String defaultTopCategory) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Map<String, Object> requestParameters = UtilHttp.getParameterMap(httpRequest);
    String topCatName = null;
    boolean fromSession = false;

    // first see if a new category was specified as a parameter
    topCatName = (String) requestParameters.get("CATALOG_TOP_CATEGORY");
    // if no parameter, try from session
    if (topCatName == null) {
      topCatName = (String) httpRequest.getSession().getAttribute("CATALOG_TOP_CATEGORY");
      if (topCatName != null) fromSession = true;
    }
    // if nothing else, just use a default top category name
    if (topCatName == null) topCatName = defaultTopCategory;
    if (topCatName == null) topCatName = "CATALOG1";

    if (!fromSession) {
      if (Debug.infoOn())
        Debug.logInfo(
            "[CategoryWorker.getCatalogTopCategory] Setting new top category: " + topCatName,
            module);
      httpRequest.getSession().setAttribute("CATALOG_TOP_CATEGORY", topCatName);
    }
    return topCatName;
  }
Ejemplo n.º 7
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;
  }
Ejemplo n.º 8
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;
   }
 }
Ejemplo n.º 9
0
  /**
   * Generate a key exchange key for use in encrypting the mwk
   *
   * @param privateKey The private key for the merchant
   * @return byte array containing the kek
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   * @throws InvalidKeyException
   */
  public byte[] generateKek(PrivateKey privateKey)
      throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
    // get the ValueLink public key
    PublicKey vlPublic = this.getValueLinkPublicKey();

    // generate shared secret key
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(privateKey);
    ka.doPhase(vlPublic, true);
    byte[] secretKey = ka.generateSecret();

    if (debug) {
      Debug.logInfo(
          "Secret Key : " + StringUtil.toHexString(secretKey) + " / " + secretKey.length, module);
    }

    // generate 3DES from secret key using VL algorithm (KEK)
    MessageDigest md = MessageDigest.getInstance("SHA1");
    byte[] digest = md.digest(secretKey);
    byte[] des2 = getByteRange(digest, 0, 16);
    byte[] first8 = getByteRange(des2, 0, 8);
    byte[] kek = copyBytes(des2, first8, 0);

    if (debug) {
      Debug.logInfo("Generated KEK : " + StringUtil.toHexString(kek) + " / " + kek.length, module);
    }

    return kek;
  }
Ejemplo n.º 10
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);
  }
Ejemplo n.º 11
0
  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);
        }
      }
    }
  }
Ejemplo n.º 12
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");
    }
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         BshUtil.eval(
             new String(this.chars, this.parseStart, this.parseLength),
             UtilMisc.makeMapWritable(context));
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "BSH scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (EvalError e) {
     Debug.logWarning(
         e,
         "Error evaluating BSH scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
Ejemplo n.º 14
0
  public static String getPartyName(GenericValue partyObject, boolean lastNameFirst) {
    if (partyObject == null) {
      return "";
    }
    if ("PartyGroup".equals(partyObject.getEntityName())
        || "Person".equals(partyObject.getEntityName())) {
      return formatPartyNameObject(partyObject, lastNameFirst);
    } else {
      String partyId = null;
      try {
        partyId = partyObject.getString("partyId");
      } catch (IllegalArgumentException e) {
        Debug.logError(e, "Party object does not contain a party ID", module);
      }

      if (partyId == null) {
        Debug.logWarning(
            "No party ID found; cannot get name based on entity: " + partyObject.getEntityName(),
            module);
        return "";
      } else {
        return getPartyName(partyObject.getDelegator(), partyId, lastNameFirst);
      }
    }
  }
Ejemplo n.º 15
0
  public static Map<String, GenericValue> getPartyOtherValues(
      ServletRequest request,
      String partyId,
      String partyAttr,
      String personAttr,
      String partyGroupAttr) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Map<String, GenericValue> result = FastMap.newInstance();
    try {
      GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));

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

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

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

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

      if (partyGroup != null) result.put(partyGroupAttr, partyGroup);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting PartyGroup entity", module);
    }
    return result;
  }
Ejemplo n.º 16
0
  /**
   * Retrieve the last deactivation date if the party is currently deactivated.
   *
   * @param partyId
   * @param delegator
   * @return the timestamp of last deactivation, null if the party is not deactivated
   * @throws GenericEntityNotFoundException
   */
  public static Timestamp getDeactivationDate(String partyId, Delegator delegator)
      throws GenericEntityException {
    // check party current status:
    if (isActive(partyId, delegator)) {
      return null;
    }

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

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

    } catch (GenericEntityException e) {
      Debug.logError(e, MODULE);
    }
    return null;
  }
Ejemplo n.º 17
0
    @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);
    }
Ejemplo n.º 18
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;
  }
Ejemplo n.º 19
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;
  }
Ejemplo n.º 20
0
  @Override
  public boolean exec(MethodContext methodContext) {
    // if anything but false it will be true
    boolean setIfNull = !"false".equals(methodContext.expandString(setIfNullStr));

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

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

    Map<String, ? extends Object> theMap = mapAcsr.get(methodContext);
    if (theMap == null) {
      Debug.logWarning(
          "In set-pk-fields could not find map with name " + mapAcsr + ", not setting any fields",
          module);
    } else {
      value.setPKFields(theMap, setIfNull);
    }
    return true;
  }
Ejemplo n.º 21
0
  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);
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         InvokerHelper.createScript(this.parsedScript, GroovyUtil.getBinding(context)).run();
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "Groovy scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (Exception e) {
     // handle other things, like the groovy.lang.MissingPropertyException
     Debug.logWarning(
         e,
         "Error evaluating Groovy scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
 @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;
 }
Ejemplo n.º 24
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;
  }
Ejemplo n.º 25
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;
  }
Ejemplo n.º 26
0
  /**
   * Gets the request fields that are configured in the properties file, such as the merchant key
   * and password. This handles version as well. If some critical data is missing, this throws
   * GenericServiceException.
   */
  private static Map buildRequestHeader(String resource) throws GenericServiceException {
    Map request = FastMap.newInstance();

    String login = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.login");
    if (UtilValidate.isEmpty(login)) {
      Debug.logWarning(
          "Authorize.NET login not configured.  Please ensure payment.authorizedotnet.login is defined in "
              + resource,
          module);
    }

    String password = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.password");
    if (UtilValidate.isEmpty(password)) {
      Debug.logWarning(
          "Authorize.NET password not configured.  Please ensure payment.authorizedotnet.password is defined in "
              + resource,
          module);
    }

    String delimited =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.delimited");
    String delimiter =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.delimiter");
    String emailcustomer =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.emailcustomer");
    String emailmerchant =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.emailmerchant");
    String transdescription =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.transdescription");

    request.put("x_login", login);
    request.put("x_password", password);
    request.put("x_delim_data", delimited);
    request.put("x_delim_char", delimiter);
    request.put("x_email_customer", emailcustomer);
    request.put("x_email_merchant", emailmerchant);
    request.put("x_description", transdescription);
    request.put("x_relay_response", "FALSE");

    String version =
        UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.version", "3.0");
    String tkey = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.trankey");

    // transaction key is only supported in 3.1
    if ("3.1".equals(version) && UtilValidate.isNotEmpty(tkey)) {
      Debug.logWarning(
          "Version 3.1 of Authorize.NET requires a transaction key.  Please define payment.authorizedotnet.trankey in "
              + resource,
          module);
      Debug.logWarning("Reverting to version 3.0 of Authorize.NET", module);
      version = "3.0";
    }

    request.put("x_version", version);
    request.put("x_tran_key", tkey);

    return request;
  }
Ejemplo n.º 27
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);
    }
  }
Ejemplo n.º 28
0
  protected Map<String, Object> parseResponse(String response) {
    if (debug) {
      Debug.logInfo("Raw Response : " + response, module);
    }

    // covert to all lowercase and trim off the html header
    String subResponse = response.toLowerCase();
    int firstIndex = subResponse.indexOf("<tr>");
    int lastIndex = subResponse.lastIndexOf("</tr>");
    subResponse = subResponse.substring(firstIndex, lastIndex);

    // check for a history table
    String history = null;
    List<Map<String, String>> historyMapList = null;
    if (subResponse.indexOf("<table") > -1) {
      int startHistory = subResponse.indexOf("<table");
      int endHistory = subResponse.indexOf("</table>") + 8;
      history = subResponse.substring(startHistory, endHistory);

      // replace the subResponse string so it doesn't conflict
      subResponse = StringUtil.replaceString(subResponse, history, "[_HISTORY_]");

      // parse the history into a list of maps
      historyMapList = this.parseHistoryResponse(history);
    }

    // replace all end rows with | this is the name delimiter
    subResponse = StringUtil.replaceString(subResponse, "</tr>", "|");

    // replace all </TD><TD> with = this is the value delimiter
    subResponse = StringUtil.replaceString(subResponse, "</td><td>", "=");

    // clean off a bunch of other useless stuff
    subResponse = StringUtil.replaceString(subResponse, "<tr>", "");
    subResponse = StringUtil.replaceString(subResponse, "<td>", "");
    subResponse = StringUtil.replaceString(subResponse, "</td>", "");

    // make the map
    Map<String, Object> responseMap = FastMap.newInstance();
    responseMap.putAll(StringUtil.strToMap(subResponse, true));

    // add the raw html back in just in case we need it later
    responseMap.put("_rawHtmlResponse", response);

    // if we have a history add it back in
    if (history != null) {
      responseMap.put("_rawHistoryHtml", history);
      responseMap.put("history", historyMapList);
    }

    if (debug) {
      Debug.logInfo("Response Map : " + responseMap, module);
    }

    return responseMap;
  }
 private boolean evalEntityPermission(Security security, GenericValue userLogin) {
   if (nameOrRole == null) {
     Debug.logWarning("Null permission name passed for evaluation", module);
     return false;
   }
   if (action == null) {
     Debug.logWarning("Null action passed for evaluation", module);
   }
   return security.hasEntityPermission(nameOrRole, action, userLogin);
 }
Ejemplo n.º 30
0
 @Override
 public boolean exec(MethodContext methodContext) throws MiniLangException {
   List<Object> messages = errorListFma.get(methodContext.getEnvMap());
   if (messages == null) {
     messages = new LinkedList<Object>();
     errorListFma.put(methodContext.getEnvMap(), messages);
   }
   String location = this.locationFse.expandString(methodContext.getEnvMap());
   Delegator delegator = getDelegator(methodContext);
   URL dataUrl = null;
   try {
     dataUrl = FlexibleLocation.resolveLocation(location, methodContext.getLoader());
   } catch (MalformedURLException e) {
     messages.add(
         "Could not find Entity Data document in resource: "
             + location
             + "; error was: "
             + e.toString());
   }
   if (dataUrl == null) {
     messages.add("Could not find Entity Data document in resource: " + location);
   }
   if ("assert".equals(mode)) {
     try {
       EntityDataAssert.assertData(dataUrl, delegator, messages);
     } catch (Exception e) {
       String xmlError =
           "Error checking/asserting XML Resource \""
               + dataUrl.toExternalForm()
               + "\"; Error was: "
               + e.getMessage();
       messages.add(xmlError);
       Debug.logWarning(e, xmlError, module);
     }
   } else {
     try {
       EntitySaxReader reader = null;
       if (timeout > 0) {
         reader = new EntitySaxReader(delegator, timeout);
       } else {
         reader = new EntitySaxReader(delegator);
       }
       reader.parse(dataUrl);
     } catch (Exception e) {
       String xmlError =
           "Error loading XML Resource \""
               + dataUrl.toExternalForm()
               + "\"; Error was: "
               + e.getMessage();
       messages.add(xmlError);
       Debug.logWarning(e, xmlError, module);
     }
   }
   return true;
 }