Skip to content

Commit

Permalink
HBX-2916: Move XMLPrettyPrinter to the API and offer the ability to s…
Browse files Browse the repository at this point in the history
…pecify the XMLPrettyPrinterStrategy

  - Add new test case 'org.hibernate.tool.api.xml.XMLPrettyPrinterTest#testXmlPrettyPrintWithStrategy()'
  - Add new method 'org.hibernate.tool.api.xml.XMLPrettyPrinter#prettyPrintFile(File,XMLPrettyPrinterStrategy)'

Signed-off-by: Koen Aers <koen.aers@gmail.com>
  • Loading branch information
koentsje committed Sep 2, 2024
1 parent 002503d commit 7c4c15f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 11 additions & 4 deletions orm/src/main/java/org/hibernate/tool/api/xml/XMLPrettyPrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@
*
*/
public final class XMLPrettyPrinter {

public static void prettyPrintFile(File file) throws IOException {
prettyPrintFile(file, null);
}

public static void prettyPrintFile(File file, XMLPrettyPrinterStrategy strategy) throws IOException {
String input = readFile(file.getAbsolutePath(), Charset.defaultCharset());
String output = prettyFormat(input);
String output = prettyFormat(input, strategy);
PrintWriter writer = new PrintWriter(file);
writer.print(output);
writer.flush();
Expand All @@ -33,9 +37,12 @@ private static String readFile(String path, Charset encoding) throws IOException
return new String(encoded, encoding);
}

private static String prettyFormat(String input) {
private static String prettyFormat(String input, XMLPrettyPrinterStrategy strategy) {
try {
return XMLPrettyPrinterStrategyFactory.newXMLPrettyPrinterStrategy().prettyPrint(input);
if (strategy == null) {
strategy = XMLPrettyPrinterStrategyFactory.newXMLPrettyPrinterStrategy();
}
return strategy.prettyPrint(input);
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public class XMLPrettyPrinterTest {
" <bar>foobar</bar>\n" +
"</foo>\n";

private static final String XML_COMMENT = "<!-- Just a comment! -->";

private static final String fileName = "foobarfile.xml";

@TempDir
Expand All @@ -43,4 +45,18 @@ public void testXmlPrettyPrintDefault() throws Exception {
assertEquals(XML_AFTER, result);
}

@Test
public void testXmlPrettyPrintWithStrategy() throws Exception {
XMLPrettyPrinter.prettyPrintFile(xmlFile, new FooBarStrategy());
String result = Files.readString(xmlFile.toPath());
assertEquals(XML_AFTER + XML_COMMENT, result);
}

public static class FooBarStrategy implements XMLPrettyPrinterStrategy {
@Override
public String prettyPrint(String xml) throws Exception {
return XML_AFTER + XML_COMMENT;
}
}

}

0 comments on commit 7c4c15f

Please sign in to comment.