Refactored classes in thematically packages
[facebook-errors] / src / main / java / de / juplo / facebook / exceptions / GraphApiExceptionJackson1Deserializer.java
diff --git a/src/main/java/de/juplo/facebook/exceptions/GraphApiExceptionJackson1Deserializer.java b/src/main/java/de/juplo/facebook/exceptions/GraphApiExceptionJackson1Deserializer.java
new file mode 100644 (file)
index 0000000..165e7ce
--- /dev/null
@@ -0,0 +1,94 @@
+package de.juplo.facebook.exceptions;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import org.codehaus.jackson.JsonParser;
+import org.codehaus.jackson.JsonProcessingException;
+import org.codehaus.jackson.JsonToken;
+import org.codehaus.jackson.map.DeserializationContext;
+import org.codehaus.jackson.map.JsonDeserializer;
+
+/**
+ * @author Kai Moritz
+ */
+public class GraphApiExceptionJackson1Deserializer
+    extends
+      JsonDeserializer<GraphApiException>
+{
+
+  @Override
+  public GraphApiException deserialize(
+      JsonParser jp,
+      DeserializationContext ctxt
+      )
+      throws
+        IOException,
+        JsonProcessingException
+  {
+    JsonToken t = jp.getCurrentToken();
+    if (t != JsonToken.START_OBJECT)
+      return null;
+
+    t = jp.nextToken();
+    if (t != JsonToken.FIELD_NAME)
+      return null;
+
+    if (!jp.getCurrentName().equals("error"))
+      return null;
+
+    t = jp.nextToken();
+    if (t != JsonToken.START_OBJECT)
+      return null;
+  
+    String message = null, type = null;
+    Integer code = null;
+
+    t = jp.nextToken();
+    Map<String, String> map = new HashMap<>();
+    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken())
+    {
+      // Must point to field name
+      String fieldName = jp.getCurrentName();
+      // And then the value...
+      t = jp.nextToken();
+
+      switch (t)
+      {
+        case VALUE_STRING:
+          switch(fieldName.toLowerCase())
+          {
+            case "message":
+              message = jp.getText();
+              break;
+            case "type":
+              type = jp.getText();
+              break;
+            default:
+              return null;
+          }
+          break;
+        case VALUE_NUMBER_INT:
+          if (!fieldName.equalsIgnoreCase("code"))
+            return null;
+          code = jp.getValueAsInt();
+          break;
+        default:
+          return null;
+      }
+    }
+
+    if (message == null || type == null || code == null)
+      return null;
+
+    switch (code)
+    {
+      case 1:   return new UnknownErrorException();
+      case 2:   return new UnexpectedErrorException();
+      case 21:  return new PageMigratedException(message);
+      case 100: return new UnsupportedGetRequestException();
+      case 613: return new RateExceededException();
+      default:  return new GraphApiException(message, type, code);
+    }
+  }
+}