Package com.restfb.exception

Examples of com.restfb.exception.FacebookJsonMappingException


      throw legacyFacebookExceptionMapper.exceptionForTypeAndMessage(
        errorObject.getInt(LEGACY_ERROR_CODE_ATTRIBUTE_NAME), httpStatusCode, null,
        errorObject.getString(LEGACY_ERROR_MSG_ATTRIBUTE_NAME));
    } catch (JsonException e) {
      throw new FacebookJsonMappingException("Unable to process the Facebook API response", e);
    }
  }
View Full Code Here


   * @see com.restfb.JsonMapper#toJavaList(java.lang.String, java.lang.Class)
   */
  @Override
  public <T> List<T> toJavaList(String json, Class<T> type) {
    if (type == null)
      throw new FacebookJsonMappingException("You must specify the Java type to map to.");

    json = trimToEmpty(json);

    if (isBlank(json)) {
      if (jsonMappingErrorHandler.handleMappingError(json, type, null))
        return null;
      throw new FacebookJsonMappingException("JSON is an empty string - can't map it.");
    }

    if (json.startsWith("{")) {
      // Sometimes Facebook returns the empty object {} when it really should be
      // returning an empty list [] (example: do an FQL query for a user's
      // affiliations - it's a list except when there are none, then it turns
      // into an object). Check for that special case here.
      if (isEmptyObject(json)) {
        if (logger.isLoggable(FINER))
          logger.finer("Encountered {} when we should've seen []. "
              + "Mapping the {} as an empty list and moving on...");

        return new ArrayList<T>();
      }

      // Special case: if the only element of this object is an array called
      // "data", then treat it as a list. The Graph API uses this convention for
      // connections and in a few other places, e.g. comments on the Post
      // object.
      // Doing this simplifies mapping, so we don't have to worry about having a
      // little placeholder object that only has a "data" value.
      try {
        JsonObject jsonObject = new JsonObject(json);
        String[] fieldNames = JsonObject.getNames(jsonObject);

        if (fieldNames != null) {
          boolean hasSingleDataProperty = fieldNames.length == 1 && "data".equals(fieldNames[0]);
          Object jsonDataObject = jsonObject.get("data");

          if (!hasSingleDataProperty && !(jsonDataObject instanceof JsonArray))
            if (jsonMappingErrorHandler.handleMappingError(json, type, null))
              return null;
            else
              throw new FacebookJsonMappingException("JSON is an object but is being mapped as a list "
                  + "instead. Offending JSON is '" + json + "'.");

          json = jsonDataObject.toString();
        }
      } catch (JsonException e) {
        // Should never get here, but just in case...
        if (jsonMappingErrorHandler.handleMappingError(json, type, e))
          return null;
        else
          throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of "
              + type.getName() + " instances.  Offending JSON is " + json, e);
      }
    }

    try {
      List<T> list = new ArrayList<T>();

      JsonArray jsonArray = new JsonArray(json);
      for (int i = 0; i < jsonArray.length(); i++)
        list.add(toJavaObject(jsonArray.get(i).toString(), type));

      return unmodifiableList(list);
    } catch (FacebookJsonMappingException e) {
      throw e;
    } catch (Exception e) {
      if (jsonMappingErrorHandler.handleMappingError(json, type, e))
        return null;
      else
        throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of "
            + type.getName() + " instances", e);
    }
  }
View Full Code Here

  public <T> T toJavaObject(String json, Class<T> type) {
    if (isBlank(json))
      if (jsonMappingErrorHandler.handleMappingError(json, type, null))
        return null;
      else
        throw new FacebookJsonMappingException("JSON is an empty string - can't map it.");

    if (json.startsWith("["))
      if (jsonMappingErrorHandler.handleMappingError(json, type, null))
        return null;
      else
        throw new FacebookJsonMappingException("JSON is an array but is being mapped as an object "
            + "- you should map it as a List instead. Offending JSON is '" + json + "'.");

    try {
      // Are we asked to map to JsonObject? If so, short-circuit right away.
      if (type.equals(JsonObject.class))
        return (T) new JsonObject(json);

      List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation = findFieldsWithAnnotation(type, Facebook.class);
      Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);

      // If there are no annotated fields, assume we're mapping to a built-in
      // type. If this is actually the empty object, just return a new instance
      // of the corresponding Java type.
      if (fieldsWithAnnotation.size() == 0)
        if (isEmptyObject(json)) {
          T instance = createInstance(type);

          // If there are any methods annotated with @JsonMappingCompleted,
          // invoke them.
          invokeJsonMappingCompletedMethods(instance);

          return instance;
        } else {
          return toPrimitiveJavaType(json, type);
        }

      // Facebook will sometimes return the string "null".
      // Check for that and bail early if we find it.
      if ("null".equals(json))
        return null;

      // Facebook will sometimes return the string "false" to mean null.
      // Check for that and bail early if we find it.
      if ("false".equals(json)) {
        if (logger.isLoggable(FINE))
          logger.fine("Encountered 'false' from Facebook when trying to map to " + type.getSimpleName()
              + " - mapping null instead.");
        return null;
      }

      JsonObject jsonObject = new JsonObject(json);
      T instance = createInstance(type);

      if (instance instanceof JsonObject)
        return (T) jsonObject;

      // For each Facebook-annotated field on the current Java object, pull data
      // out of the JSON object and put it in the Java object
      for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
        String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);

        if (!jsonObject.has(facebookFieldName)) {
          if (logger.isLoggable(FINER))
            logger.finer("No JSON value present for '" + facebookFieldName + "', skipping. JSON is '" + json + "'.");

          continue;
        }

        fieldWithAnnotation.getField().setAccessible(true);

        // Set the Java field's value.
        //
        // If we notice that this Facebook field name is mapped more than once,
        // go into a special mode where we swallow any exceptions that occur
        // when mapping to the Java field. This is because Facebook will
        // sometimes return data in different formats for the same field name.
        // See issues 56 and 90 for examples of this behavior and discussion.
        if (facebookFieldNamesWithMultipleMappings.contains(facebookFieldName)) {
          try {
            fieldWithAnnotation.getField()
              .set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName));
          } catch (FacebookJsonMappingException e) {
            logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json);
          } catch (JsonException e) {
            logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json);
          }
        } else {
          try {
            fieldWithAnnotation.getField()
              .set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName));
          } catch (Exception e) {
            if (!jsonMappingErrorHandler.handleMappingError(json, type, e))
              throw e;
          }
        }
      }

      // If there are any methods annotated with @JsonMappingCompleted,
      // invoke them.
      invokeJsonMappingCompletedMethods(instance);

      return instance;
    } catch (FacebookJsonMappingException e) {
      throw e;
    } catch (Exception e) {
      if (jsonMappingErrorHandler.handleMappingError(json, type, e))
        return null;
      else
        throw new FacebookJsonMappingException("Unable to map JSON to Java. Offending JSON is '" + json + "'.", e);
    }
  }
View Full Code Here

      if (method.getParameterTypes().length == 0)
        method.invoke(object);
      else if (method.getParameterTypes().length == 1 && JsonMapper.class.equals(method.getParameterTypes()[0]))
        method.invoke(object, this);
      else
        throw new FacebookJsonMappingException(format(
          "Methods annotated with @%s must take 0 parameters or a single %s parameter. Your method was %s",
          JsonMappingCompleted.class.getSimpleName(), JsonMapper.class.getSimpleName(), method));
    }
  }
View Full Code Here

    if (object instanceof Map<?, ?>) {
      JsonObject jsonObject = new JsonObject();
      for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
        if (!(entry.getKey() instanceof String))
          throw new FacebookJsonMappingException("Your Map keys must be of type " + String.class
              + " in order to be converted to JSON.  Offending map is " + object);

        try {
          jsonObject.put((String) entry.getKey(), toJsonInternal(entry.getValue(), ignoreNullValuedProperties));
        } catch (JsonException e) {
          throw new FacebookJsonMappingException("Unable to process value '" + entry.getValue() + "' for key '"
              + entry.getKey() + "' in Map " + object, e);
        }
      }

      return jsonObject;
    }

    if (isPrimitive(object))
      return object;

    if (object instanceof BigInteger)
      return ((BigInteger) object).longValue();

    if (object instanceof BigDecimal)
      return ((BigDecimal) object).doubleValue();

    // We've passed the special-case bits, so let's try to marshal this as a
    // plain old Javabean...

    List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation =
        findFieldsWithAnnotation(object.getClass(), Facebook.class);

    JsonObject jsonObject = new JsonObject();

    // No longer throw an exception in this case. If there are multiple fields
    // with the same @Facebook value, it's luck of the draw which is picked for
    // JSON marshaling.
    // TODO: A better implementation would query each duplicate-mapped field. If
    // it has is a non-null value and the other duplicate values are null, use
    // the non-null field.
    Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);
    if (facebookFieldNamesWithMultipleMappings.size() > 0 && logger.isLoggable(FINE))
      logger.fine(format("Unable to convert to JSON because multiple @" + Facebook.class.getSimpleName()
          + " annotations for the same name are present: " + facebookFieldNamesWithMultipleMappings));

    for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
      String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);
      fieldWithAnnotation.getField().setAccessible(true);

      try {
        Object fieldValue = fieldWithAnnotation.getField().get(object);

        if (!(ignoreNullValuedProperties && fieldValue == null))
          jsonObject.put(facebookFieldName, toJsonInternal(fieldValue, ignoreNullValuedProperties));
      } catch (Exception e) {
        throw new FacebookJsonMappingException("Unable to process field '" + facebookFieldName + "' for "
            + object.getClass(), e);
      }
    }

    return jsonObject;
View Full Code Here

      return (T) new BigDecimal(json);

    if (jsonMappingErrorHandler.handleMappingError(json, type, null))
      return null;

    throw new FacebookJsonMappingException("Don't know how to map JSON to " + type
        + ". Are you sure you're mapping to the right class? " + "Offending JSON is '" + json + "'.");
  }
View Full Code Here

    try {
      Constructor<T> defaultConstructor = type.getDeclaredConstructor();

      if (defaultConstructor == null)
        throw new FacebookJsonMappingException("Unable to find a default constructor for " + type);

      // Allows protected, private, and package-private constructors to be
      // invoked
      defaultConstructor.setAccessible(true);
      return defaultConstructor.newInstance();
    } catch (Exception e) {
      throw new FacebookJsonMappingException(errorMessage, e);
    }
  }
View Full Code Here

                : new JsonArray();

        normalizedJson.put(jsonObject.getString("name"), resultsArray);
      }
    } catch (JsonException e) {
      throw new FacebookJsonMappingException("Unable to process fql.multiquery JSON response", e);
    }

    return jsonMapper.toJavaObject(normalizedJson.toString(), resultType);
  }
View Full Code Here

  @SuppressWarnings("unchecked")
  public Connection(FacebookClient facebookClient, String json, Class<T> connectionType) {
    List<T> data = new ArrayList<T>();

    if (json == null)
      throw new FacebookJsonMappingException("You must supply non-null connection JSON.");

    JsonObject jsonObject = null;

    try {
      jsonObject = new JsonObject(json);
    } catch (JsonException e) {
      throw new FacebookJsonMappingException("The connection JSON you provided was invalid: " + json, e);
    }

    // Pull out data
    JsonArray jsonData = jsonObject.getJsonArray("data");
    for (int i = 0; i < jsonData.length(); i++)
View Full Code Here

            parametersWithAdditionalParameter(Parameter.with(IDS_PARAM_NAME, join(ids)), parameters)));

      return objectType.equals(JsonObject.class) ? (T) jsonObject : jsonMapper.toJavaObject(jsonObject.toString(),
        objectType);
    } catch (JsonException e) {
      throw new FacebookJsonMappingException("Unable to map connection JSON to Java objects", e);
    }
  }
View Full Code Here

TOP

Related Classes of com.restfb.exception.FacebookJsonMappingException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.