refactor requests to both use gson

fixed bug in getSourceRepoURLDefault
This commit is contained in:
Dimitris Stafylarakis 2014-08-30 23:21:16 +02:00
parent c8cd907cb2
commit 17dcc03a0a
4 changed files with 93 additions and 108 deletions

View File

@ -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<Date> {
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() {
}

View File

@ -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<String, Class<?>> classMap = new HashMap<String, Class<?>>();
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<Commit> commits;
public List<Commit> getCommits() {
return commits;
}
public Commit getLastCommit() {
if (commits.isEmpty()) {
return null;
}
return commits.get(commits.size() - 1);
}
public void setCommits(List<Commit> commits) {
this.commits = commits;
}

View File

@ -121,8 +121,7 @@ public class GitLabPushTrigger extends Trigger<AbstractProject<?, ?>> {
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<AbstractProject<?, ?>> {
Map<String, ParameterValue> values = new HashMap<String, ParameterValue>();
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<ParameterValue> listValues = new ArrayList<ParameterValue>(values.values());
ParametersAction parametersAction = new ParametersAction(listValues);
@ -187,7 +187,7 @@ public class GitLabPushTrigger extends Trigger<AbstractProject<?, ?>> {
RemoteConfig defaultRepository = repositories.get(repositories.size()-1);
List<URIish> 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<AbstractProject<?, ?>> {
}
final List<String> projectParentsUrl = new ArrayList<String>();
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('/');

View File

@ -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<Date> {
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));
}
}
}