becb51f703adbbbef9e8a7be56f3b20214c59182
[facebook-utils] / src / main / java / de / juplo / facebook / GraphApiExceptionJackson2Deserializer.java
1 package de.juplo.facebook;
2
3
4 import com.fasterxml.jackson.core.JsonParser;
5 import com.fasterxml.jackson.core.JsonProcessingException;
6 import com.fasterxml.jackson.core.JsonToken;
7 import com.fasterxml.jackson.databind.DeserializationContext;
8 import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
9 import java.io.IOException;
10 import java.util.HashMap;
11 import java.util.Map;
12
13
14 /**
15  * @author Kai Moritz
16  *
17  */
18 public class GraphApiExceptionJackson2Deserializer
19     extends
20       StdDeserializer<GraphApiException>
21 {
22   public GraphApiExceptionJackson2Deserializer()
23   {
24     super(GraphApiException.class);
25   }
26
27   @Override
28   public GraphApiException deserialize(
29       JsonParser jp,
30       DeserializationContext ctxt
31       )
32       throws
33         IOException,
34         JsonProcessingException
35   {
36     JsonToken t = jp.getCurrentToken();
37     if (t != JsonToken.START_OBJECT)
38       return null;
39
40     t = jp.nextToken();
41     if (t != JsonToken.FIELD_NAME)
42       return null;
43
44     if (!jp.getCurrentName().equals("error"))
45       return null;
46
47     t = jp.nextToken();
48     if (t != JsonToken.START_OBJECT)
49       return null;
50   
51     String message = null, type = null;
52     Integer code = null;
53
54     t = jp.nextToken();
55     Map<String, String> map = new HashMap<>();
56     for (; t == JsonToken.FIELD_NAME; t = jp.nextToken())
57     {
58       // Must point to field name
59       String fieldName = jp.getCurrentName();
60       // And then the value...
61       t = jp.nextToken();
62
63       switch (t)
64       {
65         case VALUE_STRING:
66           switch(fieldName.toLowerCase())
67           {
68             case "message":
69               message = jp.getText();
70               break;
71             case "type":
72               type = jp.getText();
73               break;
74             default:
75               return null;
76           }
77           break;
78         case VALUE_NUMBER_INT:
79           if (!fieldName.equalsIgnoreCase("code"))
80             return null;
81           code = jp.getValueAsInt();
82           break;
83         default:
84           return null;
85       }
86     }
87
88     if (message == null || type == null || code == null)
89       return null;
90
91     switch (code)
92     {
93       case 1:   return new UnknownErrorException();
94       case 2:   return new UnexpectedErrorException();
95       case 21:  return new PageMigratedException(message);
96       case 100: return new UnsupportedGetRequestException();
97       case 613: return new RateExceededException();
98       default:  return new GraphApiException(message, type, code);
99     }
100   }
101 }