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  import java.nio.charset.StandardCharsets;
26  
27  /**
28   * Wraps an ordinary {@link CharSequence} as a source.
29   *
30   * @author Benjamin Bentmann
31   */
32  public class StringSource
33      implements Source
34  {
35  
36      private String content;
37  
38      private String location;
39  
40      /**
41       * Creates a new source backed by the specified string.
42       *
43       * @param content The String representation, may be empty or {@code null}.
44       */
45      public StringSource( CharSequence content )
46      {
47          this( content, null );
48      }
49  
50      /**
51       * Creates a new source backed by the specified string.
52       *
53       * @param content The String representation, may be empty or {@code null}.
54       * @param location The location to report for this use, may be {@code null}.
55       */
56      public StringSource( CharSequence content, String location )
57      {
58          this.content = ( content != null ) ? content.toString() : "";
59          this.location = ( location != null ) ? location : "(memory)";
60      }
61  
62      @Override
63      public InputStream getInputStream()
64          throws IOException
65      {
66          return new ByteArrayInputStream( content.getBytes( StandardCharsets.UTF_8 ) );
67      }
68  
69      @Override
70      public String getLocation()
71      {
72          return location;
73      }
74  
75      /**
76       * Gets the content of this source.
77       *
78       * @return The underlying character stream, never {@code null}.
79       */
80      public String getContent()
81      {
82          return content;
83      }
84  
85      @Override
86      public String toString()
87      {
88          return getLocation();
89      }
90  
91  }