From 80aab0ed15de71a65d180b23a1fd2ee5ab66694e Mon Sep 17 00:00:00 2001 From: Stefan CORDES <50696194+ca-stefan-cordes@users.noreply.github.com> Date: Mon, 8 Aug 2022 17:11:57 +0200 Subject: [PATCH] Blocks: Always enclose with a new line brace. --- .../mojo/flatten/KeepCommentsInPom.java | 169 +++++++++++------- .../mojo/flatten/KeepCommentsInPomTest.java | 112 ++++++------ 2 files changed, 165 insertions(+), 116 deletions(-) diff --git a/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java b/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java index 3c68ea1b..c0aa5ed4 100644 --- a/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java +++ b/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java @@ -26,23 +26,27 @@ import org.xml.sax.SAXException; /** - * Helper class to keep the comments how they have been in the original pom.xml - * While reading with {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} the comments are not placed into the {@link org.apache.maven.model.Model} - * and so {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} is not able to re-write those comments. + * Helper class to keep the comments how they have been in the original pom.xml While reading with + * {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} the comments are not placed into the + * {@link org.apache.maven.model.Model} and so {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} is not able to + * re-write those comments. * - * Workaround (maybe until core is fixed) is to remember all the comments and restore them after MavenXpp3Writer has created the new flattened pom.xml. + * Workaround (maybe until core is fixed) is to remember all the comments and restore them after MavenXpp3Writer has + * created the new flattened pom.xml. * * Current restriction on non-unique child nodes is that this class finds the node back due to the position in the file, - * that may lead to mis-re-added comments e.g. on multiple added dependencies - * (but for e.g. resolveCiFriendliesOnly the nodes keep stable) + * that may lead to mis-re-added comments e.g. on multiple added dependencies (but for e.g. resolveCiFriendliesOnly the + * nodes keep stable) * */ -class KeepCommentsInPom { +class KeepCommentsInPom +{ /** * Create an instance with collected current comments of the passed pom.xml file. */ - static KeepCommentsInPom create(Log aLog, File aOriginalPomFile) throws MojoExecutionException { + static KeepCommentsInPom create(Log aLog, File aOriginalPomFile) throws MojoExecutionException + { KeepCommentsInPom tempKeepCommentsInPom = new KeepCommentsInPom(); tempKeepCommentsInPom.setLog(aLog); tempKeepCommentsInPom.loadComments(aOriginalPomFile); @@ -50,137 +54,168 @@ static KeepCommentsInPom create(Log aLog, File aOriginalPomFile) throws MojoExec } private Log log; - + /** * The unique path list for an original node (the comments are stored via the referenced previousSibling) */ - private Map commentsPaths; - - + private Map commentsPaths; + /** * */ - KeepCommentsInPom() { - super(); + KeepCommentsInPom() + { + super(); } - - /** + + /** * load all current comments and text fragments from xml file + * * @param anOriginalPomFile the pom.xml */ - private void loadComments(File anOriginalPomFile) throws MojoExecutionException { + private void loadComments(File anOriginalPomFile) throws MojoExecutionException + { commentsPaths = new HashMap<>(); DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance(); DocumentBuilder tempDB; - try { + try + { tempDB = tempDBF.newDocumentBuilder(); Document tempPom = tempDB.parse(anOriginalPomFile); Node tempNode = tempPom.getDocumentElement(); - walkOverNodes(tempNode,".",(node,nodePath)-> { + walkOverNodes(tempNode, ".", (node, nodePath) -> + { // collectNodesByPathNames - commentsPaths.put(nodePath,node); + commentsPaths.put(nodePath, node); }); - } catch (ParserConfigurationException | SAXException | IOException e) { - throw new MojoExecutionException("Cannot load comments from "+anOriginalPomFile, e); + } catch (ParserConfigurationException | SAXException | IOException e) + { + throw new MojoExecutionException("Cannot load comments from " + anOriginalPomFile, e); } } /** * Walk over the pom hierarchy of the Document. - * @param Node the current Node - * @param String the unique path in the parent + * + * @param Node the current Node + * @param String the unique path in the parent * @param aConsumer Function to be called with the toBeCollected/found node. */ - private void walkOverNodes(Node aNode, String aParentPath, BiConsumer aConsumer) { + private void walkOverNodes(Node aNode, String aParentPath, BiConsumer aConsumer) + { String tempNodeName = aNode.getNodeName(); - if (log.isDebugEnabled()) { - log.debug("walkOverNodes: aParentPath="+aParentPath+" tempNodeName="+tempNodeName); + if (log.isDebugEnabled()) + { + log.debug("walkOverNodes: aParentPath=" + aParentPath + " tempNodeName=" + tempNodeName); } - String tempNodePath = aParentPath+"\t"+tempNodeName; + String tempNodePath = aParentPath + "\t" + tempNodeName; aConsumer.accept(aNode, tempNodePath); NodeList tempChilds = aNode.getChildNodes(); // Copy the childs as aConsumer may change the node sequence (add a comment) List tempCopiedChilds = new ArrayList<>(); - Map tempChildWithSameName = new HashMap<>(); - for (int i=0;i tempChildWithSameName = new HashMap<>(); + for (int i = 0; i < tempChilds.getLength(); i++) + { Node tempItem = tempChilds.item(i); - if (tempItem.getNodeType() != Node.TEXT_NODE && tempItem.getNodeType() != Node.COMMENT_NODE) { + if (tempItem.getNodeType() != Node.TEXT_NODE && tempItem.getNodeType() != Node.COMMENT_NODE) + { // Take real nodes to find them back by number String tempChildNodeName = tempItem.getNodeName(); Integer tempChildWithSameNameCount = tempChildWithSameName.get(tempChildNodeName); - if (tempChildWithSameNameCount == null) { + if (tempChildWithSameNameCount == null) + { tempChildWithSameNameCount = 1; - } else { + } else + { tempChildWithSameNameCount += 1; } tempChildWithSameName.put(tempChildNodeName, tempChildWithSameNameCount); tempCopiedChilds.add(tempItem); } } - Map tempChildWithSameNameCounters = new HashMap<>(); - for (int i=0;i tempChildWithSameNameCounters = new HashMap<>(); + for (int i = 0; i < tempCopiedChilds.size(); i++) + { Node tempCopiedChild = tempCopiedChilds.get(i); String tempChildNodeName = tempCopiedChild.getNodeName(); - if (tempChildWithSameName.get(tempChildNodeName) > 1) { + if (tempChildWithSameName.get(tempChildNodeName) > 1) + { Integer tempChildWithSameNameCounter = tempChildWithSameNameCounters.get(tempChildNodeName); - if (tempChildWithSameNameCounter == null) { + if (tempChildWithSameNameCounter == null) + { tempChildWithSameNameCounter = 1; - } else { + } else + { tempChildWithSameNameCounter += 1; } - tempChildWithSameNameCounters.put(tempChildNodeName,tempChildWithSameNameCounter); + tempChildWithSameNameCounters.put(tempChildNodeName, tempChildWithSameNameCounter); // add a counter to find back the correct node. - walkOverNodes(tempCopiedChild, tempNodePath+"\t"+tempChildWithSameNameCounter, aConsumer); - } else { + walkOverNodes(tempCopiedChild, tempNodePath + "\t" + tempChildWithSameNameCounter, aConsumer); + } else + { // unique child names walkOverNodes(tempCopiedChild, tempNodePath, aConsumer); } } } - /** * @param String the XML written by {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} */ - public String restoreOriginalComments(String anXml, String aModelEncoding) throws MojoExecutionException { + public String restoreOriginalComments(String anXml, String aModelEncoding) throws MojoExecutionException + { DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance(); DocumentBuilder tempDB; - try { + try + { tempDB = tempDBF.newDocumentBuilder(); - String tempEncoding = aModelEncoding==null ? "UTF-8" : aModelEncoding; // default encoding UTF-8 when nothing in pom model. + String tempEncoding = aModelEncoding == null ? "UTF-8" : aModelEncoding; // default encoding UTF-8 when + // nothing in pom model. Document tempPom = tempDB.parse(new ByteArrayInputStream(anXml.getBytes(tempEncoding))); Node tempNode = tempPom.getDocumentElement(); - walkOverNodes(tempNode,".",(newNode,nodePath)->{ + walkOverNodes(tempNode, ".", (newNode, nodePath) -> + { Node tempOriginalNode = commentsPaths.get(nodePath); - if (tempOriginalNode != null) { + if (tempOriginalNode != null) + { String tempOriginalNodeName = tempOriginalNode.getNodeName(); - if (tempOriginalNodeName.equals(newNode.getNodeName())) { + if (tempOriginalNodeName.equals(newNode.getNodeName())) + { // found matching node Node tempRefChild = newNode; Node tempPotentialCommentOrText = tempOriginalNode.getPreviousSibling(); - while (tempPotentialCommentOrText != null && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE) { + while (tempPotentialCommentOrText != null + && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE) + { // skip text in the original xml node tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); } - while (tempPotentialCommentOrText != null && tempPotentialCommentOrText.getNodeType() == Node.COMMENT_NODE) { + while (tempPotentialCommentOrText != null + && tempPotentialCommentOrText.getNodeType() == Node.COMMENT_NODE) + { // copy the node to be able to call previoussibling for next element Node tempRefPrevious = tempRefChild.getPreviousSibling(); String tempWhitespaceTextBeforeRefNode = null; - if (tempRefPrevious != null && tempRefPrevious.getNodeType()==Node.TEXT_NODE) { + if (tempRefPrevious != null && tempRefPrevious.getNodeType() == Node.TEXT_NODE) + { tempWhitespaceTextBeforeRefNode = tempRefPrevious.getNodeValue(); } Node tempNewComment; tempNewComment = tempPom.createComment(tempPotentialCommentOrText.getNodeValue()); tempRefChild.getParentNode().insertBefore(tempNewComment, tempRefChild); // copy the whitespaces between comment and refNode - if (tempWhitespaceTextBeforeRefNode!=null) { - tempRefChild.getParentNode().insertBefore(tempPom.createTextNode(tempWhitespaceTextBeforeRefNode), tempRefChild); + if (tempWhitespaceTextBeforeRefNode != null) + { + tempRefChild.getParentNode().insertBefore( + tempPom.createTextNode(tempWhitespaceTextBeforeRefNode), tempRefChild); } - - tempRefChild=tempNewComment; - + + tempRefChild = tempNewComment; + tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); - while (tempPotentialCommentOrText != null && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE) { + while (tempPotentialCommentOrText != null + && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE) + { // skip text in the original xml node tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); } @@ -189,22 +224,27 @@ public String restoreOriginalComments(String anXml, String aModelEncoding) throw } }); return writeDocumentToString(tempPom); - } catch (ParserConfigurationException | SAXException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) { + } catch (ParserConfigurationException | SAXException | IOException | ClassNotFoundException + | InstantiationException | IllegalAccessException | ClassCastException e) + { throw new MojoExecutionException("Cannot add comments", e); } } /** * Use an LSSerializer to keep whitespaces added by MavenXpp3Writer + * * @param Document the pom to write to String. */ - private String writeDocumentToString(Document aPom) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + private String writeDocumentToString(Document aPom) + throws ClassNotFoundException, InstantiationException, IllegalAccessException + { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSOutput output = impl.createLSOutput(); output.setEncoding("UTF-8"); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - output.setByteStream(outStream ); + output.setByteStream(outStream); LSSerializer writer = impl.createLSSerializer(); writer.write(aPom, output); return new String(outStream.toByteArray()); @@ -213,18 +253,17 @@ private String writeDocumentToString(Document aPom) throws ClassNotFoundExceptio /** * @see #log */ - public Log getLog() { + public Log getLog() + { return log; } /** * @see #log */ - public void setLog(Log aLog) { + public void setLog(Log aLog) + { log = aLog; } - - - } diff --git a/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java b/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java index a3093b30..b00df593 100644 --- a/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java +++ b/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java @@ -38,72 +38,83 @@ * Test-Case for {@link FlattenMojo}. * */ -public class KeepCommentsInPomTest { - - private static final String PATH = "src/test/resources/keep-comments-in-pom/"; - private static final String TEST_TARGET_PATH = "target/test/resources/keep-comments-in-pom/"; - private static final String FLATTENED_POM = TEST_TARGET_PATH + ".flattened-pom.xml"; - private static final String EXPECTED_FLATTENED_POM = PATH + "expected-flattened-pom.xml"; - /** - * Expected result since jdk11 with updated xml header and properties sequence. - */ - private static final String EXPECTED_FLATTENED_POM_JDK11 = PATH + "expected-flattened-pom-jdk11.xml"; - - @Rule - public MojoRule rule = new MojoRule(); - - @Before - public void setup() { - new File(TEST_TARGET_PATH).mkdirs(); - } - /** - * Test method to check that profile activation file is not interpolated. - * - * @throws Exception if something goes wrong. - */ - @Test - public void keepsProfileActivationFile() throws Exception { - MavenProject project = rule.readMavenProject( new File( PATH ) ); - FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo( project, "flatten" ); - - DefaultPlexusConfiguration tempPluginConfiguration = new DefaultPlexusConfiguration("test"); - tempPluginConfiguration.addChild("outputDirectory", TEST_TARGET_PATH); - tempPluginConfiguration.addChild("keepCommentsInPom", "true"); - rule.configureMojo(flattenMojo, tempPluginConfiguration); - - // execute writes new FLATTENED_POM - flattenMojo.execute(); - - String tempExpectedContent; - if (isJdk8()) { - tempExpectedContent = getContent(EXPECTED_FLATTENED_POM); - } else { - tempExpectedContent = getContent(EXPECTED_FLATTENED_POM_JDK11); - } +public class KeepCommentsInPomTest +{ + + private static final String PATH = "src/test/resources/keep-comments-in-pom/"; + private static final String TEST_TARGET_PATH = "target/test/resources/keep-comments-in-pom/"; + private static final String FLATTENED_POM = TEST_TARGET_PATH + ".flattened-pom.xml"; + private static final String EXPECTED_FLATTENED_POM = PATH + "expected-flattened-pom.xml"; + /** + * Expected result since jdk11 with updated xml header and properties sequence. + */ + private static final String EXPECTED_FLATTENED_POM_JDK11 = PATH + "expected-flattened-pom-jdk11.xml"; + + @Rule + public MojoRule rule = new MojoRule(); + + @Before + public void setup() + { + new File(TEST_TARGET_PATH).mkdirs(); + } + + /** + * Test method to check that profile activation file is not interpolated. + * + * @throws Exception if something goes wrong. + */ + @Test + public void keepsProfileActivationFile() throws Exception + { + MavenProject project = rule.readMavenProject(new File(PATH)); + FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo(project, "flatten"); + + DefaultPlexusConfiguration tempPluginConfiguration = new DefaultPlexusConfiguration("test"); + tempPluginConfiguration.addChild("outputDirectory", TEST_TARGET_PATH); + tempPluginConfiguration.addChild("keepCommentsInPom", "true"); + rule.configureMojo(flattenMojo, tempPluginConfiguration); + + // execute writes new FLATTENED_POM + flattenMojo.execute(); + + String tempExpectedContent; + if (isJdk8()) + { + tempExpectedContent = getContent(EXPECTED_FLATTENED_POM); + } else + { + tempExpectedContent = getContent(EXPECTED_FLATTENED_POM_JDK11); + } String tempActualContent = getContent(FLATTENED_POM); - assertEquals("Expected POM does not match, see "+FLATTENED_POM, tempExpectedContent,tempActualContent); - - } + assertEquals("Expected POM does not match, see " + FLATTENED_POM, tempExpectedContent, tempActualContent); - /** + } + + /** * Check runtime version. * * @return true when runtime is JDK11 */ - private boolean isJdk8() { + private boolean isJdk8() + { // With Java 9 can be switched to java.lang.Runtime.version() String tempPropertyVersion = System.getProperty("java.version"); - if (tempPropertyVersion.startsWith("1.8.")) { + if (tempPropertyVersion.startsWith("1.8.")) + { return true; } return false; } + /** * */ - private String getContent(String aPomFile) throws IOException { + private String getContent(String aPomFile) throws IOException + { String tempString; - try (InputStream tempIn = new FileInputStream(aPomFile)) { + try (InputStream tempIn = new FileInputStream(aPomFile)) + { tempString = IOUtils.toString(tempIn); } // remove platform dependent CR/LF @@ -111,5 +122,4 @@ private String getContent(String aPomFile) throws IOException { return tempString; } - }