List of usage examples for javax.xml.stream.events StartElement getNamespaceContext
public NamespaceContext getNamespaceContext();
From source file:Main.java
/** * Constructs a new StartElement that merges the attributes and namespaces * found in the specified StartElement, with the provided attributes. The * returned StartElement will contain all the attributes and namespaces of * the original, plus those defined in the map. * /*from w w w.j av a 2s. c om*/ * @param tag The original StartElement * @param attrs An iterator of Atributes to add to the element. * @return A new StartElement that contains all the original attributes and * namespaces, plus the provided attributes. */ public static StartElement mergeAttributes(StartElement tag, Iterator attrs, XMLEventFactory factory) { // create Attribute map Map attributes = new HashMap(); // iterate through start tag's attributes for (Iterator i = tag.getAttributes(); i.hasNext();) { Attribute attr = (Attribute) i.next(); attributes.put(attr.getName(), attr); } // iterate through new attributes while (attrs.hasNext()) { Attribute attr = (Attribute) attrs.next(); attributes.put(attr.getName(), attr); } factory.setLocation(tag.getLocation()); QName tagName = tag.getName(); return factory.createStartElement(tagName.getPrefix(), tagName.getNamespaceURI(), tagName.getLocalPart(), attributes.values().iterator(), tag.getNamespaces(), tag.getNamespaceContext()); }
From source file:Main.java
/** * Like {@link javanet.staxutils.XMLStreamUtils#mergeAttributes} but it can * also merge namespaces/*from ww w. j a v a2s . c om*/ * * @param tag * @param attrs * @param nsps */ public static StartElement mergeAttributes(StartElement tag, Iterator<? extends Attribute> attrs, Iterator<? extends Namespace> nsps, XMLEventFactory factory) { // create Attribute map Map<QName, Attribute> attributes = new HashMap<QName, Attribute>(); // iterate through start tag's attributes for (Iterator i = tag.getAttributes(); i.hasNext();) { Attribute attr = (Attribute) i.next(); attributes.put(attr.getName(), attr); } if (attrs != null) { // iterate through new attributes while (attrs.hasNext()) { Attribute attr = attrs.next(); attributes.put(attr.getName(), attr); } } Map<QName, Namespace> namespaces = new HashMap<QName, Namespace>(); for (Iterator i = tag.getNamespaces(); i.hasNext();) { Namespace ns = (Namespace) i.next(); namespaces.put(ns.getName(), ns); } if (nsps != null) { while (nsps.hasNext()) { Namespace ns = nsps.next(); namespaces.put(ns.getName(), ns); } } factory.setLocation(tag.getLocation()); QName tagName = tag.getName(); return factory.createStartElement(tagName.getPrefix(), tagName.getNamespaceURI(), tagName.getLocalPart(), attributes.values().iterator(), namespaces.values().iterator(), tag.getNamespaceContext()); }
From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java
/** * The actual injection procedure/*w w w.jav a 2 s . c o m*/ * @param in the input stream where the XML is coming from (will be closed in the end) * @param out the output stream where we write the annotated XML into (remains open) * @param refs a list of references * @throws IOException */ public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException { StringBuilder pb; String characters = null; NamespaceContext context = null; int marked; current_path = new Stack<String>(); current_path.push("//"); try { XMLEventReader r = inFac.createXMLEventReader(in); XMLEventWriter w = outFac.createXMLEventWriter(out); XMLStreamWriter ws = outFac.createXMLStreamWriter(System.out); while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement se = (StartElement) e; context = se.getNamespaceContext(); if (elementReferences == null) { // process the namespaces in the references this.prepareReferences(refs, context); } // store location col = e.getLocation().getColumnNumber(); // add to current xpath current_path.add(generator.asXPathString((StartElement) e)); //XPathHelper.addCurrentElementToStack(current_path, se); // check if the current xpath is in our list of attribute references if (attributeReferences.size() > 0) { for (int i = 0; i < refs.size(); i++) { Stack<String> stack = attributeReferences.get(refs.get(i)); if (matcher.matches(current_path, stack, true, context)) { // yes, let's inject the reference (only valid for attributes here) this.handleAttribute(w, refs.get(i)); attributeReferences.remove(refs.get(i)); refs.remove(i); } } } w.add(e); break; case XMLEvent.END_ELEMENT: // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now) if (characters != null) this.current_path.push(characters); if (elementReferences.size() > 0) { for (int i = 0; i < refs.size(); i++) { Stack<String> stack = elementReferences.get(refs.get(i)); if (matcher.matches(current_path, stack, true, context)) { // yes, let's inject the reference (only valid for attributes here) this.interceptingElement = refs.get(i); elementReferences.remove(refs.get(i)); refs.remove(i); } } } if (characters != null) { // clean up this.current_path.pop(); characters = null; } this.current_path.pop(); w.add(e); // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element if (this.interceptingElement != null) { w.add(eventFac.createSpace("\n")); writeElementIntoStream(w, interceptingElement); } break; case XMLEvent.CHARACTERS: characters = generator.asXPathString((Characters) e); w.add(e); break; default: w.add(e); break; } } } catch (XPathExpressionException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Not a valid XPath", e); } throw new IOException(e); } catch (XMLStreamException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e); } throw new IOException(e); } finally { in.close(); } }
From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java
/** * The actual injection procedure/*ww w. ja v a2 s . c om*/ * @param in the input stream where the XML is coming from (will be closed in the end) * @param out the output stream where we write the annotated XML into (remains open) * @param refs a list of references * @throws IOException */ public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException { StringBuilder pb; XPathElement characters = null; int marked; interceptingElements = new ArrayList<Reference>(); try { XMLEventReader r = getXMLInputFactory().createXMLEventReader(in); XMLEventWriter w = getXMLOutputFactory().createXMLEventWriter(out); while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement se = (StartElement) e; if (super.getNamespaceContext() == null) { super.updateNamespaceContext(se.getNamespaceContext()); } if (references == null) { // process the namespaces in the references references = this.prepareReferences(refs); } // store location col = e.getLocation().getColumnNumber(); // add to current xpath updateCurrentPath(getGenerator().asXPathElement((StartElement) e)); System.out.println(getCurrentPath()); // check if the current xpath is in our list of attribute references for (XPathPattern p : references.keySet()) { if (references.get(p) == null) continue; if (p.isAttribute()) { if (getMatcher().matches(p, getCurrentPath())) { se = this.handleAttribute(w, references.get(p), se); references.put(p, null); // removing it would lead to concurrentmodificationexcpetion } } } w.add(se); break; case XMLEvent.END_ELEMENT: updateCurrentPath(characters); // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now) XPathStack currentPath = getCurrentPath(); for (XPathPattern p : references.keySet()) { if (references.get(p) == null) continue; if (getMatcher().matches(p, currentPath)) { if (p.isSiblingElement()) { // injection happens below this.interceptingElements.add(references.get(p)); } else if (p.isChildElement()) { // we can add it directly w.add(getXMLEventFactory().createSpace("\n")); writeElementIntoStream(w, references.get(p)); } else { throw new IOException("Invalid Reference: " + p); } references.put(p, null); // removing it would lead to concurrentmodificationexcpetion //references.remove(p); //break; //otherwise ConcurrentModificationException } } // clean up if (characters != null) { getCurrentPath().pop(); characters = null; } getCurrentPath().pop(); w.add(e); // do not change position // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element if (this.interceptingElements.size() > 0) { // write all references into stream for (Reference ref : this.interceptingElements) { w.add(getXMLEventFactory().createSpace("\n")); writeElementIntoStream(w, ref); } // reset list this.interceptingElements.clear(); } break; case XMLEvent.CHARACTERS: characters = getGenerator().asXPathElement((Characters) e); w.add(e); break; default: w.add(e); break; } } } catch (XPathExpressionException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Not a valid XPath", e); } throw new IOException(e); } catch (XMLStreamException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e); } throw new IOException(e); } finally { in.close(); } }
From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java
/** * If the reference is a attribute (e.g. sawsdl:modelreference), we add it here (by creating * the according XMLEvent). The ref//from ww w .j a v a 2s . c om * @param w * @param ref * @param se * @throws XMLStreamException */ private StartElement handleAttribute(XMLEventWriter w, Reference ref, StartElement se) throws XMLStreamException { /* we are having attributes which are in both, the reference and the current element. We only add * a new Attribute event, if it is not already contained in the Start Element * * Example: * reference <element ns:attr1="value" reference="http://example.com"> * element <element ns:attr1="value"> */ StringBuilder referenceString = new StringBuilder(ref.getTarget().toString()); Matcher matcher = findAttributeInReference.matcher(referenceString); List<Attribute> attributeList = new ArrayList<Attribute>(); // copy namespaces LocalNamespaceContext lnc = new LocalNamespaceContext((BaseNsContext) se.getNamespaceContext()); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String key = null; String prefix = null; String value = null; // [ns:attr1, "value"] String[] l = referenceString.substring(start, end).split("="); if (l.length > 0) { // [ns, attr1] String[] n = l[0].split(":"); if (n.length == 2) { key = n[1]; prefix = n[0]; } else { key = n[0]; } if (l.length == 2) { value = l[1].substring(1, l[1].length() - 1); // remove "" } } // check if this is a namespace definition if ((prefix != null) && ("xmlns".contentEquals(prefix))) { lnc.put(key, value); } else { QName name = null; // create QName if (prefix != null) { name = new QName(null, key, prefix); } else { String namespaceURI = se.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX); name = new QName(namespaceURI, key); } if (name != null) { Attribute created = getXMLEventFactory().createAttribute(name, value); attributeList.add(created); } } } // remove redundant attribute from reference list Iterator<?> it = se.getAttributes(); while (it.hasNext()) { Attribute ae = (Attribute) it.next(); for (Attribute ar : attributeList) { if ((ar.getName().getLocalPart().contentEquals(ae.getName().getLocalPart())) && (ar.getValue().contentEquals(ae.getValue()))) { //System.out.println("Attribute removed! -> " + ar.getName() + "= " + ar.getValue()); attributeList.remove(ar); break; } } } // merge everything again Iterator<? extends Attribute> it2 = se.getAttributes(); while (it2.hasNext()) { attributeList.add(it2.next()); } // create a new element with the attribute set and return it return StartElementEventImpl.construct(se.getLocation(), se.getName(), attributeList.iterator(), lnc.getNamespaces().iterator(), lnc); }
From source file:org.apereo.portal.portlet.registry.PortletWindowRegistryImpl.java
protected StartElement addPortletWindowId(StartElement element, IPortletWindowId portletWindowId) { final Attribute windowIdAttribute = xmlEventFactory.createAttribute(PORTLET_WINDOW_ID_ATTR_NAME, portletWindowId.getStringId()); //Clone the start element to add the new attribute final QName name = element.getName(); final String prefix = name.getPrefix(); final String namespaceURI = name.getNamespaceURI(); final String localPart = name.getLocalPart(); @SuppressWarnings("unchecked") final Iterator<Attribute> attributes = element.getAttributes(); @SuppressWarnings("unchecked") final Iterator<Namespace> namespaces = element.getNamespaces(); final NamespaceContext namespaceContext = element.getNamespaceContext(); //Create a new iterator of the existing attributes + the new window id attribute final Iterator<Attribute> newAttributes = Iterators.concat(attributes, Iterators.forArray(windowIdAttribute)); return xmlEventFactory.createStartElement(prefix, namespaceURI, localPart, newAttributes, namespaces, namespaceContext);/*from w ww . j a v a 2s . co m*/ }