Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}

}
Loading