• R/O
  • SSH
  • HTTPS

util: Commit


Commit MetaInfo

Revision152 (tree)
Time2018-03-14 19:45:55
Authorhirukawa_ryo

Log Message

* jersey-log-viewer 0.2.1
jersey標準では戻り値として null を返すと 204 No Content になってしまいます。これを 200 OK で返し、ボディに null という4文字が設定されるようにしました。

Change Summary

Incremental Difference

--- jersey-log-viewer/trunk/jersey-logger/src/main/java/net/osdn/util/jersey/log/InvocationLogger.java (revision 151)
+++ jersey-log-viewer/trunk/jersey-logger/src/main/java/net/osdn/util/jersey/log/InvocationLogger.java (revision 152)
@@ -15,12 +15,22 @@
1515 import java.util.regex.Matcher;
1616 import java.util.regex.Pattern;
1717
18+import javax.ws.rs.Produces;
1819 import javax.ws.rs.container.ContainerRequestContext;
1920 import javax.ws.rs.container.ResourceInfo;
21+import javax.ws.rs.core.MediaType;
2022
23+import com.fasterxml.jackson.core.JsonGenerator;
24+import com.fasterxml.jackson.core.JsonProcessingException;
25+import com.fasterxml.jackson.databind.JsonSerializer;
26+import com.fasterxml.jackson.databind.SerializerProvider;
27+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
28+
2129 public class InvocationLogger implements InvocationHandler {
2230 private static final Pattern SIMPLE_NAME = Pattern.compile("[^.<@]+\\.");
23-
31+ private static final NullObject NULL = new NullObject();
32+
33+
2434 @Override
2535 public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
2636 try {
@@ -30,6 +40,15 @@
3040 }
3141 try {
3242 Object result = method.invoke(obj, args);
43+ if(result == null) {
44+ try {
45+ if(isProduceMediaTypeJson(method)) {
46+ result = NULL;
47+ }
48+ } catch(Exception e) {
49+ // ignore
50+ }
51+ }
3352 return result;
3453 } catch(Throwable t) {
3554 try {
@@ -41,6 +60,24 @@
4160 }
4261 }
4362
63+ private static boolean isProduceMediaTypeJson(Method method) {
64+ Annotation[] annotations = method.getAnnotations();
65+ if(annotations != null) {
66+ for(int i = 0; i < annotations.length; i++) {
67+ Annotation annotation = annotations[i];
68+ if(annotation instanceof Produces) {
69+ Produces produces = (Produces)annotation;
70+ for(String s : produces.value()) {
71+ if(MediaType.APPLICATION_JSON.equals(s)) {
72+ return true;
73+ }
74+ }
75+ }
76+ }
77+ }
78+ return false;
79+ }
80+
4481 private void log(Object obj, Object[] args) throws IOException {
4582 ContainerRequestContext requestContext = getRequestContext(obj);
4683 if(requestContext == null) {
@@ -268,4 +305,15 @@
268305 m.appendTail(sb);
269306 return sb.toString();
270307 }
308+
309+ @JsonSerialize(using=NullObjectSerializer.class)
310+ public static class NullObject {
311+ }
312+
313+ public static class NullObjectSerializer extends JsonSerializer<NullObject> {
314+ @Override
315+ public void serialize(NullObject value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
316+ gen.writeNull();
317+ }
318+ }
271319 }
Show on old repository browser