Skip to content

Commit

Permalink
Minor cleanup - mainly replaced deprecated jenkins.getInstance() with…
Browse files Browse the repository at this point in the history
… jenkins.get() (#2143)

* replaced deprecated jenkins.getInstance() with jenkins.get() call, removed obsolete imports, removed obsoloete throws and use StandardCharsets

* fixed some failing tests

* fixed a failing tests

Co-authored-by: Olivier Lamy <[email protected]>
  • Loading branch information
StefanSpieker and olamy authored Jul 17, 2021
1 parent 6279f82 commit ef78020
Show file tree
Hide file tree
Showing 40 changed files with 66 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ protected void configure() {

if(server.getComputerSet().getTotalExecutors() < 10) {
server.runScript(
"jenkins.model.Jenkins.getInstance().setNumExecutors(10);\n" +
"jenkins.model.Jenkins.getInstance().save();\n", true);
"jenkins.model.Jenkins.get().setNumExecutors(10);\n" +
"jenkins.model.Jenkins.get().save();\n", true);
}

Properties properties = new Properties();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public String getAvatar() {

@Override
public boolean isJenkinsOrganizationPipeline() {
for(TopLevelItem item: Jenkins.getInstance().getItems()){
for(TopLevelItem item: Jenkins.get().getItems()){
if(item instanceof OrganizationFolder){
OrganizationFolder folder = (OrganizationFolder) item;
for(SCMNavigator navigator: folder.getNavigators()) {
Expand All @@ -67,4 +67,4 @@ public boolean isJenkinsOrganizationPipeline() {
public ScmRepositoryContainer getRepositories() {
return new BitbucketRepositoryContainer(project, api, this);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ protected boolean repoHasJenkinsFile(@Nonnull SCMSource scmSource) {
try {
scmSource.fetch(criteria, new SCMHeadObserver() {
@Override
public void observe(@Nonnull SCMHead head, @Nonnull SCMRevision revision) throws IOException, InterruptedException {
public void observe(@Nonnull SCMHead head, @Nonnull SCMRevision revision) {
//do nothing
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ private HttpRequest(@NonNull String apiUrl, @Nullable StandardUsernamePasswordCr
}else{
this.authorizationHeader = authHeader;
}

}

public HttpResponse head(String url) {
Expand Down Expand Up @@ -108,7 +107,7 @@ private HttpClient getHttpClient(@NonNull String apiUrl) {
private void setClientProxyParams(String apiUrl, HttpClientBuilder clientBuilder) {
try {
URL url = new URL(apiUrl);
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
ProxyConfiguration proxyConfig = Jenkins.get().proxy;
Proxy proxy = proxyConfig != null ? proxyConfig.createProxy(url.getHost()) : Proxy.NO_PROXY;
if (!proxy.equals(Proxy.NO_PROXY) && proxyConfig != null) {
clientBuilder.setProxy(new HttpHost(proxyConfig.name, proxyConfig.port));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import hudson.Extension;
import hudson.Plugin;
import hudson.model.UsageStatistics;
import hudson.security.AuthorizationStrategy;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.SecurityRealm;
Expand Down Expand Up @@ -41,7 +40,7 @@ public String getStatePropertyPath() {
@Override
public String getStateJson() {
StringWriter writer = new StringWriter();
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.get();
VersionNumber versionNumber = Jenkins.getVersion();
String version = versionNumber != null ? versionNumber.toString() : Jenkins.VERSION;

Expand All @@ -51,7 +50,7 @@ public String getStateJson() {
allowAnonymousRead = ((FullControlOnceLoggedInAuthorizationStrategy) authorizationStrategy).isAllowAnonymousRead();
}

String jwtTokenEndpointHostUrl = Jenkins.getInstance().getRootUrl();
String jwtTokenEndpointHostUrl = Jenkins.get().getRootUrl();
JwtTokenServiceEndpoint jwtTokenServiceEndpoint = JwtTokenServiceEndpoint.first();
if(jwtTokenServiceEndpoint != null){
jwtTokenEndpointHostUrl = jwtTokenServiceEndpoint.getHostUrl();
Expand Down Expand Up @@ -98,7 +97,7 @@ private JSONBuilder addFeatures(JSONBuilder builder) {

/** gives Blueocean plugin version. blueocean-web being core module is looked at to determine the version */
private String getBlueOceanPluginVersion(){
Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-web");
Plugin plugin = Jenkins.get().getPlugin("blueocean-web");
if(plugin == null) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private static String getGav(Map ext){
}

private static void refreshCacheIfNeeded(){
List<PluginWrapper> latestPlugins = Jenkins.getInstance().getPluginManager().getPlugins();
List<PluginWrapper> latestPlugins = Jenkins.get().getPluginManager().getPlugins();
if(!latestPlugins.equals(pluginCache)){
refreshCache(latestPlugins);
}
Expand Down Expand Up @@ -150,7 +150,7 @@ private synchronized static void refreshCache(List<PluginWrapper> latestPlugins)
String type = (String) extension.get("type");
if (type != null) {
BlueExtensionClassContainer extensionClassContainer
= Jenkins.getInstance().getExtensionList(BlueExtensionClassContainer.class).get(0);
= Jenkins.get().getExtensionList(BlueExtensionClassContainer.class).get(0);
Map classInfo = (Map) mergeObjects(extensionClassContainer.get(type));
List classInfoClasses = (List) classInfo.get("_classes");
classInfoClasses.add(0, type);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package io.jenkins.blueocean.config;

import com.google.common.collect.ImmutableSet;
import io.jenkins.blueocean.rest.factory.BlueOceanConfigFactory;
import io.jenkins.blueocean.rest.model.BlueOceanConfig;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;

import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Collections;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

public class BlueOceanConfigFactoryTest {
@Rule
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public byte[] invoke(Repository repo) throws IOException, InterruptedException {
void save() throws IOException {
invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {
@Override
public Void invoke(Repository repo) throws IOException, InterruptedException {
public Void invoke(Repository repo) throws IOException {
String localBranchRef = LOCAL_REF_BASE + sourceBranch;

ObjectId branchHead = repo.resolve(localBranchRef);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
Expand Down Expand Up @@ -252,17 +253,13 @@ protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
JSch jsch = new JSch();
configureJSch(jsch);
// TODO: might need this: jsch.setHostKeyRepository(new KnownHosts(this));
try {
KeyPair pair = KeyPair.load(jsch, privateKey.getPrivateKey().getBytes("utf-8"), null);
byte[] passphrase = new byte[0];
jsch.addIdentity(privateKey.getUsername(),
pair.forSSHAgent(),
null,
passphrase);
return jsch;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
KeyPair pair = KeyPair.load(jsch, privateKey.getPrivateKey().getBytes(StandardCharsets.UTF_8), null);
byte[] passphrase = new byte[0];
jsch.addIdentity(privateKey.getUsername(),
pair.forSSHAgent(),
null,
passphrase);
return jsch;
}
};
return new TransportConfigCallback() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;

/**
Expand All @@ -49,7 +50,7 @@ public static String generateKey(int keySize) {
KeyPair pair = KeyPair.genKeyPair(jsch, KeyPair.RSA, keySize);
ByteArrayOutputStream keyOut = new ByteArrayOutputStream();
pair.writePrivateKey(keyOut);
return new String(keyOut.toByteArray(), "utf-8");
return new String(keyOut.toByteArray(), StandardCharsets.UTF_8);
} catch(Exception ex) {
throw ex instanceof RuntimeException ? (RuntimeException)ex : new RuntimeException(ex);
}
Expand All @@ -64,10 +65,10 @@ public static String generateKey(int keySize) {
public static String getPublicKey(String privateKey, String comment) {
try {
JSch jsch = new JSch();
KeyPair pair = KeyPair.load(jsch, privateKey.getBytes("utf-8"), null );
KeyPair pair = KeyPair.load(jsch, privateKey.getBytes(StandardCharsets.UTF_8), null );
ByteArrayOutputStream keyOut = new ByteArrayOutputStream();
pair.writePublicKey(keyOut, comment);
return new String(keyOut.toByteArray(), "utf-8");
return new String(keyOut.toByteArray(), StandardCharsets.UTF_8);
} catch(Exception ex) {
throw ex instanceof RuntimeException ? (RuntimeException)ex : new RuntimeException(ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ public void shouldNotProvideIdForMissingCredentials() throws Exception {
.get(repoPath)
.build(Map.class);

assertEquals(null, resp.get("credentialId"));
assertNull(resp.get("credentialId"));
}

@Test
Expand All @@ -397,7 +397,7 @@ public void shouldBePoliteAboutBadUrl() throws Exception {
.get(repoPath)
.build(Map.class);

assertEquals(null, resp.get("credentialId"));
assertNull(resp.get("credentialId"));
}

@Test
Expand Down Expand Up @@ -569,15 +569,15 @@ public TestOrganizationFactoryImpl() {
private void setOrgRoot(String root) {
if (root != null) {
try {
MockFolder itemGroup = Jenkins.getInstance().createProject(MockFolder.class, root);
MockFolder itemGroup = Jenkins.get().createProject(MockFolder.class, root);
instance = new OrganizationImpl(root, itemGroup);
} catch (IOException e) {
throw new RuntimeException("Test setup failed!", e);
}

}
else {
instance = new OrganizationImpl("jenkins", Jenkins.getInstance());
instance = new OrganizationImpl("jenkins", Jenkins.get());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -207,7 +208,7 @@ static BundleParams getBundleParameters(String restOfPath) {

@CheckForNull
static PluginWrapper getPlugin(String pluginName) {
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.get();
return jenkins.getPluginManager().getPlugin(pluginName);
}

Expand Down Expand Up @@ -339,7 +340,7 @@ public BundleCacheEntry(JSONObject bundleData, BundleParams bundleParams) {

static class JSONObjectResponse implements HttpResponse {

private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Charset UTF8 = StandardCharsets.UTF_8;

private final JSONObject jsonObject = new JSONObject();
private BundleCacheEntry bundleCacheEntry;
Expand All @@ -366,7 +367,7 @@ private static JSONObjectResponse errorJson(String message, int errorCode) {
* {@inheritDoc}
*/
@Override
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException {
rsp.setStatus(statusCode);
rsp.setContentType("application/json; charset=UTF-8");
if (bundleCacheEntry != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ public void issueEqualityAndHashCode() {
BlueJiraIssue issue1 = new BlueJiraIssue("TEST-123", "http://jira.example.com/browse/TEST-123");
BlueJiraIssue issue2 = new BlueJiraIssue("TEST-124", "http://jira.example.com/browse/TEST-124");

Assert.assertTrue(issue1.equals(issue1));
Assert.assertFalse(issue1.equals(issue2));
Assert.assertFalse(issue1.equals(new Object()));
Assert.assertEquals(issue1, issue1);
Assert.assertNotEquals(issue1, issue2);
Assert.assertNotEquals(issue1, new Object());

Assert.assertNotEquals(issue1.hashCode(), issue2.hashCode());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public JwtToken getToken(@Nullable @QueryParameter("expiryTimeInMins") Integer e
if(p!=null)
email = p.getAddress();
}
Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-jwt");
Plugin plugin = Jenkins.get().getPlugin("blueocean-jwt");
String issuer = "blueocean-jwt:"+ ((plugin!=null) ? plugin.getWrapper().getVersion() : "");

JwtToken jwtToken = new JwtToken();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public JwtAuthentication(String subject) {
throw new ServiceException.UnauthorizedException("Invalid JWT token: subject " + subject + " not found");
}
//TODO: UserDetails call is expensive, encode it in token and create UserDetails from it
UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(user.getId());
UserDetails d = Jenkins.get().getSecurityRealm().loadUserByUsername(user.getId());
this.grantedAuthorities = d.getAuthorities();
this.name = subject;
super.setAuthenticated(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,12 @@
import io.jenkins.blueocean.rest.model.BluePipeline;
import io.jenkins.blueocean.rest.model.BlueRun;
import io.jenkins.blueocean.rest.model.Container;
import io.jenkins.blueocean.rest.model.Resource;
import io.jenkins.blueocean.rest.pageable.PagedResponse;
import io.jenkins.blueocean.service.embedded.rest.ChangeSetResource;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -82,7 +78,7 @@ public FetchData getFetchData(Container<BlueChangeSetEntry> containerChangeSets)

for (BlueChangeSetEntry changeSetEntry: containerChangeSets) {
changeSetEntries.add(JSONObject.fromObject(Export.toJson(changeSetEntry)));
};
}

// organizations/jenkins/pipelines/changes/runs/12/changeSet/?start=0&limit=101
return new FetchData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,10 @@
import javax.annotation.Nonnull;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ protected FetchData getFetchData(@Nonnull BlueUrlTokenizer blueUrl) {

private BluePipeline getPipeline(BlueUrlTokenizer blueUrl) {
if (addPipelineRuns(blueUrl)) {
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.get();
String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ protected FetchData getFetchData(@NonNull BlueUrlTokenizer blueUrl) {
return null;
}

Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.get();
String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);
String branchName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.BRANCH);
String runId = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE_RUN_DETAIL_ID);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected FetchData getFetchData(@NonNull BlueUrlTokenizer blueUrl) {
return null;
}

Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.get();
String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);

try {
Expand Down
Loading

0 comments on commit ef78020

Please sign in to comment.