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.Source;
027 import javax.xml.transform.stream.StreamSource;
028
029 /**
030 * A helper class which provides a JAXP {@link Source} from a String
031 * which can be read as many times as required.
032 *
033 * @version $Revision: 523731 $
034 */
035 public class StringSource extends StreamSource implements Serializable {
036
037 private final String text;
038 private String encoding = "UTF-8";
039
040 public StringSource(String text) {
041 if (text == null) {
042 throw new NullPointerException("text can not be null");
043 }
044 this.text = text;
045 }
046
047 public StringSource(String text, String systemId) {
048 this(text);
049 setSystemId(systemId);
050 }
051
052 public StringSource(String text, String systemId, String encoding) {
053 this.text = text;
054 this.encoding=encoding;
055 setSystemId(systemId);
056 }
057
058 public InputStream getInputStream() {
059 try {
060 return new ByteArrayInputStream(text.getBytes(encoding));
061 } catch (UnsupportedEncodingException e) {
062 throw new RuntimeException(e);
063 }
064 }
065
066 public Reader getReader() {
067 return new StringReader(text);
068 }
069
070 public String toString() {
071 return "StringSource[" + text + "]";
072 }
073
074 public String getText() {
075 return text;
076 }
077
078 }