/** * 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; }
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 static Process getInstance(EntityPersistentMgr mgr, String processId) throws PersistenceException { Process proc = new Process(mgr, SharkContainer.getDelegator(), processId); if (proc.isLoaded()) { Debug.logInfo("Returning loaded Process", module); return proc; } Debug.logInfo("Returning null Process ID : " + processId, module); if (processId == null) Debug.logError(new Exception(), module); return null; }
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; }
public static Map<String, Object> convertOrderIdListToHeaders( DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); List<GenericValue> orderHeaderList = UtilGenerics.checkList(context.get("orderHeaderList")); List<String> orderIdList = UtilGenerics.checkList(context.get("orderIdList")); // we don't want to process if there is already a header list if (orderHeaderList == null) { // convert the ID list to headers if (orderIdList != null) { List<EntityCondition> conditionList1 = FastList.newInstance(); List<EntityCondition> conditionList2 = FastList.newInstance(); // we are only concerned about approved sales orders conditionList2.add( EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED")); conditionList2.add( EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER")); // build the expression list from the IDs for (String orderId : orderIdList) { conditionList1.add( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId)); } // create the conditions EntityCondition idCond = EntityCondition.makeCondition(conditionList1, EntityOperator.OR); conditionList2.add(idCond); EntityCondition cond = EntityCondition.makeCondition(conditionList2, EntityOperator.AND); // run the query try { orderHeaderList = delegator.findList( "OrderHeader", cond, null, UtilMisc.toList("+orderDate"), null, false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } Debug.logInfo("Recieved orderIdList - " + orderIdList, module); Debug.logInfo("Found orderHeaderList - " + orderHeaderList, module); } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("orderHeaderList", orderHeaderList); return result; }
/** * 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; }
/** * 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); }
/** * 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 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; }
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; } }
@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; }
/** * Finds or creates a specialized (auto-save) shopping list used to record shopping bag contents * between user visits. */ public static String getAutoSaveListId( Delegator delegator, LocalDispatcher dispatcher, String partyId, GenericValue userLogin, String productStoreId) throws GenericEntityException, GenericServiceException { if (partyId == null && userLogin != null) { partyId = userLogin.getString("partyId"); } String autoSaveListId = null; GenericValue list = null; // TODO: add sorting, just in case there are multiple... if (partyId != null) { Map<String, Object> findMap = UtilMisc.<String, Object>toMap( "partyId", partyId, "productStoreId", productStoreId, "shoppingListTypeId", "SLT_SPEC_PURP", "listName", PERSISTANT_LIST_NAME); List<GenericValue> existingLists = EntityQuery.use(delegator).from("ShoppingList").where(findMap).queryList(); Debug.logInfo( "Finding existing auto-save shopping list with: \nfindMap: " + findMap + "\nlists: " + existingLists, module); if (UtilValidate.isNotEmpty(existingLists)) { list = EntityUtil.getFirst(existingLists); autoSaveListId = list.getString("shoppingListId"); } } if (list == null && dispatcher != null) { Map<String, Object> listFields = UtilMisc.<String, Object>toMap( "userLogin", userLogin, "productStoreId", productStoreId, "shoppingListTypeId", "SLT_SPEC_PURP", "listName", PERSISTANT_LIST_NAME); Map<String, Object> newListResult = dispatcher.runSync("createShoppingList", listFields); if (newListResult != null) { autoSaveListId = (String) newListResult.get("shoppingListId"); } } return autoSaveListId; }
@Override public int doEndTag() { try { BodyContent body = getBodyContent(); if (body != null) { JspWriter out = body.getEnclosingWriter(); String bodyString = body.getString(); body.clearBody(); out.print(bodyString); } } catch (IOException e) { Debug.logInfo("IteratorTag IO Error", module); Debug.logInfo(e, module); } return EVAL_PAGE; }
public void run() { Debug.logInfo("Starting JMS Listener Factory Thread", module); while (firstPass || connected < loadable) { if (Debug.verboseOn()) Debug.logVerbose( "First Pass: "******" Connected: " + connected + " Available: " + loadable, module); this.loadListeners(); firstPass = false; try { Thread.sleep(20000); } catch (InterruptedException ie) { } continue; } Debug.logInfo("JMS Listener Factory Thread Finished; All listeners connected.", module); }
protected ValueLinkApi(Delegator delegator, Properties props) { String mId = (String) props.get("payment.valuelink.merchantId"); String tId = (String) props.get("payment.valuelink.terminalId"); this.delegator = delegator; this.merchantId = mId; this.terminalId = tId; this.props = props; if ("Y".equalsIgnoreCase((String) props.get("payment.valuelink.debug"))) { this.debug = true; } if (debug) { Debug.logInfo("New ValueLinkApi instance created", module); Debug.logInfo("Merchant ID : " + merchantId, module); Debug.logInfo("Terminal ID : " + terminalId, module); } }
public void remove() throws GenericEntityException { if (!newValue) { delegator.removeValue(process); Debug.logInfo("**** REMOVED : " + this, module); } delegator.removeByAnd( org.ofbiz.shark.SharkConstants.WfRequester, UtilMisc.toMap(org.ofbiz.shark.SharkConstants.processId, this.getId())); }
/** * 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); } }
/** * 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; }
@Override public boolean exec(MethodContext methodContext) { Object fieldVal = null; if (!mapAcsr.isEmpty()) { Map<String, ? extends Object> fromMap = mapAcsr.get(methodContext); if (fromMap == null) { if (Debug.infoOn()) Debug.logInfo( "Map not found with name " + mapAcsr + ", not copying from this map", module); return true; } fieldVal = fieldAcsr.get(fromMap, methodContext); } else { // no map name, try the env fieldVal = fieldAcsr.get(methodContext); } if (fieldVal == null) { if (Debug.verboseOn()) Debug.logVerbose( "Field value not found with name " + fieldAcsr + " in Map with name " + mapAcsr + ", not copying field", module); return true; } // note that going to an env field will only work if it came from an env // field because if not specified the to-map-name will be set to the map-name // to go from a map field to an env field, use the field-to-env operation Map<String, Object> toMap = null; if (!toMapAcsr.isEmpty()) { toMap = toMapAcsr.get(methodContext); if (toMap == null) { if (Debug.verboseOn()) Debug.logVerbose("Map not found with name " + toMapAcsr + ", creating new map", module); toMap = FastMap.newInstance(); toMapAcsr.put(methodContext, toMap); } toFieldAcsr.put(toMap, fieldVal, methodContext); } else { // no to-map, so put in env toFieldAcsr.put(methodContext, fieldVal); } return true; }
/** * Processes the request and returns an AuthorizeResponse. This service causes a * GenericServiceException if there is a fatal confguration error that must be addressed. */ private static AuthorizeResponse processRequest(Map request, String resource) throws GenericServiceException { boolean testMode = isTestMode(resource); String url = UtilProperties.getPropertyValue(resource, "payment.authorizedotnet.url"); if (UtilValidate.isEmpty(url)) { throw new GenericServiceException( "Authorize.NET transaction URL not configured. Please ensure payment.authorizedotnet.test is defined in " + resource); } Debug.logInfo("Sending eCheck.NET request type " + request.get("x_type"), module); if (testMode) { Debug.logInfo("Request URL: " + url, module); Debug.logInfo("Request Map: " + request, module); } // post the request to the url String responseString = null; try { HttpClient client = new HttpClient(url, request); client.setClientCertificateAlias("AUTHORIZE_NET"); responseString = client.post(); } catch (HttpClientException e) { Debug.logError( e, "Failed to send eCheck.NET request due to client exception: " + e.getMessage(), module); return null; } if (testMode) { Debug.logInfo("Response from eCheck.NET: " + responseString, module); } return new AuthorizeResponse(responseString); }
/** * Returns the current working key index * * @return Long number of the current working key index */ public Long getWorkingKeyIndex() { if (this.mwkIndex == null) { synchronized (this) { if (this.mwkIndex == null) { this.mwkIndex = this.getGenericValue().getLong("workingKeyIndex"); } } } if (debug) { Debug.logInfo("Current Working Key Index : " + this.mwkIndex, module); } return this.mwkIndex; }
public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); // get/create the visit // NOTE: don't create the visit here, just let the control servlet do it; GenericValue visit = // VisitHandler.getVisit(session); countCreateSession(); // property setting flag for logging stats if (System.getProperty("org.ofbiz.log.session.stats") != null) { session.setAttribute("org.ofbiz.log.session.stats", "Y"); } Debug.logInfo("Creating session: " + session.getId(), module); }
public static void getRelatedCategories( ServletRequest request, String attributeName, boolean limitView) { Map<String, Object> requestParameters = UtilHttp.getParameterMap((HttpServletRequest) request); String requestId = null; requestId = UtilFormatOut.checkNull( (String) requestParameters.get("catalog_id"), (String) requestParameters.get("CATALOG_ID"), (String) requestParameters.get("category_id"), (String) requestParameters.get("CATEGORY_ID")); if (requestId.equals("")) return; if (Debug.infoOn()) Debug.logInfo("[CategoryWorker.getRelatedCategories] RequestID: " + requestId, module); getRelatedCategories(request, attributeName, requestId, limitView); }
/** * @see org.ofbiz.webapp.event.EventHandler#invoke(Event, * org.ofbiz.webapp.control.ConfigXMLReader.RequestMap, HttpServletRequest, * HttpServletResponse) */ public String invoke( Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException { String report = request.getParameter("echo"); if (report != null) { StringBuilder buf = new StringBuilder(); try { // read the inputstream buffer String line; BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); while ((line = reader.readLine()) != null) { buf.append(line).append("\n"); } } catch (Exception e) { throw new EventHandlerException(e.getMessage(), e); } Debug.logInfo("Echo: " + buf.toString(), module); // echo back the request try { response.setContentType("text/xml"); Writer out = response.getWriter(); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.write("<methodResponse>"); out.write("<params><param>"); out.write("<value><string><![CDATA["); out.write(buf.toString()); out.write("]]></string></value>"); out.write("</param></params>"); out.write("</methodResponse>"); out.flush(); } catch (Exception e) { throw new EventHandlerException(e.getMessage(), e); } } else { try { this.execute(this.getXmlRpcConfig(request), new HttpStreamConnection(request, response)); } catch (XmlRpcException e) { Debug.logError(e, module); throw new EventHandlerException(e.getMessage(), e); } } return null; }
private void createAndSendSOAPResponse( Map<String, Object> serviceResults, String serviceName, HttpServletResponse response) throws EventHandlerException { try { // setup the response Debug.logVerbose("[EventHandler] : Setting up response message", module); String xmlResults = SoapSerializer.serialize(serviceResults); // Debug.logInfo("xmlResults ==================" + xmlResults, module); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xmlResults)); StAXOMBuilder resultsBuilder = new StAXOMBuilder(reader); OMElement resultSer = resultsBuilder.getDocumentElement(); // create the response soap SOAPFactory factory = OMAbstractFactory.getSOAP11Factory(); SOAPEnvelope resEnv = factory.createSOAPEnvelope(); SOAPBody resBody = factory.createSOAPBody(); OMElement resService = factory.createOMElement(new QName(serviceName + "Response")); resService.addChild(resultSer.getFirstElement()); resBody.addChild(resService); resEnv.addChild(resBody); // The declareDefaultNamespace method doesn't work see // (https://issues.apache.org/jira/browse/AXIS2-3156) // so the following doesn't work: // resService.declareDefaultNamespace(ModelService.TNS); // instead, create the xmlns attribute directly: OMAttribute defaultNS = factory.createOMAttribute("xmlns", null, ModelService.TNS); resService.addAttribute(defaultNS); // log the response message if (Debug.verboseOn()) { try { Debug.logInfo("Response Message:\n" + resEnv + "\n", module); } catch (Throwable t) { } } resEnv.serialize(response.getOutputStream()); response.getOutputStream().flush(); } catch (Exception e) { Debug.logError(e, module); throw new EventHandlerException(e.getMessage(), e); } }
/** @see javax.servlet.Servlet#init(javax.servlet.ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); if (Debug.infoOn()) Debug.logInfo( "LOADING WEBAPP [" + config.getServletContext().getContextPath().substring(1) + "] " + config.getServletContext().getServletContextName() + ", located at " + config.getServletContext().getRealPath("/"), module); // configure custom BSF engines configureBsf(); // initialize the request handler getRequestHandler(); }
// Load the JMS listeners private void loadListeners() { try { Element rootElement = ServiceConfigUtil.getXmlRootElement(); NodeList nodeList = rootElement.getElementsByTagName("jms-service"); if (Debug.verboseOn()) Debug.logVerbose("[ServiceDispatcher] : Loading JMS Listeners.", module); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); StringBuilder serverKey = new StringBuilder(); for (Element server : UtilXml.childElementList(element, "server")) { try { String listenerEnabled = server.getAttribute("listen"); if (listenerEnabled.equalsIgnoreCase("true")) { // create a server key serverKey.append(server.getAttribute("jndi-server-name") + ":"); serverKey.append(server.getAttribute("jndi-name") + ":"); serverKey.append(server.getAttribute("topic-queue")); // store the server element servers.put(serverKey.toString(), server); // load the listener GenericMessageListener listener = loadListener(serverKey.toString(), server); // store the listener w/ the key if (serverKey.length() > 0 && listener != null) listeners.put(serverKey.toString(), listener); } } catch (GenericServiceException gse) { Debug.logInfo( "Cannot load message listener " + serverKey + " error: (" + gse.toString() + ").", module); } catch (Exception e) { Debug.logError(e, "Uncaught exception.", module); } } } } catch (org.ofbiz.base.config.GenericConfigException gce) { Debug.logError(gce, "Cannot get serviceengine.xml root element.", module); } catch (Exception e) { Debug.logError(e, "Uncaught exception.", module); } }
/** * 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; }