List of usage examples for org.w3c.dom Element getFirstChild
public Node getFirstChild();
From source file:com.google.appengine.tools.mapreduce.ConfigurationTemplatePreprocessor.java
/** * For a single {@code Configuration} property, process it, looking * for parameter-related attributes, and updating the relevant object maps * if found.//from w ww.j a va 2 s . c o m */ private void populateParameterFromProperty(Element prop) { String name = null; String humanName = null; Element templateValue = null; String defaultValue = null; NodeList fields = prop.getChildNodes(); for (int j = 0; j < fields.getLength(); j++) { Node fieldNode = fields.item(j); if (!(fieldNode instanceof Element)) { continue; } Element field = (Element) fieldNode; if ("name".equals(field.getTagName())) { if (field.hasAttribute("human")) { humanName = field.getAttribute("human"); } name = ((Text) field.getFirstChild()).getData().trim(); } if ("value".equals(field.getTagName()) && field.hasAttribute("template")) { templateValue = field; if (field.getAttribute("template").equals("optional")) { if (field.getFirstChild() != null) { defaultValue = field.getFirstChild().getTextContent(); } else { defaultValue = ""; } } } } if (templateValue != null) { nameToMetadata.put(name, new TemplateEntryMetadata(name, humanName, defaultValue)); nameToValueElement.put(name, templateValue); } }
From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java
private synchronized Element getSubSection(Element eRootSection, String sSectionType) { assert eRootSection != null : "Suplied root section is empty"; if (eRootSection.hasChildNodes()) { Node nTemp = eRootSection.getFirstChild(); while (nTemp != null) { if (nTemp.getNodeType() == Node.ELEMENT_NODE && nTemp.getNodeName().equals(sSectionType)) { return (Element) nTemp; }/*from w w w . j av a2 s . co m*/ nTemp = nTemp.getNextSibling(); } } return null; }
From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java
private Element doFindElementById(Element element, String id) { Element result = null;//from w w w . java 2 s .c om Node child = element.getFirstChild(); while (child != null) { if (child instanceof Element) { Element childElement = (Element) child; if (id.equals(childElement.getAttribute(ViewXmlConstants.ATTRIBUTE_ID))) { result = childElement; break; } } child = child.getNextSibling(); } if (result == null) { child = element.getFirstChild(); while (child != null) { if (child instanceof Element) { result = doFindElementById((Element) child, id); if (result != null) break; } child = child.getNextSibling(); } } return result; }
From source file:com.enonic.esl.xml.XMLTool.java
/** * Removes a child element from a parent element, and returns the next element to the removed one. * * @param parent The parent element to the child to be removed. * @param child The child element to remove. * @return The next element to the removed child. *//*from www . ja va 2 s. c om*/ public static Element removeChildFromParent(Element parent, Element child) { Element previousChild = (Element) child.getPreviousSibling(); // If the child to remove is the first child if (previousChild == null) { parent.removeChild(child); // Return the first child as the next child return (Element) parent.getFirstChild(); } // If the child is not the first child else { parent.removeChild(child); return (Element) previousChild.getNextSibling(); } }
From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java
@SuppressWarnings("unchecked") private void postProcessNodeReplacement(Element element) { Document ownerDocument = element.getOwnerDocument(); Node child = element.getFirstChild(); while (child != null) { Node nextChild = child.getNextSibling(); if (child instanceof Element) { if (child.getUserData("dorado.delete") != null) { List<Element> replaceContent = (List<Element>) child.getUserData("dorado.replace"); if (replaceContent != null) { for (Element el : replaceContent) { Element clonedElement = (Element) ownerDocument.importNode(el, true); element.insertBefore(clonedElement, child); }/*from ww w.j a v a 2 s .co m*/ child.setUserData("dorado.replace", null, null); } element.removeChild(child); child.setUserData("dorado.delete", null, null); } } child = nextChild; } }
From source file:edu.lternet.pasta.portal.search.BrowseGroup.java
private void addFetchDownElements() { String fetchDownXML = ControlledVocabularyClient.webServiceFetchDown(this.termId); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try {//from w w w . j a v a 2s .c om DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(fetchDownXML, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList documentNodeList = documentElement.getElementsByTagName("term"); for (int i = 0; i < documentNodeList.getLength(); i++) { Node documentNode = documentNodeList.item(i); NodeList childNodes = documentNode.getChildNodes(); String termId = null; String value = null; String hasMoreDown = null; for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); if (childNode instanceof Element) { Element childElement = (Element) childNode; if (childElement.getTagName().equals("term_id")) { Text text = (Text) childElement.getFirstChild(); termId = text.getData().trim(); } else if (childElement.getTagName().equals("string")) { Text text = (Text) childElement.getFirstChild(); value = text.getData().trim(); } else if (childElement.getTagName().equals("hasMoreDown")) { Text text = (Text) childElement.getFirstChild(); hasMoreDown = text.getData().trim(); } } } if (hasMoreDown != null && hasMoreDown.equals("1")) { BrowseGroup downTerm = new BrowseGroup(value); this.addBrowseGroup(downTerm); downTerm.setTermId(termId); downTerm.setHasMoreDown(hasMoreDown); downTerm.addFetchDownElements(); } else { BrowseTerm downTerm = new BrowseTerm(value); downTerm.setTermId(termId); this.addBrowseTerm(downTerm); } } } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); } if (!isBlacklistedTerm(this.value)) { BrowseTerm browseTerm = new BrowseTerm(this.value); browseTerm.setLevel(level + 1); this.addBrowseTerm(browseTerm); } }
From source file:com.firegnom.valkyrie.map.tiled.TiledZoneLoader.java
/** * Gets the action index.// www .j av a2s . c om * * @param element the element * @return the action index * @throws UnsupportedEncodingException the unsupported encoding exception */ public ActionIndex getActionIndex(Element element) throws UnsupportedEncodingException { ActionIndex ret = new ActionIndex(); if (!element.getAttribute("name").equals("_ContextActions")) { return null; } // read object properties NodeList objectNodes = element.getElementsByTagName("object"); for (int i = 0; i < objectNodes.getLength(); i++) { Element objElement = (Element) objectNodes.item(i); String container = objElement.getAttribute("name"); int x = Integer.parseInt(objElement.getAttribute("x")); int y = Integer.parseInt(objElement.getAttribute("y")); int width = Integer.parseInt(objElement.getAttribute("width")); int height = Integer.parseInt(objElement.getAttribute("height")); // now read the layer properties Element propsElement = (Element) objElement.getElementsByTagName("properties").item(0); if (propsElement != null) { NodeList properties = propsElement.getElementsByTagName("property"); if (properties != null) { for (int p = 0; p < properties.getLength(); p++) { try { ContextAction ca = new ContextAction(); ca.container = container; ca.x = x; ca.y = y; ca.width = width; ca.height = height; Element propElement = (Element) properties.item(p); ca.name = propElement.getAttribute("name"); String script = ((CDATASection) (propElement.getFirstChild().getNextSibling())) .getData(); ca.script = script.getBytes("UTF-8"); // Log.d("",ca.toString()); ret.put(ca); } catch (Exception e) { e.printStackTrace(); Log.e("TiledZoneLoader", "Problems with loading actions from context action layer"); } } } } } return ret; }
From source file:com.google.appengine.tools.mapreduce.ConfigurationTemplatePreprocessor.java
/** * Substitutes in the values in params for templated values. After this method * is called, any subsequent calls to this method for the same object result in * an {@link IllegalStateException}. To preprocess the template again, * create another {@code ConfigurationTemplatePreprocessor} from the source XML. * * @param params a map from key to value of all the template parameters * @return the document as an XML string with the template parameters filled * in/*from www.j a va 2s .com*/ * @throws MissingTemplateParameterException if any required parameter is * omitted * @throws IllegalStateException if this method has previously been called * on this object */ public String preprocess(Map<String, String> params) { HashMap<String, String> paramsCopy = new HashMap<String, String>(params); if (preprocessCalled) { throw new IllegalStateException("Preprocess can't be called twice for the same object"); } preprocessCalled = true; for (Entry<String, Element> entry : nameToValueElement.entrySet()) { Element valueElem = entry.getValue(); boolean isTemplateValue = valueElem.hasAttribute("template"); if (paramsCopy.containsKey(entry.getKey()) && isTemplateValue) { // Modifies the map in place, but that's fine for our use. Text valueData = (Text) valueElem.getFirstChild(); String newValue = paramsCopy.get(entry.getKey()); if (valueData != null) { valueData.setData(newValue); } else { valueElem.appendChild(doc.createTextNode(newValue)); } // Remove parameter, so we can tell if they gave us extras. paramsCopy.remove(entry.getKey()); } else if (isTemplateValue) { String templateAttribute = valueElem.getAttribute("template"); if ("required".equals(templateAttribute)) { throw new MissingTemplateParameterException( "Couldn't find expected parameter " + entry.getKey()); } else if ("optional".equals(templateAttribute)) { // The default value is the one already in the value text, so // leave it be. The one exception is if they self-closed the value tag, // so go ahead and add a Text child so Configuration doesn't barf. if (valueElem.getFirstChild() == null) { valueElem.appendChild(doc.createTextNode("")); } } else { throw new IllegalArgumentException("Value " + templateAttribute + " is not a valid template " + "attribute. Valid possibilities are: \"required\" or \"optional\"."); } // Remove parameter, so we can tell if they gave us extras. paramsCopy.remove(entry.getKey()); } else { throw new IllegalArgumentException( "Configuration property " + entry.getKey() + " is not a template property"); } // removeAttribute has no effect if the attributes don't exist valueElem.removeAttribute("template"); } if (paramsCopy.size() > 0) { // TODO(user): Is there a good way to bubble up all bad parameters? throw new UnexpectedTemplateParameterException("Parameter " + paramsCopy.keySet().iterator().next() + " wasn't found in the configuration template."); } return getDocAsXmlString(); }
From source file:edu.lternet.pasta.client.JournalCitationsClient.java
public String citationsOptionsHTML() 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 {//ww w . j a v a 2 s.c om DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList citationsList = documentElement.getElementsByTagName("journalCitation"); int nCitations = citationsList.getLength(); for (int i = 0; i < nCitations; i++) { Node journalCitationNode = citationsList.item(i); NodeList journalCitationChildren = journalCitationNode.getChildNodes(); String journalCitationId = ""; for (int j = 0; j < journalCitationChildren.getLength(); j++) { Node childNode = journalCitationChildren.item(j); if (childNode instanceof Element) { Element journalCitationElement = (Element) childNode; if (journalCitationElement.getTagName().equals("journalCitationId")) { Text text = (Text) journalCitationElement.getFirstChild(); if (text != null) { journalCitationId = text.getData().trim(); } } } } sb.append(String.format("<option value='%s'>%s</option>\n", journalCitationId, journalCitationId)); } 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.mdt.rtm.Invoker.java
public Element invoke(Param... params) throws ServiceException { Element result;/*from w ww. jav a 2s .c o m*/ long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation; if (timeSinceLastInvocation < INVOCATION_INTERVAL) { // In order not to invoke the RTM service too often try { Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation); } catch (InterruptedException e) { throw new ServiceInternalException( "Unexpected interruption while attempting to pause for some time before invoking the RTM service back", e); } } log.debug("Invoker running at " + new Date()); HttpClient client = new HttpClient(); if (proxyHostName != null) { // Sets an HTTP proxy and the credentials for authentication client.getHostConfiguration().setProxy(proxyHostName, proxyPortNumber); if (proxyLogin != null) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyLogin, proxyPassword)); } } GetMethod method = new GetMethod(serviceBaseUrl + REST_SERVICE_URL_POSTFIX); method.setRequestHeader(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8"); NameValuePair[] pairs = new NameValuePair[params.length + 1]; int i = 0; for (Param param : params) { log.debug(" setting " + param.getName() + "=" + param.getValue()); pairs[i++] = param.toNameValuePair(); } pairs[i++] = new NameValuePair(API_SIG_PARAM, calcApiSig(params)); method.setQueryString(pairs); try { URI methodUri; try { methodUri = method.getURI(); log.info("Executing the method:" + methodUri); } catch (URIException exception) { String message = "Cannot determine the URI of the web method"; log.error(message); throw new ServiceInternalException(message, exception); } int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + method.getStatusLine()); throw new ServiceInternalException("method failed: " + method.getStatusLine()); } // THINK: this method is deprecated, but the only way to get the body as a string, without consuming // the body input stream: the HttpMethodBase issues a warning but does not let you call the "setResponseStream()" method! String responseBodyAsString = method.getResponseBodyAsString(); log.info(" Invocation response:\r\n" + responseBodyAsString); Document responseDoc = builder.parse(method.getResponseBodyAsStream()); Element wrapperElt = responseDoc.getDocumentElement(); if (!wrapperElt.getNodeName().equals("rsp")) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + responseBodyAsString); } 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: " + responseBodyAsString); } else { 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: " + responseBodyAsString); } else { result = (Element) dataElt; } } } } catch (HttpException e) { throw new ServiceInternalException("", e); } catch (IOException e) { throw new ServiceInternalException("", e); } catch (SAXException e) { throw new ServiceInternalException("", e); } finally { // Release the connection. method.releaseConnection(); } lastInvocation = System.currentTimeMillis(); return result; }