From 17dcc03a0a38496e0189a98ee3a2a41fd1c03c40 Mon Sep 17 00:00:00 2001 From: Dimitris Stafylarakis Date: Sat, 30 Aug 2014 23:21:16 +0200 Subject: [PATCH] refactor requests to both use gson fixed bug in getSourceRepoURLDefault --- .../gitlabjenkins/GitLabMergeRequest.java | 38 ++--------- .../gitlabjenkins/GitLabPushRequest.java | 64 +++---------------- .../gitlabjenkins/GitLabPushTrigger.java | 45 +++++++------ .../gitlabjenkins/GitLabRequest.java | 54 ++++++++++++++++ 4 files changed, 93 insertions(+), 108 deletions(-) create mode 100644 src/main/java/com/dabsquared/gitlabjenkins/GitLabRequest.java diff --git a/src/main/java/com/dabsquared/gitlabjenkins/GitLabMergeRequest.java b/src/main/java/com/dabsquared/gitlabjenkins/GitLabMergeRequest.java index f63a51f..0823de7 100644 --- a/src/main/java/com/dabsquared/gitlabjenkins/GitLabMergeRequest.java +++ b/src/main/java/com/dabsquared/gitlabjenkins/GitLabMergeRequest.java @@ -12,6 +12,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.gitlab.api.models.GitlabProject; +import com.dabsquared.gitlabjenkins.GitLabRequest.Builder; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -25,44 +26,17 @@ import com.google.gson.JsonParseException; * * @author Daniel Brooks */ -public class GitLabMergeRequest { +public class GitLabMergeRequest extends GitLabRequest { - public static GitLabMergeRequest create(String payload) { + public static GitLabMergeRequest create(String payload) { if (payload == null) { throw new IllegalArgumentException("payload should not be null"); } - - Gson gson = new GsonBuilder() - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .registerTypeAdapter(Date.class, new GitLabMergeRequest.DateSerializer()) - .create(); - GitLabMergeRequest mergeRequest = gson.fromJson(payload, GitLabMergeRequest.class); - - return mergeRequest; + + GitLabMergeRequest pushRequest = Builder.INSTANCE.get().fromJson(payload, GitLabMergeRequest.class); + return pushRequest; } - private static final String[] DATE_FORMATS = new String[] { - "yyyy-MM-dd HH:mm:ss Z", - "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" - }; - - - private static class DateSerializer implements JsonDeserializer { - public Date deserialize(JsonElement jsonElement, Type typeOF, - JsonDeserializationContext context) throws JsonParseException { - for (String format : DATE_FORMATS) { - try { - return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString()); - } catch (ParseException e) { - } - } - throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() - + "\". Supported formats: " + Arrays.toString(DATE_FORMATS)); - } - } - - - public GitLabMergeRequest() { } diff --git a/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushRequest.java b/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushRequest.java index e9e2fc3..6b9bb0a 100644 --- a/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushRequest.java +++ b/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushRequest.java @@ -1,62 +1,23 @@ package com.dabsquared.gitlabjenkins; -import net.sf.json.JSONObject; -import net.sf.json.JsonConfig; -import net.sf.json.util.JavaIdentifierTransformer; +import java.util.List; + import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Represents for WebHook payload * * @author Daniel Brooks */ -public class GitLabPushRequest { - +public class GitLabPushRequest extends GitLabRequest { public static GitLabPushRequest create(String payload) { if (payload == null) { throw new IllegalArgumentException("payload should not be null"); } - return create(JSONObject.fromObject(payload)); - } - - public static GitLabPushRequest create(JSONObject payload) { - if (payload == null || payload.isNullObject()) { - throw new IllegalArgumentException("payload should not be null"); - } - - JsonConfig config = createJsonConfig(); - return (GitLabPushRequest) JSONObject.toBean(payload, config); - } - - private static JsonConfig createJsonConfig() { - JsonConfig config = new JsonConfig(); - config.setRootClass(GitLabPushRequest.class); - - Map> classMap = new HashMap>(); - classMap.put("commits", Commit.class); - config.setClassMap(classMap); - - config.setJavaIdentifierTransformer(new JavaIdentifierTransformer() { - - @Override - public String transformToJavaIdentifier(String param) { - if (param == null) { - return null; - } - if ("private".equals(param)) { - return "private_"; - } - return param; - } - - }); - - return config; + + GitLabPushRequest pushRequest = Builder.INSTANCE.get().fromJson(payload, GitLabPushRequest.class); + return pushRequest; } public GitLabPushRequest() { @@ -64,34 +25,25 @@ public class GitLabPushRequest { private String before; - private String after; - private String ref; - private Integer user_id; - private String user_name; - private Integer project_id; - private Integer total_commits_count; - private Repository repository; - private List commits; - + public List getCommits() { return commits; } - public Commit getLastCommit() { if (commits.isEmpty()) { return null; } return commits.get(commits.size() - 1); } - + public void setCommits(List commits) { this.commits = commits; } diff --git a/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushTrigger.java b/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushTrigger.java index 2716374..4b1a18c 100644 --- a/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushTrigger.java +++ b/src/main/java/com/dabsquared/gitlabjenkins/GitLabPushTrigger.java @@ -121,8 +121,7 @@ public class GitLabPushTrigger extends Trigger> { LOGGER.log(Level.INFO, "{0} triggered.", job.getName()); String name = " #" + job.getNextBuildNumber(); GitLabMergeCause cause = createGitLabMergeCause(req); - Action[] actions = createActions(req); - + Action[] actions = createActions(req); if (job.scheduleBuild(job.getQuietPeriod(), cause, actions)) { LOGGER.log(Level.INFO, "GitLab Merge Request detected in {0}. Triggering {1}", new String[]{job.getName(), name}); } else { @@ -146,22 +145,23 @@ public class GitLabPushTrigger extends Trigger> { Map values = new HashMap(); values.put("gitlabSourceBranch", new StringParameterValue("gitlabSourceBranch", String.valueOf(req.getObjectAttribute().getSourceBranch()))); values.put("gitlabTargetBranch", new StringParameterValue("gitlabTargetBranch", String.valueOf(req.getObjectAttribute().getTargetBranch()))); - - // Get source repository if communication to Gitlab is possible + String sourceRepoName = "origin"; - String sourceRepoURL = null; + String sourceRepoURL = getSourceRepoURLDefault(); - try { - sourceRepoName = req.getSourceProject(getDesc().getGitlab()).getPathWithNamespace(); - sourceRepoURL = req.getSourceProject(getDesc().getGitlab()).getSshUrl(); - } catch (IOException ex) { - LOGGER.log(Level.WARNING, "Could not fetch source project''s data from Gitlab. '('{0}':' {1}')'", new String[]{ex.toString(), ex.getMessage()}); - sourceRepoURL = getSourceRepoURLDefault(); - } finally { - values.put("gitlabSourceRepoName", new StringParameterValue("gitlabSourceRepoName", sourceRepoName)); - values.put("gitlabSourceRepoURL", new StringParameterValue("gitlabSourceRepoURL", sourceRepoURL)); + if (!getDescriptor().getGitlabHostUrl().isEmpty()) { + // Get source repository if communication to Gitlab is possible + try { + sourceRepoName = req.getSourceProject(getDesc().getGitlab()).getPathWithNamespace(); + sourceRepoURL = req.getSourceProject(getDesc().getGitlab()).getSshUrl(); + } catch (IOException ex) { + LOGGER.log(Level.WARNING, "Could not fetch source project''s data from Gitlab. '('{0}':' {1}')'", new String[]{ex.toString(), ex.getMessage()}); + } } + values.put("gitlabSourceRepoName", new StringParameterValue("gitlabSourceRepoName", sourceRepoName)); + values.put("gitlabSourceRepoURL", new StringParameterValue("gitlabSourceRepoURL", sourceRepoURL)); + List listValues = new ArrayList(values.values()); ParametersAction parametersAction = new ParametersAction(listValues); @@ -187,7 +187,7 @@ public class GitLabPushTrigger extends Trigger> { RemoteConfig defaultRepository = repositories.get(repositories.size()-1); List uris = defaultRepository.getURIs(); if (!uris.isEmpty()) { - URIish defaultUri = uris.get(uris.size()); + URIish defaultUri = uris.get(uris.size()-1); url = defaultUri.toString(); } } @@ -246,11 +246,16 @@ public class GitLabPushTrigger extends Trigger> { } final List projectParentsUrl = new ArrayList(); - for (Object parent = project.getParent(); parent instanceof Item; parent = ((Item) parent).getParent()) { - projectParentsUrl.add(0, ((Item) parent).getName()); - } - - final StringBuilder projectUrl = new StringBuilder(); + + try { + for (Object parent = project.getParent(); parent instanceof Item; parent = ((Item) parent) + .getParent()) { + projectParentsUrl.add(0, ((Item) parent).getName()); + } + } catch (IllegalStateException e) { + return "Build when a change is pushed to GitLab, unknown URL"; + } + final StringBuilder projectUrl = new StringBuilder(); projectUrl.append(Jenkins.getInstance().getRootUrl()); projectUrl.append(GitLabWebHook.WEBHOOK_URL); projectUrl.append('/'); diff --git a/src/main/java/com/dabsquared/gitlabjenkins/GitLabRequest.java b/src/main/java/com/dabsquared/gitlabjenkins/GitLabRequest.java new file mode 100644 index 0000000..19eb166 --- /dev/null +++ b/src/main/java/com/dabsquared/gitlabjenkins/GitLabRequest.java @@ -0,0 +1,54 @@ +package com.dabsquared.gitlabjenkins; + +import java.lang.reflect.Type; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.Locale; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +public class GitLabRequest { + protected enum Builder { + INSTANCE; + private final Gson gson; + + Builder() { + gson = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) + .registerTypeAdapter(Date.class, new GitLabRequest.DateSerializer()) + .create(); + } + + public Gson get(){ + return gson; + } + }; + + private static final String[] DATE_FORMATS = new String[] { + "yyyy-MM-dd HH:mm:ss Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" }; + + private static class DateSerializer implements JsonDeserializer { + public Date deserialize(JsonElement jsonElement, Type typeOF, + JsonDeserializationContext context) throws JsonParseException { + for (String format : DATE_FORMATS) { + try { + return new SimpleDateFormat(format, Locale.US) + .parse(jsonElement.getAsString()); + } catch (ParseException e) { + } + } + throw new JsonParseException("Unparseable date: \"" + + jsonElement.getAsString() + "\". Supported formats: " + + Arrays.toString(DATE_FORMATS)); + } + } + +}