You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicemix.apache.org by ge...@apache.org on 2008/08/25 12:57:29 UTC
svn commit: r688693 [3/5] - in /servicemix/utils/trunk: ./ src/ src/main/
src/main/java/ src/main/java/org/ src/main/java/org/apache/
src/main/java/org/apache/servicemix/
src/main/java/org/apache/servicemix/components/
src/main/java/org/apache/servicem...
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamReader.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamReader.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamReader.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamReader.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,338 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+/*
+ * This implementation comes from the XFire project
+ * https://svn.codehaus.org/xfire/trunk/xfire/xfire-core/src/main/org/codehaus/xfire/util/stax/
+ */
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.stream.Location;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+
+/**
+ * Abstract logic for creating XMLStreamReader from DOM documents. Its works
+ * using adapters for Element, Node and Attribute (
+ *
+ * @author <a href="mailto:tsztelak@gmail.com">Tomasz Sztelak</a>
+ */
+public abstract class DOMStreamReader implements XMLStreamReader {
+
+ protected Map properties = new HashMap();
+
+ protected int currentEvent = XMLStreamConstants.START_DOCUMENT;
+
+ protected FastStack<ElementFrame> frames = new FastStack<ElementFrame>();
+
+ protected ElementFrame frame;
+
+ /**
+ *
+ */
+ public static class ElementFrame {
+
+ Object element;
+ boolean started;
+ boolean ended;
+ int currentChild = -1;
+ int currentAttribute = -1;
+ int currentElement = -1;
+ List<String> uris;
+ List<String> prefixes;
+ List attributes;
+ final ElementFrame parent;
+
+ public ElementFrame(Object element, ElementFrame parent) {
+ this.element = element;
+ this.parent = parent;
+ }
+ }
+
+ /**
+ * @param element
+ */
+ public DOMStreamReader(ElementFrame frame) {
+ init(frame); // NOPMD
+ }
+
+ private void init(ElementFrame f) {
+ this.frame = f;
+ frames.push(this.frame);
+ newFrame(f);
+ }
+
+ protected ElementFrame getCurrentFrame() {
+ return frame;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#getProperty(java.lang.String)
+ */
+ public Object getProperty(String key) throws IllegalArgumentException {
+ return properties.get(key);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#next()
+ */
+ public int next() throws XMLStreamException {
+ if (frame.ended) {
+ frames.pop();
+ if (!frames.empty()) {
+ frame = frames.peek();
+ } else {
+ currentEvent = END_DOCUMENT;
+ return currentEvent;
+ }
+ }
+
+ if (!frame.started) {
+ frame.started = true;
+ currentEvent = START_ELEMENT;
+ } else if (frame.currentAttribute < getAttributeCount() - 1) {
+ frame.currentAttribute++;
+ currentEvent = ATTRIBUTE;
+ } else if (frame.currentChild < getChildCount() - 1) {
+ frame.currentChild++;
+
+ currentEvent = moveToChild(frame.currentChild);
+
+ if (currentEvent == START_ELEMENT) {
+ ElementFrame newFrame = getChildFrame(frame.currentChild);
+ newFrame.started = true;
+ frame = newFrame;
+ frames.push(this.frame);
+ currentEvent = START_ELEMENT;
+
+ newFrame(newFrame);
+ }
+ } else {
+ frame.ended = true;
+ currentEvent = END_ELEMENT;
+ endElement();
+ }
+ return currentEvent;
+ }
+
+ protected void newFrame(ElementFrame newFrame) {
+ }
+
+ protected void endElement() {
+ }
+
+ protected abstract int moveToChild(int currentChild);
+
+ protected abstract ElementFrame getChildFrame(int currentChild);
+
+ protected abstract int getChildCount();
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#require(int, java.lang.String,
+ * java.lang.String)
+ */
+ public void require(int arg0, String arg1, String arg2) throws XMLStreamException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#getElementText()
+ */
+ public abstract String getElementText() throws XMLStreamException;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#nextTag()
+ */
+ public int nextTag() throws XMLStreamException {
+ while (hasNext()) {
+ if (START_ELEMENT == next()) {
+ return START_ELEMENT;
+ }
+ }
+
+ return currentEvent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#hasNext()
+ */
+ public boolean hasNext() throws XMLStreamException {
+ return !(frames.size() == 0 && frame.ended);
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#close()
+ */
+ public void close() throws XMLStreamException {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#getNamespaceURI(java.lang.String)
+ */
+ public abstract String getNamespaceURI(String prefix);
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isStartElement()
+ */
+ public boolean isStartElement() {
+ return currentEvent == START_ELEMENT;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isEndElement()
+ */
+ public boolean isEndElement() {
+ return currentEvent == END_ELEMENT;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isCharacters()
+ */
+ public boolean isCharacters() {
+ return currentEvent == CHARACTERS;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.stream.XMLStreamReader#isWhiteSpace()
+ */
+ public boolean isWhiteSpace() {
+ return currentEvent == SPACE;
+ }
+
+ public int getEventType() {
+ return currentEvent;
+ }
+
+ public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) throws XMLStreamException {
+ char[] src = getText().toCharArray();
+
+ if (sourceStart + length >= src.length) {
+ length = src.length - sourceStart;
+ }
+
+ for (int i = 0; i < length; i++) {
+ target[targetStart + i] = src[i + sourceStart];
+ }
+
+ return length;
+ }
+
+ public boolean hasText() {
+ return currentEvent == CHARACTERS || currentEvent == DTD
+ || currentEvent == ENTITY_REFERENCE || currentEvent == COMMENT
+ || currentEvent == SPACE;
+ }
+
+ public Location getLocation() {
+ return new Location() {
+
+ public int getCharacterOffset() {
+ return 0;
+ }
+
+ public int getColumnNumber() {
+ return 0;
+ }
+
+ public int getLineNumber() {
+ return 0;
+ }
+
+ public String getPublicId() {
+ return null;
+ }
+
+ public String getSystemId() {
+ return null;
+ }
+
+ };
+ }
+
+ public boolean hasName() {
+ return currentEvent == START_ELEMENT || currentEvent == END_ELEMENT;
+ }
+
+ public String getVersion() {
+ return null;
+ }
+
+ public boolean isStandalone() {
+ return false;
+ }
+
+ public boolean standaloneSet() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public String getCharacterEncodingScheme() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public class FastStack<T> extends ArrayList<T> {
+
+ public void push(T o) {
+ add(o);
+ }
+
+ public T pop() {
+ return remove(size() - 1);
+ }
+
+ public boolean empty() {
+ return size() == 0;
+ }
+
+ public T peek() {
+ return get(size() - 1);
+ }
+ }
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamWriter.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamWriter.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamWriter.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/DOMStreamWriter.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+/*
+ * This implementation comes from the XFire project
+ * https://svn.codehaus.org/xfire/trunk/xfire/xfire-core/src/main/org/codehaus/xfire/util/stax/
+ */
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+public abstract class DOMStreamWriter implements XMLStreamWriter {
+
+ public void close() throws XMLStreamException {
+ }
+
+ public void flush() throws XMLStreamException {
+ }
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedNamespaceContext.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedNamespaceContext.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedNamespaceContext.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedNamespaceContext.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.util.Iterator;
+
+import javax.xml.namespace.NamespaceContext;
+
+public interface ExtendedNamespaceContext extends NamespaceContext {
+
+ /**
+ * Returns an {@link Iterator} of all namespace prefixes in scope within
+ * this context, including those inherited from ancestor contexts.
+ *
+ * @return An {@link Iterator} of prefix {@link String}s.
+ */
+ Iterator getPrefixes();
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedXMLStreamReader.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedXMLStreamReader.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedXMLStreamReader.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ExtendedXMLStreamReader.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.util.StreamReaderDelegate;
+
+public class ExtendedXMLStreamReader extends StreamReaderDelegate {
+
+ private SimpleNamespaceContext context = new SimpleNamespaceContext();
+
+ public ExtendedXMLStreamReader(XMLStreamReader delegate) {
+ super(delegate);
+ }
+
+ public NamespaceContext getNamespaceContext() {
+ return context;
+ }
+
+ public int nextTag() throws XMLStreamException {
+ int eventType = next();
+ while ((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace())
+ // skip whitespace
+ || (eventType == XMLStreamConstants.CDATA && isWhiteSpace())
+ // skip whitespace
+ || eventType == XMLStreamConstants.SPACE
+ || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
+ || eventType == XMLStreamConstants.COMMENT) {
+ eventType = next();
+ }
+ if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
+ throw new XMLStreamException("expected start or end tag", getLocation());
+ }
+ return eventType;
+ }
+
+ public int next() throws XMLStreamException {
+ int next = super.next();
+ if (next == START_ELEMENT) {
+ context = new SimpleNamespaceContext(context, getNamespaces());
+ } else if (next == END_ELEMENT) {
+ context = context.getParent();
+ }
+ return next;
+ }
+
+ private Map getNamespaces() {
+ Map ns = new HashMap();
+ for (int i = 0; i < getNamespaceCount(); i++) {
+ ns.put(getNamespacePrefix(i), getNamespaceURI(i));
+ }
+ return ns;
+ }
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/FragmentStreamReader.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/FragmentStreamReader.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/FragmentStreamReader.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/FragmentStreamReader.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,149 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.util.StreamReaderDelegate;
+
+public class FragmentStreamReader extends StreamReaderDelegate implements XMLStreamReader {
+
+ private static final int STATE_START_DOC = 0;
+ private static final int STATE_FIRST_ELEM = 1;
+ private static final int STATE_FIRST_RUN = 2;
+ private static final int STATE_RUN = 3;
+ private static final int STATE_END_DOC = 4;
+
+ private int depth;
+ private int state = STATE_START_DOC;
+ private int event = START_DOCUMENT;
+ private List rootPrefixes;
+
+ public FragmentStreamReader(XMLStreamReader parent) {
+ super(parent);
+ rootPrefixes = new ArrayList();
+ NamespaceContext ctx = getParent().getNamespaceContext();
+ if (ctx instanceof ExtendedNamespaceContext) {
+ Iterator it = ((ExtendedNamespaceContext) ctx).getPrefixes();
+ while (it.hasNext()) {
+ String prefix = (String) it.next();
+ rootPrefixes.add(prefix);
+ }
+ }
+ }
+
+ public int getEventType() {
+ return event;
+ }
+
+ public boolean hasNext() throws XMLStreamException {
+ return event != END_DOCUMENT;
+ }
+
+ public int next() throws XMLStreamException {
+ switch (state) {
+ case STATE_START_DOC:
+ state = STATE_FIRST_ELEM;
+ event = START_DOCUMENT;
+ break;
+ case STATE_FIRST_ELEM:
+ state = STATE_FIRST_RUN;
+ depth++;
+ event = START_ELEMENT;
+ break;
+ case STATE_FIRST_RUN:
+ case STATE_RUN:
+ state = STATE_RUN;
+ event = getParent().next();
+ if (event == START_ELEMENT) {
+ depth++;
+ } else if (event == END_ELEMENT) {
+ depth--;
+ if (depth == 0) {
+ state = STATE_END_DOC;
+ }
+ }
+ break;
+ case STATE_END_DOC:
+ event = END_DOCUMENT;
+ break;
+ default:
+ throw new IllegalStateException();
+ }
+ return event;
+ }
+
+ public int nextTag() throws XMLStreamException {
+ int eventType = next();
+ while ((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip
+ // whitespace
+ || (eventType == XMLStreamConstants.CDATA && isWhiteSpace()) // skip
+ // whitespace
+ || eventType == XMLStreamConstants.SPACE
+ || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
+ || eventType == XMLStreamConstants.COMMENT) {
+ eventType = next();
+ }
+ if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
+ throw new XMLStreamException("expected start or end tag", getLocation());
+ }
+ return eventType;
+ }
+
+ public int getNamespaceCount() {
+ if (state == STATE_FIRST_RUN) {
+ return rootPrefixes.size();
+ } else {
+ return getParent().getNamespaceCount();
+ }
+ }
+
+ public String getNamespacePrefix(int i) {
+ if (state == STATE_FIRST_RUN) {
+ return (String) rootPrefixes.get(i);
+ } else {
+ return getParent().getNamespacePrefix(i);
+ }
+ }
+
+ public String getNamespaceURI(int i) {
+ if (state == STATE_FIRST_RUN) {
+ return getParent().getNamespaceContext().getNamespaceURI((String) rootPrefixes.get(i));
+ } else {
+ return getParent().getNamespaceURI(i);
+ }
+ }
+
+ public String getNamespaceURI(String prefix) {
+ if (state == STATE_FIRST_RUN) {
+ return getParent().getNamespaceContext().getNamespaceURI(prefix);
+ } else {
+ return getParent().getNamespaceURI(prefix);
+ }
+ }
+
+ @Override
+ public boolean isStartElement() {
+ return event == START_ELEMENT;
+ }
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/NamespaceContextImpl.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/NamespaceContextImpl.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/NamespaceContextImpl.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/NamespaceContextImpl.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+
+/**
+ * A simple namespace context with a clean xbean configuration.
+ *
+ * @org.apache.xbean.XBean element="namespace-context"
+ * description="A NamespaceContext implementation"
+ * @author gnodet
+ * @version $Revision: 397796 $
+ */
+public class NamespaceContextImpl implements NamespaceContext {
+
+ /**
+ * map containing bound namespaces, keyed by their prefix. A LinkedHashMap
+ * is used to ensure that {@link #getPrefix(String)} always returns the same
+ * prefix, unless that prefix is removed.
+ */
+ private Map<String, String> namespaces;
+
+ /**
+ * Constructs a SimpleNamespaceContext with no parent context or namespace
+ * declarations.
+ */
+ public NamespaceContextImpl() {
+ this.namespaces = new LinkedHashMap<String, String>();
+ }
+
+ /**
+ * Constructs a SimpleNamespaceContext with no parent context that contains
+ * the specified prefixes.
+ *
+ * @param namespaces A Map of namespace URIs, keyed by their prefixes.
+ */
+ public NamespaceContextImpl(Map<String, String> namespaces) {
+ this.namespaces = new LinkedHashMap<String, String>(namespaces);
+ }
+
+ /**
+ * @org.apache.xbean.Map entryName="namespace" keyName="prefix"
+ * @return Returns the namespaces.
+ */
+ public Map<String, String> getNamespaces() {
+ return namespaces;
+ }
+
+ /**
+ * @param namespaces The namespaces to set.
+ */
+ public void setNamespaces(Map<String, String> namespaces) {
+ this.namespaces.clear();
+ if (namespaces != null) {
+ this.namespaces.putAll(namespaces);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String)
+ */
+ public String getNamespaceURI(String prefix) {
+ if (prefix == null) {
+ throw new IllegalArgumentException("prefix argument was null");
+ } else if (prefix.equals(XMLConstants.XML_NS_PREFIX)) {
+ return XMLConstants.XML_NS_URI;
+ } else if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) {
+ return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
+ } else if (namespaces.containsKey(prefix)) {
+ String uri = namespaces.get(prefix);
+ if (uri.length() == 0) {
+ return null;
+ } else {
+ return uri;
+ }
+ } else {
+ return null;
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String)
+ */
+ public String getPrefix(String nsURI) {
+ if (nsURI == null) {
+ throw new IllegalArgumentException("nsURI was null");
+ } else if (nsURI.length() == 0) {
+ throw new IllegalArgumentException("nsURI was empty");
+ } else if (nsURI.equals(XMLConstants.XML_NS_URI)) {
+ return XMLConstants.XML_NS_PREFIX;
+ } else if (nsURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
+ return XMLConstants.XMLNS_ATTRIBUTE;
+ }
+ Iterator iter = namespaces.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry entry = (Map.Entry) iter.next();
+ String uri = (String) entry.getValue();
+ if (uri.equals(nsURI)) {
+ return (String) entry.getKey();
+ }
+ }
+ if (nsURI.length() == 0) {
+ return "";
+ } else {
+ return null;
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String)
+ */
+ public Iterator<String> getPrefixes(String nsURI) {
+ if (nsURI == null) {
+ throw new IllegalArgumentException("nsURI was null");
+ } else if (nsURI.length() == 0) {
+ throw new IllegalArgumentException("nsURI was empty");
+ } else if (nsURI.equals(XMLConstants.XML_NS_URI)) {
+ return Collections.singleton(XMLConstants.XML_NS_PREFIX).iterator();
+ } else if (nsURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
+ return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE).iterator();
+ }
+ Set<String> prefixes = null;
+ for (Map.Entry<String, String> entry : namespaces.entrySet()) {
+ String uri = entry.getValue();
+ if (uri.equals(nsURI)) {
+ if (prefixes == null) {
+ prefixes = new HashSet<String>();
+ }
+ prefixes.add(entry.getKey());
+ }
+ }
+ if (prefixes != null) {
+ return Collections.unmodifiableSet(prefixes).iterator();
+ } else if (nsURI.length() == 0) {
+ return Collections.singleton("").iterator();
+ } else {
+ List<String> l = Collections.emptyList();
+ return l.iterator();
+ }
+ }
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/QNameHelper.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/QNameHelper.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/QNameHelper.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/QNameHelper.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import javax.xml.namespace.NamespaceContext;
+import javax.xml.namespace.QName;
+
+/**
+ * @version $Revision: 1.1 $
+ */
+public final class QNameHelper {
+
+ private QNameHelper() {
+ }
+
+ public static String getQualifiedName(QName qname) {
+ String prefix = qname.getPrefix();
+ String localPart = qname.getLocalPart();
+ if (prefix != null && prefix.length() > 0) {
+ return prefix + ":" + localPart;
+ }
+ return localPart;
+ }
+
+ /**
+ * Turns the given String into a QName using the current namespace context
+ */
+ public static QName asQName(NamespaceContext context, String text) {
+ int idx = text.indexOf(':');
+ if (idx >= 0) {
+ String prefix = text.substring(0, idx);
+ String localPart = text.substring(idx + 1);
+ String uri = context.getNamespaceURI(prefix);
+ return new QName(uri, localPart, prefix);
+ } else {
+ return new QName(text);
+ }
+ }
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ResourceSource.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ResourceSource.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ResourceSource.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/ResourceSource.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+
+import javax.xml.transform.stream.StreamSource;
+
+import org.springframework.core.io.Resource;
+
+/**
+ * A JAXP {@link StreamSource} which uses a Spring {@link Resource} as the source of the input stream.
+ * This implementation is re-entrant and can be used as many times as required to parse XML.
+ *
+ * @version $Revision: 564607 $
+ */
+public class ResourceSource extends StreamSource {
+
+ private final Resource resource;
+
+ public ResourceSource(Resource resource) {
+ this.resource = resource;
+ }
+
+ public InputStream getInputStream() {
+ try {
+ return resource.getInputStream();
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to open resource: " + resource + ". Reason: " + e, e);
+ }
+ }
+
+ public Reader getReader() {
+ return new InputStreamReader(getInputStream());
+ }
+
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SimpleNamespaceContext.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SimpleNamespaceContext.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SimpleNamespaceContext.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SimpleNamespaceContext.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+public class SimpleNamespaceContext implements ExtendedNamespaceContext {
+
+ private SimpleNamespaceContext parent;
+
+ private Map namespaces;
+
+ public SimpleNamespaceContext() {
+ namespaces = new HashMap();
+ }
+
+ public SimpleNamespaceContext(SimpleNamespaceContext parent, Map namespaces) {
+ this.parent = parent;
+ this.namespaces = namespaces;
+ }
+
+ public SimpleNamespaceContext getParent() {
+ return parent;
+ }
+
+ public Iterator getPrefixes() {
+ Set prefixes = new HashSet();
+ for (SimpleNamespaceContext context = this; context != null; context = context.parent) {
+ prefixes.addAll(context.namespaces.keySet());
+ }
+ return prefixes.iterator();
+ }
+
+ public String getNamespaceURI(String prefix) {
+ String uri = (String) namespaces.get(prefix);
+ if (uri == null && parent != null) {
+ uri = parent.getNamespaceURI(prefix);
+ }
+ return uri;
+ }
+
+ public String getPrefix(String namespaceURI) {
+ for (SimpleNamespaceContext context = this; context != null; context = context.parent) {
+ for (Iterator it = context.namespaces.keySet().iterator(); it.hasNext();) {
+ Map.Entry entry = (Map.Entry) it.next();
+ if (entry.getValue().equals(namespaceURI)) {
+ return (String) entry.getKey();
+ }
+ }
+ }
+ return null;
+ }
+
+ public Iterator getPrefixes(String namespaceURI) {
+ Set prefixes = new HashSet();
+ for (SimpleNamespaceContext context = this; context != null; context = context.parent) {
+ for (Iterator it = context.namespaces.keySet().iterator(); it.hasNext();) {
+ Map.Entry entry = (Map.Entry) it.next();
+ if (entry.getValue().equals(namespaceURI)) {
+ prefixes.add(entry.getKey());
+ }
+ }
+ }
+ return prefixes.iterator();
+ }
+
+ public void add(String prefix, String uri) {
+ namespaces.put(prefix, uri);
+ }
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceMarshaler.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceMarshaler.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceMarshaler.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceMarshaler.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.io.StringWriter;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.stream.StreamResult;
+
+/**
+ * @version $Revision: 564374 $
+ */
+public class SourceMarshaler {
+
+ private SourceTransformer transformer = new SourceTransformer();
+
+ public Source asSource(String text) {
+ return new StringSource(text);
+ }
+
+ public String asString(Source source) throws TransformerException {
+ StringWriter buffer = new StringWriter();
+ transformer.toResult(source, new StreamResult(buffer));
+ return buffer.toString();
+ }
+
+ public SourceTransformer getTransformer() {
+ return transformer;
+ }
+
+ public void setTransformer(SourceTransformer transformer) {
+ this.transformer = transformer;
+ }
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceTransformer.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceTransformer.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceTransformer.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/SourceTransformer.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,503 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.lang.reflect.Constructor;
+
+import javax.jbi.messaging.MessagingException;
+import javax.jbi.messaging.NormalizedMessage;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
+/**
+ * A helper class to transform from one type of {@link Source} to another
+ *
+ * @version $Revision: 670459 $
+ */
+public class SourceTransformer {
+
+ public static final String DEFAULT_CHARSET_PROPERTY = "org.apache.servicemix.default.charset";
+
+ /*
+ * When converting a DOM tree to a SAXSource, we try to use Xalan internal
+ * DOM parser if available. Else, transform the DOM tree to a String and
+ * build a SAXSource on top of it.
+ */
+ private static final Class DOM_2_SAX_CLASS;
+ static {
+ Class cl = null;
+ try {
+ cl = Class.forName("org.apache.xalan.xsltc.trax.DOM2SAX");
+ } catch (Throwable t) {
+ // Ignore
+ }
+ DOM_2_SAX_CLASS = cl;
+ }
+
+ private static String defaultCharset = System.getProperty(DEFAULT_CHARSET_PROPERTY, "UTF-8");
+
+ private DocumentBuilderFactory documentBuilderFactory;
+
+ private TransformerFactory transformerFactory;
+
+ public SourceTransformer() {
+ }
+
+ public SourceTransformer(DocumentBuilderFactory documentBuilderFactory) {
+ this.documentBuilderFactory = documentBuilderFactory;
+ }
+
+ public static String getDefaultCharset() {
+ return defaultCharset;
+ }
+
+ public static void setDefaultCharset(String defaultCharset) {
+ SourceTransformer.defaultCharset = defaultCharset;
+ }
+
+ /**
+ * Converts the given input Source into the required result, using the default charset
+ */
+ public void toResult(Source source, Result result) throws TransformerException {
+ toResult(source, result, defaultCharset);
+ }
+
+ /**
+ * Converts the given input Source into the required result, using the specified encoding
+ * @param source the input Source
+ * @param result the output Result
+ * @param charset the required charset, if you specify <code>null</code> the default charset will be used
+ */
+ public void toResult(Source source, Result result, String charset)
+ throws TransformerConfigurationException, TransformerException {
+ if (source == null) {
+ return;
+ }
+ if (charset == null) {
+ charset = defaultCharset;
+ }
+ Transformer transformer = createTransfomer();
+ if (transformer == null) {
+ throw new TransformerException("Could not create a transformer - JAXP is misconfigured!");
+ }
+ transformer.setOutputProperty(OutputKeys.ENCODING, charset);
+ transformer.transform(source, result);
+ }
+
+ /**
+ * Converts the given input Source into text
+ */
+ public String toString(Source source) throws TransformerException {
+ if (source == null) {
+ return null;
+ } else if (source instanceof StringSource) {
+ return ((StringSource) source).getText();
+ } else if (source instanceof BytesSource) {
+ return new String(((BytesSource) source).getData());
+ } else {
+ StringWriter buffer = new StringWriter();
+ toResult(source, new StreamResult(buffer));
+ return buffer.toString();
+ }
+ }
+
+ /**
+ * Converts the given input Node into text
+ */
+ public String toString(Node node) throws TransformerException {
+ return toString(new DOMSource(node));
+ }
+
+ /**
+ * Converts the content of the given message to a String
+ *
+ * @throws SAXException
+ * @throws IOException
+ * @throws ParserConfigurationException
+ */
+ public String contentToString(NormalizedMessage message) throws MessagingException, TransformerException, ParserConfigurationException,
+ IOException, SAXException {
+ return toString(message.getContent());
+ }
+
+ /**
+ * Converts the source instance to a {@link DOMSource} or returns null if
+ * the conversion is not supported (making it easy to derive from this class
+ * to add new kinds of conversion).
+ */
+ public DOMSource toDOMSource(Source source) throws ParserConfigurationException, IOException, SAXException, TransformerException {
+ if (source instanceof DOMSource) {
+ return (DOMSource) source;
+ } else if (source instanceof SAXSource) {
+ return toDOMSourceFromSAX((SAXSource) source);
+ } else if (source instanceof StreamSource) {
+ return toDOMSourceFromStream((StreamSource) source);
+ } else {
+ return null;
+ }
+ }
+
+ public Source toDOMSource(NormalizedMessage message) throws MessagingException, TransformerException, ParserConfigurationException,
+ IOException, SAXException {
+ Node node = toDOMNode(message);
+ return new DOMSource(node);
+ }
+
+ /**
+ * Converts the source instance to a {@link SAXSource} or returns null if
+ * the conversion is not supported (making it easy to derive from this class
+ * to add new kinds of conversion).
+ */
+ public SAXSource toSAXSource(Source source) throws IOException, SAXException, TransformerException {
+ if (source instanceof SAXSource) {
+ return (SAXSource) source;
+ } else if (source instanceof DOMSource) {
+ return toSAXSourceFromDOM((DOMSource) source);
+ } else if (source instanceof StreamSource) {
+ return toSAXSourceFromStream((StreamSource) source);
+ } else {
+ return null;
+ }
+ }
+
+ public StreamSource toStreamSource(Source source) throws TransformerException {
+ if (source instanceof StreamSource) {
+ return (StreamSource) source;
+ } else if (source instanceof DOMSource) {
+ return toStreamSourceFromDOM((DOMSource) source);
+ } else if (source instanceof SAXSource) {
+ return toStreamSourceFromSAX((SAXSource) source);
+ } else {
+ return null;
+ }
+ }
+
+ public StreamSource toStreamSourceFromSAX(SAXSource source) throws TransformerException {
+ InputSource inputSource = source.getInputSource();
+ if (inputSource != null) {
+ if (inputSource.getCharacterStream() != null) {
+ return new StreamSource(inputSource.getCharacterStream());
+ }
+ if (inputSource.getByteStream() != null) {
+ return new StreamSource(inputSource.getByteStream());
+ }
+ }
+ String result = toString(source);
+ return new StringSource(result);
+ }
+
+ public StreamSource toStreamSourceFromDOM(DOMSource source) throws TransformerException {
+ String result = toString(source);
+ return new StringSource(result);
+ }
+
+ public SAXSource toSAXSourceFromStream(StreamSource source) {
+ InputSource inputSource;
+ if (source.getReader() != null) {
+ inputSource = new InputSource(source.getReader());
+ } else {
+ inputSource = new InputSource(source.getInputStream());
+ }
+ inputSource.setSystemId(source.getSystemId());
+ inputSource.setPublicId(source.getPublicId());
+ return new SAXSource(inputSource);
+ }
+
+ public Reader toReaderFromSource(Source src) throws TransformerException {
+ StreamSource stSrc = toStreamSource(src);
+ Reader r = stSrc.getReader();
+ if (r == null) {
+ r = new InputStreamReader(stSrc.getInputStream());
+ }
+ return r;
+ }
+
+ public DOMSource toDOMSourceFromStream(StreamSource source) throws ParserConfigurationException, IOException, SAXException {
+ DocumentBuilder builder = createDocumentBuilder();
+ String systemId = source.getSystemId();
+ Document document = null;
+ Reader reader = source.getReader();
+ if (reader != null) {
+ document = builder.parse(new InputSource(reader));
+ } else {
+ InputStream inputStream = source.getInputStream();
+ if (inputStream != null) {
+ InputSource inputsource = new InputSource(inputStream);
+ inputsource.setSystemId(systemId);
+ document = builder.parse(inputsource);
+ } else {
+ throw new IOException("No input stream or reader available");
+ }
+ }
+ return new DOMSource(document, systemId);
+ }
+
+ public SAXSource toSAXSourceFromDOM(DOMSource source) throws TransformerException {
+ if (DOM_2_SAX_CLASS != null) {
+ try {
+ Constructor cns = DOM_2_SAX_CLASS.getConstructor(new Class[] {Node.class });
+ XMLReader converter = (XMLReader) cns.newInstance(new Object[] {source.getNode() });
+ return new SAXSource(converter, new InputSource());
+ } catch (Exception e) {
+ throw new TransformerException(e);
+ }
+ } else {
+ String str = toString(source);
+ StringReader reader = new StringReader(str);
+ return new SAXSource(new InputSource(reader));
+ }
+ }
+
+ public DOMSource toDOMSourceFromSAX(SAXSource source) throws IOException, SAXException, ParserConfigurationException,
+ TransformerException {
+ return new DOMSource(toDOMNodeFromSAX(source));
+ }
+
+ public Node toDOMNodeFromSAX(SAXSource source) throws ParserConfigurationException, IOException, SAXException, TransformerException {
+ DOMResult result = new DOMResult();
+ toResult(source, result);
+ return result.getNode();
+ }
+
+ /**
+ * Converts the given TRaX Source into a W3C DOM node
+ *
+ * @throws SAXException
+ * @throws IOException
+ * @throws ParserConfigurationException
+ */
+ public Node toDOMNode(Source source) throws TransformerException, ParserConfigurationException, IOException, SAXException {
+ DOMSource domSrc = toDOMSource(source);
+ return domSrc != null ? domSrc.getNode() : null;
+ }
+
+ /**
+ * Avoids multple parsing to DOM by caching the DOM representation in the
+ * message as a property so future calls will avoid the reparse - and avoid
+ * issues with stream based Source instances.
+ *
+ * @param message
+ * the normalized message
+ * @return the W3C DOM node for this message
+ * @throws SAXException
+ * @throws IOException
+ * @throws ParserConfigurationException
+ */
+ public Node toDOMNode(NormalizedMessage message) throws MessagingException, TransformerException, ParserConfigurationException,
+ IOException, SAXException {
+ Source content = message.getContent();
+ return toDOMNode(content);
+ }
+
+ /**
+ * Create a DOM element from the normalized message.
+ *
+ * @param message
+ * @return
+ * @throws MessagingException
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ public Element toDOMElement(NormalizedMessage message) throws MessagingException, TransformerException, ParserConfigurationException,
+ IOException, SAXException {
+ Node node = toDOMNode(message);
+ return toDOMElement(node);
+ }
+
+ /**
+ * Create a DOM element from the given source.
+ *
+ * @param source
+ * @return
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ public Element toDOMElement(Source source) throws TransformerException, ParserConfigurationException, IOException, SAXException {
+ Node node = toDOMNode(source);
+ return toDOMElement(node);
+ }
+
+ /**
+ * Create a DOM element from the DOM node. Simply cast if the node is an
+ * Element, or return the root element if it is a Document.
+ *
+ * @param node
+ * @return
+ * @throws TransformerException
+ */
+ public Element toDOMElement(Node node) throws TransformerException {
+ // If the node is an document, return the root element
+ if (node instanceof Document) {
+ return ((Document) node).getDocumentElement();
+ // If the node is an element, just cast it
+ } else if (node instanceof Element) {
+ return (Element) node;
+ // Other node types are not handled
+ } else {
+ throw new TransformerException("Unable to convert DOM node to an Element");
+ }
+ }
+
+ /**
+ * Create a DOM document from the given normalized message
+ *
+ * @param message
+ * @return
+ * @throws MessagingException
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ public Document toDOMDocument(NormalizedMessage message) throws MessagingException, TransformerException, ParserConfigurationException,
+ IOException, SAXException {
+ Node node = toDOMNode(message);
+ return toDOMDocument(node);
+ }
+
+ /**
+ * Create a DOM document from the given source.
+ *
+ * @param source
+ * @return
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ public Document toDOMDocument(Source source) throws TransformerException, ParserConfigurationException, IOException, SAXException {
+ Node node = toDOMNode(source);
+ return toDOMDocument(node);
+ }
+
+ /**
+ * Create a DOM document from the given Node. If the node is an document,
+ * just cast it, if the node is an root element, retrieve its owner element
+ * or create a new document and import the node.
+ *
+ * @param node
+ * @return
+ * @throws ParserConfigurationException
+ * @throws TransformerException
+ */
+ public Document toDOMDocument(Node node) throws ParserConfigurationException, TransformerException {
+ // If the node is the document, just cast it
+ if (node instanceof Document) {
+ return (Document) node;
+ // If the node is an element
+ } else if (node instanceof Element) {
+ Element elem = (Element) node;
+ // If this is the root element, return its owner document
+ if (elem.getOwnerDocument().getDocumentElement() == elem) {
+ return elem.getOwnerDocument();
+ // else, create a new doc and copy the element inside it
+ } else {
+ Document doc = createDocument();
+ doc.appendChild(doc.importNode(node, true));
+ return doc;
+ }
+ // other element types are not handled
+ } else {
+ throw new TransformerException("Unable to convert DOM node to a Document");
+ }
+ }
+
+ // Properties
+ // -------------------------------------------------------------------------
+ public DocumentBuilderFactory getDocumentBuilderFactory() {
+ if (documentBuilderFactory == null) {
+ documentBuilderFactory = createDocumentBuilderFactory();
+ }
+ return documentBuilderFactory;
+ }
+
+ public void setDocumentBuilderFactory(DocumentBuilderFactory documentBuilderFactory) {
+ this.documentBuilderFactory = documentBuilderFactory;
+ }
+
+ // Helper methods
+ // -------------------------------------------------------------------------
+ public DocumentBuilderFactory createDocumentBuilderFactory() {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ factory.setIgnoringElementContentWhitespace(true);
+ factory.setIgnoringComments(true);
+ return factory;
+ }
+
+ public DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
+ DocumentBuilderFactory factory = getDocumentBuilderFactory();
+ return factory.newDocumentBuilder();
+ }
+
+ public Document createDocument() throws ParserConfigurationException {
+ DocumentBuilder builder = createDocumentBuilder();
+ return builder.newDocument();
+ }
+
+ public TransformerFactory getTransformerFactory() {
+ if (transformerFactory == null) {
+ transformerFactory = createTransformerFactory();
+ }
+ return transformerFactory;
+ }
+
+ public void setTransformerFactory(TransformerFactory transformerFactory) {
+ this.transformerFactory = transformerFactory;
+ }
+
+ public Transformer createTransfomer() throws TransformerConfigurationException {
+ TransformerFactory factory = getTransformerFactory();
+ return factory.newTransformer();
+ }
+
+ public TransformerFactory createTransformerFactory() {
+ return TransformerFactory.newInstance();
+ }
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StAXSourceTransformer.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StAXSourceTransformer.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StAXSourceTransformer.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StAXSourceTransformer.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.io.IOException;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.sax.SAXSource;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import org.xml.sax.SAXException;
+
+/**
+ * An enhanced {@link org.apache.servicemix.jbi.jaxp.SourceTransformer} which
+ * adds support for converting from and to {@link StaxSource} instances. Since
+ * this class introduces a runtime dependency on StAX which some users may not
+ * use/require, this class is separated out from the core JAXP transformer.
+ *
+ * @version $Revision: 564900 $
+ */
+public class StAXSourceTransformer extends SourceTransformer {
+
+ private XMLInputFactory inputFactory;
+
+ private XMLOutputFactory outputFactory;
+
+ /**
+ * Converts the source instance to a
+ * {@link javax.xml.transform.dom.DOMSource} or returns null if the
+ * conversion is not supported (making it easy to derive from this class to
+ * add new kinds of conversion).
+ */
+ public StaxSource toStaxSource(Source source) throws XMLStreamException {
+ if (source instanceof StaxSource) {
+ return (StaxSource) source;
+ } else {
+ XMLInputFactory factory = getInputFactory();
+ XMLStreamReader reader = factory.createXMLStreamReader(source);
+ return new StaxSource(reader);
+ }
+ }
+
+ public XMLStreamReader toXMLStreamReader(Source source) throws XMLStreamException, TransformerException {
+ if (source instanceof StaxSource) {
+ return ((StaxSource) source).getXMLStreamReader();
+ }
+ // It seems that woodstox 2.9.3 throws some NPE in the servicemix-soap
+ // when using DOM, so use our own dom / stax parser
+ if (source instanceof DOMSource) {
+ Node n = ((DOMSource) source).getNode();
+ Element el = n instanceof Document ? ((Document) n).getDocumentElement() : n instanceof Element ? (Element) n : null;
+ if (el != null) {
+ return new W3CDOMStreamReader(el);
+ }
+ }
+ XMLInputFactory factory = getInputFactory();
+ try {
+ return factory.createXMLStreamReader(source);
+ } catch (XMLStreamException e) {
+ return factory.createXMLStreamReader(toReaderFromSource(source));
+ }
+ }
+
+ public DOMSource toDOMSource(Source source) throws ParserConfigurationException, IOException, SAXException, TransformerException {
+ DOMSource answer = super.toDOMSource(source);
+ if (answer == null && source instanceof StaxSource) {
+ answer = toDOMSourceFromStax((StaxSource) source);
+ }
+ return answer;
+ }
+
+ public SAXSource toSAXSource(Source source) throws IOException, SAXException, TransformerException {
+ SAXSource answer = super.toSAXSource(source);
+ if (answer == null && source instanceof StaxSource) {
+ answer = toSAXSourceFromStax((StaxSource) source);
+ }
+ return answer;
+ }
+
+ public DOMSource toDOMSourceFromStax(StaxSource source) throws TransformerException {
+ Transformer transformer = createTransfomer();
+ DOMResult result = new DOMResult();
+ transformer.transform(source, result);
+ return new DOMSource(result.getNode(), result.getSystemId());
+ }
+
+ public SAXSource toSAXSourceFromStax(StaxSource source) {
+ return (SAXSource) source;
+ }
+
+ // Properties
+ // -------------------------------------------------------------------------
+ public XMLInputFactory getInputFactory() {
+ if (inputFactory == null) {
+ inputFactory = createInputFactory();
+ }
+ return inputFactory;
+ }
+
+ public void setInputFactory(XMLInputFactory inputFactory) {
+ this.inputFactory = inputFactory;
+ }
+
+ public XMLOutputFactory getOutputFactory() {
+ if (outputFactory == null) {
+ outputFactory = createOutputFactory();
+ }
+ return outputFactory;
+ }
+
+ public void setOutputFactory(XMLOutputFactory outputFactory) {
+ this.outputFactory = outputFactory;
+ }
+
+ // Implementation methods
+ // -------------------------------------------------------------------------
+ protected XMLInputFactory createInputFactory() {
+ return XMLInputFactory.newInstance();
+ }
+
+ protected XMLOutputFactory createOutputFactory() {
+ return XMLOutputFactory.newInstance();
+ }
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StaxSource.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StaxSource.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StaxSource.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StaxSource.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import javax.xml.XMLConstants;
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.sax.SAXSource;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.ext.LexicalHandler;
+import org.xml.sax.helpers.AttributesImpl;
+
+public class StaxSource extends SAXSource implements XMLReader {
+
+ private XMLStreamReader streamReader;
+
+ private ContentHandler contentHandler;
+
+ private LexicalHandler lexicalHandler;
+
+ public StaxSource(XMLStreamReader streamReader) {
+ this.streamReader = streamReader;
+ setInputSource(new InputSource());
+ }
+
+ public XMLReader getXMLReader() {
+ return this;
+ }
+
+ public XMLStreamReader getXMLStreamReader() {
+ return streamReader;
+ }
+
+ protected void parse() throws SAXException {
+ try {
+ while (true) {
+ switch (streamReader.getEventType()) {
+ // Attributes are handled in START_ELEMENT
+ case XMLStreamConstants.ATTRIBUTE:
+ break;
+ case XMLStreamConstants.CDATA:
+ {
+ if (lexicalHandler != null) {
+ lexicalHandler.startCDATA();
+ }
+ int length = streamReader.getTextLength();
+ int start = streamReader.getTextStart();
+ char[] chars = streamReader.getTextCharacters();
+ contentHandler.characters(chars, start, length);
+ if (lexicalHandler != null) {
+ lexicalHandler.endCDATA();
+ }
+ break;
+ }
+ case XMLStreamConstants.CHARACTERS:
+ {
+ int length = streamReader.getTextLength();
+ int start = streamReader.getTextStart();
+ char[] chars = streamReader.getTextCharacters();
+ contentHandler.characters(chars, start, length);
+ break;
+ }
+ case XMLStreamConstants.SPACE:
+ {
+ int length = streamReader.getTextLength();
+ int start = streamReader.getTextStart();
+ char[] chars = streamReader.getTextCharacters();
+ contentHandler.ignorableWhitespace(chars, start, length);
+ break;
+ }
+ case XMLStreamConstants.COMMENT:
+ if (lexicalHandler != null) {
+ int length = streamReader.getTextLength();
+ int start = streamReader.getTextStart();
+ char[] chars = streamReader.getTextCharacters();
+ lexicalHandler.comment(chars, start, length);
+ }
+ break;
+ case XMLStreamConstants.DTD:
+ break;
+ case XMLStreamConstants.END_DOCUMENT:
+ contentHandler.endDocument();
+ return;
+ case XMLStreamConstants.END_ELEMENT: {
+ String uri = streamReader.getNamespaceURI();
+ String localName = streamReader.getLocalName();
+ String prefix = streamReader.getPrefix();
+ String qname = prefix != null && prefix.length() > 0 ? prefix + ":" + localName : localName;
+ contentHandler.endElement(uri, localName, qname);
+ //for (int i = 0; i < streamReader.getNamespaceCount(); i++) {
+ // contentHandler.endPrefixMapping(streamReader.getNamespaceURI(i));
+ //}
+ break;
+ }
+ case XMLStreamConstants.ENTITY_DECLARATION:
+ case XMLStreamConstants.ENTITY_REFERENCE:
+ case XMLStreamConstants.NAMESPACE:
+ case XMLStreamConstants.NOTATION_DECLARATION:
+ break;
+ case XMLStreamConstants.PROCESSING_INSTRUCTION:
+ break;
+ case XMLStreamConstants.START_DOCUMENT:
+ contentHandler.startDocument();
+ break;
+ case XMLStreamConstants.START_ELEMENT: {
+ //for (int i = 0; i < streamReader.getNamespaceCount(); i++) {
+ // contentHandler.startPrefixMapping(streamReader.getNamespacePrefix(i),
+ // streamReader.getNamespaceURI(i));
+ //}
+ String uri = streamReader.getNamespaceURI();
+ String localName = streamReader.getLocalName();
+ String prefix = streamReader.getPrefix();
+ String qname = prefix != null && prefix.length() > 0 ? prefix + ":" + localName : localName;
+ contentHandler.startElement(uri == null ? "" : uri, localName, qname, getAttributes());
+ break;
+ }
+ default:
+ break;
+ }
+ streamReader.next();
+ }
+ } catch (XMLStreamException e) {
+ SAXParseException spe;
+ if (e.getLocation() != null) {
+ spe = new SAXParseException(e.getMessage(), null, null, e.getLocation().getLineNumber(), e.getLocation()
+ .getColumnNumber(), e);
+ } else {
+ spe = new SAXParseException(e.getMessage(), null, null, -1, -1, e);
+ }
+ spe.initCause(e);
+ throw spe;
+ }
+ }
+
+ protected String getQualifiedName() {
+ String prefix = streamReader.getPrefix();
+ if (prefix != null && prefix.length() > 0) {
+ return prefix + ":" + streamReader.getLocalName();
+ } else {
+ return streamReader.getLocalName();
+ }
+ }
+
+ protected Attributes getAttributes() {
+ AttributesImpl attrs = new AttributesImpl();
+ // Adding namespace declaration as attributes is necessary because
+ // the xalan implementation that ships with SUN JDK 1.4 is bugged
+ // and does not handle the startPrefixMapping method
+ for (int i = 0; i < streamReader.getNamespaceCount(); i++) {
+ String prefix = streamReader.getNamespacePrefix(i);
+ String uri = streamReader.getNamespaceURI(i);
+ if (uri == null) {
+ uri = "";
+ }
+ // Default namespace
+ if (prefix == null || prefix.length() == 0) {
+ attrs.addAttribute(XMLConstants.DEFAULT_NS_PREFIX,
+ null,
+ XMLConstants.XMLNS_ATTRIBUTE,
+ "CDATA",
+ uri);
+ } else {
+ attrs.addAttribute(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
+ prefix,
+ XMLConstants.XMLNS_ATTRIBUTE + ":" + prefix,
+ "CDATA",
+ uri);
+ }
+ }
+ for (int i = 0; i < streamReader.getAttributeCount(); i++) {
+ String uri = streamReader.getAttributeNamespace(i);
+ String localName = streamReader.getAttributeLocalName(i);
+ String prefix = streamReader.getAttributePrefix(i);
+ String qName;
+ if (prefix != null && prefix.length() > 0) {
+ qName = prefix + ':' + localName;
+ } else {
+ qName = localName;
+ }
+ String type = streamReader.getAttributeType(i);
+ String value = streamReader.getAttributeValue(i);
+ if (value == null) {
+ value = "";
+ }
+
+ attrs.addAttribute(uri == null ? "" : uri, localName, qName, type, value);
+ }
+ return attrs;
+ }
+
+ public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
+ return false;
+ }
+
+ public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
+ }
+
+ public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
+ return null;
+ }
+
+ public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
+ if ("http://xml.org/sax/properties/lexical-handler".equals(name)) {
+ lexicalHandler = (LexicalHandler) value;
+ } else {
+ throw new SAXNotRecognizedException(name);
+ }
+ }
+
+ public void setEntityResolver(EntityResolver resolver) {
+ }
+
+ public EntityResolver getEntityResolver() {
+ return null;
+ }
+
+ public void setDTDHandler(DTDHandler handler) {
+ }
+
+ public DTDHandler getDTDHandler() {
+ return null;
+ }
+
+ public void setContentHandler(ContentHandler handler) {
+ this.contentHandler = handler;
+ }
+
+ public ContentHandler getContentHandler() {
+ return this.contentHandler;
+ }
+
+ public void setErrorHandler(ErrorHandler handler) {
+ }
+
+ public ErrorHandler getErrorHandler() {
+ return null;
+ }
+
+ public void parse(InputSource input) throws SAXException {
+ StaxSource.this.parse();
+ }
+
+ public void parse(String systemId) throws SAXException {
+ StaxSource.this.parse();
+ }
+
+}
Added: servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StringSource.java
URL: http://svn.apache.org/viewvc/servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StringSource.java?rev=688693&view=auto
==============================================================================
--- servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StringSource.java (added)
+++ servicemix/utils/trunk/src/main/java/org/apache/servicemix/jbi/jaxp/StringSource.java Mon Aug 25 03:57:27 2008
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.servicemix.jbi.jaxp;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.Serializable;
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+
+import javax.xml.transform.stream.StreamSource;
+
+/**
+ * A helper class which provides a JAXP {@link javax.xml.transform.Source} from a String which can
+ * be read as many times as required.
+ *
+ * @version $Revision: 564607 $
+ */
+public class StringSource extends StreamSource implements Serializable {
+
+ private final String text;
+
+ private String encoding = "UTF-8";
+
+ public StringSource(String text) {
+ if (text == null) {
+ throw new NullPointerException("text can not be null");
+ }
+ this.text = text;
+ }
+
+ public StringSource(String text, String systemId) {
+ this(text);
+ setSystemId(systemId);
+ }
+
+ public StringSource(String text, String systemId, String encoding) {
+ this.text = text;
+ this.encoding = encoding;
+ setSystemId(systemId);
+ }
+
+ public InputStream getInputStream() {
+ try {
+ return new ByteArrayInputStream(text.getBytes(encoding));
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Reader getReader() {
+ return new StringReader(text);
+ }
+
+ public String toString() {
+ return "StringSource[" + text + "]";
+ }
+
+ public String getText() {
+ return text;
+ }
+
+}