List of usage examples for org.w3c.dom NamedNodeMap getNamedItem
public Node getNamedItem(String name);
From source file:org.ajax4jsf.context.ViewResources.java
private void mergeHeadResourceNode(List<Node> nodes, Set<String> renderedScripts, Node node) { boolean shouldAdd = true; String nodeName = node.getNodeName(); if (SCRIPT.equals(nodeName) || SCRIPT_UC.equals(nodeName)) { if (node.getFirstChild() == null) { //no text content etc. NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { Node item = attributes.getNamedItem(SRC); if (item == null) { attributes.getNamedItem(SRC_UC); }/*from w ww. j a v a 2s .co m*/ if (item != null) { String src = item.getNodeValue(); if (src != null) { if (renderedScripts.contains(src)) { shouldAdd = false; } else { renderedScripts.add(src); } } } } } } if (shouldAdd) { nodes.add(node); } }
From source file:org.ajax4jsf.templatecompiler.elements.vcp.FCallTemplateElement.java
public FCallTemplateElement(final Node element, final CompilationContext componentBean) throws CompilationException { super(element, componentBean); this.useOnlyEnumeratingParaments = false; NamedNodeMap nnm = element.getAttributes(); Node functionNameNode = nnm.getNamedItem(FUNCTION_NAME_ATTRIBUTE_NAME); if (functionNameNode != null) { this.functionName = functionNameNode.getNodeValue(); } else {// w ww . j a v a 2s .com throw new CompilationException("function name is not set"); } Node nodeUseOnlyThisParameters = nnm.getNamedItem(USE_ONLY_THIS_PARAMETERS); if (nodeUseOnlyThisParameters != null) { this.useOnlyEnumeratingParaments = Boolean.getBoolean(nodeUseOnlyThisParameters.getNodeValue()); } // if // read name of variable if need Node variableName = nnm.getNamedItem(VAR_ATTRIBUTE_NAME); if (variableName != null) { this.variable = variableName.getNodeValue(); } // if // read name of parameters if need ParameterProcessor parameterProcessor = new ParameterProcessor(element, componentBean); this.parameters = parameterProcessor.getParameters(); log.debug(this.parameters); List decodeFunctionName = null; decodeFunctionName = Arrays.asList(this.functionName.split(FUNCTION_DELIMITER)); if (null == decodeFunctionName) { decodeFunctionName = new ArrayList(); decodeFunctionName.add(this.functionName); } ArrayList functionNames = new ArrayList(); String lastClassName = componentBean.getFullBaseclass(); for (Iterator iter = decodeFunctionName.iterator(); iter.hasNext();) { String elementFunction = (String) iter.next(); try { log.debug("Try to load class : " + lastClassName); Class clazz = componentBean.loadClass(lastClassName); if (!iter.hasNext()) { String method = getMethod(clazz, elementFunction); if (method != null) { log.debug(method); functionNames.add(method); } else { log.error("Method " + elementFunction + " not found in class : " + lastClassName); throw new CompilationException(); } } else { // // Probing properties !!!! // PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, elementFunction); if (propertyDescriptor != null) { functionNames.add(propertyDescriptor.getReadMethod().getName() + "()"); log.debug("Property " + elementFunction + " mapped to function : " + propertyDescriptor.getReadMethod().getName()); lastClassName = propertyDescriptor.getPropertyType().getName(); } else { log.error("Property " + elementFunction + " not found in class : " + lastClassName); throw new CompilationException(); } } } catch (Throwable e) { log.error("Error load class : " + lastClassName + ", " + e.getLocalizedMessage()); e.printStackTrace(); throw new CompilationException("Error load class : " + lastClassName, e); } } StringBuffer tmpbuf = new StringBuffer(); for (Iterator iter = functionNames.iterator(); iter.hasNext();) { String tmpElement = (String) iter.next(); if (tmpbuf.length() != 0) { tmpbuf.append("."); } tmpbuf.append(tmpElement); } this.fullFunctionName = tmpbuf.toString(); }
From source file:org.alfresco.repo.workflow.activiti.ActivitiWorkflowEngine.java
private String getProcessKey(InputStream workflowDefinition) throws Exception { try {//from w w w .java2s. co m InputSource inputSource = new InputSource(workflowDefinition); DOMParser parser = new DOMParser(); parser.parse(inputSource); Document document = parser.getDocument(); NodeList elemnts = document.getElementsByTagName("process"); if (elemnts.getLength() < 1) { throw new IllegalArgumentException("The input stream does not contain a process definition!"); } NamedNodeMap attributes = elemnts.item(0).getAttributes(); Node idAttrib = attributes.getNamedItem("id"); if (idAttrib == null) { throw new IllegalAccessError("The process definition does not have an id!"); } if (activitiUtil.isMultiTenantWorkflowDeploymentEnabled()) { // Workflow-definition is deployed tenant-aware, key should be altered return factory.getDomainProcessKey(idAttrib.getNodeValue()); } else { return idAttrib.getNodeValue(); } } finally { workflowDefinition.close(); } }
From source file:org.alternativevision.gpx.GPXParser.java
/** * Parses a wpt node into a Waypoint object * //ww w .j ava 2 s . c o m * @param node * @return Waypoint object with info from the received node */ private Waypoint parseWaypoint(Node node) { if (node == null) { logger.error("null node received"); return null; } Waypoint w = new Waypoint(); NamedNodeMap attrs = node.getAttributes(); //check for lat attribute Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR); if (latNode != null) { Double latVal = null; try { latVal = Double.parseDouble(latNode.getNodeValue()); } catch (NumberFormatException ex) { logger.error("bad lat value in waypoint data: " + latNode.getNodeValue()); } w.setLatitude(latVal); } else { logger.warn("no lat value in waypoint data."); } //check for lon attribute Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR); if (lonNode != null) { Double lonVal = null; try { lonVal = Double.parseDouble(lonNode.getNodeValue()); } catch (NumberFormatException ex) { logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue()); } w.setLongitude(lonVal); } else { logger.warn("no lon value in waypoint data."); } NodeList childNodes = node.getChildNodes(); if (childNodes != null) { for (int idx = 0; idx < childNodes.getLength(); idx++) { Node currentNode = childNodes.item(idx); if (GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found ele node in waypoint data"); w.setElevation(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found time node in waypoint data"); w.setTime(getNodeValueAsDate(currentNode)); } else if (GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found name node in waypoint data"); w.setName(getNodeValueAsString(currentNode)); } else if (GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found cmt node in waypoint data"); w.setComment(getNodeValueAsString(currentNode)); } else if (GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found desc node in waypoint data"); w.setDescription(getNodeValueAsString(currentNode)); } else if (GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found src node in waypoint data"); w.setSrc(getNodeValueAsString(currentNode)); } else if (GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found magvar node in waypoint data"); w.setMagneticDeclination(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found geoidheight node in waypoint data"); w.setGeoidHeight(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found link node in waypoint data"); //TODO: parse link //w.setGeoidHeight(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found sym node in waypoint data"); w.setSym(getNodeValueAsString(currentNode)); } else if (GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found fix node in waypoint data"); w.setFix(getNodeValueAsFixType(currentNode)); } else if (GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found type node in waypoint data"); w.setType(getNodeValueAsString(currentNode)); } else if (GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found sat node in waypoint data"); w.setSat(getNodeValueAsInteger(currentNode)); } else if (GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found hdop node in waypoint data"); w.setHdop(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found vdop node in waypoint data"); w.setVdop(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found pdop node in waypoint data"); w.setPdop(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found ageofgpsdata node in waypoint data"); w.setAgeOfGPSData(getNodeValueAsDouble(currentNode)); } else if (GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found dgpsid node in waypoint data"); w.setDgpsid(getNodeValueAsInteger(currentNode)); } else if (GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("found extensions node in waypoint data"); Iterator<IExtensionParser> it = extensionParsers.iterator(); while (it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseWaypointExtension(currentNode); w.addExtensionData(parser.getId(), data); } } } } else { if (logger.isDebugEnabled()) logger.debug("no child nodes found in waypoint"); } return w; }
From source file:org.ambraproject.service.article.FetchArticleServiceImpl.java
/** * Returns the publication type attribute (Journal, Book, etc) of a citation node. * * @param citationNode citation element//w w w. ja v a2 s. c o m * @return publication type */ private String getCitationType(Node citationNode) { NamedNodeMap nnm = citationNode.getAttributes(); Node nnmNode = nnm.getNamedItem("citation-type"); // nlm 3.0 has this attribute listed as 'publication-type' nnmNode = nnmNode == null ? nnm.getNamedItem("publication-type") : nnmNode; // some old articles do not have this attribute return nnmNode == null ? null : nnmNode.getTextContent(); }
From source file:org.ambraproject.struts2.AmbraFeedResult.java
/** * Build a <code>List<Entry></code> from the articles found from solr * * @param searchParams data model// w ww. j ava 2 s . c o m * @param xmlBase xml base url * @param result list of articles * @return List of entries for the feed */ private List<Entry> buildArticleFeed(FeedSearchParameters searchParams, String xmlBase, Document result) { // Add each Article as a Feed Entry List<Entry> entries = new ArrayList<Entry>(); // default is 2pm local time int publishTime = CONF.getInt("ambra.services.feed.publishTime", 14); NodeList nodes = result.getElementsByTagName("result"); NodeList docs = null; // there should be only one if (nodes.getLength() == 1) { Node node = nodes.item(0); docs = node.getChildNodes(); } // looping through children of result element for (int i = 0; i < docs.getLength(); i++) { // doc element Node doc = docs.item(i); Entry entry = new Entry(); String volume = null; String issue = null; String articleType = null; String abstractText = null; String copyright = null; NodeList authorsForContent = null; Node subjectHierarchyNode = null; // children elements of doc element NodeList fields = doc.getChildNodes(); for (int j = 0; j < fields.getLength(); j++) { Node field = fields.item(j); NamedNodeMap nnm = field.getAttributes(); Node attrNameNode = nnm.getNamedItem("name"); String attrName = attrNameNode.getNodeValue(); if (attrName.equals("id")) { // id entry.setId("info:doi/" + field.getTextContent()); } else if (attrName.equals("copyright")) { // rights copyright = field.getTextContent(); } else if (attrName.equals("publication_date")) { // published and updated dates // the only values we care about are the month, day and year String date = field.getTextContent(); int year = Integer.valueOf(date.substring(0, 4)); int month = Integer.valueOf(date.substring(5, 7)); int day = Integer.valueOf(date.substring(8, 10)); // we want the local time zone Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); // month value is 0 based cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, publishTime); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); entry.setPublished(cal.getTime()); entry.setUpdated(cal.getTime()); } else if (attrName.equals("title_display")) { // title if (includeformatting) { Content title = new Content(); title.setType("html"); title.setValue(field.getTextContent()); entry.setTitleEx(title); } else { entry.setTitle(TextUtils.simpleStripAllTags(field.getTextContent())); } } else if (attrName.equals("author_display")) { // display ALL the authors in the content element // authors and collab authors authorsForContent = field.getChildNodes(); } else if (attrName.equals("author_without_collab_display")) { // authors (without the collaborative authors) ArrayList<Person> authors = newAuthorsList(searchParams, field); entry.setAuthors(authors); } else if (attrName.equals("author_collab_only_display")) { // contributors (collaborative authors) List<Person> contributors = new ArrayList<Person>(); NodeList children = field.getChildNodes(); for (int k = 0; k < children.getLength(); k++) { Node child = children.item(k); Person contributor = new Person(); contributor.setName(child.getTextContent()); contributors.add(contributor); } entry.setContributors(contributors); } else if (attrName.equals("volume")) { // volume (used for ForeignMarkup) volume = field.getTextContent(); } else if (attrName.equals("issue")) { // issue (used for ForeignMarkup) issue = field.getTextContent(); } else if (attrName.equals("article_type")) { // article type (used for ForeignMarkup) articleType = field.getTextContent(); } else if (attrName.equals("subject_hierarchy")) { subjectHierarchyNode = field; } else if (attrName.equals("abstract_primary_display")) { // abstract (used in Contents) abstractText = field.getTextContent(); } } // foreign markup if (searchParams.isExtended()) { List<Element> foreignMarkup = newForeignMarkUp(subjectHierarchyNode, volume, issue, articleType); if (foreignMarkup.size() > 0) { entry.setForeignMarkup(foreignMarkup); } } // alternative links List<Link> altLinks = newAltLinks(entry.getId(), xmlBase, entry.getTitle()); // Add alternative links to this entry entry.setAlternateLinks(altLinks); // contents List<Content> contents = newContentsList(searchParams, authorsForContent, abstractText); entry.setContents(contents); // rights if (copyright != null) { entry.setRights(copyright); } else { // Default is CC BY SA 3.0 entry.setRights(JOURNAL_COPYRIGHT()); } // Add completed Entry to List entries.add(entry); } return entries; }
From source file:org.apache.any23.extractor.html.EmbeddedJSONLDExtractor.java
/** * It extracts prefixes defined in the <i>LINK</i> meta tags. * * @param in/*from w w w .ja v a 2 s . c o m*/ */ private void extractLinkDefinedPrefixes(Document in) { List<Node> linkNodes = DomUtils.findAll(in, "/HTML/HEAD/LINK"); for (Node linkNode : linkNodes) { NamedNodeMap attributes = linkNode.getAttributes(); Node relNode = attributes.getNamedItem("rel"); String rel = relNode == null ? null : relNode.getTextContent(); Node hrefNode = attributes.getNamedItem("href"); String href = hrefNode == null ? null : hrefNode.getTextContent(); if (rel != null && href != null && RDFUtils.isAbsoluteIRI(href)) { prefixes.put(rel, SimpleValueFactory.getInstance().createIRI(href)); } } }
From source file:org.apache.any23.extractor.html.EmbeddedJSONLDExtractor.java
private Set<JSONLDScript> extractJSONLDScript(Document in, String baseProfile, ExtractionParameters extractionParameters, ExtractionContext extractionContext, ExtractionResult out) throws IOException, ExtractionException { List<Node> scriptNodes = DomUtils.findAll(in, "//SCRIPT"); Set<JSONLDScript> result = new HashSet<>(); extractor = new JSONLDExtractorFactory().createExtractor(); for (Node jsonldNode : scriptNodes) { NamedNodeMap attributes = jsonldNode.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { if ("application/ld+json".equalsIgnoreCase(attributes.item(i).getTextContent())) { extractor.run(extractionParameters, extractionContext, IOUtils.toInputStream(jsonldNode.getTextContent(), StandardCharsets.UTF_8), out); }// w w w .j a v a2 s. c o m } Node nameAttribute = attributes.getNamedItem("name"); Node contentAttribute = attributes.getNamedItem("content"); if (nameAttribute == null || contentAttribute == null) { continue; } String name = nameAttribute.getTextContent(); String content = contentAttribute.getTextContent(); String xpath = DomUtils.getXPathForNode(jsonldNode); IRI nameAsIRI = getPrefixIfExists(name); if (nameAsIRI == null) { nameAsIRI = SimpleValueFactory.getInstance().createIRI(baseProfile + name); } JSONLDScript jsonldScript = new JSONLDScript(xpath, nameAsIRI, content); result.add(jsonldScript); } return result; }
From source file:org.apache.any23.extractor.html.HCardExtractor.java
private void fixIncludes(HTMLDocument document, Node node, IssueReport report) { NamedNodeMap attributes = node.getAttributes(); // header case test 32 if ("TD".equals(node.getNodeName()) && (null != attributes.getNamedItem("headers"))) { String id = attributes.getNamedItem("headers").getNodeValue(); Node header = document.findNodeById(id); if (null != header) { node.appendChild(header.cloneNode(true)); attributes.removeNamedItem("headers"); }/*from w w w . ja va2s. co m*/ } // include pattern, test 31 for (Node current : DomUtils.findAllByAttributeName(document.getDocument(), "class")) { if (!DomUtils.hasClassName(current, "include")) continue; // we have to remove the field soon to avoid infinite loops // no null check, we know it's there or we won't be in the loop current.getAttributes().removeNamedItem("class"); ArrayList<TextField> res = new ArrayList<TextField>(); HTMLDocument.readUrlField(res, current); TextField id = res.get(0); if (null == id) continue; TextField refId = new TextField(StringUtils.substringAfter(id.value(), "#"), id.source()); Node included = document.findNodeById(refId.value()); if (null == included) continue; if (DomUtils.isAncestorOf(included, current)) { final int[] nodeLocation = DomUtils.getNodeLocation(current); report.notifyIssue(IssueReport.IssueLevel.Warning, "Current node tries to include an ancestor node.", nodeLocation[0], nodeLocation[1]); continue; } current.appendChild(included.cloneNode(true)); } }
From source file:org.apache.any23.extractor.microdata.MicrodataParser.java
/** * Returns all the <b>itemprop</b>s for the given <b>itemscope</b> node. * * @param scopeNode node representing the <b>itemscope</b> * @param skipRoot if <code>true</code> the given root <code>node</code> * will be not read as a property, even if it contains the <b>itemprop</b> attribute. * @return the list of <b>itemprop</b>s detected within the given <b>itemscope</b>. * @throws MicrodataParserException if an error occurs while retrieving an property value. *//*w w w. j av a2 s.com*/ public List<ItemProp> getItemProps(final Node scopeNode, boolean skipRoot) throws MicrodataParserException { final Set<Node> accepted = new LinkedHashSet<>(); if (!skipRoot) { NamedNodeMap attributes = scopeNode.getAttributes(); if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null) { accepted.add(scopeNode); } } // TreeWalker to walk DOM tree starting with the scopeNode. Nodes maybe visited multiple times. TreeWalker treeWalker = ((DocumentTraversal) scopeNode.getOwnerDocument()).createTreeWalker(scopeNode, NodeFilter.SHOW_ELEMENT, new NodeFilter() { @Override public short acceptNode(Node node) { if (node.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap attributes = node.getAttributes(); if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null && !scopeNode.equals(node)) { accepted.add(node); } if (attributes.getNamedItem(ITEMSCOPE_ATTRIBUTE) != null) { // Don't visit descendants of nodes that define a new scope return FILTER_REJECT; } } return FILTER_ACCEPT; } }, false); // To populate accepted we only need to walk the tree. while (treeWalker.nextNode() != null) ; final List<ItemProp> result = new ArrayList<>(); for (Node itemPropNode : accepted) { final String itemProp = DomUtils.readAttribute(itemPropNode, ITEMPROP_ATTRIBUTE, null); if (StringUtils.isBlank(itemProp)) { manageError(new MicrodataParserException("invalid property name '" + itemProp + "'", itemPropNode)); continue; } final String[] propertyNames = itemProp.trim().split("\\s+"); ItemPropValue itemPropValue; for (String propertyName : propertyNames) { try { itemPropValue = getPropertyValue(itemPropNode); } catch (MicrodataParserException mpe) { manageError(mpe); continue; } result.add(new ItemProp(DomUtils.getXPathForNode(itemPropNode), propertyName, itemPropValue)); } } return result; }