Skip to content

Commit

Permalink
Merge pull request #36 from basil/improvements
Browse files Browse the repository at this point in the history
Miscellaneous code cleanup
  • Loading branch information
basil authored Sep 12, 2021
2 parents ff2659a + a3ad7eb commit 0265608
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ of this software and associated documentation files (the "Software"), to deal
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
Expand Down Expand Up @@ -101,14 +102,13 @@ public GitLabAuthenticationToken(String accessToken, String gitlabServer, TokenT
this.accessToken = accessToken;
this.gitLabAPI = GitlabAPI.connect(gitlabServer, accessToken, tokenType);

this.me = gitLabAPI.getUser();
assert this.me != null;
this.me = Objects.requireNonNull(gitLabAPI.getUser());

setAuthenticated(true);

this.userName = this.me.getUsername();
authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins != null && jenkins.getSecurityRealm() instanceof GitLabSecurityRealm) {
if (myRealm == null) {
myRealm = (GitLabSecurityRealm) jenkins.getSecurityRealm();
Expand Down Expand Up @@ -152,7 +152,7 @@ public GitlabAPI getGitLabAPI() {

@Override
public GrantedAuthority[] getAuthorities() {
return authorities.toArray(new GrantedAuthority[authorities.size()]);
return authorities.toArray(new GrantedAuthority[0]);
}

@Override
Expand Down Expand Up @@ -192,7 +192,7 @@ public boolean hasOrganizationPermission(String candidateName, String organizati
Set<String> v = userOrganizationCache.get(candidateName, unused -> {
try {
List<GitlabGroup> groups = gitLabAPI.getGroups();
Set<String> groupsNames = new HashSet<String>();
Set<String> groupsNames = new HashSet<>();
for (GitlabGroup group : groups) {
groupsNames.add(group.getName());
}
Expand Down Expand Up @@ -237,7 +237,7 @@ public Set<String> myRepositories() {
}

public Set<String> listToNames(Collection<GitlabProject> repositories) {
Set<String> names = new HashSet<String>();
Set<String> names = new HashSet<>();
for (GitlabProject repository : repositories) {
// String ownerName = repository.getOwner().getUsername();
// String repoName = repository.getName();
Expand All @@ -260,7 +260,7 @@ public boolean isPublicRepository(final String repositoryName) {
}
});

return isPublic != null && isPublic.booleanValue();
return isPublic != null && isPublic;
}

private static final Logger LOGGER = Logger.getLogger(GitLabAuthenticationToken.class.getName());
Expand Down Expand Up @@ -314,7 +314,7 @@ public GitLabOAuthUserDetails getUserDetails(String username) {
GitlabUser user = loadUser(username);
if (user != null) {
// FIXME to implement
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
List<GrantedAuthority> groups = new ArrayList<>();
try {
List<GitlabGroup> gitLabGroups = gitLabAPI.getGroups();
for (GitlabGroup gitlabGroup : gitLabGroups) {
Expand All @@ -323,7 +323,7 @@ public GitLabOAuthUserDetails getUserDetails(String username) {
} catch (IOException e) {
LOGGER.log(Level.FINE, e.getMessage(), e);
}
return new GitLabOAuthUserDetails(user, groups.toArray(new GrantedAuthority[groups.size()]));
return new GitLabOAuthUserDetails(user, groups.toArray(new GrantedAuthority[0]));
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public ACL getACL(Job<?,?> job) {
*/
@Override
public Collection<String> getGroups() {
return new ArrayList<String>(0);
return new ArrayList<>(0);
}

private Object readResolve() {
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/org/jenkinsci/plugins/GitLabLogoutAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public String getUrlName() {

@Restricted(NoExternalUse.class) // jelly only
public String getGitLabURL() {
Jenkins j = Jenkins.getInstance();
assert j != null;
Jenkins j = Jenkins.get();
SecurityRealm r = j.getSecurityRealm();
if (r instanceof GitLabSecurityRealm) {
GitLabSecurityRealm glsr = (GitLabSecurityRealm) r;
Expand All @@ -71,8 +70,7 @@ public String getGitLabURL() {

@Restricted(NoExternalUse.class) // jelly only
public String getGitLabText() {
Jenkins jenkins = Jenkins.getInstance();
assert jenkins != null;
Jenkins jenkins = Jenkins.get();
SecurityRealm r = jenkins.getSecurityRealm();
if (r instanceof GitLabSecurityRealm) {
return "GitLab";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@

import hudson.security.GroupDetails;

import java.net.URI;

/**
* Represent a group from Gitlab as a group in Jenkins terms.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ of this software and associated documentation files (the "Software"), to deal
package org.jenkinsci.plugins;

import java.net.URI;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
Expand Down Expand Up @@ -207,12 +208,12 @@ public boolean hasPermission(Authentication a, Permission permission) {

private boolean currentUriPathStartsWith( String specificPath){
String requestUri = requestURI();
return requestUri==null?false:requestUri.startsWith(specificPath);
return requestUri != null && requestUri.startsWith(specificPath);
}

private boolean currentUriPathEquals( String specificPath ) {
String requestUri = requestURI();
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins != null && requestUri != null) {
String basePath = URI.create(jenkins.getRootUrl()).getPath();
return URI.create(requestUri).getPath().equals(basePath + specificPath);
Expand Down Expand Up @@ -314,21 +315,19 @@ public GitLabRequireOrganizationMembershipACL(String adminUserNames,
this.allowCcTrayPermission = allowCcTrayPermission;
this.allowAnonymousReadPermission = allowAnonymousReadPermission;
this.allowAnonymousJobStatusPermission = allowAnonymousJobStatusPermission;
this.adminUserNameList = new LinkedList<String>();
this.adminUserNameList = new LinkedList<>();

String[] parts = adminUserNames.split(",");

for (String part : parts) {
adminUserNameList.add(part.trim());
}

this.adminOrganizationNameList = new LinkedList<String>();
this.adminOrganizationNameList = new LinkedList<>();
parts= adminOrganizationNames.split(",");
for (String part : parts) {
this.adminOrganizationNameList.add(part);
}
this.adminOrganizationNameList.addAll(Arrays.asList(parts));

this.organizationNameList = new LinkedList<String>();
this.organizationNameList = new LinkedList<>();

parts = organizationNames.split(",");

Expand Down
22 changes: 8 additions & 14 deletions src/main/java/org/jenkinsci/plugins/GitLabSecurityRealm.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import jenkins.security.SecurityListener;
import org.acegisecurity.Authentication;
Expand All @@ -42,8 +40,6 @@
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.ParameterParser;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.http.HttpEntity;
Expand Down Expand Up @@ -72,7 +68,6 @@
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.xstream.converters.ConversionException;
Expand Down Expand Up @@ -274,10 +269,10 @@ public HttpResponse doCommenceLogin(StaplerRequest request, @QueryParameter Stri
String redirectOnFinish;
if (from != null && Util.isSafeToRedirectTo(from)) {
redirectOnFinish = from;
} else if (referer != null && (referer.startsWith(Jenkins.getInstance().getRootUrl()) || Util.isSafeToRedirectTo(referer))) {
} else if (referer != null && (referer.startsWith(Jenkins.get().getRootUrl()) || Util.isSafeToRedirectTo(referer))) {
redirectOnFinish = referer;
} else {
redirectOnFinish = Jenkins.getInstance().getRootUrl();
redirectOnFinish = Jenkins.get().getRootUrl();
}

List<NameValuePair> parameters = new ArrayList<>();
Expand All @@ -290,8 +285,8 @@ public HttpResponse doCommenceLogin(StaplerRequest request, @QueryParameter Stri
}

private String buildRedirectUrl(StaplerRequest request, String referer) throws MalformedURLException {
URL currentUrl = new URL(Jenkins.getInstance().getRootUrl());
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
URL currentUrl = new URL(Jenkins.get().getRootUrl());
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("state", referer));

URL redirect_uri = new URL(currentUrl.getProtocol(), currentUrl.getHost(), currentUrl.getPort(),
Expand All @@ -314,7 +309,7 @@ public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
String state = request.getParameter("state");

HttpPost httpPost = new HttpPost(gitlabWebUri + "/oauth/token");
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("client_id", clientID));
parameters.add(new BasicNameValuePair("client_secret", clientSecret));
parameters.add(new BasicNameValuePair("code", code));
Expand Down Expand Up @@ -380,8 +375,8 @@ public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
/**
* Returns the proxy to be used when connecting to the given URI.
*/
private HttpHost getProxy(HttpUriRequest method) throws URIException {
Jenkins jenkins = Jenkins.getInstance();
private HttpHost getProxy(HttpUriRequest method) {
Jenkins jenkins = Jenkins.get();
ProxyConfiguration proxy = jenkins.proxy;
if (proxy == null) {
return null; // defensive check
Expand Down Expand Up @@ -463,8 +458,7 @@ public String getLoginUrl() {
protected String getPostLogOutUrl(StaplerRequest req, Authentication auth) {
// if we just redirect to the root and anonymous does not have Overall read then we will start a login all over again.
// we are actually anonymous here as the security context has been cleared
Jenkins jenkins = Jenkins.getInstance();
assert jenkins != null;
Jenkins jenkins = Jenkins.get();
if (jenkins.hasPermission(Jenkins.READ)) {
// TODO until JEP-227 is merged and core requirement is updated, this will prevent stackoverflow
return req.getContextPath() + "/";
Expand Down

0 comments on commit 0265608

Please sign in to comment.