Merge pull request #11 from DABSquared/issue_9
Support different date formats
This commit is contained in:
commit
58e0863342
|
@ -1,7 +1,12 @@
|
|||
package com.dabsquared.gitlabjenkins;
|
||||
|
||||
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.Locale;
|
||||
|
||||
import org.apache.commons.lang.builder.ToStringBuilder;
|
||||
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.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;
|
||||
|
||||
/**
|
||||
* Represents for WebHook payload
|
||||
|
@ -23,13 +32,36 @@ public class GitLabMergeRequest {
|
|||
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);
|
||||
|
||||
return mergeRequest;
|
||||
}
|
||||
|
||||
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() {
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue