View Javadoc
1   package org.apache.maven.building;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  
26  /**
27   * Wraps an ordinary {@link CharSequence} as a source.
28   *
29   * @author Benjamin Bentmann
30   */
31  public class StringSource
32      implements Source
33  {
34  
35      private String content;
36  
37      private String location;
38  
39      /**
40       * Creates a new source backed by the specified string.
41       *
42       * @param content The String representation, may be empty or {@code null}.
43       */
44      public StringSource( CharSequence content )
45      {
46          this( content, null );
47      }
48  
49      /**
50       * Creates a new source backed by the specified string.
51       *
52       * @param content The String representation, may be empty or {@code null}.
53       * @param location The location to report for this use, may be {@code null}.
54       */
55      public StringSource( CharSequence content, String location )
56      {
57          this.content = ( content != null ) ? content.toString() : "";
58          this.location = ( location != null ) ? location : "(memory)";
59      }
60  
61      @Override
62      public InputStream getInputStream()
63          throws IOException
64      {
65          return new ByteArrayInputStream( content.getBytes( "UTF-8" ) );
66      }
67  
68      @Override
69      public String getLocation()
70      {
71          return location;
72      }
73  
74      /**
75       * Gets the content of this source.
76       *
77       * @return The underlying character stream, never {@code null}.
78       */
79      public String getContent()
80      {
81          return content;
82      }
83  
84      @Override
85      public String toString()
86      {
87          return getLocation();
88      }
89  
90  }