List of usage examples for org.w3c.dom Element toString
public String toString()
From source file:Main.java
/** * text of a leaf node, without child element * //from w ww. java 2 s . com * @param tag * @return String */ public static String getNodeText(Element tag) { String text = tag.toString(); int i = text.indexOf(">"); //$NON-NLS-1$ int j = text.lastIndexOf("</"); //$NON-NLS-1$ if (i < 0 || j < 0 || j < i) { return ""; //$NON-NLS-1$ } return text.substring(i + 1, j); }
From source file:Main.java
public static synchronized String formatXml(Element e, int indent) { indent++;/*w w w . j a v a 2 s . c o m*/ for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) { appendIndent(e, n, indent); } return e.toString(); }
From source file:Main.java
/** * Retrieve the value of an XML tag. For internal use only during parsing the accounts * configuration file./*from w w w. j a va 2 s . c o m*/ * * @param element The elemement containing the tag * @param tagName The string name of the tag * @return Tag value */ public static String getTagValue(Element element, String tagName) throws Exception { try { NodeList tagList = element.getElementsByTagName(tagName); Element tagElement = (Element) tagList.item(0); NodeList textTagList = tagElement.getChildNodes(); return (textTagList.item(0)).getNodeValue().trim(); } catch (Exception e) { throw new Exception( "Error in parsing the element \"" + element.toString() + "\" with the tag \"" + tagName + "\""); } }
From source file:net.mumie.coursecreator.xml.ELClassListWrapper.java
public Map getELClasses() { LinkedHashMap map = new LinkedHashMap(); try {//from w w w.ja v a 2 s.c o m babble("getELClasses(): constructing XPaths"); XPath docPath = new DOMXPath("/mumie:pseudo_documents/mumie:class"); docPath.addNamespace(StringUtils.substringBefore(XMLConstants.PREFIX_META, ":"), XMLConstants.NS_META); // XPath idPath = new DOMXPath("./@id"); // XPath namePath = new DOMXPath("./name/*"); XPath idPath = new DOMXPath("attribute::id"); XPath pathPath = new DOMXPath("attribute::path"); idPath.addNamespace(StringUtils.substringBefore(XMLConstants.PREFIX_META, ":"), XMLConstants.NS_META); XPath namePath = new DOMXPath("child::mumie:name/child::text()"); namePath.addNamespace(StringUtils.substringBefore(XMLConstants.PREFIX_META, ":"), XMLConstants.NS_META); Element doc = classList.getDocumentElement(); babble("getELClasses(): this is my document root: " + doc.toString()); List li = docPath.selectNodes(doc); babble("getELClasses(): got back a list which " + (li == null ? "is null" : "has " + li.size() + " element(s)")); for (Iterator lit = li.iterator(); lit.hasNext();) { // FIXME(2): the loop body might use a minor code cleanup babble("getELClasses(): looping through nodes..."); Object node = lit.next(); //Object theID = idPath.selectSingleNode(node); Object thePath = pathPath.selectSingleNode(node); Object theName = namePath.selectSingleNode(node); String theNameStr = (theName instanceof Text ? ((Text) theName).getNodeValue() : "---"); //Integer theNewId = (theID instanceof Attr ? Integer.valueOf(((Attr)theID).getValue()) : new Integer(XMLConstants.UNDEFINED_ID)); String theNewPath = (thePath instanceof Attr ? ((Attr) thePath).getValue() : "/"); babble("getELClasses(): Will put (" + theNewPath //theID.toString() + ",\"" + theNameStr + "\") into the map."); map.put(theNewPath, theNameStr); babble("getELClasses(): ...end of one loop"); } // end of for (Iterator lit = li.iterator(); lit.hasNext();) } catch (Exception ex) { CCController.dialogErrorOccured("ELClassListWrapper: Exception", "ELClassListWrapper: Exception: " + ex, JOptionPane.ERROR_MESSAGE); return null; } // end of try-catch return map; }
From source file:org.pegadi.server.article.ArticleServerImpl.java
/** * Change the main tag name of an article. Used when the article type changes. * * @param art The article./*from ww w. j a va 2 s. com*/ * @param ID The ID of the new article type. */ protected void changeArticleType(Article art, int ID) { Map<String, Object> map = template.queryForMap("SELECT tagname FROM ArticleType WHERE ID=:id", Collections.singletonMap("id", ID)); String tag = (String) map.get("tagname"); Document doc = art.getDocument(); if (doc == null) { art.parseText(); doc = art.getDocument(); } if (doc == null) { log.error("changeArticleType: Can't get document for article, article is NOT changed."); return; } Element root = doc.getDocumentElement(); log.info("Root before: " + doc.getDocumentElement().toString()); Element replace = doc.createElement(tag); NamedNodeMap att = root.getAttributes(); for (int i = 0; i < att.getLength(); i++) { Node n = att.item(i); if (n instanceof Attr) { replace.setAttribute(((Attr) n).getName(), ((Attr) n).getValue()); } } NodeList nl = root.getChildNodes(); log.info("changeArticleType: Root node has {} children.", nl.getLength()); for (int i = 0; i < nl.getLength(); i++) { Node clone = nl.item(i).cloneNode(true); log.info("Adding node {} to replace", (i + 1)); replace.appendChild(clone); } log.info("Replacement node: {}", replace.toString()); doc.replaceChild(replace, root); log.info("Root after: {}", doc.getDocumentElement().toString()); if (!art.serialize()) { log.error("changeArticleType: Can't serialize the changed XML."); } }
From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java
private void submitPost(String actionType, HttpEntity postentity, List<NameValuePair> qparam, CallingContext cc) {//from ww w . j a v a 2s . c o m try { HttpResponse response = this.sendHttpRequest(POST, getUrl(), postentity, qparam, cc); int statusCode = response.getStatusLine().getStatusCode(); String responseString = WebUtils.readResponse(response); if (responseString.length() != 0) { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); xmlFactory.setNamespaceAware(true); xmlFactory.setIgnoringComments(true); xmlFactory.setCoalescing(true); DocumentBuilder builder = xmlFactory.newDocumentBuilder(); InputStream is = new ByteArrayInputStream(responseString.getBytes(UTF_CHARSET)); Document doc; try { doc = builder.parse(is); } finally { is.close(); } Element root = doc.getDocumentElement(); NodeList errorNodes = root.getElementsByTagName("error"); StringBuilder b = new StringBuilder(); if (errorNodes != null) { for (int i = 0; i < errorNodes.getLength(); ++i) { if (i != 0) { b.append("\n"); } Element e = (Element) errorNodes.item(i); b.append(e.getTextContent()); } String error = b.toString(); if (error.length() != 0) { throw new IllegalArgumentException(actionType + " to REDCap server failed. statusCode: " + statusCode + " error: " + error); } } } else { // this seems to be the common case??? logger.info(actionType + " to REDCap server returned no body"); } if (statusCode != HttpStatus.SC_OK) { throw new IllegalArgumentException( actionType + " to REDCap server failed - but no error content. Reason: " + response.getStatusLine().getReasonPhrase() + " status code: " + statusCode); } } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString()); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString()); } catch (SAXException e) { e.printStackTrace(); throw new IllegalArgumentException(actionType + " to REDCap server failed - " + e.toString()); } }
From source file:com.streamreduce.util.JiraClient.java
/** * Returns the project key based on the activity:object element. * * @param activityObjectElement the activity:object element * @param monitoredProjectKeys the set of project keys monitored in Nodeable * @return the project key or null if one couldn't be found *//*from w w w.j av a2 s. c o m*/ public String getProjectKeyOfEntry(org.apache.abdera.model.Element activityObjectElement, Set<String> monitoredProjectKeys) { // not sure how/why this would happen, but logs indicate it does if (activityObjectElement == null) { LOGGER.error("activityObjectElement is null"); return null; } QName linkQname = new QName("http://www.w3.org/2005/Atom", "link"); org.apache.abdera.model.Element linkElement = activityObjectElement.getFirstChild(linkQname); if (linkElement == null) { LOGGER.error("Unable to parse the linkElement of the Jira activity:object " + JSONUtils.xmlToJSON(activityObjectElement.toString())); return null; } URL href = getURLFromLinkElement(linkElement); // the returned href may be null if (href == null) { LOGGER.error("Unable to parse the link of the Jira activity:object for: " + JSONUtils.xmlToJSON(activityObjectElement.toString())); return null; } String hrefAsString = href.toString(); String[] pathParts = href.getPath().split("/"); String projectKey = getProjectKeyFromId(pathParts[pathParts.length - 1]); if (!monitoredProjectKeys.contains(projectKey)) { // Since the activity:object > link didn't give us the project key based on the logic // above (last path segment is the project key), lets try to see if we can adjust our // logic for the special cases as the approach above is the norm. if (hrefAsString.contains("/wiki/display/")) { // This is specialized logic to handle wiki comment activity projectKey = hrefAsString.split("/wiki/display/")[1].split("/")[0]; } else if (hrefAsString.contains("/wiki/download/")) { // This is specialized logic to handle wiki attachment activity linkElement = ((Entry) activityObjectElement.getParentElement()).getFirstChild(linkQname); href = getURLFromLinkElement(linkElement); hrefAsString = href.toString(); projectKey = hrefAsString.split("/wiki/display/")[1].split("/")[0]; } else { // This is specialized logic to handle new/updated/deleted wiki org.apache.abdera.model.Element activityTargetElement = ((Entry) activityObjectElement .getParentElement()).getFirstChild( new QName("http://activitystrea.ms/spec/1.0/", "target", "activity")); if (activityTargetElement != null) { linkElement = activityTargetElement.getFirstChild(linkQname); href = getURLFromLinkElement(linkElement); pathParts = href.getPath().split("/"); projectKey = pathParts[pathParts.length - 1]; } } projectKey = getProjectKeyFromId(projectKey); if (!monitoredProjectKeys.contains(projectKey)) { // Revert back to null projectKey = null; } } return projectKey; }
From source file:com.hp.hpl.inkml.InkMLDOMParser.java
/** * Method to bind AnnotationXML element// w w w . j av a2 s.c om * * @param element the AnnotationXML element * @return AnnotationXML data object * @throws InkMLException */ protected AnnotationXML getAnnotationXML(final Element element) throws InkMLException { final AnnotationXML aXml = new AnnotationXML(); final NamedNodeMap attributesMap = element.getAttributes(); final int length = attributesMap.getLength(); for (int index = 0; index < length; index++) { final Attr attribute = (Attr) attributesMap.item(index); final String attributeName = attribute.getName(); if ("type".equals(attributeName)) { aXml.setType(attribute.getValue()); } else if ("encoding".equals(attributeName)) { aXml.setEncoding(attribute.getValue()); } else { aXml.addToOtherAttributesMap(attributeName, attribute.getValue()); } } InkMLDOMParser.LOG.finest("annotationXML received: " + element.toString()); final NodeList list = element.getChildNodes(); final int nChildren = list.getLength(); if (nChildren > 0) { for (int i = 0; i < nChildren; i++) { final Node node = list.item(i); if (!(node instanceof Element)) { continue; } final Element childElement = (Element) node; // get the tagName to use as Key in the valueMap final String tagName = childElement.getLocalName(); // String key = this.parentXPath+"/"+tagName; final String value = childElement.getFirstChild().getNodeValue(); // propertyElementsMap.put(key, childElement); // propertyElementsMap.put(key, value); aXml.addToPropertyElementsMap(tagName, value); InkMLDOMParser.LOG .finer("The property with name = " + tagName + " is added to the propertyElementsMap."); } } return aXml; }
From source file:com.streamreduce.util.JiraClient.java
/** * Handles the auto-tags, extra metadata, to be added to the activity message for Jira issue activity. * * @param projectKey the project key of the inventory item * @param activityObject the raw <activity:object /> element of the activity * @param entry the root element for the activity entry * @param hashtags the hashtags set we will manipulate *///from w w w .j av a 2 s . co m private void handleJiraWikiAutotags(String projectKey, org.apache.abdera.model.Element activityObject, Entry entry, Set<String> hashtags) { // Right now, the only additional auto-tags we add for wiki activity are the page's labels. To do this, we // parse the page id from ref attribute of the <thr:in-reply-to /> element. Once we get this, we make a SOAP // call to get the page labels for that id. // // Note: This does not appear to work for blog/article entries. The pageId we parse from the activity entry // always returns an empty array response when gathering the labels. We will still attempt to retrieve // the labels for blog/article entries just in case it gets fixed. org.apache.abdera.model.Element thr = entry .getFirstChild(new QName("http://purl.org/syndication/thread/1.0", "in-reply-to", "thr")); if (thr != null) { String pageUrl = thr.getAttributeValue("ref"); long pageId; // Just in case if (pageUrl == null) { LOGGER.error("Unable to parse the thr:in-reply-to of the Jira activity:object for: " + JSONUtils.xmlToJSON(activityObject.toString())); return; } try { pageId = Long.valueOf(pageUrl.substring(pageUrl.lastIndexOf("/") + 1)); } catch (NumberFormatException e) { // Not much we can do so log the error and continue processing LOGGER.error("Unexpected wiki page id when parsing activity URL (" + pageUrl + "): ", e.getMessage()); return; } try { List<org.w3c.dom.Element> labels = getWikiPageLabels(pageId); for (org.w3c.dom.Element label : labels) { // Confluence labels are returned as an array and we're only interested in ones that have children. // // Note: When a page has no labels, we get back an empty array element and so we need to check that // the label has children before trying to use it. if (!label.hasChildNodes()) { continue; } NodeList labelNames = label.getElementsByTagName("name"); if (labelNames == null) { // Not much we can do at this point but log the problem LOGGER.error("Unexpected response when retrieving labels for wiki page with an " + "id of " + pageId + " in the " + projectKey + " project."); } else { hashtags.add(removeIllegalHashtagCharacters("#" + labelNames.item(0).getTextContent())); } } } catch (SOAPException e) { // Not much we can do at this point but log the problem LOGGER.error( "Unable to make SOAP call to get wiki labels for " + projectKey + ": " + e.getMessage()); } } }
From source file:com.streamreduce.util.JiraClient.java
/** * Handles the auto-tags, extra metadata, to be added to the activity message for Jira issue activity. * * @param projectKey the project key of the invenentory item * @param activityObject the raw <activity:object /> element of the activity * @param hashtags the hashtags set we will manipulate *//*from w w w . j av a 2 s . c om*/ private void handleJiraIssueAutotags(String projectKey, org.apache.abdera.model.Element activityObject, Set<String> hashtags) { // Right now, the only additional auto-tags we add for issue activity are the issue's type, status and // priority. To do this, we parse the first href attribute of the first <link /> element of the // <activity:object /> tag. Once we get the issue name, we get the issues details with a SOAP call. Once we // get the issue's details, we get the integer id for the issue type, status and priority. We then have to // make three subsequent calls to get the list of issue types, issue statuses and issue priorities. Once those // are available, we reference the integer (id) value for the issue's type, status and priority against the // list to get the display name for the issue type, status and priority. org.apache.abdera.model.Element linkElement = ((Entry) activityObject.getParentElement()) .getFirstChild(new QName("http://www.w3.org/2005/Atom", "link")); // Just in case if (linkElement == null) { LOGGER.error("Unable to find the link of the Jira activity entry for: " + JSONUtils.xmlToJSON(activityObject.toString())); return; } URL activityLink = getURLFromLinkElement(linkElement); // Just in case if (activityLink == null) { LOGGER.error("Unable to parse the link of the Jira activity:object for: " + JSONUtils.xmlToJSON(activityObject.toString())); return; } String[] pathParts = activityLink.getPath().split("/"); String issueId = pathParts[pathParts.length - 1]; if (!issueId.contains("-")) { // Not much we can do at this point but log the problem LOGGER.error("Unable to get the Jira issue id from the following url: " + activityLink.toString()); return; } try { List<org.w3c.dom.Element> allIssueDetails = getIssueDetails(issueId); if (allIssueDetails == null || allIssueDetails.size() == 0) { // Not much we can do at this point but log the problem LOGGER.error("Unexpected response when retrieving Jira issue details for " + issueId + " in the " + projectKey + " project."); return; } // Our DOM parsing code is verbose, not my fault, but also very cautious. // Retrieve the issue details org.w3c.dom.Element issueDetails = allIssueDetails.get(0); NodeList issueDetailsPriorityNodes = issueDetails.getElementsByTagName("priority"); NodeList issueDetailsStatusNodes = issueDetails.getElementsByTagName("status"); NodeList issueDetailsTypeNodes = issueDetails.getElementsByTagName("type"); // Validate the responses if (issueDetailsPriorityNodes == null || issueDetailsPriorityNodes.getLength() == 0 || issueDetailsStatusNodes == null || issueDetailsStatusNodes.getLength() == 0 || issueDetailsTypeNodes == null || issueDetailsTypeNodes.getLength() == 0) { // Not much we can do at this point but log the problem LOGGER.error("Unexpected response when retrieving Jira issue detail priority/status/type for " + issueId + " in the " + projectKey + " project."); return; } // These represent the actual low-level identifiers for issue priority, status and type. These will // be compared against the priorites, statuses and types below. String issueDetailsPriority = issueDetailsPriorityNodes.item(0).getTextContent(); String issueDetailsStatus = issueDetailsStatusNodes.item(0).getTextContent(); String issueDetailsType = issueDetailsTypeNodes.item(0).getTextContent(); // Retrieve the issue priorities, statuses and types. List<org.w3c.dom.Element> issuePriorities = getIssuePriorities(); List<org.w3c.dom.Element> issueStatuses = getIssueStatuses(); List<org.w3c.dom.Element> issueTypes = getIssueTypes(); List<org.w3c.dom.Element> subTaskIssueTypes = getSubTaskIssueTypes(); // Validate the responses if (issuePriorities == null || issuePriorities.size() == 0 || issueStatuses == null || issueStatuses.size() == 0 || issueTypes == null || issueTypes.size() == 0 || subTaskIssueTypes == null) { // Not much we can do at this point but log the problem LOGGER.error("Unexpected response when retrieving Jira issue priority/status/type for " + issueId + " in the " + projectKey + " project."); return; } // Get the priority and add the hashtag String issuePriorityName = getNameForId(issuePriorities, issueDetailsPriority); String issueStatusName = getNameForId(issueStatuses, issueDetailsStatus); String issueTypeName = getNameForId(issueTypes, issueDetailsType); String subTaskIssueTypeName = getNameForId(subTaskIssueTypes, issueDetailsType); if (issueTypeName == null && subTaskIssueTypeName == null) { // Not much we can do at this point but log the problem LOGGER.error("Unable to get the issue type name for id " + issueDetailsType + " of the " + issueId + " issue in the " + projectKey + " project."); } else { hashtags.add( removeIllegalHashtagCharacters("#" + (issueTypeName != null ? issueTypeName.toLowerCase() : subTaskIssueTypeName.toLowerCase()))); } if (issuePriorityName == null) { // Not much we can do at this point but log the problem LOGGER.error("Unable to get the issue priority name for id " + issueDetailsPriority + " of the " + issueId + " issue in the " + projectKey + " project."); } else { hashtags.add(removeIllegalHashtagCharacters("#" + issuePriorityName.toLowerCase())); } if (issueStatusName == null) { // Not much we can do at this point but log the problem LOGGER.error("Unable to get the issue status name for id " + issueDetailsStatus + " of the " + issueId + " issue in the " + projectKey + " project."); } else { hashtags.add(removeIllegalHashtagCharacters("#" + issueStatusName.toLowerCase())); } // Would be nice to get the labels on the issue but there doesn't appear to be an API to retrieve them } catch (SOAPException e) { LOGGER.error("Unable to get the issue details for " + issueId + " in the " + projectKey + " project."); } }