Skip to content

Commit

Permalink
Use reflection to access protected field result from the build, see J…
Browse files Browse the repository at this point in the history
…ENKINS-25406 as well.

As of jenkinsci/jenkins@28dfd90#diff-c4f9931d88bca347279b881007d71f0eL445
the field may not be set anymore directly when the build already was completed.
TODO: the summary still thinks the build was a SUCCESS.
  • Loading branch information
mfriedenhagen committed Dec 17, 2014
1 parent 2caf8b2 commit 677dc89
Showing 1 changed file with 38 additions and 6 deletions.
44 changes: 38 additions & 6 deletions src/main/java/hudson/plugins/violations/ViolationsReport.java
Expand Up @@ -4,6 +4,7 @@
import java.io.IOException;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -532,17 +533,48 @@ private boolean isFailed() {
/**
* Set the unstable/failed status of a build based
* on this violations report.
*
* Because of JENKINS-25406 we need to access this field via reflection.
*/
public void setBuildResult() {
if (isFailed()) {
build.setResult(Result.FAILURE);
return;
final Field resultField;
final Result result = build.getResult();
try {
Class<? extends AbstractBuild> klass = build.getClass();
resultField = getField(klass, "result");
resultField.setAccessible(true);
if (isFailed()) {
if (result == null || result.isBetterThan(Result.FAILURE)) {
resultField.set(build, Result.FAILURE);
}
return;
}
if (isUnstable()) {
if (result == null || result.isBetterThan(Result.UNSTABLE)) {
resultField.set(build, Result.UNSTABLE);
}
}
} catch (NoSuchFieldException e) {
throw new RuntimeException("Could not get resultField from build.", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Could not set value for resultField.", e);
}
if (isUnstable()) {
build.setResult(Result.UNSTABLE);
}

// http://stackoverflow.com/a/735311/49132
private static Field getField(Class clazz, String fieldName) throws NoSuchFieldException {
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
Class superClass = clazz.getSuperclass();
if (superClass == null) {
throw e;
} else {
return getField(superClass, fieldName);
}
}
}

private static final long serialVersionUID = 1L;

public static ViolationsReport findViolationsReport(
Expand Down

0 comments on commit 677dc89

Please sign in to comment.