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 private final String content;
33
34 private final String location;
35
36 private final int hashCode;
37
38 /**
39 * Creates a new source backed by the specified string.
40 *
41 * @param content The String representation, may be empty or {@code null}.
42 */
43 public StringSource(CharSequence content) {
44 this(content, null);
45 }
46
47 /**
48 * Creates a new source backed by the specified string.
49 *
50 * @param content The String representation, may be empty or {@code null}.
51 * @param location The location to report for this use, may be {@code null}.
52 */
53 public StringSource(CharSequence content, String location) {
54 this.content = (content != null) ? content.toString() : "";
55 this.location = (location != null) ? location : "(memory)";
56 this.hashCode = this.content.hashCode();
57 }
58
59 @Override
60 public InputStream getInputStream() throws IOException {
61 return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
62 }
63
64 @Override
65 public String getLocation() {
66 return location;
67 }
68
69 /**
70 * Gets the content of this source.
71 *
72 * @return The underlying character stream, never {@code null}.
73 */
74 public String getContent() {
75 return content;
76 }
77
78 @Override
79 public String toString() {
80 return getLocation();
81 }
82
83 @Override
84 public int hashCode() {
85 return hashCode;
86 }
87
88 @Override
89 public boolean equals(Object obj) {
90 if (this == obj) {
91 return true;
92 }
93
94 if (obj == null) {
95 return false;
96 }
97
98 if (!StringSource.class.equals(obj.getClass())) {
99 return false;
100 }
101
102 StringSource other = (StringSource) obj;
103 return this.content.equals(other.content);
104 }
105 }