Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
sanderv32 committed May 9, 2018
1 parent f93aff1 commit 66256e6
Show file tree
Hide file tree
Showing 8 changed files with 21 additions and 46 deletions.
12 changes: 4 additions & 8 deletions src/main/java/org/jenkinsci/plugins/gogs/GogsCause.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ associated documentation files (the "Software"), to deal in the Software without

class GogsCause extends Cause {
private String deliveryID;
private GogsPayloadData gogsPayloadData;
private Map<String, String> envVars = new HashMap<>();
private final Map<String, String> envVars = new HashMap<>();
private final static Logger LOGGER = Logger.getLogger(GogsCause.class.getName());


Expand All @@ -46,10 +45,6 @@ public GogsCause(String deliveryID) {
this.deliveryID = deliveryID;
}

public String getDeliveryID() {
return deliveryID;
}

public Map<String, String> getEnvVars() {
return envVars;
}
Expand All @@ -66,13 +61,13 @@ public void setGogsPayloadData(String json) {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

try {
gogsPayloadData = objectMapper.readValue(json, GogsPayloadData.class);
GogsPayloadData gogsPayloadData = objectMapper.readValue(json, GogsPayloadData.class);
map = objectMapper.convertValue(gogsPayloadData, new TypeReference<Map<String, Object>>() {
});
} catch (Exception e) {
LOGGER.severe(e.getMessage());
}
if (gogsPayloadData != null) {
if (map != null) {
iterate(map, null);
}

Expand All @@ -85,6 +80,7 @@ private void iterate(Map<String, Object> map, String prefix) {
env_name.append(prefix.toUpperCase()).append("_");

if (entry.getValue() instanceof Map) {
//noinspection unchecked
iterate((Map<String, Object>) entry.getValue(), env_name + entry.getKey().toUpperCase());
} else if (entry.getValue() instanceof String || entry.getValue() instanceof Long || entry.getValue() instanceof Boolean) {
env_name.append(entry.getKey().toUpperCase());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@
import jenkins.model.CoreEnvironmentContributor;

import javax.annotation.Nonnull;
import java.io.IOException;

@SuppressWarnings("unused")
@Extension
public class GogsEnvironmentContributor extends CoreEnvironmentContributor {
@Override
public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener)
throws IOException, InterruptedException {
public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) {
GogsCause gogsCause;

gogsCause = (GogsCause) r.getCause(GogsCause.class);
Expand Down
17 changes: 2 additions & 15 deletions src/main/java/org/jenkinsci/plugins/gogs/GogsPayload.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,19 @@
import hudson.model.EnvironmentContributingAction;
import hudson.model.InvisibleAction;

import javax.annotation.Nonnull;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

class GogsPayload extends InvisibleAction implements EnvironmentContributingAction {
private Map<String, String> payload;
private GogsCause gogsCause;

public GogsPayload(Map<String, String> payload) {
this.payload = payload;
}
private final GogsCause gogsCause;

public GogsPayload(GogsCause gogsCause) {
this.gogsCause = gogsCause;
}

@Nonnull
public Map<String, String> getPayload() {
return payload;
}

@Override
public void buildEnvVars(AbstractBuild<?, ?> abstractBuild, EnvVars envVars) {
LOGGER.log(Level.FINEST, "Injecting GOGS_PAYLOAD: {0}", getPayload());
// payload.forEach((key, value) -> envVars.put("GOGS_" + key.toUpperCase(), value));
LOGGER.log(Level.FINEST, "Injecting GOGS_PAYLOAD: {0}", gogsCause.getEnvVars());
envVars.putAll(gogsCause.getEnvVars());
}

Expand Down
5 changes: 5 additions & 0 deletions src/main/java/org/jenkinsci/plugins/gogs/GogsPayloadData.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

import java.util.List;

@SuppressWarnings("unused")
public class GogsPayloadData {
@SuppressWarnings("unused")
public static class UserDetails {
public String name;
public String email;
public String username;
}

@SuppressWarnings("unused")
public static class Owner {
public Long id;
public String login;
Expand All @@ -18,6 +21,7 @@ public static class Owner {
public String username;
}

@SuppressWarnings("unused")
public static class Commits {
public String id;
public String message;
Expand All @@ -30,6 +34,7 @@ public static class Commits {
public String timestamp;
}

@SuppressWarnings("unused")
public static class Repository {
public Long id;
public Owner owner;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,11 @@ associated documentation files (the "Software"), to deal in the Software without

import hudson.model.BuildableItem;
import hudson.security.ACL;
import hudson.security.ACLContext;
import jenkins.triggers.SCMTriggerItem;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
Expand All @@ -41,7 +38,6 @@ associated documentation files (the "Software"), to deal in the Software without

class GogsPayloadProcessor {
private static final Logger LOGGER = Logger.getLogger(GogsPayloadProcessor.class.getName());
private final Map<String, String> payload = new HashMap<>();
private GogsCause gogsCause = new GogsCause();

GogsPayloadProcessor() {
Expand All @@ -53,10 +49,9 @@ public void setCause(GogsCause gogsCause) {

public GogsResults triggerJobs(String jobName) {
AtomicBoolean jobdone = new AtomicBoolean(false);
SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
GogsResults result = new GogsResults();

try {
try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
BuildableItem project = GogsUtils.find(jobName, BuildableItem.class);
if (project != null) {

Expand Down Expand Up @@ -92,7 +87,6 @@ public GogsResults triggerJobs(String jobName) {
result.setStatus(404, msg);
LOGGER.warning(msg);
}
SecurityContextHolder.setContext(saveCtx);
}

return result;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jenkinsci/plugins/gogs/GogsUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private GogsUtils() {
* @return the Job matching the given name, or {@code null} when not found
*/
static <T extends Item> T find(String jobName, Class<T> type) {
Jenkins jenkins = Jenkins.getActiveInstance();
Jenkins jenkins = Jenkins.getInstance();
// direct search, can be used to find folder based items <folder>/<folder>/<jobName>
T item = jenkins.getItemByFullName(jobName, type);
if (item == null) {
Expand Down
11 changes: 3 additions & 8 deletions src/main/java/org/jenkinsci/plugins/gogs/GogsWebHook.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ associated documentation files (the "Software"), to deal in the Software without
import hudson.model.Job;
import hudson.model.UnprotectedRootAction;
import hudson.security.ACL;
import hudson.security.ACLContext;
import net.sf.json.JSONObject;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.io.IOUtils;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
Expand Down Expand Up @@ -145,9 +144,7 @@ public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException
gogsCause.setDeliveryID(getGogsDelivery());
payloadProcessor.setCause(gogsCause);

SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);

try {
try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
StringJoiner stringJoiner = new StringJoiner("%2F");
Pattern.compile("/").splitAsStream((String) jsonObject.get("ref")).skip(2)
.forEach(stringJoiner::add);
Expand All @@ -161,8 +158,6 @@ public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException
jSecret.set(property.getGogsSecret()); /* Secret provided by Jenkins */
}
});
} finally {
SecurityContextHolder.setContext(saveCtx);
}

String gSecret = null;
Expand Down Expand Up @@ -205,7 +200,7 @@ public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException
*
* @param req Request
* @param rsp Response
* @throws IOException
* @throws IOException Exception
*/
private boolean sanityChecks(StaplerRequest req, StaplerResponse rsp) throws IOException {
//Check that we have something to process
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,9 @@ int createWebHook(String jsonCommand, String projectName) throws IOException {
String result = executor
.execute(Request.Post(gogsHooksConfigUrl).bodyString(jsonCommand, ContentType.APPLICATION_JSON))
.returnContent().asString();
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result );
int id = jsonObject.getInt("id");
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(result);

return id;
return jsonObject.getInt("id");
}

/**
Expand Down

0 comments on commit 66256e6

Please sign in to comment.