001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.converter.jaxp;
018
019 import java.io.ByteArrayInputStream;
020 import java.io.InputStream;
021 import java.io.Reader;
022 import java.io.Serializable;
023 import java.io.StringReader;
024 import java.io.UnsupportedEncodingException;
025
026 import javax.xml.transform.stream.StreamSource;
027
028 /**
029 * A helper class which provides a JAXP {@link Source} from a String which can
030 * be read as many times as required.
031 *
032 * @version $Revision: 563607 $
033 */
034 public class StringSource extends StreamSource implements Serializable {
035
036 private final String text;
037 private String encoding = "UTF-8";
038
039 public StringSource(String text) {
040 if (text == null) {
041 throw new NullPointerException("text can not be null");
042 }
043 this.text = text;
044 }
045
046 public StringSource(String text, String systemId) {
047 this(text);
048 setSystemId(systemId);
049 }
050
051 public StringSource(String text, String systemId, String encoding) {
052 this.text = text;
053 this.encoding = encoding;
054 setSystemId(systemId);
055 }
056
057 public InputStream getInputStream() {
058 try {
059 return new ByteArrayInputStream(text.getBytes(encoding));
060 } catch (UnsupportedEncodingException e) {
061 throw new RuntimeException(e);
062 }
063 }
064
065 public Reader getReader() {
066 return new StringReader(text);
067 }
068
069 public String toString() {
070 return "StringSource[" + text + "]";
071 }
072
073 public String getText() {
074 return text;
075 }
076
077 }