Skip to content

Commit

Permalink
Use IntelliJ autoformatter and cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
uhafner committed May 15, 2024
1 parent 0b68793 commit 5efdaad
Showing 1 changed file with 63 additions and 30 deletions.
93 changes: 63 additions & 30 deletions src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
package edu.hm.hafner.coverage.parser;

import com.google.errorprone.annotations.CanIgnoreReturnValue;
import edu.hm.hafner.coverage.*;
import edu.hm.hafner.util.FilteredLog;
import edu.hm.hafner.util.SecureXmlParserFactory;
import edu.hm.hafner.util.SecureXmlParserFactory.ParsingException;
import edu.hm.hafner.util.TreeString;

import java.io.Reader;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.Reader;

import com.google.errorprone.annotations.CanIgnoreReturnValue;

import edu.hm.hafner.coverage.ClassNode;
import edu.hm.hafner.coverage.Coverage;
import edu.hm.hafner.coverage.CoverageParser;
import edu.hm.hafner.coverage.FileNode;
import edu.hm.hafner.coverage.Metric;
import edu.hm.hafner.coverage.ModuleNode;
import edu.hm.hafner.coverage.Node;
import edu.hm.hafner.coverage.PackageNode;
import edu.hm.hafner.util.FilteredLog;
import edu.hm.hafner.util.SecureXmlParserFactory;
import edu.hm.hafner.util.SecureXmlParserFactory.ParsingException;
import edu.hm.hafner.util.TreeString;

/**
* Parses Clover reports into a hierarchical Java Object Model.
*/
public class CloverParser extends CoverageParser {
private static final long serialVersionUID = -1903059983931698657L;

Expand All @@ -32,12 +43,18 @@ public class CloverParser extends CoverageParser {
private static final QName NUM = new QName("num");
private static final QName COUNT = new QName("count");

/**
* Creates a new instance of {@link CloverParser}.
*
* @param processingMode
* determines whether to ignore errors
*/
public CloverParser(final ProcessingMode processingMode) {
super(processingMode);
}

@Override
protected ModuleNode parseReport(Reader reader, String fileName, FilteredLog log) {
protected ModuleNode parseReport(final Reader reader, final String fileName, final FilteredLog log) {
try {
var factory = new SecureXmlParserFactory();
var eventReader = factory.createXmlEventReader(reader);
Expand All @@ -51,21 +68,24 @@ protected ModuleNode parseReport(Reader reader, String fileName, FilteredLog log
ModuleNode root = new ModuleNode("");
if (!readCoverage(eventReader, root, fileName).hasChildren()) {
handleEmptyResults(fileName, log);
} else {
}
else {
return root;
}

Check warning on line 74 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / PMD

ConfusingTernary

NORMAL: Avoid if (x != y) ..; else ..;.
Raw output
Avoid negation within an "if" expression with an "else" clause. For example, rephrase: `if (x != y) diff(); else same();` as: `if (x == y) same(); else diff();`. Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?". <pre> <code> boolean bar(int x, int y) { return (x != y) ? diff : same; } </code> </pre> <a href="https://docs.pmd-code.org/pmd-doc-7.0.0/pmd_rules_java_codestyle.html#confusingternary"> See PMD documentation. </a>
}
}
}
handleEmptyResults(fileName, log);
return new ModuleNode("empty");
} catch (XMLStreamException exception) {
}
catch (XMLStreamException exception) {
throw new SecureXmlParserFactory.ParsingException(exception);
}
}

@CanIgnoreReturnValue
private ModuleNode readCoverage(final XMLEventReader reader, final ModuleNode root, String fileName) throws XMLStreamException {
private ModuleNode readCoverage(final XMLEventReader reader, final ModuleNode root, final String fileName)
throws XMLStreamException {
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();

Expand All @@ -74,7 +94,8 @@ private ModuleNode readCoverage(final XMLEventReader reader, final ModuleNode ro
if (PROJECT.equals(startElement.getName())) {
readProject(reader, root, fileName);
}
} else if (event.isEndElement()) {
}
else if (event.isEndElement()) {
var endElement = event.asEndElement();
if (COVERAGE.equals((endElement.getName()))) {

Check warning on line 100 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / PMD

UselessParentheses

NORMAL: Useless parentheses.
Raw output
Parenthesized expressions are used to override the default operator precedence rules. Parentheses whose removal would not change the relative nesting of operators are unnecessary, because they don't change the semantics of the enclosing expression. Some parentheses that strictly speaking are unnecessary, may still be considered useful for readability. This rule allows to ignore violations on two kinds of unnecessary parentheses: - "Clarifying" parentheses, which separate operators of difference precedence. While unnecessary, they make precedence rules explicit, which may be useful for rarely used operators. For example: ```java (a + b) & c // is equivalent to `a + b & c`, but probably clearer ``` Unset the property `ignoreClarifying` to report them. - "Balancing" parentheses, which are unnecessary but visually balance out another pair of parentheses around an equality operator. For example, those two expressions are equivalent: ```java (a == null) != (b == null) a == null != (b == null) ``` The parentheses on the right are required, and the parentheses on the left are just more visually pleasing. Unset the property `ignoreBalancing` to report them. <pre> <code> public class Foo { { int n = 0; n = (n); // here n = (n * 2) * 3; // and here n = n * (2 * 3); // and here } } </code> </pre> <a href="https://docs.pmd-code.org/pmd-doc-7.0.0/pmd_rules_java_codestyle.html#uselessparentheses"> See PMD documentation. </a>
return root;
Expand All @@ -85,7 +106,8 @@ private ModuleNode readCoverage(final XMLEventReader reader, final ModuleNode ro
}

@CanIgnoreReturnValue
private ModuleNode readProject(final XMLEventReader reader, final ModuleNode root, String fileName) throws XMLStreamException {
private ModuleNode readProject(final XMLEventReader reader, final ModuleNode root, final String fileName)
throws XMLStreamException {
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();

Expand All @@ -94,10 +116,12 @@ private ModuleNode readProject(final XMLEventReader reader, final ModuleNode roo
if (METRICS.equals(startElement.getName())) {
addBranchCoverage(root, startElement);
addInstructionCoverage(root, startElement);
} else if (PACKAGE.equals(startElement.getName())) {
}
else if (PACKAGE.equals(startElement.getName())) {
readPackage(reader, root, startElement, fileName);
}
} else if (event.isEndElement()) {
}
else if (event.isEndElement()) {
var endElement = event.asEndElement();
if (PROJECT.equals((endElement.getName()))) {

Check warning on line 126 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / PMD

UselessParentheses

NORMAL: Useless parentheses.
Raw output
Parenthesized expressions are used to override the default operator precedence rules. Parentheses whose removal would not change the relative nesting of operators are unnecessary, because they don't change the semantics of the enclosing expression. Some parentheses that strictly speaking are unnecessary, may still be considered useful for readability. This rule allows to ignore violations on two kinds of unnecessary parentheses: - "Clarifying" parentheses, which separate operators of difference precedence. While unnecessary, they make precedence rules explicit, which may be useful for rarely used operators. For example: ```java (a + b) & c // is equivalent to `a + b & c`, but probably clearer ``` Unset the property `ignoreClarifying` to report them. - "Balancing" parentheses, which are unnecessary but visually balance out another pair of parentheses around an equality operator. For example, those two expressions are equivalent: ```java (a == null) != (b == null) a == null != (b == null) ``` The parentheses on the right are required, and the parentheses on the left are just more visually pleasing. Unset the property `ignoreBalancing` to report them. <pre> <code> public class Foo { { int n = 0; n = (n); // here n = (n * 2) * 3; // and here n = n * (2 * 3); // and here } } </code> </pre> <a href="https://docs.pmd-code.org/pmd-doc-7.0.0/pmd_rules_java_codestyle.html#uselessparentheses"> See PMD documentation. </a>
return root;
Expand All @@ -108,7 +132,8 @@ private ModuleNode readProject(final XMLEventReader reader, final ModuleNode roo
}

@CanIgnoreReturnValue
private PackageNode readPackage(final XMLEventReader reader, final ModuleNode root, final StartElement packageElement, String fileName)
private PackageNode readPackage(final XMLEventReader reader, final ModuleNode root,
final StartElement packageElement, final String fileName)
throws XMLStreamException {
var packageName = getValueOf(packageElement, NAME);
var packageNode = root.findOrCreatePackageNode(packageName);
Expand All @@ -125,7 +150,8 @@ private PackageNode readPackage(final XMLEventReader reader, final ModuleNode ro
else if (FILE.equals(startElement.getName())) {
readFile(reader, packageNode, startElement);
}
} else if (event.isEndElement()) {
}
else if (event.isEndElement()) {
var endElement = event.asEndElement();
if (PACKAGE.equals((endElement.getName()))) {

Check warning on line 156 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / PMD

UselessParentheses

NORMAL: Useless parentheses.
Raw output
Parenthesized expressions are used to override the default operator precedence rules. Parentheses whose removal would not change the relative nesting of operators are unnecessary, because they don't change the semantics of the enclosing expression. Some parentheses that strictly speaking are unnecessary, may still be considered useful for readability. This rule allows to ignore violations on two kinds of unnecessary parentheses: - "Clarifying" parentheses, which separate operators of difference precedence. While unnecessary, they make precedence rules explicit, which may be useful for rarely used operators. For example: ```java (a + b) & c // is equivalent to `a + b & c`, but probably clearer ``` Unset the property `ignoreClarifying` to report them. - "Balancing" parentheses, which are unnecessary but visually balance out another pair of parentheses around an equality operator. For example, those two expressions are equivalent: ```java (a == null) != (b == null) a == null != (b == null) ``` The parentheses on the right are required, and the parentheses on the left are just more visually pleasing. Unset the property `ignoreBalancing` to report them. <pre> <code> public class Foo { { int n = 0; n = (n); // here n = (n * 2) * 3; // and here n = n * (2 * 3); // and here } } </code> </pre> <a href="https://docs.pmd-code.org/pmd-doc-7.0.0/pmd_rules_java_codestyle.html#uselessparentheses"> See PMD documentation. </a>
return packageNode;
Expand All @@ -136,7 +162,8 @@ else if (FILE.equals(startElement.getName())) {
}

@CanIgnoreReturnValue
private FileNode readFile(final XMLEventReader reader, final PackageNode packageNode, final StartElement fileElement) throws XMLStreamException {
private FileNode readFile(final XMLEventReader reader, final PackageNode packageNode,

Check warning on line 165 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / PMD

CognitiveComplexity

NORMAL: The method 'readFile(XMLEventReader, PackageNode, StartElement)' has a cognitive complexity of 17, current threshold is 15.
Raw output
Methods that are highly complex are difficult to read and more costly to maintain. If you include too much decisional logic within a single method, you make its behavior hard to understand and more difficult to modify. Cognitive complexity is a measure of how difficult it is for humans to read and understand a method. Code that contains a break in the control flow is more complex, whereas the use of language shorthands doesn't increase the level of complexity. Nested control flows can make a method more difficult to understand, with each additional nesting of the control flow leading to an increase in cognitive complexity. Information about Cognitive complexity can be found in the original paper here: <https://www.sonarsource.com/docs/CognitiveComplexity.pdf> By default, this rule reports methods with a complexity of 15 or more. Reported methods should be broken down into less complex components. <pre> <code> public class Foo { // Has a cognitive complexity of 0 public void createAccount() { Account account = new Account(&quot;PMD&quot;); // save account } // Has a cognitive complexity of 1 public Boolean setPhoneNumberIfNotExisting(Account a, String phone) { if (a.phone == null) { // +1 a.phone = phone; return true; } return false; } // Has a cognitive complexity of 4 public void updateContacts(List&lt;Contact&gt; contacts) { List&lt;Contact&gt; contactsToUpdate = new ArrayList&lt;Contact&gt;(); for (Contact contact : contacts) { // +1 if (contact.department.equals(&quot;Finance&quot;)) { // +2 (nesting = 1) contact.title = &quot;Finance Specialist&quot;; contactsToUpdate.add(contact); } else if (contact.department.equals(&quot;Sales&quot;)) { // +1 contact.title = &quot;Sales Specialist&quot;; contactsToUpdate.add(contact); } } // save contacts } } </code> </pre> <a href="https://docs.pmd-code.org/pmd-doc-7.0.0/pmd_rules_java_design.html#cognitivecomplexity"> See PMD documentation. </a>
final StartElement fileElement) throws XMLStreamException {
String fileName = getValueOf(fileElement, NAME);
String className = fileName.substring(0, fileName.lastIndexOf("."));

Check warning on line 168 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / PMD

UseIndexOfChar

NORMAL: String.indexOf(char) is faster than String.indexOf(String).
Raw output
Use String.indexOf(char) when checking for the index of a single character; it executes faster. <pre> <code> String s = &quot;hello world&quot;; // avoid this if (s.indexOf(&quot;d&quot;) {} // instead do this if (s.indexOf(&#x27;d&#x27;) {} </code> </pre> <a href="https://docs.pmd-code.org/pmd-doc-7.0.0/pmd_rules_java_performance.html#useindexofchar"> See PMD documentation. </a>
String filePath = getValueOf(fileElement, PATH);
Expand All @@ -150,18 +177,24 @@ private FileNode readFile(final XMLEventReader reader, final PackageNode package
if (METRICS.equals(e.getName())) {
addBranchCoverage(classNode, e);
addInstructionCoverage(classNode, e);
} else if (LINE.equals(e.getName())) {
int line = getIntegerValueOf(e, NUM);
}
else if (LINE.equals(e.getName())) {
int line = getIntegerValueOf(e, NUM);
int count = getIntegerValueOf(e, COUNT);
if (count > 0) {
fileNode.addCounters(line, 1, 0);
} else {
}
else {
fileNode.addCounters(line, 0, 1);
}
} else {
new ParsingException(String.format("Unexpected element '%s' in <file> block in file '%s'", e.getName(), fileName));
}
} else if (event.isEndElement()) {
else {
new ParsingException(

Check warning on line 192 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / Java Compiler

compiler:compile

NORMAL: Format strings must be either literals or variables. Other expressions are not valid.
String.format("Unexpected element '%s' in <file> block in file '%s'", e.getName(),

Check warning on line 193 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / SpotBugs

RV_EXCEPTION_NOT_THROWN

HIGH: new edu.hm.hafner.util.SecureXmlParserFactory$ParsingException(String, Object[]) not thrown in edu.hm.hafner.coverage.parser.CloverParser.readFile(XMLEventReader, PackageNode, StartElement)
Raw output
<p> This code creates an exception (or error) object, but doesn't do anything with it. For example, something like </p> <pre><code>if (x &lt; 0) { new IllegalArgumentException("x must be nonnegative"); } </code></pre> <p>It was probably the intent of the programmer to throw the created exception:</p> <pre><code>if (x &lt; 0) { throw new IllegalArgumentException("x must be nonnegative"); } </code></pre>
fileName));
}
}
else if (event.isEndElement()) {
var endElement = event.asEndElement();
if (FILE.equals(endElement.getName())) {
resolveLines(fileNode);
Expand All @@ -175,27 +208,27 @@ private FileNode readFile(final XMLEventReader reader, final PackageNode package
private void resolveLines(final FileNode fileNode) {
var val = createValue("LINE", fileNode.getCoveredLines().size(), fileNode.getMissedLines().size());
fileNode.addValue(val);
for (ClassNode c: fileNode.getAllClassNodes()) {
for (ClassNode c : fileNode.getAllClassNodes()) {
c.addValue(val);
}
}

private void addBranchCoverage(final Node node, StartElement e) {// final int covered, final int total) {
private void addBranchCoverage(final Node node, final StartElement e) {// final int covered, final int total) {

Check warning on line 216 in src/main/java/edu/hm/hafner/coverage/parser/CloverParser.java

View check run for this annotation

ci.jenkins.io / CheckStyle

WhitespaceAroundCheck

NORMAL: '{' is not followed by whitespace.
Raw output
<p>Since Checkstyle 3.0</p><p> Checks that a token is surrounded by whitespace. Empty constructor, method, class, enum, interface, loop bodies (blocks), lambdas of the form </p><pre><code>public MyClass() {} // empty constructor public void func() {} // empty method public interface Foo {} // empty interface public class Foo {} // empty class public enum Foo {} // empty enum MyClass c = new MyClass() {}; // empty anonymous class while (i = 1) {} // empty while loop for (int i = 1; i &gt; 1; i++) {} // empty for loop do {} while (i = 1); // empty do-while loop Runnable noop = () -&gt; {}; // empty lambda public @interface Beta {} // empty annotation type </code></pre><p> may optionally be exempted from the policy using the <code> allowEmptyMethods</code>, <code>allowEmptyConstructors </code>, <code>allowEmptyTypes</code>, <code>allowEmptyLoops</code><code>allowEmptyLambdas</code> and <code>allowEmptyCatches</code> properties. </p><p>This check does not flag as violation double brace initialization like:</p><pre><code> new Properties() {{ setProperty("key", "value"); }}; </code></pre><p>Parameter allowEmptyCatches allows to suppress violations when token list contains SLIST to check if beginning of block is surrounded by whitespace and catch block is empty, for example:</p><pre><code> try { k = 5 / i; } catch (ArithmeticException ex) {} </code></pre> With this property turned off, this raises violation because the beginning of the catch block (left curly bracket) is not separated from the end of the catch block (right curly bracket).
int condTotal = getIntegerValueOf(e, CONDITIONALS);
int condCovered = getIntegerValueOf(e, COVERED_CONDITIONALS);
addCoverage(node, "BRANCH", condCovered, condTotal);
}

private void addInstructionCoverage(final Node node, StartElement e) { //final int covered, final int total) {
private void addInstructionCoverage(final Node node, final StartElement e) { //final int covered, final int total) {
int stmntsTotal = getIntegerValueOf(e, STATEMENTS);
int stmntsCovered = getIntegerValueOf(e, COVERED_STATEMENTS);
addCoverage(node, "INSTRUCTION", stmntsCovered, stmntsTotal);
}

private void addCoverage(final Node node, String metricName, final int covered, final int total) {
private void addCoverage(final Node node, final String metricName, final int covered, final int total) {
var builder = new Coverage.CoverageBuilder();
node.addValue(builder.withMetric(Metric.valueOf(metricName))
.withCovered(covered)
.withMissed(total - covered).build());
}
}
}

0 comments on commit 5efdaad

Please sign in to comment.