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