Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove logic for old Jenkins versions #530

Merged
merged 1 commit into from
Nov 30, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
60 changes: 9 additions & 51 deletions src/main/java/org/jvnet/hudson/test/JenkinsRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@
import hudson.util.PersistedList;
import hudson.util.ReflectionUtils;
import hudson.util.StreamTaskListener;
import hudson.util.VersionNumber;
import hudson.util.jna.GNUCLibrary;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
Expand Down Expand Up @@ -184,7 +183,6 @@
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsAdaptor;
import jenkins.model.JenkinsLocationConfiguration;
Expand Down Expand Up @@ -245,7 +243,6 @@
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.Dispatcher;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.MetaClass;
import org.kohsuke.stapler.MetaClassLoader;
import org.kohsuke.stapler.Stapler;
Expand Down Expand Up @@ -1051,7 +1048,6 @@ public DumbSlave createSlave(@CheckForNull String labels, @CheckForNull EnvVars
public DumbSlave createSlave(@NonNull String nodeName, @CheckForNull String labels, @CheckForNull EnvVars env) throws Exception {
synchronized (jenkins) {
DumbSlave slave = new DumbSlave(nodeName, new File(jenkins.getRootDir(), "agent-work-dirs/" + nodeName).getAbsolutePath(), createComputerLauncher(env));
slave.setNumExecutors(1); // TODO pending 2.234+
if (labels != null) {
slave.setLabelString(labels);
}
Expand Down Expand Up @@ -1125,51 +1121,19 @@ public DumbSlave createOnlineSlave(@CheckForNull Label l, @CheckForNull EnvVars
* Use the new API token system introduced in 2.129 to generate a token for the given user.
*/
public @NonNull String createApiToken(@NonNull User user) {
ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class);
try {
// TODO could be simplified when core dependency will be higher
if (Jenkins.getVersion().isOlderThan(new VersionNumber("2.260"))) {
ApiTokenProperty.DescriptorImpl descriptor = this.jenkins.getDescriptorByType(ApiTokenProperty.DescriptorImpl.class);
HttpResponse httpResponse = descriptor.doGenerateNewToken(user, null);

// hacky way to prevent call to WebClient
ResponseCapturingOutput mockResponse = new ResponseCapturingOutput();
httpResponse.generateResponse(null, mockResponse, null);
String content = mockResponse.getOutputContent();
JSONObject json = JSONObject.fromObject(content);
return json.getJSONObject("data").getString("tokenValue");
} else {
// we can use the new methods from
// https://github.com/jenkinsci/jenkins/commit/eb0876cdb981a83c9f4c6f07d1eede585614612a
Method addFixedNewTokenMethod = ApiTokenProperty.class.getDeclaredMethod("addFixedNewToken", String.class, String.class);

ApiTokenProperty apiTokenProperty = user.getProperty(ApiTokenProperty.class);
if (apiTokenProperty == null) {
apiTokenProperty = new ApiTokenProperty();
user.addProperty(apiTokenProperty);
}

String tokenRandomName = "TestToken_" + (int) Math.floor(Math.random() * 1_000_000);
String tokenValue = generateNewApiTokenValue();
// could also use generateNewToken but only after 2.265
// https://github.com/jenkinsci/jenkins/commit/9c256ad8305db82e7186b7687e3300a8115a2d10
addFixedNewTokenMethod.invoke(apiTokenProperty, tokenRandomName, tokenValue);
return tokenValue;
if (apiTokenProperty == null) {
apiTokenProperty = new ApiTokenProperty();
user.addProperty(apiTokenProperty);
}
}
catch (IOException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ServletException e) {
throw new AssertionError(e);
String tokenRandomName = "TestToken_" + (int) Math.floor(Math.random() * 1_000_000);
return apiTokenProperty.generateNewToken(tokenRandomName).plainValue;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

// copy from ApiTokenStore#generateNewToken, version 2.138.4
private String generateNewApiTokenValue() {
byte[] random = new byte[16];
RANDOM.nextBytes(random);
String secretValue = Util.toHexString(random);
// 11 is the version for the new API Token system
return 11 + secretValue;
}

/**
* Waits for a newly created slave to come online.
* @see #createSlave()
Expand Down Expand Up @@ -2308,13 +2272,7 @@ public void fatalError(final CSSParseException exception) throws CSSException {
}

private boolean ignore(final CSSParseException exception) {
String uri = exception.getURI();
VersionNumber coreVersion = Jenkins.getVersion();
if (coreVersion != null && coreVersion.isNewerThan(new VersionNumber("2.343"))) {
return uri.contains("/yui/");
}
return uri.contains("/yui/")
|| uri.contains("/css/style.css") || uri.contains("/css/responsive-grid.css") || uri.contains("/base-styles-v2.css");
return exception.getURI().contains("/yui/");
}
});

Expand Down
32 changes: 10 additions & 22 deletions src/main/java/org/jvnet/hudson/test/PropertiesTestSuite.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

package org.jvnet.hudson.test;

import hudson.util.VersionNumber;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -35,13 +34,9 @@
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import jenkins.model.Jenkins;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.io.IOUtils;
Expand Down Expand Up @@ -81,28 +76,21 @@ public synchronized Object put(Object key, Object value) {
}
};

VersionNumber jv = Jenkins.getVersion();
if (jv != null && jv.isOlderThan(new VersionNumber("2.357"))) {
byte[] contents = IOUtils.toByteArray(resource);
if (!isEncoded(contents, StandardCharsets.US_ASCII)) {
boolean isUtf8 = isEncoded(contents, StandardCharsets.UTF_8);
boolean isIso88591 = isEncoded(contents, StandardCharsets.ISO_8859_1);
if (isUtf8 && isIso88591) {
throw new AssertionError(resource + " is valid UTF-8 and valid ISO-8859-1. To avoid problems when auto-detecting the encoding, use the lowest common denominator of ASCII encoding and express non-ASCII characters with escape sequences using a tool like `native2ascii`.");
}
byte[] contents = IOUtils.toByteArray(resource);
if (!isEncoded(contents, StandardCharsets.US_ASCII)) {
boolean isUtf8 = isEncoded(contents, StandardCharsets.UTF_8);
boolean isIso88591 = isEncoded(contents, StandardCharsets.ISO_8859_1);
if (!isUtf8 && !isIso88591) {
throw new AssertionError(resource + " must be either valid UTF-8 or valid ISO-8859-1.");
}
}

try (InputStream is = resource.openStream()) {
PropertyResourceBundle propertyResourceBundle = new PropertyResourceBundle(is);
Enumeration<String> keys = propertyResourceBundle.getKeys();
// TODO Java 9+ can use 'asIterator' and get rid of below collections conversion
List<String> keysAsSaneType = Collections.list(keys);

for (String localKey : keysAsSaneType) {
String value = propertyResourceBundle.getString(localKey);
props.setProperty(localKey, value);
}
propertyResourceBundle
.getKeys()
.asIterator()
.forEachRemaining(key -> props.setProperty(key, propertyResourceBundle.getString(key)));
}
}

Expand Down
22 changes: 2 additions & 20 deletions src/main/java/org/jvnet/hudson/test/RealJenkinsRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
import hudson.security.csrf.CrumbExclusion;
import hudson.util.NamingThreadFactory;
import hudson.util.StreamCopyThread;
import hudson.util.VersionNumber;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
Expand Down Expand Up @@ -72,7 +71,6 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.logging.ConsoleHandler;
Expand Down Expand Up @@ -144,7 +142,6 @@ public final class RealJenkinsRule implements TestRule {

private static final Logger LOGGER = Logger.getLogger(RealJenkinsRule.class.getName());

private static final VersionNumber v2339 = new VersionNumber("2.339");
private static final String REAL_JENKINS_RULE_LOGGING = "RealJenkinsRule.logging.";

private Description description;
Expand Down Expand Up @@ -191,7 +188,6 @@ public final class RealJenkinsRule implements TestRule {

// TODO may need to be relaxed for Gradle-based plugins
private static final Pattern SNAPSHOT_INDEX_JELLY = Pattern.compile("(file:/.+/target)/classes/index.jelly");
private transient boolean supportsPortFileName;

private final PrefixedOutputStream.Builder prefixedOutputStreamBuilder = PrefixedOutputStream.builder();

Expand Down Expand Up @@ -337,10 +333,6 @@ public RealJenkinsRule includeTestClasspathPlugins(boolean includeTestClasspathP
if (war == null) {
war = findJenkinsWar();
}
supportsPortFileName = supportsPortFileName(war.getAbsolutePath());
if (!supportsPortFileName) {
port = IOUtil.randomTcpPort();
}
File plugins = new File(home, "plugins");
plugins.mkdir();
FileUtils.copyURLToFile(RealJenkinsRule.class.getResource("RealJenkinsRuleInit.jpi"), new File(plugins, "RealJenkinsRuleInit.jpi"));
Expand Down Expand Up @@ -542,10 +534,8 @@ public void startJenkins() throws Throwable {
for (Map.Entry<String, Level> e : loggers.entrySet()) {
argv.add("-D" + REAL_JENKINS_RULE_LOGGING + e.getKey() + "=" + e.getValue().getName());
}
if (supportsPortFileName) {
portFile = new File(home, "jenkins-port.txt");
argv.add("-Dwinstone.portFileName=" + portFile);
}
portFile = new File(home, "jenkins-port.txt");
argv.add("-Dwinstone.portFileName=" + portFile);
if (new DisableOnDebug(null).isDebugging()) {
argv.add("-agentlib:jdwp=transport=dt_socket,server=y");
}
Expand Down Expand Up @@ -658,14 +648,6 @@ private void addTimeout() {
}
}

private static boolean supportsPortFileName(String war) throws IOException {
try (JarFile warFile = new JarFile(war)) {
String jenkinsVersion = warFile.getManifest().getMainAttributes().getValue("Jenkins-Version");
VersionNumber version = new VersionNumber(jenkinsVersion);
return version.compareTo(v2339) >= 0;
}
}

private static int readPort(File portFile) throws IOException {
String s = FileUtils.readFileToString(portFile, StandardCharsets.UTF_8);

Expand Down
13 changes: 1 addition & 12 deletions src/main/java/org/jvnet/hudson/test/WarExploder.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,8 @@ static File findJenkinsWar() throws Exception {
} else {
// locate jenkins.war
URL winstone = WarExploder.class.getResource("/executable/winstone.jar");
String className = "executable.Main";

// TODO: Delete the next statement once we drop support for versions older than 2.358.
if (winstone == null) {
// Prior to 2.358
winstone = WarExploder.class.getResource("/winstone.jar");
if (winstone != null) {
className = "executable.Executable";
}
}

if (winstone != null) {
war = Which.jarFile(Class.forName(className));
war = Which.jarFile(Class.forName("executable.Main"));
} else {
// JENKINS-45245: work around incorrect test classpath in IDEA. Note that this will not correctly handle timestamped snapshots; in that case use `mvn test`.
File core = Which.jarFile(Jenkins.class); // will fail with IllegalArgumentException if have neither jenkins-war.war nor jenkins-core.jar in ${java.class.path}
Expand Down