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