List of usage examples for org.w3c.dom Node getFirstChild
public Node getFirstChild();
From source file:org.dasein.cloud.aws.platform.SNS.java
@Override public String confirmSubscription(String providerTopicId, String token, boolean authenticateUnsubscribe) throws CloudException, InternalException { APITrace.begin(provider, "Notifications.confirmSubscription"); try {//w w w. j a va 2 s .co m Map<String, String> parameters = provider.getStandardSnsParameters(provider.getContext(), CONFIRM_SUBSCRIPTION); EC2Method method; NodeList blocks; Document doc; parameters.put("TopicArn", providerTopicId); parameters.put("Token", token); if (authenticateUnsubscribe) { parameters.put("AuthenticateOnUnsubscribe", "true"); } method = new EC2Method(SERVICE_ID, provider, parameters); try { doc = method.invoke(); } catch (EC2Exception e) { throw new CloudException(e); } blocks = doc.getElementsByTagName("ConfirmSubscriptionResult"); for (int i = 0; i < blocks.getLength(); i++) { Node item = blocks.item(i); for (int j = 0; j < item.getChildNodes().getLength(); j++) { Node attr = item.getChildNodes().item(j); String name; name = attr.getNodeName(); if (name.equals("SubscriptionArn")) { return attr.getFirstChild().getNodeValue().trim(); } } } return null; } finally { APITrace.end(); } }
From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java
private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException { if (node == null || !node.hasChildNodes()) { return null; }//from w w w.j a v a 2 s .c o m NodeList attributes = node.getChildNodes(); VolumeState state = null; String volumeId = null; for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); String nodeName = attr.getNodeName(); if (nodeName.equalsIgnoreCase("ID") && attr.hasChildNodes()) { volumeId = attr.getFirstChild().getNodeValue().trim(); } else if (nodeName.equalsIgnoreCase("State") && attr.hasChildNodes()) { String status = attr.getFirstChild().getNodeValue().trim(); state = toState(status); } if (volumeId != null && state != null) { break; } } if (volumeId == null) { return null; } return new ResourceStatus(volumeId, state == null ? VolumeState.PENDING : state); }
From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java
private static HashMap<String, Object> parseHtmlTable(Node table_node, String replaceWith) { if (table_node.getNodeName().equalsIgnoreCase("table") && table_node.hasChildNodes()) { Node topNode = table_node; boolean tbody = table_node.getFirstChild().getNodeName().equalsIgnoreCase("tbody"); if (tbody) topNode = table_node.getFirstChild(); if (topNode.hasChildNodes()) { NodeList rows = topNode.getChildNodes(); List<String> headers = null; ArrayList<HashMap<String, String>> data = null; int headerLength = 0; boolean[] skip = null; if (null != replaceWith) { if (replaceWith.equals("[]")) { headers = new ArrayList<String>(); headerLength = 0;// ww w. ja va 2 s. c o m } // TESTED (by eye - 2) else { //Remove square brackets if (replaceWith.startsWith("[") && replaceWith.endsWith("]")) replaceWith = replaceWith.substring(1, replaceWith.length() - 1); //Turn the provided list of headers into a list object headers = Arrays.asList(replaceWith.split("\\s*,\\s*")); headerLength = headers.size(); skip = new boolean[headerLength]; for (int h = 0; h < headerLength; h++) { String val = headers.get(h); if (val.length() == 0 || val.equalsIgnoreCase("null")) skip[h] = true; else skip[h] = false; } } // TESTED (by eye - 3a) } //traverse rows for (int i = 0; i < rows.getLength(); i++) { Node row = rows.item(i); if (row.getNodeName().equalsIgnoreCase("tr") || row.getNodeName().equalsIgnoreCase("th")) { //If the header value has not been set, the first row will be set as the headers if (null == headers) { //Traverse through cells headers = new ArrayList<String>(); if (row.hasChildNodes()) { NodeList cells = row.getChildNodes(); headerLength = cells.getLength(); skip = new boolean[headerLength]; for (int j = 0; j < headerLength; j++) { headers.add(cells.item(j).getTextContent()); skip[j] = false; } } // TESTED (by eye - 1) } else { if (null == data) { data = new ArrayList<HashMap<String, String>>(); } if (row.hasChildNodes()) { HashMap<String, String> cellList = new HashMap<String, String>(); NodeList cells = row.getChildNodes(); for (int j = 0; j < cells.getLength(); j++) { // Skip Code (TESTED by eye - 4) if (headerLength == 0 || (j < headerLength && skip[j] == false)) { String key = Integer.toString(j); // TESTED (by eye - 3b) if (j < headerLength) key = headers.get(j); cellList.put(key, cells.item(j).getTextContent()); } } data.add(cellList); } } } } //Create final hashmap containing attributes HashMap<String, Object> table_attrib = new HashMap<String, Object>(); NamedNodeMap nnm = table_node.getAttributes(); for (int i = 0; i < nnm.getLength(); i++) { Node att = nnm.item(i); table_attrib.put(att.getNodeName(), att.getNodeValue()); } table_attrib.put("table", data); //TESTED (by eye) attributes added to table value // eg: {"id":"search","cellpadding":"1","table":[{"Status":"B","two":"ONE6313" ...... return table_attrib; } } return null; }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * retrieves the WSTrust element from the soap body. * @param soapBody not null//from www . java 2 s . c om * @return Node of the WSTrust element. * @throws XMLSignatureException when unable to locate the WSTrust element. */ private Node getWsTrustNode(Node soapBody) throws XMLSignatureException { assert soapBody != null; Node wsTrustNode = null; // - All <wst:RequestSecurityToken>, <wst:RequestSecurityTokenResponse>, // and <wst:RequestSecurityTokenResponseCollection> elements must be carried // as the single direct child of the body of a SOAP 1.1 <S11:Envelope> element. wsTrustNode = soapBody.getFirstChild(); if (wsTrustNode == null) { throw new XMLSignatureException("Unexpected Soap structure. Body element is empty."); } else if (wsTrustNode.getNodeType() != Node.ELEMENT_NODE) { throw new XMLSignatureException(String.format( "Unexpected Soap structure. Body element has a child of type '%s'. Expect WSTrust element.", wsTrustNode.getNodeType())); } return wsTrustNode; }
From source file:org.dasein.cloud.aws.platform.SNS.java
private void setTopicAttributes(Topic topic) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); }//from w w w. ja v a2 s .co m APITrace.begin(provider, "Notifications.getTopicAttributes"); try { topic.setProviderRegionId(ctx.getRegionId()); topic.setProviderOwnerId(ctx.getAccountNumber()); topic.setActive(true); Map<String, String> parameters = provider.getStandardSnsParameters(provider.getContext(), GET_TOPIC_ATTRIBUTES); EC2Method method; NodeList blocks; Document doc; parameters.put("TopicArn", topic.getProviderTopicId()); method = new EC2Method(SERVICE_ID, provider, parameters); try { doc = method.invoke(); } catch (EC2Exception e) { throw new CloudException(e); } blocks = doc.getElementsByTagName("Attributes"); for (int i = 0; i < blocks.getLength(); i++) { NodeList items = blocks.item(i).getChildNodes(); for (int j = 0; j < items.getLength(); j++) { Node item = items.item(j); if (item.getNodeName().equals("entry")) { NodeList parts = item.getChildNodes(); String name = null; String value = null; if (parts != null) { for (int k = 0; k < parts.getLength(); k++) { Node node = parts.item(k); if (node != null) { if (node.getNodeName().equals("key")) { name = node.getFirstChild().getNodeValue().trim(); } else if (node.getNodeName().equals("value")) { if (node.getFirstChild() != null) { value = node.getFirstChild().getNodeValue().trim(); } else { value = node.getNodeValue(); } } } } } if (name != null) { if (name.equals("DisplayName")) { if (value != null) { topic.setName(value); topic.setDescription(value + " (" + topic.getProviderTopicId() + ")"); } } else if (name.equals("Owner") && value != null) { topic.setProviderOwnerId(value); } } } } } if (topic.getName() == null) { String id = topic.getProviderTopicId(); int idx = id.lastIndexOf(":"); if (idx > 0 && idx < id.length() - 1) { id = id.substring(idx + 1); } topic.setName(id); } if (topic.getDescription() == null) { topic.setDescription(topic.getName() + " (" + topic.getProviderTopicId() + ")"); } } finally { APITrace.end(); } }
From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java
@Override public @Nonnull Iterable<VolumeProduct> listVolumeProducts() throws InternalException, CloudException { ArrayList<VolumeProduct> products = new ArrayList<VolumeProduct>(); ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was configured for this request"); }/*from ww w .j a v a 2 s . co m*/ SCEMethod method = new SCEMethod(provider); Document xml = method.getAsXML("offerings/storage"); if (xml == null) { throw new CloudException("No storage offerings exist"); } NodeList nodes = xml.getElementsByTagName("Offerings"); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); if (item.hasChildNodes()) { NodeList attrs = item.getChildNodes(); String id = null, format = null; int[] sizes = new int[0]; for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); String n = attr.getNodeName(); if (n.equalsIgnoreCase("ID")) { id = attr.getFirstChild().getNodeValue().trim(); } else if (n.equalsIgnoreCase("SupportedSizes")) { String s = attr.getFirstChild().getNodeValue().trim(); String[] parts; if (s.contains(",")) { parts = s.split(","); } else { parts = new String[] { s }; } sizes = new int[parts.length]; for (int k = 0; k < parts.length; k++) { sizes[k] = Integer.parseInt(parts[k].trim()); } } else if (n.equalsIgnoreCase("SupportedFormats") && attr.hasChildNodes()) { NodeList formats = attr.getChildNodes(); for (int k = 0; k < formats.getLength(); k++) { Node fmt = formats.item(k); if (fmt.getNodeName().equalsIgnoreCase("Format") && fmt.hasChildNodes()) { NodeList fa = fmt.getChildNodes(); for (int l = 0; l < fa.getLength(); l++) { Node fan = fa.item(l); if (fan.getNodeName().equalsIgnoreCase("ID") && fan.hasChildNodes()) { format = fan.getFirstChild().getNodeValue().trim(); if (!format.equalsIgnoreCase("RAW")) { format = null; } } } } } } } if (sizes.length > 0 && format != null) { products.add(VolumeProduct.getInstance(id, id + " - " + format, id + " - " + format + " - " + sizes[0], VolumeType.HDD, new Storage<Gigabyte>(sizes[0], Storage.GIGABYTE))); } } } return products; }
From source file:com.google.enterprise.connector.salesforce.security.BaseAuthorizationManager.java
/** * Connector manager sends a collection of documentIDs to the connector * to authorize for an authenticated context * * @param col Collection the docIDs to authorize * @param id AuthenticationIdentity the identity to auth * @return Collection of docs that are authorized *///from ww w. ja v a2 s . c o m public Collection authorizeDocids(Collection col, AuthenticationIdentity id) { logger.log(Level.FINER, " SalesForceAuthorizationManager. authorizeDocids called for " + id.getUsername()); //first see if we have a callable authorization module to try String callable_az_module = System .getProperty(BaseConstants.CALLABLE_AZ + "_" + connector.getInstanceName()); if (callable_az_module != null) { logger.log(Level.FINE, "Using Loadable Authorization Module : " + callable_az_module); try { Class cls = Class.forName(callable_az_module); java.lang.reflect.Constructor co = cls.getConstructor(); IAuthorizationModule icau = (IAuthorizationModule) co.newInstance(); Collection auth_col = icau.authorizeDocids(col, id.getUsername()); Collection ret_col = new ArrayList(); for (Iterator i = auth_col.iterator(); i.hasNext();) { String did = (String) i.next(); AuthorizationResponse ap = new AuthorizationResponse(true, did); ret_col.add(ap); } return ret_col; } catch (Exception ex) { logger.log(Level.SEVERE, "Unable to load Authorization Module " + callable_az_module); } } else { logger.log(Level.FINER, "Using Default Authorization Module"); } Iterator itr = col.iterator(); logger.log(Level.FINER, " AUTHORIZING BATCH OF : " + col.size() + " documents"); //vector to hold the list of docs that will eventually get authorized Vector v_docIDs = new Vector(); //create a string of 'docid1','docid2','docid3' to send into the AZ query String doc_wildcard = ""; while (itr.hasNext()) { String docID = (String) itr.next(); v_docIDs.add(docID); doc_wildcard = doc_wildcard + "'" + docID + "'"; if (itr.hasNext()) doc_wildcard = doc_wildcard + ","; } //initialize the collection for the response Collection col_resp = new ArrayList(); String query = connector.getAzquery(); //substitute the doc IDs into the AZ query String modified_az_query = query.replace("$DOCIDS", doc_wildcard); modified_az_query = modified_az_query.replace("$USERID", id.getUsername()); logger.log(Level.FINER, "Attempting Authorizing DocList " + modified_az_query); //get ready to submit the query SFQuery sfq = new SFQuery(); //get the user's sessionID, login server thats in context //this step maynot be necessary if we use the connector's login context //instead of the users... //TODO: figure out which way is better later on Properties session_props = connector.getUserSession(id.getUsername()); //not that it matters, how did the user authenticate.. //if its strong (i.e, we got a session ID, we can submit a full AZ query) String auth_strength = (String) session_props.get(BaseConstants.AUTHENTICATION_TYPE); if (auth_strength.equals(BaseConstants.STRONG_AUTHENTICATION)) { logger.log(Level.FINER, "Using Strong Authentication"); try { //following section is used if we want to AZ using the connectors authenticated super context //its commented out for now but we'll touch on this later // if (connector.getSessionID().equalsIgnoreCase("")){ // SalesForceLogin sfl = new SalesForceLogin(connector.getUsername(),connector.getPassword(),connector.getLoginsrv()); // if (sfl.isLoggedIn()){ // connector.setSessionID(sfl.getSessionID()); // connector.setEndPointServer(sfl.getEndPointServer()); // } // } //for connector-managed sessions //todo figure out someway to purge the older sessions logger.log(Level.INFO, "Submitting [" + (String) session_props.getProperty(BaseConstants.LOGIN_SERVER) + "] [" + (String) session_props.getProperty(BaseConstants.SESSIONID) + "]"); org.w3c.dom.Document az_resp = sfq.submitStatement(modified_az_query, BaseConstants.QUERY_TYPE, (String) session_props.getProperty(BaseConstants.LOGIN_SERVER), (String) session_props.getProperty(BaseConstants.SESSIONID)); //if using system session to check AZ //org.w3c.dom.Document az_resp = sfq.submitStatement(modified_az_query, BaseConstants.QUERY_TYPE,connector.getEndPointServer() , connector.getSessionID()); //now transform the AZ SOAP response into the canonical form using //the AZ XLST provided. String encodedXSLT = connector.getAzxslt(); byte[] decode = org.apache.commons.codec.binary.Base64.decodeBase64(encodedXSLT.getBytes()); org.w3c.dom.Document az_xsl = Util.XMLStringtoDoc(new String(decode)); logger.log(Level.FINER, "AZ Query Response " + Util.XMLDoctoString(az_resp)); Document tx_xml = Util.TransformDoctoDoc(az_resp, az_xsl); tx_xml.getDocumentElement().normalize(); logger.log(Level.FINER, "AZ transform result for " + id.getUsername() + " " + Util.XMLDoctoString(tx_xml)); //TODO...figure out why I can use tx_xml as a document by itself //have to resort to convert tx_xml to string and then back to Document //for some reason DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringBuffer sb1 = new StringBuffer(Util.XMLDoctoString(tx_xml)); ByteArrayInputStream bis = new ByteArrayInputStream(sb1.toString().getBytes("UTF-8")); Document doc = db.parse(bis); doc.getDocumentElement().normalize(); //now that the soap response is transformed, extract the documents that were //authorized from the canonical XML AZ form NodeList nl_documents = doc.getElementsByTagName("azdecisions"); //get the NodeList under <document> HashMap hm_azdecisions = new HashMap(); ; Node n_documents = nl_documents.item(0); for (int i = 0; i < n_documents.getChildNodes().getLength(); i++) { Node n_doc = n_documents.getChildNodes().item(i); if (n_doc.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.INDENT, "yes"); if (n_doc.getNodeName().equalsIgnoreCase("docID")) { //ok...so this doc ID was returned so we'll allow/permit this hm_azdecisions.put(n_doc.getFirstChild().getNodeValue(), "PERMIT"); } } } //for each doc ID we got in, iterate and authorize the docs that we got back.. //TODO, ofcourse we could just forego this loop //and simply iterate the hm_azdecisions hashmap to create col_resp for (int i = 0; i < v_docIDs.size(); i++) { //a doc id we got to test String in_docID = (String) v_docIDs.get(i); //if the doc exists in the set we authorized //the more i write this the more i want to just iterate the hm_azdecisions //and get it over with...i'll work on that next week if (hm_azdecisions.containsKey(in_docID)) { AuthorizationResponse ap = new AuthorizationResponse(true, in_docID); col_resp.add(ap); } } } catch (Exception bex) { logger.log(Level.SEVERE, " ERROR SUBMITTING AZ Query " + bex); } } //if the user was just authenticated //we don't have the sessionid so we'lll authorize all docs. //WEAK_AUTH flag should never get set since //we've failed the AU attempt in the BaseAuthenticationManager already else if (auth_strength.equals(BaseConstants.WEAK_AUTHENTICATION)) { logger.log(Level.FINER, "Using Weak Authentication"); if (connector.allowWeakAuth()) { col_resp = new ArrayList(); for (int i = 0; i < v_docIDs.size(); i++) { String docID = (String) v_docIDs.get(i); logger.log(Level.FINER, "Authorizing " + docID); AuthorizationResponse ap = new AuthorizationResponse(true, docID); col_resp.add(ap); } } } return col_resp; }
From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java
private SCEOffering findOffering(@Nonnull String productId) throws InternalException, CloudException { SCEOffering offering;//from www .j a va 2s . co m ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was configured for this request"); } SCEMethod method = new SCEMethod(provider); Document xml = method.getAsXML("offerings/storage"); if (xml == null) { throw new CloudException("No storage offerings exist"); } NodeList nodes = xml.getElementsByTagName("Offerings"); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); if (item.hasChildNodes()) { NodeList attrs = item.getChildNodes(); String id = null, format = null; int[] sizes = new int[0]; for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); String n = attr.getNodeName(); if (n.equalsIgnoreCase("ID")) { id = attr.getFirstChild().getNodeValue().trim(); } else if (n.equalsIgnoreCase("SupportedSizes")) { String s = attr.getFirstChild().getNodeValue().trim(); String[] parts; if (s.contains(",")) { parts = s.split(","); } else { parts = new String[] { s }; } sizes = new int[parts.length]; for (int k = 0; k < parts.length; k++) { sizes[k] = Integer.parseInt(parts[k].trim()); } } else if (n.equalsIgnoreCase("SupportedFormats") && attr.hasChildNodes()) { NodeList formats = attr.getChildNodes(); for (int k = 0; k < formats.getLength(); k++) { Node fmt = formats.item(k); if (fmt.getNodeName().equalsIgnoreCase("Format") && fmt.hasChildNodes()) { NodeList fa = fmt.getChildNodes(); for (int l = 0; l < fa.getLength(); l++) { Node fan = fa.item(l); if (fan.getNodeName().equalsIgnoreCase("ID") && fan.hasChildNodes()) { format = fan.getFirstChild().getNodeValue().trim(); if (!format.equalsIgnoreCase("RAW")) { format = null; } } } } } } } if (id == null || !id.equals(productId)) { continue; } offering = new SCEOffering(); offering.format = format; offering.offeringId = id; offering.size = sizes[0]; return offering; } } return null; }
From source file:com.konakart.actions.gateways.Eway_auAction.java
public String execute() { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String message = null;//from w ww. j a v a 2 s . c o m String errorMessage = null; String gatewayResult = null; String transactionId = null; // Create these outside of try / catch since they are needed in the case of a general // exception IpnHistoryIf ipnHistory = new IpnHistory(); ipnHistory.setModuleCode(Eway_au.EWAY_AU_GATEWAY_CODE); KKAppEng kkAppEng = null; try { int custId; kkAppEng = this.getKKAppEng(request, response); custId = this.loggedIn(request, response, kkAppEng, "Checkout"); // Check to see whether the user is logged in if (custId < 0) { return KKLOGIN; } // Ensure we are using the correct protocol. Redirect if not. String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */false); if (redirForward != null) { setupResponseForSSLRedirect(response, redirForward); return null; } // Get the order OrderIf order = kkAppEng.getOrderMgr().getCheckoutOrder(); validateOrder(order, Eway_au.EWAY_AU_GATEWAY_CODE); // Set the order id for the ipnHistory object ipnHistory.setOrderId(order.getId()); PaymentDetailsIf pd = order.getPaymentDetails(); // Create a parameter list for the credit card details. List<NameValueIf> parmList = new ArrayList<NameValueIf>(); parmList.add(new NameValue(Eway_au.EWAY_AU_CARD_NUMBER, URLEncoder.encode(pd.getCcNumber(), "UTF-8"))); if (pd.isShowCVV()) { parmList.add(new NameValue(Eway_au.EWAY_AU_CARD_CVV2, URLEncoder.encode(pd.getCcCVV(), "UTF-8"))); } parmList.add(new NameValue(Eway_au.EWAY_AU_CARD_EXPIRY_MONTH, URLEncoder.encode(pd.getCcExpiryMonth(), "UTF-8"))); parmList.add(new NameValue(Eway_au.EWAY_AU_CARD_EXPIRY_YEAR, URLEncoder.encode(pd.getCcExpiryYear(), "UTF-8"))); parmList.add( new NameValue(Eway_au.EWAY_AU_CARDHOLDERS_NAME, URLEncoder.encode(pd.getCcOwner(), "UTF-8"))); // Do the post String gatewayResp = null; try { gatewayResp = postData(pd, parmList); } catch (Exception e) { // Save the ipnHistory ipnHistory.setGatewayFullResponse(e.getMessage()); ipnHistory.setKonakartResultDescription(getResultDescription(RET4_DESC + e.getMessage())); ipnHistory.setKonakartResultId(RET4); ipnHistory.setOrderId(order.getId()); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // Set the message and return String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { RET3_DESC }); addActionError(msg); // Redirect the user back to the credit card screen return "TryAgain"; } gatewayResp = URLDecoder.decode(gatewayResp, "UTF-8"); if (log.isDebugEnabled()) { log.debug("Unformatted GatewayResp = \n" + gatewayResp); } // Now process the XML response int txReturnAmount = 0; String txTrxnNumber = ""; String txTrxnReference = ""; String txTrxnOption1 = ""; String txTrxnOption2 = ""; String txTrxnOption3 = ""; boolean txTrxnStatus = false; String txAuthCode = ""; String txTrxnError = ""; double txBeagleScore = -1; try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); ByteArrayInputStream bais = new ByteArrayInputStream(gatewayResp.getBytes()); Document doc = builder.parse(bais); // get the root node Node rootnode = doc.getDocumentElement(); String root = rootnode.getNodeName(); if (!root.equals("ewayResponse")) { throw new Exception("Bad root element in eWay response: " + root); } // get all elements NodeList list = doc.getElementsByTagName("*"); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); String name = node.getNodeName(); if (name.equals("ewayResponse")) { continue; } Text textnode = (Text) node.getFirstChild(); String value = ""; if (textnode != null) { value = textnode.getNodeValue(); } if (name.equals("ewayTrxnError")) { txTrxnError = value; } else if (name.equals("ewayTrxnStatus")) { if (value.toLowerCase().trim().equals("true")) { txTrxnStatus = true; } } else if (name.equals("ewayTrxnNumber")) { txTrxnNumber = value; } else if (name.equals("ewayTrxnOption1")) { txTrxnOption1 = value; } else if (name.equals("ewayTrxnOption2")) { txTrxnOption2 = value; } else if (name.equals("ewayTrxnOption3")) { txTrxnOption3 = value; } else if (name.equals("ewayReturnAmount")) { if (!value.equals("")) { txReturnAmount = Integer.parseInt(value); } } else if (name.equals("ewayAuthCode")) { txAuthCode = value; } else if (name.equals("ewayTrxnReference")) { txTrxnReference = value; } else if (name.equals("ewayBeagleScore")) { if (!value.equals("")) { txBeagleScore = Double.parseDouble(value); } } else { if (log.isWarnEnabled()) { log.warn("Unknown field in eWay response: " + name); } } } } catch (Exception e) { // Problems parsing the XML if (log.isWarnEnabled()) { log.warn("Problems parsing eWay response: " + e.getMessage()); e.printStackTrace(); } // Save the ipnHistory ipnHistory.setGatewayFullResponse(e.getMessage()); ipnHistory.setKonakartResultDescription(getResultDescription(RET4_DESC + e.getMessage())); ipnHistory.setKonakartResultId(RET4); ipnHistory.setOrderId(order.getId()); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // Set the message and return String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { RET3_DESC }); addActionError(msg); // Redirect the user back to the credit card screen return "TryAgain"; } gatewayResult = txTrxnStatus ? "Successful" : "Failed"; ipnHistory.setGatewayResult(gatewayResult); transactionId = txTrxnNumber; ipnHistory.setGatewayTransactionId(transactionId); message = txAuthCode; errorMessage = txTrxnError; // Put the response in the ipnHistory record ipnHistory.setGatewayFullResponse(gatewayResp); if (log.isDebugEnabled()) { log.debug("eWay response data:\n\t" + " txReturnAmount = " + txReturnAmount + "\n\t txTrxnNumber = " + txTrxnNumber + "\n\t txTrxnReference = " + txTrxnReference + "\n\t txTrxnOption1 = " + txTrxnOption1 + "\n\t txTrxnOption2 = " + txTrxnOption2 + "\n\t txTrxnOption3 = " + txTrxnOption3 + "\n\t txTrxnStatus = " + txTrxnStatus + "\n\t txAuthCode = " + txAuthCode + "\n\t txTrxnError = " + txTrxnError + "\n\t txBeagleScore = " + txBeagleScore); } // See if we need to send an email, by looking at the configuration String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS); boolean sendEmail = false; if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) { sendEmail = true; } OrderUpdateIf updateOrder = new OrderUpdate(); updateOrder.setUpdatedById(kkAppEng.getActiveCustId()); // Determine whether the request was successful or not. If successful, we update the // inventory as well as changing the state of the order if (gatewayResult.equals("Successful")) { /* * Payment approved */ String comment = ORDER_HISTORY_COMMENT_OK + transactionId; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), order.getId(), com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, /* customerNotified */ sendEmail, comment, updateOrder); // Update the inventory kkAppEng.getOrderMgr().updateInventory(order.getId()); // Save the ipnHistory ipnHistory.setKonakartResultDescription(RET0_DESC); ipnHistory.setKonakartResultId(RET0); ipnHistory.setOrderId(order.getId()); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // If we received no exceptions, delete the basket kkAppEng.getBasketMgr().emptyBasket(); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, order.getId(), /* success */true); } return "Approved"; } else if (gatewayResult.equals("Failed")) { /* * Payment declined */ String comment = ORDER_HISTORY_COMMENT_KO + errorMessage; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), order.getId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, /* customerNotified */ sendEmail, comment, updateOrder); // Save the ipnHistory ipnHistory.setKonakartResultDescription(RET0_DESC); ipnHistory.setKonakartResultId(RET0); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, order.getId(), /* success */false); } String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { errorMessage }); addActionError(msg); // Redirect the user back to the credit card screen return "TryAgain"; } else { /* * We only get to here if there was an error from the gateway */ String comment = RET1_DESC + message; kkAppEng.getEng().updateOrder(kkAppEng.getSessionId(), order.getId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, /* customerNotified */ sendEmail, comment, updateOrder); // Save the ipnHistory ipnHistory.setKonakartResultDescription(getResultDescription(RET1_DESC + message)); ipnHistory.setKonakartResultId(RET1); ipnHistory.setCustomerId(kkAppEng.getCustomerMgr().getCurrentCustomer().getId()); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, order.getId(), /* success */false); } String msg = kkAppEng.getMsg("checkout.cc.gateway.error", new String[] { RET1_DESC + gatewayResult }); addActionError(msg); // Redirect the user back to the credit card screen return "TryAgain"; } } catch (Exception e) { try { ipnHistory.setKonakartResultDescription(getResultDescription(RET4_DESC + e.getMessage())); ipnHistory.setKonakartResultId(RET4); if (kkAppEng != null) { kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); } } catch (KKException e1) { return super.handleException(request, e1); } return super.handleException(request, e); } }
From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java
private @Nullable ExtendedVolume toVolume(@Nonnull ProviderContext ctx, @Nullable Node node) throws CloudException, InternalException { if (node == null || !node.hasChildNodes()) { return null; }//from ww w . j ava 2s .c o m NodeList attributes = node.getChildNodes(); ExtendedVolume volume = new ExtendedVolume(); volume.setCurrentState(VolumeState.PENDING); volume.setType(VolumeType.HDD); volume.setFormat(VolumeFormat.BLOCK); for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); String nodeName = attr.getNodeName(); if (nodeName.equalsIgnoreCase("ID") && attr.hasChildNodes()) { volume.setProviderVolumeId(attr.getFirstChild().getNodeValue().trim()); } else if (nodeName.equalsIgnoreCase("Name") && attr.hasChildNodes()) { volume.setName(attr.getFirstChild().getNodeValue().trim()); } else if (nodeName.equalsIgnoreCase("Description") && attr.hasChildNodes()) { volume.setName(attr.getFirstChild().getNodeValue().trim()); } else if (nodeName.equalsIgnoreCase("Location") && attr.hasChildNodes()) { volume.setProviderRegionId(attr.getFirstChild().getNodeValue().trim()); volume.setProviderDataCenterId(volume.getProviderRegionId()); } else if (nodeName.equalsIgnoreCase("Size") && attr.hasChildNodes()) { volume.setSize(new Storage<Gigabyte>(Integer.parseInt(attr.getFirstChild().getNodeValue().trim()), Storage.GIGABYTE)); } else if (nodeName.equalsIgnoreCase("State") && attr.hasChildNodes()) { String status = attr.getFirstChild().getNodeValue().trim(); volume.setCurrentState(toState(status)); volume.setRealState(status); } else if (nodeName.equalsIgnoreCase("CreatedTime") && attr.hasChildNodes()) { volume.setCreationTimestamp(provider.parseTimestamp(attr.getFirstChild().getNodeValue().trim())); } else if (nodeName.equalsIgnoreCase("InstanceID") && attr.hasChildNodes()) { volume.setProviderVirtualMachineId(attr.getFirstChild().getNodeValue().trim()); } } if (volume.getProviderVolumeId() == null) { return null; } String regionId = volume.getProviderRegionId(); if (regionId == null || !regionId.equals(ctx.getRegionId())) { return null; } if (volume.getName() == null) { volume.setName(volume.getProviderVolumeId()); } return volume; }