List of usage examples for org.w3c.dom Element getFirstChild
public Node getFirstChild();
From source file:Main.java
/** * Checks whether the expected XML element is contained in the actual * element. I.e., every attribute of the expected element must occur in the * actual element, with the same value, and all child nodes in the expected * element must occur in the actual element; if multiple child nodes with * the same name are found in the expected element, the first found * identifying attribute in the expected child element is used to identify * the child in the actual element./*from w ww. jav a 2 s. co m*/ * * @param expected * @param actual * @return */ public static void assertContains(Element expected, Element actual, String messagePrefix, String... identifyingAttributes) { if (!expected.getTagName().equals(actual.getTagName())) { throw new AssertionError(messagePrefix + "\nExpected tagname differs from actual tagname (expected '" + printNodeOnly(expected) + "', found " + printNodeOnly(actual) + ")"); } // Compare attributes NamedNodeMap expectedAttributes = expected.getAttributes(); for (int i = expectedAttributes.getLength() - 1; i >= 0; i--) { String expectedAttributeName = expectedAttributes.item(i).getNodeName(); String expectedAttributeValue = expectedAttributes.item(i).getNodeValue(); String actualValue = actual.getAttribute(expectedAttributeName); if (actualValue == null || actualValue.isEmpty()) { throw new AssertionError(messagePrefix + "\nThe attribute '" + expectedAttributeName + "' with value '" + expectedAttributeValue + "' was not found in the result " + printNodeOnly(actual)); } if (!expectedAttributeValue.equals(actualValue)) { throw new AssertionError(messagePrefix + "\nThe attribute '" + expectedAttributeName + "' has value '" + actualValue + "' instead of '" + expectedAttributeValue + "' in the result " + printNodeOnly(actual)); } } // Compare child elements Node child = expected.getFirstChild(); while (child != null) { if (child instanceof Element) { assertContainsChildElement((Element) child, actual, messagePrefix, identifyingAttributes); } child = child.getNextSibling(); } }
From source file:org.weloveastrid.rmilk.api.Invoker.java
public Element invoke(boolean repeat, Param... params) throws ServiceException { long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation; if (timeSinceLastInvocation < INVOCATION_INTERVAL) { // In order not to invoke the RTM service too often try {/*from ww w .ja va 2 s. co m*/ Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation); } catch (InterruptedException e) { return null; } } // We compute the URI final StringBuffer requestUri = computeRequestUri(params); HttpResponse response = null; final HttpGet request = new HttpGet("http://" //$NON-NLS-1$ + ServiceImpl.SERVER_HOST_NAME + requestUri.toString()); final String methodUri = request.getRequestLine().getUri(); Element result; try { Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$ response = httpClient.execute(request); lastInvocation = System.currentTimeMillis(); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$ // Tim: HTTP error. Let's wait a little bit if (!repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } response.getEntity().consumeContent(); return invoke(true, params); } throw new ServiceInternalException("method failed: " + response.getStatusLine()); } final Document responseDoc = builder.parse(response.getEntity().getContent()); final Element wrapperElt = responseDoc.getDocumentElement(); if (!wrapperElt.getNodeName().equals("rsp")) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + wrapperElt.getNodeName()); } else { String stat = wrapperElt.getAttribute("stat"); if (stat.equals("fail")) { Node errElt = wrapperElt.getFirstChild(); while (errElt != null && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) { errElt = errElt.getNextSibling(); } if (errElt == null) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + wrapperElt.getNodeValue()); } else { if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } return invoke(true, params); } throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")), ((Element) errElt).getAttribute("msg")); } } else { Node dataElt = wrapperElt.getFirstChild(); while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE || dataElt.getNodeName().equals("transaction") == true)) { try { Node nextSibling = dataElt.getNextSibling(); if (nextSibling == null) { break; } else { dataElt = nextSibling; } } catch (IndexOutOfBoundsException exception) { // Some implementation may throw this exception, // instead of returning a null sibling break; } } if (dataElt == null) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + wrapperElt.getNodeValue()); } else { result = (Element) dataElt; } } } } catch (IOException e) { throw new ServiceInternalException("Error making connection: " + e.getMessage(), e); } catch (SAXException e) { // repeat call if possible. if (!repeat) return invoke(true, params); else throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e); } finally { httpClient.getConnectionManager().closeExpiredConnections(); } return result; }
From source file:org.weloveastrid.hive.api.Invoker.java
public Element invoke(boolean repeat, Param... params) throws ServiceException { long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation; if (timeSinceLastInvocation < INVOCATION_INTERVAL) { // In order not to invoke the Hiveminder service too often try {//from w ww . j ava 2s . com Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation); } catch (InterruptedException e) { return null; } } // We compute the URI final StringBuffer requestUri = computeRequestUri(params); HttpResponse response = null; final HttpGet request = new HttpGet("http://" //$NON-NLS-1$ + ServiceImpl.SERVER_HOST_NAME + requestUri.toString()); final String methodUri = request.getRequestLine().getUri(); Element result; try { Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$ response = httpClient.execute(request); lastInvocation = System.currentTimeMillis(); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$ // Tim: HTTP error. Let's wait a little bit if (!repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } response.getEntity().consumeContent(); return invoke(true, params); } throw new ServiceInternalException("method failed: " + response.getStatusLine()); } final Document responseDoc = builder.parse(response.getEntity().getContent()); final Element wrapperElt = responseDoc.getDocumentElement(); if (!wrapperElt.getNodeName().equals("rsp")) { throw new ServiceInternalException( "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeName()); } else { String stat = wrapperElt.getAttribute("stat"); if (stat.equals("fail")) { Node errElt = wrapperElt.getFirstChild(); while (errElt != null && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) { errElt = errElt.getNextSibling(); } if (errElt == null) { throw new ServiceInternalException( "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue()); } else { if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } return invoke(true, params); } throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")), ((Element) errElt).getAttribute("msg")); } } else { Node dataElt = wrapperElt.getFirstChild(); while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE || dataElt.getNodeName().equals("transaction") == true)) { try { Node nextSibling = dataElt.getNextSibling(); if (nextSibling == null) { break; } else { dataElt = nextSibling; } } catch (IndexOutOfBoundsException exception) { // Some implementation may throw this exception, // instead of returning a null sibling break; } } if (dataElt == null) { throw new ServiceInternalException( "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue()); } else { result = (Element) dataElt; } } } } catch (IOException e) { throw new ServiceInternalException("Error making connection: " + e.getMessage(), e); } catch (SAXException e) { // repeat call if possible. if (!repeat) return invoke(true, params); else throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e); } finally { httpClient.getConnectionManager().closeExpiredConnections(); } return result; }
From source file:edu.lternet.pasta.client.JournalCitationsClient.java
public String citationsTableHTML() throws Exception { String html = ""; if (this.uid != null && !this.uid.equals("public")) { StringBuilder sb = new StringBuilder(""); String xmlString = listPrincipalOwnerCitations(this.uid); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try {/*www . jav a 2s . c o m*/ DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList citationsNodeList = documentElement.getElementsByTagName("journalCitation"); int nJournalCitations = citationsNodeList.getLength(); for (int i = 0; i < nJournalCitations; i++) { Node journalCitationNode = citationsNodeList.item(i); NodeList journalCitationChildren = journalCitationNode.getChildNodes(); String journalCitationId = ""; String packageId = ""; String articleDoi = ""; String articleUrl = ""; String articleTitle = ""; String journalTitle = ""; for (int j = 0; j < journalCitationChildren.getLength(); j++) { Node childNode = journalCitationChildren.item(j); if (childNode instanceof Element) { Element subscriptionElement = (Element) childNode; if (subscriptionElement.getTagName().equals("journalCitationId")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { journalCitationId = text.getData().trim(); } } else if (subscriptionElement.getTagName().equals("packageId")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { packageId = text.getData().trim(); } } else if (subscriptionElement.getTagName().equals("articleDoi")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { articleDoi = text.getData().trim(); } } else if (subscriptionElement.getTagName().equals("articleUrl")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { articleUrl = text.getData().trim(); } } else if (subscriptionElement.getTagName().equals("articleTitle")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { articleTitle = text.getData().trim(); } } else if (subscriptionElement.getTagName().equals("journalTitle")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { journalTitle = text.getData().trim(); } } } } sb.append("<tr>\n"); sb.append("<td class='nis' align='center'>"); sb.append(journalCitationId); sb.append("</td>\n"); sb.append("<td class='nis' align='center'>"); sb.append(packageId); sb.append("</td>\n"); sb.append("<td class='nis'>"); sb.append(articleDoi); sb.append("</td>\n"); sb.append("<td class='nis'>"); sb.append(articleUrl); sb.append("</td>\n"); sb.append("<td class='nis'>"); sb.append(articleTitle); sb.append("</td>\n"); sb.append("<td class='nis'>"); sb.append(journalTitle); sb.append("</td>\n"); sb.append("</tr>\n"); } html = sb.toString(); } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); throw new PastaEventException(e.getMessage()); } } return html; }
From source file:XMLDocumentWriter.java
/** * Output the specified DOM Node object, printing it using the specified * indentation string//w w w . j av a 2 s . co m */ public void write(Node node, String indent) { // The output depends on the type of the node switch (node.getNodeType()) { case Node.DOCUMENT_NODE: { // If its a Document node Document doc = (Document) node; out.println(indent + "<?xml version='1.0'?>"); // Output header Node child = doc.getFirstChild(); // Get the first node while (child != null) { // Loop 'till no more nodes write(child, indent); // Output node child = child.getNextSibling(); // Get next node } break; } case Node.DOCUMENT_TYPE_NODE: { // It is a <!DOCTYPE> tag DocumentType doctype = (DocumentType) node; // Note that the DOM Level 1 does not give us information about // the the public or system ids of the doctype, so we can't output // a complete <!DOCTYPE> tag here. We can do better with Level 2. out.println("<!DOCTYPE " + doctype.getName() + ">"); break; } case Node.ELEMENT_NODE: { // Most nodes are Elements Element elt = (Element) node; out.print(indent + "<" + elt.getTagName()); // Begin start tag NamedNodeMap attrs = elt.getAttributes(); // Get attributes for (int i = 0; i < attrs.getLength(); i++) { // Loop through them Node a = attrs.item(i); out.print(" " + a.getNodeName() + "='" + // Print attr. name fixup(a.getNodeValue()) + "'"); // Print attr. value } out.println(">"); // Finish start tag String newindent = indent + " "; // Increase indent Node child = elt.getFirstChild(); // Get child while (child != null) { // Loop write(child, newindent); // Output child child = child.getNextSibling(); // Get next child } out.println(indent + "</" + // Output end tag elt.getTagName() + ">"); break; } case Node.TEXT_NODE: { // Plain text node Text textNode = (Text) node; String text = textNode.getData().trim(); // Strip off space if ((text != null) && text.length() > 0) // If non-empty out.println(indent + fixup(text)); // print text break; } case Node.PROCESSING_INSTRUCTION_NODE: { // Handle PI nodes ProcessingInstruction pi = (ProcessingInstruction) node; out.println(indent + "<?" + pi.getTarget() + " " + pi.getData() + "?>"); break; } case Node.ENTITY_REFERENCE_NODE: { // Handle entities out.println(indent + "&" + node.getNodeName() + ";"); break; } case Node.CDATA_SECTION_NODE: { // Output CDATA sections CDATASection cdata = (CDATASection) node; // Careful! Don't put a CDATA section in the program itself! out.println(indent + "<" + "![CDATA[" + cdata.getData() + "]]" + ">"); break; } case Node.COMMENT_NODE: { // Comments Comment c = (Comment) node; out.println(indent + "<!--" + c.getData() + "-->"); break; } default: // Hopefully, this won't happen too much! System.err.println("Ignoring node: " + node.getClass().getName()); break; } }
From source file:com.amalto.workbench.actions.XSDNewParticleFromParticleAction.java
public Map<String, List<String>> cloneXSDAnnotation(XSDAnnotation oldAnn) { Map<String, List<String>> infor = new HashMap<String, List<String>>(); try {/*from ww w.j a v a 2 s. c om*/ if (oldAnn != null) { for (int i = 0; i < oldAnn.getApplicationInformation().size(); i++) { Element oldElem = oldAnn.getApplicationInformation().get(i); String type = oldElem.getAttributes().getNamedItem("source").getNodeValue();//$NON-NLS-1$ // X_Write,X_Hide,X_Workflow if (type.equals("X_Write") || type.equals("X_Hide") || type.equals("X_Workflow")) {//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ if (!infor.containsKey(type)) { List<String> typeList = new ArrayList<String>(); typeList.add(oldElem.getFirstChild().getNodeValue()); infor.put(type, typeList); } else { (infor.get(type)).add(oldElem.getFirstChild().getNodeValue()); } } } } } catch (Exception e) { log.error(e.getMessage(), e); MessageDialog.openError(this.page.getSite().getShell(), Messages._Error, Messages.bind(Messages._ErrorPasteEntity, e.getLocalizedMessage())); } return infor; }
From source file:edu.lternet.pasta.client.EventSubscriptionClient.java
public String subscriptionOptionsHTML() throws PastaEventException { String html = ""; if (this.uid != null && !this.uid.equals("public")) { StringBuilder sb = new StringBuilder(""); String xmlString = readByFilter(""); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try {/*from w w w.ja va2s .c o m*/ DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList subscriptionList = documentElement.getElementsByTagName("subscription"); int nSubscriptions = subscriptionList.getLength(); for (int i = 0; i < nSubscriptions; i++) { Node subscriptionNode = subscriptionList.item(i); NodeList subscriptionChildren = subscriptionNode.getChildNodes(); String subscriptionId = ""; for (int j = 0; j < subscriptionChildren.getLength(); j++) { Node childNode = subscriptionChildren.item(j); if (childNode instanceof Element) { Element subscriptionElement = (Element) childNode; if (subscriptionElement.getTagName().equals("id")) { Text text = (Text) subscriptionElement.getFirstChild(); if (text != null) { subscriptionId = text.getData().trim(); } } } } sb.append(String.format("<option value='%s'>%s</option>\n", subscriptionId, subscriptionId)); } html = sb.toString(); } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); throw new PastaEventException(e.getMessage()); } } return html; }
From source file:com.icesoft.faces.context.DOMResponseWriter.java
private Element fixHead() { Element html = document.getDocumentElement(); Element head = document.createElement("head"); html.insertBefore(head, html.getFirstChild()); return head;// w w w . j av a 2s. c o m }
From source file:com.verisign.epp.codec.gen.EPPUtil.java
/** * Decode a <code>List</code> of <code>String</code>'s by XML namespace and * tag name, from an XML Element. The children elements of * <code>aElement</code> will be searched for the specified <code>aNS</code> * namespace URI and the specified <code>aTagName</code>. Each XML element * found will be decoded and added to the returned <code>List</code>. Empty * child elements, will result in empty string ("") return <code>List</code> * elements./*from w ww . ja va2 s . c om*/ * * @param aElement * XML Element to scan. For example, the element could be * <domain:update> * @param aNS * XML namespace of the elements. For example, for domain element * this is "urn:iana:xmlns:domain". * @param aTagName * Tag name of the element including an optional namespace * prefix. For example, the tag name for the domain name servers * is "domain:server". * @return <code>List</code> of <code>String</code> elements representing * the text nodes of the found XML elements. * @exception EPPDecodeException * Error decoding <code>aElement</code>. */ public static List decodeList(Element aElement, String aNS, String aTagName) throws EPPDecodeException { List retVal = new ArrayList(); Vector theChildren = EPPUtil.getElementsByTagNameNS(aElement, aNS, aTagName); for (int i = 0; i < theChildren.size(); i++) { Element currChild = (Element) theChildren.elementAt(i); Text currVal = (Text) currChild.getFirstChild(); // Element has text? if (currVal != null) { retVal.add(currVal.getNodeValue()); } else { // No text in element. retVal.add(""); } } return retVal; }
From source file:com.verisign.epp.codec.gen.EPPUtil.java
/** * Decode a <code>Vector</code> of <code>String</code>'s by XML namespace * and tag name, from an XML Element. The children elements of * <code>aElement</code> will be searched for the specified <code>aNS</code> * namespace URI and the specified <code>aTagName</code>. Each XML element * found will be decoded and added to the returned <code>Vector</code>. * Empty child elements, will result in empty string ("") return * <code>Vector</code> elements. * // www . j a v a2 s. c om * @param aElement * XML Element to scan. For example, the element could be * <domain:update> * @param aNS * XML namespace of the elements. For example, for domain element * this is "urn:iana:xmlns:domain". * @param aTagName * Tag name of the element including an optional namespace * prefix. For example, the tag name for the domain name servers * is "domain:server". * @return <code>Vector</code> of <code>String</code> elements representing * the text nodes of the found XML elements. * @exception EPPDecodeException * Error decoding <code>aElement</code>. */ public static <X> Vector<X> decodeVector(Element aElement, String aNS, String aTagName) throws EPPDecodeException { Vector retVal = new Vector(); Vector theChildren = EPPUtil.getElementsByTagNameNS(aElement, aNS, aTagName); for (int i = 0; i < theChildren.size(); i++) { Element currChild = (Element) theChildren.elementAt(i); Text currVal = (Text) currChild.getFirstChild(); // Element has text? if (currVal != null) { retVal.addElement(currVal.getNodeValue()); } else { // No text in element. retVal.addElement(""); } } return retVal; }