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 */
30 public class StringSource implements Source {
31 private final String content;
32
33 private final String location;
34
35 private final int hashCode;
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 this.hashCode = this.content.hashCode();
56 }
57
58 @Override
59 public InputStream getInputStream() throws IOException {
60 return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
61 }
62
63 @Override
64 public String getLocation() {
65 return location;
66 }
67
68 /**
69 * Gets the content of this source.
70 *
71 * @return The underlying character stream, never {@code null}.
72 */
73 public String getContent() {
74 return content;
75 }
76
77 @Override
78 public String toString() {
79 return getLocation();
80 }
81
82 @Override
83 public int hashCode() {
84 return hashCode;
85 }
86
87 @Override
88 public boolean equals(Object obj) {
89 if (this == obj) {
90 return true;
91 }
92
93 if (obj == null) {
94 return false;
95 }
96
97 if (!StringSource.class.equals(obj.getClass())) {
98 return false;
99 }
100
101 StringSource other = (StringSource) obj;
102 return this.content.equals(other.content);
103 }
104 }