View Javadoc
1   /*
2    * XML Format Maven Plugin (https://github.com/acegi/xml-format-maven-plugin)
3    *
4    * Copyright 2011-2025 Acegi Technology Pty Limited.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package au.com.acegi.xmlformat;
19  
20  import static java.nio.charset.StandardCharsets.UTF_8;
21  
22  import static org.hamcrest.CoreMatchers.not;
23  import static org.hamcrest.CoreMatchers.nullValue;
24  import static org.hamcrest.MatcherAssert.assertThat;
25  
26  import java.io.File;
27  import java.io.IOException;
28  import java.io.InputStream;
29  import java.io.InputStreamReader;
30  import java.io.OutputStream;
31  import java.io.OutputStreamWriter;
32  import java.io.StringWriter;
33  import java.io.Writer;
34  import java.nio.file.Files;
35  
36  /**
37   * Utility methods required by the test package.
38   */
39  final class TestUtil {
40  
41      private TestUtil() {
42      }
43  
44      static String fileToString(final File in) {
45          try (InputStream is = Files.newInputStream(in.toPath())) {
46              return streamToString(is);
47          } catch (final IOException ex) {
48              throw new IllegalStateException(ex);
49          }
50      }
51  
52      static InputStream getResource(final String resource) {
53          final InputStream in = FormatUtilTest.class.getResourceAsStream(resource);
54          assertThat(resource + " not found", in, not(nullValue()));
55          return in;
56      }
57  
58      static String streamToString(final InputStream in) {
59          final StringWriter sw = new StringWriter();
60          final InputStreamReader reader = new InputStreamReader(in, UTF_8);
61          final char[] buffer = new char[4_096];
62          int n;
63          try {
64              while (-1 != (n = reader.read(buffer))) {
65                  sw.write(buffer, 0, n);
66              }
67          } catch (final IOException ex) {
68              throw new IllegalStateException(ex);
69          }
70          return sw.toString();
71      }
72  
73      static void stringToFile(final String msg, final File out) {
74          try (OutputStream fos = Files.newOutputStream(out.toPath());
75                  Writer writer = new OutputStreamWriter(fos, UTF_8)) {
76              writer.append(msg);
77          } catch (final IOException ex) {
78              throw new IllegalStateException(ex);
79          }
80      }
81  
82  }