/** * 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; }
public void populateFromAttributes(Element element) { author = element.getAttribute("author").intern(); copyright = element.getAttribute("copyright").intern(); description = StringUtil.internString(UtilXml.childElementValue(element, "description")); title = element.getAttribute("title").intern(); version = element.getAttribute("version").intern(); defaultResourceName = StringUtil.internString(element.getAttribute("default-resource-name")); }
protected SecretKey getMwkKey() { if (mwk == null) { mwk = this.getDesEdeKey(getByteRange(getMwk(), 8, 24)); } if (debug) { Debug.logInfo("Raw MWK : " + StringUtil.toHexString(getMwk()), module); Debug.logInfo("MWK : " + StringUtil.toHexString(mwk.getEncoded()), module); } return mwk; }
protected SecretKey getKekKey() { if (kek == null) { kek = this.getDesEdeKey(getKek()); } if (debug) { Debug.logInfo("Raw KEK : " + StringUtil.toHexString(getKek()), module); Debug.logInfo("KEK : " + StringUtil.toHexString(kek.getEncoded()), module); } return kek; }
private List<Map<String, String>> parseHistoryResponse(String response) { if (debug) { Debug.logInfo("Raw History : " + 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); // clean up the html and replace the delimiters with '|' subResponse = StringUtil.replaceString(subResponse, "<td>", ""); subResponse = StringUtil.replaceString(subResponse, "</td>", "|"); // test the string to make sure we have fields to parse String testResponse = StringUtil.replaceString(subResponse, "<tr>", ""); testResponse = StringUtil.replaceString(testResponse, "</tr>", ""); testResponse = StringUtil.replaceString(testResponse, "|", ""); testResponse = testResponse.trim(); if (testResponse.length() == 0) { if (debug) { Debug.logInfo("History did not contain any fields, returning null", module); } return null; } // break up the keys from the values int valueStart = subResponse.indexOf("</tr>"); String keys = subResponse.substring(4, valueStart - 1); String values = subResponse.substring(valueStart + 9, subResponse.length() - 6); // split sets of values up values = StringUtil.replaceString(values, "|</tr><tr>", "&"); List<String> valueList = StringUtil.split(values, "&"); // create a List of Maps for each set of values List<Map<String, String>> valueMap = FastList.newInstance(); for (int i = 0; i < valueList.size(); i++) { valueMap.add( StringUtil.createMap( StringUtil.split(keys, "|"), StringUtil.split(valueList.get(i), "|"))); } if (debug) { Debug.logInfo("History Map : " + valueMap, module); } return valueMap; }
/** * 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; } }
/** * Generate a new MWK * * @param mwkdes3 pre-generated DES3 SecretKey * @return Hex String of the new encrypted MWK ready for transmission to ValueLink */ public byte[] generateMwk(SecretKey mwkdes3) { // zeros for checksum byte[] zeros = {0, 0, 0, 0, 0, 0, 0, 0}; // 8 bytes random data byte[] random = new byte[8]; Random ran = new Random(); ran.nextBytes(random); // open a cipher using the new mwk Cipher cipher = this.getCipher(mwkdes3, Cipher.ENCRYPT_MODE); // make the checksum - encrypted 8 bytes of 0's byte[] encryptedZeros = new byte[0]; try { encryptedZeros = cipher.doFinal(zeros); } catch (IllegalStateException e) { Debug.logError(e, module); } catch (IllegalBlockSizeException e) { Debug.logError(e, module); } catch (BadPaddingException e) { Debug.logError(e, module); } // make the 40 byte MWK - random 8 bytes + key + checksum byte[] newMwk = copyBytes(mwkdes3.getEncoded(), encryptedZeros, 0); newMwk = copyBytes(random, newMwk, 0); if (debug) { Debug.logInfo("Random 8 byte : " + StringUtil.toHexString(random), module); Debug.logInfo("Encrypted 0's : " + StringUtil.toHexString(encryptedZeros), module); Debug.logInfo( "Decrypted MWK : " + StringUtil.toHexString(mwkdes3.getEncoded()) + " / " + mwkdes3.getEncoded().length, module); Debug.logInfo( "Encrypted MWK : " + StringUtil.toHexString(newMwk) + " / " + newMwk.length, module); } return newMwk; }
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; }
public StringBuilder appendTo(StringBuilder sb) { sb.append("INSERT INTO "); tableName.appendTo(sb); if (columns != null && !columns.isEmpty()) { sb.append(" ("); StringUtil.append(sb, columns, null, null, ", "); sb.append(')'); } sb.append(' '); source.appendTo(sb); return sb; }
// using the prime and generator provided by valuelink; create a parameter object protected DHParameterSpec getDHParameterSpec() { String primeHex = (String) props.get("payment.valuelink.prime"); String genString = (String) props.get("payment.valuelink.generator"); // convert the p/g hex values byte[] primeByte = StringUtil.fromHexString(primeHex); BigInteger prime = new BigInteger(1, primeByte); // force positive (unsigned) BigInteger generator = new BigInteger(genString); // initialize the parameter spec DHParameterSpec dhParamSpec = new DHParameterSpec(prime, generator, 1024); return dhParamSpec; }
public void populateFromElements(Element element) { author = StringUtil.internString(UtilXml.childElementValue(element, "author")); copyright = StringUtil.internString(UtilXml.childElementValue(element, "copyright")); description = StringUtil.internString(UtilXml.childElementValue(element, "description")); title = StringUtil.internString(UtilXml.childElementValue(element, "title")); version = StringUtil.internString(UtilXml.childElementValue(element, "version")); defaultResourceName = StringUtil.internString(UtilXml.childElementValue(element, "default-resource-name")); }
/** * Initializes the rules for this RecurrenceInfo object. * * @throws RecurrenceRuleException */ public void init() throws RecurrenceRuleException { // Check the validity of the rule String freq = rule.getString("frequency"); if (!checkFreq(freq)) throw new RecurrenceRuleException("Recurrence FREQUENCY is a required parameter."); if (rule.getLong("intervalNumber").longValue() < 1) throw new RecurrenceRuleException("Recurrence INTERVAL must be a positive integer."); // Initialize the byXXX lists bySecondList = StringUtil.split(rule.getString("bySecondList"), ","); byMinuteList = StringUtil.split(rule.getString("byMinuteList"), ","); byHourList = StringUtil.split(rule.getString("byHourList"), ","); byDayList = StringUtil.split(rule.getString("byDayList"), ","); byMonthDayList = StringUtil.split(rule.getString("byMonthDayList"), ","); byYearDayList = StringUtil.split(rule.getString("byYearDayList"), ","); byWeekNoList = StringUtil.split(rule.getString("byWeekNoList"), ","); byMonthList = StringUtil.split(rule.getString("byMonthList"), ","); bySetPosList = StringUtil.split(rule.getString("bySetPosList"), ","); }
private boolean isDisableIfEmpty(ModelMenuItem menuItem, Map<String, Object> context) { boolean disabled = false; String disableIfEmpty = menuItem.getDisableIfEmpty(); if (UtilValidate.isNotEmpty(disableIfEmpty)) { List<String> keys = StringUtil.split(disableIfEmpty, "|"); for (String key : keys) { Object obj = context.get(key); if (obj == null) { disabled = true; break; } } } return disabled; }
public CallBsh(Element element, SimpleMethod simpleMethod) throws MiniLangException { super(element, simpleMethod); if (MiniLangValidate.validationOn()) { MiniLangValidate.handleError( "<call-bsh> element is deprecated (use <script>)", simpleMethod, element); MiniLangValidate.attributeNames(simpleMethod, element, "resource"); MiniLangValidate.constantAttributes(simpleMethod, element, "resource"); MiniLangValidate.noChildElements(simpleMethod, element); } boolean elementModified = autoCorrect(element); if (elementModified && MiniLangUtil.autoCorrectOn()) { MiniLangUtil.flagDocumentAsCorrected(element); } this.inline = StringUtil.convertOperatorSubstitutions(UtilXml.elementValue(element)); this.resource = element.getAttribute("resource"); }
/** XML Constructor */ public ModelIndex(ModelEntity mainEntity, Element indexElement) { super(mainEntity); this.name = UtilXml.checkEmpty(indexElement.getAttribute("name")).intern(); this.unique = "true".equals(UtilXml.checkEmpty(indexElement.getAttribute("unique"))); this.description = StringUtil.internString(UtilXml.childElementValue(indexElement, "description")); NodeList indexFieldList = indexElement.getElementsByTagName("index-field"); for (int i = 0; i < indexFieldList.getLength(); i++) { Element indexFieldElement = (Element) indexFieldList.item(i); if (indexFieldElement.getParentNode() == indexElement) { String fieldName = indexFieldElement.getAttribute("name").intern(); this.fieldNames.add(fieldName); } } }
/** * Get a public key object for the ValueLink supplied public key * * @return PublicKey object of ValueLinks's public key * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public PublicKey getValueLinkPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException { // read the valuelink public key String publicValue = (String) props.get("payment.valuelink.publicValue"); byte[] publicKeyBytes = StringUtil.fromHexString(publicValue); // initialize the parameter spec DHParameterSpec dhParamSpec = this.getDHParameterSpec(); // load the valuelink public key KeyFactory keyFactory = KeyFactory.getInstance("DH"); BigInteger publicKeyInt = new BigInteger(publicKeyBytes); DHPublicKeySpec dhPublicSpec = new DHPublicKeySpec(publicKeyInt, dhParamSpec.getP(), dhParamSpec.getG()); PublicKey vlPublic = keyFactory.generatePublic(dhPublicSpec); return vlPublic; }
/** * Encrypt the defined pin using the configured keys * * @param pin Plain text String of the pin * @return Hex String of the encrypted pin (EAN) for transmission to ValueLink */ public String encryptPin(String pin) { // get the Cipher Cipher mwkCipher = this.getCipher(this.getMwkKey(), Cipher.ENCRYPT_MODE); // pin to bytes byte[] pinBytes = pin.getBytes(); // 7 bytes of random data byte[] random = this.getRandomBytes(7); // pin checksum byte[] checkSum = this.getPinCheckSum(pinBytes); // put all together byte[] eanBlock = new byte[16]; int i; for (i = 0; i < random.length; i++) { eanBlock[i] = random[i]; } eanBlock[7] = checkSum[0]; for (i = 0; i < pinBytes.length; i++) { eanBlock[i + 8] = pinBytes[i]; } // encrypy the ean String encryptedEanHex = null; try { byte[] encryptedEan = mwkCipher.doFinal(eanBlock); encryptedEanHex = StringUtil.toHexString(encryptedEan); } catch (IllegalStateException e) { Debug.logError(e, module); } catch (IllegalBlockSizeException e) { Debug.logError(e, module); } catch (BadPaddingException e) { Debug.logError(e, module); } if (debug) { Debug.logInfo("encryptPin : " + pin + " / " + encryptedEanHex, module); } return encryptedEanHex; }
public static String receiveAppletRequest( HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); String sessionId = request.getParameter("sessionId"); String visitId = request.getParameter("visitId"); sessionId = sessionId.trim(); visitId = visitId.trim(); String responseString = "ERROR"; GenericValue visit = null; try { visit = delegator.findOne("Visit", false, "visitId", visitId); } catch (GenericEntityException e) { Debug.logError(e, "Cannot Visit Object", module); } if (visit.getString("sessionId").equals(sessionId)) { String currentPage = request.getParameter("currentPage"); if (appletSessions.containsKey(sessionId)) { Map<String, String> sessionMap = appletSessions.get(sessionId); String followers = sessionMap.get("followers"); List<String> folList = StringUtil.split(followers, ","); for (String follower : folList) { Map<String, String> folSesMap = UtilMisc.toMap("followPage", currentPage); appletSessions.put(follower, folSesMap); } } responseString = "OK"; } try { PrintWriter out = response.getWriter(); response.setContentType("text/plain"); out.println(responseString); out.close(); } catch (IOException e) { Debug.logError(e, "Problems writing servlet output!", module); } return "success"; }
/** * Decrypt an encrypted pin using the configured keys * * @param pin Hex String of the encrypted pin (EAN) * @return Plain text String of the pin */ public String decryptPin(String pin) { // get the Cipher Cipher mwkCipher = this.getCipher(this.getMwkKey(), Cipher.DECRYPT_MODE); // decrypt pin String decryptedPinString = null; try { byte[] decryptedEan = mwkCipher.doFinal(StringUtil.fromHexString(pin)); byte[] decryptedPin = getByteRange(decryptedEan, 8, 8); decryptedPinString = new String(decryptedPin); } catch (IllegalStateException e) { Debug.logError(e, module); } catch (IllegalBlockSizeException e) { Debug.logError(e, module); } catch (BadPaddingException e) { Debug.logError(e, module); } if (debug) { Debug.logInfo("decryptPin : " + pin + " / " + decryptedPinString, module); } return decryptedPinString; }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Delegator delegator = (Delegator) httpRequest.getSession().getServletContext().getAttribute("delegator"); // Get ServletContext ServletContext servletContext = config.getServletContext(); ContextFilter.setCharacterEncoding(request); // Set request attribute and session UrlServletHelper.setRequestAttributes(request, delegator, servletContext); // set initial parameters String initDefaultLocalesString = config.getInitParameter("defaultLocaleString"); String initRedirectUrl = config.getInitParameter("redirectUrl"); defaultLocaleString = UtilValidate.isNotEmpty(initDefaultLocalesString) ? initDefaultLocalesString : ""; redirectUrl = UtilValidate.isNotEmpty(initRedirectUrl) ? initRedirectUrl : ""; String pathInfo = httpRequest.getServletPath(); if (UtilValidate.isNotEmpty(pathInfo)) { List<String> pathElements = StringUtil.split(pathInfo, "/"); String alternativeUrl = pathElements.get(0); String productId = null; String productCategoryId = null; String urlContentId = null; try { // look for productId if (alternativeUrl.endsWith("-p")) { List<EntityCondition> productContentConds = FastList.newInstance(); productContentConds.add( EntityCondition.makeCondition("productContentTypeId", "ALTERNATIVE_URL")); productContentConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productContentInfos = EntityQuery.use(delegator) .from("ProductContentAndInfo") .where(productContentConds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productContentInfos)) { for (GenericValue productContentInfo : productContentInfos) { String contentId = (String) productContentInfo.get("contentId"); List<GenericValue> ContentAssocDataResourceViewTos = EntityQuery.use(delegator) .from("ContentAssocDataResourceViewTo") .where( "contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) { for (GenericValue ContentAssocDataResourceViewTo : ContentAssocDataResourceViewTos) { GenericValue ElectronicText = ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productIdStr = null; productIdStr = alternativeUrl.replace(textData + "-", ""); productIdStr = productIdStr.replace("-p", ""); String checkProductId = (String) productContentInfo.get("productId"); if (productIdStr.equalsIgnoreCase(checkProductId)) { productId = checkProductId; break; } } } } } if (UtilValidate.isEmpty(productId)) { List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator) .from("ContentDataResourceView") .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); for (GenericValue contentDataResourceView : contentDataResourceViews) { GenericValue ElectronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productIdStr = null; productIdStr = alternativeUrl.replace(textData + "-", ""); productIdStr = productIdStr.replace("-p", ""); String checkProductId = (String) productContentInfo.get("productId"); if (productIdStr.equalsIgnoreCase(checkProductId)) { productId = checkProductId; break; } } } } } } } } } // look for productCategoryId if (alternativeUrl.endsWith("-c")) { List<EntityCondition> productCategoryContentConds = FastList.newInstance(); productCategoryContentConds.add( EntityCondition.makeCondition("prodCatContentTypeId", "ALTERNATIVE_URL")); productCategoryContentConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryContentInfos = EntityQuery.use(delegator) .from("ProductCategoryContentAndInfo") .where(productCategoryContentConds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productCategoryContentInfos)) { for (GenericValue productCategoryContentInfo : productCategoryContentInfos) { String contentId = (String) productCategoryContentInfo.get("contentId"); List<GenericValue> ContentAssocDataResourceViewTos = EntityQuery.use(delegator) .from("ContentAssocDataResourceViewTo") .where( "contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) { for (GenericValue ContentAssocDataResourceViewTo : ContentAssocDataResourceViewTos) { GenericValue ElectronicText = ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productCategoryStr = null; productCategoryStr = alternativeUrl.replace(textData + "-", ""); productCategoryStr = productCategoryStr.replace("-c", ""); String checkProductCategoryId = (String) productCategoryContentInfo.get("productCategoryId"); if (productCategoryStr.equalsIgnoreCase(checkProductCategoryId)) { productCategoryId = checkProductCategoryId; break; } } } } } } if (UtilValidate.isEmpty(productCategoryId)) { List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator) .from("ContentDataResourceView") .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT") .cache(true) .queryList(); for (GenericValue contentDataResourceView : contentDataResourceViews) { GenericValue ElectronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); if (UtilValidate.isNotEmpty(ElectronicText)) { String textData = (String) ElectronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productCategoryStr = null; productCategoryStr = alternativeUrl.replace(textData + "-", ""); productCategoryStr = productCategoryStr.replace("-c", ""); String checkProductCategoryId = (String) productCategoryContentInfo.get("productCategoryId"); if (productCategoryStr.equalsIgnoreCase(checkProductCategoryId)) { productCategoryId = checkProductCategoryId; break; } } } } } } } } } } catch (GenericEntityException e) { Debug.logWarning("Cannot look for product and product category", module); } // generate forward URL StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("/" + CONTROL_MOUNT_POINT); if (UtilValidate.isNotEmpty(productId)) { try { List<EntityCondition> conds = FastList.newInstance(); conds.add(EntityCondition.makeCondition("productId", productId)); conds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryMembers = EntityQuery.use(delegator) .select("productCategoryId") .from("ProductCategoryMember") .where(conds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productCategoryMembers)) { GenericValue productCategoryMember = EntityUtil.getFirst(productCategoryMembers); productCategoryId = productCategoryMember.getString("productCategoryId"); } } catch (GenericEntityException e) { Debug.logError(e, "Cannot find product category for product: " + productId, module); } urlBuilder.append("/" + PRODUCT_REQUEST); } else { urlBuilder.append("/" + CATEGORY_REQUEST); } // generate trail belong to a top category String topCategoryId = CategoryWorker.getCatalogTopCategory(httpRequest, null); List<GenericValue> trailCategories = CategoryWorker.getRelatedCategoriesRet( httpRequest, "trailCategories", topCategoryId, false, false, true); List<String> trailCategoryIds = EntityUtil.getFieldListFromEntityList(trailCategories, "productCategoryId", true); // look for productCategoryId from productId if (UtilValidate.isNotEmpty(productId)) { try { List<EntityCondition> rolllupConds = FastList.newInstance(); rolllupConds.add(EntityCondition.makeCondition("productId", productId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryMembers = EntityQuery.use(delegator) .from("ProductCategoryMember") .where(rolllupConds) .orderBy("-fromDate") .cache(true) .queryList(); for (GenericValue productCategoryMember : productCategoryMembers) { String trailCategoryId = productCategoryMember.getString("productCategoryId"); if (trailCategoryIds.contains(trailCategoryId)) { productCategoryId = trailCategoryId; break; } } } catch (GenericEntityException e) { Debug.logError(e, "Cannot generate trail from product category", module); } } // generate trail elements from productCategoryId if (UtilValidate.isNotEmpty(productCategoryId)) { List<String> trailElements = FastList.newInstance(); trailElements.add(productCategoryId); String parentProductCategoryId = productCategoryId; while (UtilValidate.isNotEmpty(parentProductCategoryId)) { // find product category rollup try { List<EntityCondition> rolllupConds = FastList.newInstance(); rolllupConds.add( EntityCondition.makeCondition("productCategoryId", parentProductCategoryId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryRollups = EntityQuery.use(delegator) .from("ProductCategoryRollup") .where(rolllupConds) .orderBy("-fromDate") .cache(true) .queryList(); if (UtilValidate.isNotEmpty(productCategoryRollups)) { // add only categories that belong to the top category to trail for (GenericValue productCategoryRollup : productCategoryRollups) { String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId"); parentProductCategoryId = trailCategoryId; if (trailCategoryIds.contains(trailCategoryId)) { trailElements.add(trailCategoryId); break; } } } else { parentProductCategoryId = null; } } catch (GenericEntityException e) { Debug.logError(e, "Cannot generate trail from product category", module); } } Collections.reverse(trailElements); List<String> trail = CategoryWorker.getTrail(httpRequest); if (trail == null) { trail = FastList.newInstance(); } // adjust trail String previousCategoryId = null; if (trail.size() > 0) { previousCategoryId = trail.get(trail.size() - 1); } trail = CategoryWorker.adjustTrail(trail, productCategoryId, previousCategoryId); if (trailElements.size() == 1) { CategoryWorker.setTrail(request, trailElements.get(0), null); } else if (trailElements.size() == 2) { CategoryWorker.setTrail(request, trailElements.get(1), trailElements.get(0)); } else if (trailElements.size() > 2) { if (trail.contains(trailElements.get(0))) { // first category is in the trail, so remove it everything after that and fill it in // with the list from the pathInfo int firstElementIndex = trail.indexOf(trailElements.get(0)); while (trail.size() > firstElementIndex) { trail.remove(firstElementIndex); } trail.addAll(trailElements); } else { // first category is NOT in the trail, so clear out the trail and use the trailElements // list trail.clear(); trail.addAll(trailElements); } CategoryWorker.setTrail(request, trail); } request.setAttribute("productCategoryId", productCategoryId); if (productId != null) { request.setAttribute("product_id", productId); request.setAttribute("productId", productId); } } // Set view query parameters UrlServletHelper.setViewQueryParameters(request, urlBuilder); if (UtilValidate.isNotEmpty(productId) || UtilValidate.isNotEmpty(productCategoryId) || UtilValidate.isNotEmpty(urlContentId)) { Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); ContextFilter.setAttributesFromRequestBody(request); RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString()); dispatch.forward(request, response); return; } // Check path alias UrlServletHelper.checkPathAlias(request, httpResponse, delegator, pathInfo); } // we're done checking; continue on chain.doFilter(request, response); }
public static Map<String, Object> getExpressCheckout( DispatchContext dctx, Map<String, Object> context) { Locale locale = (Locale) context.get("locale"); LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); ShoppingCart cart = (ShoppingCart) context.get("cart"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null); if (payPalConfig == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale)); } NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "GetExpressCheckoutDetails"); String token = (String) cart.getAttribute("payPalCheckoutToken"); if (UtilValidate.isNotEmpty(token)) { encoder.add("TOKEN", token); } else { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale)); } NVPDecoder decoder; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) { cart.addOrderNote(decoder.get("NOTE")); } if (cart.getUserLogin() == null) { try { GenericValue userLogin = EntityQuery.use(delegator) .from("UserLogin") .where("userLoginId", "anonymous") .queryOne(); try { cart.setUserLogin(userLogin, dispatcher); } catch (CartItemModifyException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId")); // Even if anon, a party could already have been created String partyId = cart.getOrderPartyId(); if (partyId == null && anon) { // Check nothing has been set on the anon userLogin either partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null; cart.setOrderPartyId(partyId); } if (partyId != null) { GenericValue party = null; try { party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne(); } catch (GenericEntityException e) { Debug.logError(e, module); } if (party == null) { partyId = null; } } Map<String, Object> inMap = FastMap.newInstance(); Map<String, Object> outMap = null; // Create the person if necessary boolean newParty = false; if (partyId == null) { newParty = true; inMap.put("userLogin", cart.getUserLogin()); inMap.put("personalTitle", decoder.get("SALUTATION")); inMap.put("firstName", decoder.get("FIRSTNAME")); inMap.put("middleName", decoder.get("MIDDLENAME")); inMap.put("lastName", decoder.get("LASTNAME")); inMap.put("suffix", decoder.get("SUFFIX")); try { outMap = dispatcher.runSync("createPerson", inMap); partyId = (String) outMap.get("partyId"); cart.setOrderPartyId(partyId); cart.getUserLogin().setString("partyId", partyId); inMap.clear(); inMap.put("userLogin", cart.getUserLogin()); inMap.put("partyId", partyId); inMap.put("roleTypeId", "CUSTOMER"); dispatcher.runSync("createPartyRole", inMap); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } // Create a new email address if necessary String emailContactMechId = null; String emailContactPurposeTypeId = "PRIMARY_EMAIL"; String emailAddress = decoder.get("EMAIL"); if (!newParty) { EntityCondition cond = EntityCondition.makeCondition( UtilMisc.toList( EntityCondition.makeCondition( UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")), EntityCondition.makeCondition( EntityFunction.UPPER_FIELD("infoString"), EntityComparisonOperator.EQUALS, EntityFunction.UPPER(emailAddress)))); try { GenericValue matchingEmail = EntityQuery.use(delegator) .from("PartyAndContactMech") .where(cond) .orderBy("fromDate") .filterByDate() .queryFirst(); if (matchingEmail != null) { emailContactMechId = matchingEmail.getString("contactMechId"); } else { // No email found so we'll need to create one but first check if it should be PRIMARY or // just BILLING long primaryEmails = EntityQuery.use(delegator) .from("PartyContactWithPurpose") .where( "partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS", "contactMechPurposeTypeId", "PRIMARY_EMAIL") .filterByDate( "contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate") .queryCount(); if (primaryEmails > 0) emailContactPurposeTypeId = "BILLING_EMAIL"; } } catch (GenericEntityException e) { Debug.logError(e, module); } } if (emailContactMechId == null) { inMap.clear(); inMap.put("userLogin", cart.getUserLogin()); inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId); inMap.put("emailAddress", emailAddress); inMap.put("partyId", partyId); inMap.put("roleTypeId", "CUSTOMER"); inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us inMap.put("fromDate", UtilDateTime.nowTimestamp()); try { outMap = dispatcher.runSync("createPartyEmailAddress", inMap); emailContactMechId = (String) outMap.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } cart.addContactMech("ORDER_EMAIL", emailContactMechId); // Phone number String phoneNumber = decoder.get("PHONENUM"); String phoneContactId = null; if (phoneNumber != null) { inMap.clear(); if (phoneNumber.startsWith("+")) { // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber String[] phoneNumbers = phoneNumber.split(" "); inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0])); inMap.put("contactNumber", phoneNumbers[1]); } else { // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber inMap.put("countryCode", "1"); String[] phoneNumbers = phoneNumber.split("-"); inMap.put("areaCode", phoneNumbers[0]); inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]); } inMap.put("userLogin", cart.getUserLogin()); inMap.put("partyId", partyId); try { outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap); phoneContactId = (String) outMap.get("contactMechId"); cart.addContactMech("PHONE_BILLING", phoneContactId); } catch (GenericServiceException e) { Debug.logError(e, module); } } // Create a new Postal Address if necessary String postalContactId = null; boolean needsShippingPurpose = true; // if the cart for some reason already has a billing address, we'll leave it be boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null); Map<String, Object> postalMap = FastMap.newInstance(); postalMap.put("toName", decoder.get("SHIPTONAME")); postalMap.put("address1", decoder.get("SHIPTOSTREET")); postalMap.put("address2", decoder.get("SHIPTOSTREET2")); postalMap.put("city", decoder.get("SHIPTOCITY")); String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator); postalMap.put("countryGeoId", countryGeoId); postalMap.put( "stateProvinceGeoId", parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator)); postalMap.put("postalCode", decoder.get("SHIPTOZIP")); if (!newParty) { // We want an exact match only EntityCondition cond = EntityCondition.makeCondition( UtilMisc.toList( EntityCondition.makeCondition(postalMap), EntityCondition.makeCondition( UtilMisc.toMap( "attnName", null, "directions", null, "postalCodeExt", null, "postalCodeGeoId", null)), EntityCondition.makeCondition("partyId", partyId))); try { GenericValue postalMatch = EntityQuery.use(delegator) .from("PartyAndPostalAddress") .where(cond) .orderBy("fromDate") .filterByDate() .queryFirst(); if (postalMatch != null) { postalContactId = postalMatch.getString("contactMechId"); List<GenericValue> postalPurposes = EntityQuery.use(delegator) .from("PartyContactMechPurpose") .where("partyId", partyId, "contactMechId", postalContactId) .filterByDate() .queryList(); List<Object> purposeStrings = EntityUtil.getFieldListFromEntityList( postalPurposes, "contactMechPurposeTypeId", false); if (UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("SHIPPING_LOCATION")) { needsShippingPurpose = false; } if (needsBillingPurpose && UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("BILLING_LOCATION")) { needsBillingPurpose = false; } } } catch (GenericEntityException e) { Debug.logError(e, module); } } if (postalContactId == null) { postalMap.put("userLogin", cart.getUserLogin()); postalMap.put("fromDate", UtilDateTime.nowTimestamp()); try { outMap = dispatcher.runSync("createPartyPostalAddress", postalMap); postalContactId = (String) outMap.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } } if (needsShippingPurpose || needsBillingPurpose) { inMap.clear(); inMap.put("userLogin", cart.getUserLogin()); inMap.put("contactMechId", postalContactId); inMap.put("partyId", partyId); try { if (needsShippingPurpose) { inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION"); dispatcher.runSync("createPartyContactMechPurpose", inMap); } if (needsBillingPurpose) { inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION"); dispatcher.runSync("createPartyContactMechPurpose", inMap); } } catch (GenericServiceException e) { // Not the end of the world, we'll carry on Debug.logInfo(e.getMessage(), module); } } // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work // with is the shipping option label // that was shown to the customer String shipMethod = decoder.get("SHIPPINGOPTIONNAME"); if ("Calculated Offline".equals(shipMethod)) { cart.setAllCarrierPartyId("_NA_"); cart.setAllShipmentMethodTypeId("NO_SHIPPING"); } else { String[] shipMethodSplit = shipMethod.split(" - "); cart.setAllCarrierPartyId(shipMethodSplit[0]); String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length); try { GenericValue shipmentMethod = EntityQuery.use(delegator) .from("ProductStoreShipmentMethView") .where( "productStoreId", cart.getProductStoreId(), "partyId", shipMethodSplit[0], "roleTypeId", "CARRIER", "description", shippingMethodTypeDesc) .queryFirst(); cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId")); } catch (GenericEntityException e1) { Debug.logError(e1, module); } } // Get rid of any excess ship groups List<CartShipInfo> shipGroups = cart.getShipGroups(); for (int i = 1; i < shipGroups.size(); i++) { Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i); for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) { cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false); } } cart.cleanUpShipGroups(); cart.setAllShippingContactMechId(postalContactId); Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0); if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) { return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE)); } BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal"); if (shippingTotal == null) { shippingTotal = BigDecimal.ZERO; } cart.setItemShipGroupEstimate(shippingTotal, 0); CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart); try { cho.calcAndAddTax(); } catch (GeneralException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // Create the PayPal payment method inMap.clear(); inMap.put("userLogin", cart.getUserLogin()); inMap.put("partyId", partyId); inMap.put("contactMechId", postalContactId); inMap.put("fromDate", UtilDateTime.nowTimestamp()); inMap.put("payerId", decoder.get("PAYERID")); inMap.put("expressCheckoutToken", token); inMap.put("payerStatus", decoder.get("PAYERSTATUS")); try { outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } String paymentMethodId = (String) outMap.get("paymentMethodId"); cart.clearPayments(); BigDecimal maxAmount = cart.getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP); cart.addPaymentAmount(paymentMethodId, maxAmount, true); return ServiceUtil.returnSuccess(); }
public static void setViewQueryParameters(ServletRequest request, StringBuilder urlBuilder) { HttpServletRequest httpRequest = (HttpServletRequest) request; if (UtilValidate.isEmpty(httpRequest.getServletPath())) { return; } String pathInfo = httpRequest.getServletPath(); String viewIndex = null; String viewSize = null; String viewSort = null; String searchString = null; int queryStringIndex = pathInfo.indexOf("?"); if (queryStringIndex >= 0) { List<String> queryStringTokens = StringUtil.split(pathInfo.substring(queryStringIndex + 1), "&"); for (String queryStringToken : queryStringTokens) { int equalIndex = queryStringToken.indexOf("="); String name = queryStringToken.substring(0, equalIndex - 1); String value = queryStringToken.substring(equalIndex + 1, queryStringToken.length() - 1); if ("viewIndex".equals(name)) { viewIndex = value; } else if ("viewSize".equals(name)) { viewSize = value; } else if ("viewSort".equals(name)) { viewSort = value; } else if ("searchString".equals(name)) { searchString = value; } } } if (UtilValidate.isNotEmpty(httpRequest.getParameter("viewIndex"))) { viewIndex = httpRequest.getParameter("viewIndex"); } if (UtilValidate.isNotEmpty(httpRequest.getParameter("viewSize"))) { viewSize = httpRequest.getParameter("viewSize"); } if (UtilValidate.isNotEmpty(httpRequest.getParameter("viewSort"))) { viewSort = httpRequest.getParameter("viewSort"); } if (UtilValidate.isNotEmpty(httpRequest.getParameter("searchString"))) { searchString = httpRequest.getParameter("searchString"); } // Set query string parameters to url if (UtilValidate.isNotEmpty(viewIndex)) { urlBuilder.append("/~VIEW_INDEX=" + viewIndex); request.setAttribute("VIEW_INDEX", viewIndex); } if (UtilValidate.isNotEmpty(viewSize)) { urlBuilder.append("/~VIEW_SIZE=" + viewSize); request.setAttribute("VIEW_SIZE", viewSize); } if (UtilValidate.isNotEmpty(viewSort)) { urlBuilder.append("/~VIEW_SORT=" + viewSort); request.setAttribute("VIEW_SORT", viewSort); } if (UtilValidate.isNotEmpty(searchString)) { urlBuilder.append("/~SEARCH_STRING=" + searchString); request.setAttribute("SEARCH_STRING", searchString); } }
private StringBuffer outputKeyCreation(int loop, boolean kekOnly, String kekTest) { StringBuffer buf = new StringBuffer(); loop++; if (loop > 100) { // only loop 100 times; then throw an exception throw new IllegalStateException("Unable to create 128 byte keys in 100 tries"); } // place holder for the keys DHPrivateKey privateKey = null; DHPublicKey publicKey = null; if (!kekOnly) { KeyPair keyPair = null; try { keyPair = this.createKeys(); } catch (NoSuchAlgorithmException e) { Debug.logError(e, module); } catch (InvalidAlgorithmParameterException e) { Debug.logError(e, module); } catch (InvalidKeySpecException e) { Debug.logError(e, module); } if (keyPair != null) { publicKey = (DHPublicKey) keyPair.getPublic(); privateKey = (DHPrivateKey) keyPair.getPrivate(); if (publicKey == null || publicKey.getY().toByteArray().length != 128) { // run again until we get a 128 byte public key for VL return this.outputKeyCreation(loop, kekOnly, kekTest); } } else { Debug.logInfo("Returned a null KeyPair", module); return this.outputKeyCreation(loop, kekOnly, kekTest); } } else { // use our existing private key to generate a KEK try { privateKey = (DHPrivateKey) this.getPrivateKey(); } catch (Exception e) { Debug.logError(e, module); } } // the KEK byte[] kekBytes = null; try { kekBytes = this.generateKek(privateKey); } catch (NoSuchAlgorithmException e) { Debug.logError(e, module); } catch (InvalidKeySpecException e) { Debug.logError(e, module); } catch (InvalidKeyException e) { Debug.logError(e, module); } // the 3DES KEK value SecretKey loadedKek = this.getDesEdeKey(kekBytes); byte[] loadKekBytes = loadedKek.getEncoded(); // test the KEK Cipher cipher = this.getCipher(this.getKekKey(), Cipher.ENCRYPT_MODE); byte[] kekTestB = {0, 0, 0, 0, 0, 0, 0, 0}; byte[] kekTestC = new byte[0]; if (kekTest != null) { kekTestB = StringUtil.fromHexString(kekTest); } // encrypt the test bytes try { kekTestC = cipher.doFinal(kekTestB); } catch (Exception e) { Debug.logError(e, module); } if (!kekOnly) { // public key (just Y) BigInteger y = publicKey.getY(); byte[] yBytes = y.toByteArray(); String yHex = StringUtil.toHexString(yBytes); buf.append("======== Begin Public Key (Y @ ") .append(yBytes.length) .append(" / ") .append(yHex.length()) .append(") ========\n"); buf.append(yHex).append("\n"); buf.append("======== End Public Key ========\n\n"); // private key (just X) BigInteger x = privateKey.getX(); byte[] xBytes = x.toByteArray(); String xHex = StringUtil.toHexString(xBytes); buf.append("======== Begin Private Key (X @ ") .append(xBytes.length) .append(" / ") .append(xHex.length()) .append(") ========\n"); buf.append(xHex).append("\n"); buf.append("======== End Private Key ========\n\n"); // private key (full) byte[] privateBytes = privateKey.getEncoded(); String privateHex = StringUtil.toHexString(privateBytes); buf.append("======== Begin Private Key (Full @ ") .append(privateBytes.length) .append(" / ") .append(privateHex.length()) .append(") ========\n"); buf.append(privateHex).append("\n"); buf.append("======== End Private Key ========\n\n"); } if (kekBytes != null) { buf.append("======== Begin KEK (").append(kekBytes.length).append(") ========\n"); buf.append(StringUtil.toHexString(kekBytes)).append("\n"); buf.append("======== End KEK ========\n\n"); buf.append("======== Begin KEK (DES) (").append(loadKekBytes.length).append(") ========\n"); buf.append(StringUtil.toHexString(loadKekBytes)).append("\n"); buf.append("======== End KEK (DES) ========\n\n"); buf.append("======== Begin KEK Test (").append(kekTestC.length).append(") ========\n"); buf.append(StringUtil.toHexString(kekTestC)).append("\n"); buf.append("======== End KEK Test ========\n\n"); } else { Debug.logError("KEK came back empty", module); } return buf; }
protected byte[] getPrivateKeyBytes() { return StringUtil.fromHexString(this.getGenericValue().getString("privateKey")); }
protected byte[] getKek() { return StringUtil.fromHexString(this.getGenericValue().getString("exchangeKey")); }
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Delegator delegator = (Delegator) getServletContext().getAttribute("delegator"); String pathInfo = request.getPathInfo(); List<String> pathElements = StringUtil.split(pathInfo, "/"); // look for productId String productId = null; try { String lastPathElement = pathElements.get(pathElements.size() - 1); if (lastPathElement.startsWith("p_") || delegator.findOne("Product", UtilMisc.toMap("productId", lastPathElement), true) != null) { if (lastPathElement.startsWith("p_")) { productId = lastPathElement.substring(2); } else { productId = lastPathElement; } pathElements.remove(pathElements.size() - 1); } } catch (GenericEntityException e) { Debug.logError( e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), module); } // get category info going with the IDs that remain String categoryId = null; if (pathElements.size() == 1) { CategoryWorker.setTrail(request, pathElements.get(0), null); categoryId = pathElements.get(0); } else if (pathElements.size() == 2) { CategoryWorker.setTrail(request, pathElements.get(1), pathElements.get(0)); categoryId = pathElements.get(1); } else if (pathElements.size() > 2) { List<String> trail = CategoryWorker.getTrail(request); if (trail == null) { trail = FastList.newInstance(); } if (trail.contains(pathElements.get(0))) { // first category is in the trail, so remove it everything after that and fill it in with // the list from the pathInfo int firstElementIndex = trail.indexOf(pathElements.get(0)); while (trail.size() > firstElementIndex) { trail.remove(firstElementIndex); } trail.addAll(pathElements); } else { // first category is NOT in the trail, so clear out the trail and use the pathElements list trail.clear(); trail.addAll(pathElements); } CategoryWorker.setTrail(request, trail); categoryId = pathElements.get(pathElements.size() - 1); } if (categoryId != null) { request.setAttribute("productCategoryId", categoryId); } String rootCategoryId = null; if (pathElements.size() >= 1) { rootCategoryId = pathElements.get(0); } if (rootCategoryId != null) { request.setAttribute("rootCategoryId", rootCategoryId); } if (productId != null) { request.setAttribute("product_id", productId); request.setAttribute("productId", productId); } RequestDispatcher rd = request.getRequestDispatcher( "/" + CONTROL_MOUNT_POINT + "/" + (productId != null ? PRODUCT_REQUEST : CATEGORY_REQUEST)); rd.forward(request, response); }
protected byte[] getMwk() { return StringUtil.fromHexString(this.getGenericValue().getString("workingKey")); }