support multiple date formats

This commit is contained in:
Dimitris Stafylarakis 2014-08-08 15:04:01 +02:00
parent 6b5482fe20
commit 469bc22936
1 changed files with 33 additions and 1 deletions

View File

@ -1,7 +1,12 @@
package com.dabsquared.gitlabjenkins; package com.dabsquared.gitlabjenkins;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle; import org.apache.commons.lang.builder.ToStringStyle;
@ -10,6 +15,10 @@ import org.gitlab.api.models.GitlabProject;
import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; 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;
/** /**
* Represents for WebHook payload * Represents for WebHook payload
@ -23,13 +32,36 @@ public class GitLabMergeRequest {
throw new IllegalArgumentException("payload should not be null"); throw new IllegalArgumentException("payload should not be null");
} }
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setDateFormat("yyyy-MM-dd HH:mm:ss Z").create(); Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new GitLabMergeRequest.DateSerializer())
.create();
GitLabMergeRequest mergeRequest = gson.fromJson(payload, GitLabMergeRequest.class); GitLabMergeRequest mergeRequest = gson.fromJson(payload, GitLabMergeRequest.class);
return mergeRequest; return mergeRequest;
} }
private static final String[] DATE_FORMATS = new String[] {
"yyyy-MM-dd HH:mm:ss Z",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
};
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() { public GitLabMergeRequest() {
} }