Exemplo n.º 1
0
  private void addTypeAdaptersForDate(
      String datePattern, int dateStyle, int timeStyle, List<TypeAdapterFactory> factories) {
    DefaultDateTypeAdapter dateTypeAdapter;
    if (datePattern != null && !"".equals(datePattern.trim())) {
      dateTypeAdapter = new DefaultDateTypeAdapter(datePattern);
    } else if (dateStyle != DateFormat.DEFAULT && timeStyle != DateFormat.DEFAULT) {
      dateTypeAdapter = new DefaultDateTypeAdapter(dateStyle, timeStyle);
    } else {
      return;
    }

    factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Date.class), dateTypeAdapter));
    factories.add(TreeTypeAdapter.newFactory(TypeToken.get(Timestamp.class), dateTypeAdapter));
    factories.add(TreeTypeAdapter.newFactory(TypeToken.get(java.sql.Date.class), dateTypeAdapter));
  }
Exemplo n.º 2
0
 /**
  * Reads the next JSON value from {@code reader} and convert it to an object of type {@code
  * typeOfT}. Since Type is not parameterized by T, this method is type unsafe and should be used
  * carefully
  *
  * @throws JsonIOException if there was a problem writing to the Reader
  * @throws JsonSyntaxException if json is not a valid representation for an object of type
  */
 @SuppressWarnings("unchecked")
 public <T> T fromJson(JsonReader reader, Type typeOfT)
     throws JsonIOException, JsonSyntaxException {
   boolean isEmpty = true;
   boolean oldLenient = reader.isLenient();
   reader.setLenient(true);
   try {
     reader.peek();
     isEmpty = false;
     TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT);
     TypeAdapter<T> typeAdapter = getAdapter(typeToken);
     T object = typeAdapter.read(reader);
     return object;
   } catch (EOFException e) {
     /*
      * For compatibility with JSON 1.5 and earlier, we return null for empty
      * documents instead of throwing.
      */
     if (isEmpty) {
       return null;
     }
     throw new JsonSyntaxException(e);
   } catch (IllegalStateException e) {
     throw new JsonSyntaxException(e);
   } catch (IOException e) {
     // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException
     throw new JsonSyntaxException(e);
   } finally {
     reader.setLenient(oldLenient);
   }
 }
Exemplo n.º 3
0
 public <T> T fromJson(JsonReader jsonReader, Type type)
     throws JsonIOException, JsonSyntaxException {
   boolean z = true;
   boolean isLenient = jsonReader.isLenient();
   jsonReader.setLenient(true);
   try {
     jsonReader.peek();
     z = DEFAULT_JSON_NON_EXECUTABLE;
     T read = getAdapter(TypeToken.get(type)).read(jsonReader);
     jsonReader.setLenient(isLenient);
     return read;
   } catch (Throwable e) {
     if (z) {
       jsonReader.setLenient(isLenient);
       return null;
     }
     throw new JsonSyntaxException(e);
   } catch (Throwable e2) {
     throw new JsonSyntaxException(e2);
   } catch (Throwable e22) {
     throw new JsonSyntaxException(e22);
   } catch (Throwable th) {
     jsonReader.setLenient(isLenient);
   }
 }
  @SuppressWarnings("unchecked")
  @Override
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != ImmutableMap.class || !(type instanceof ParameterizedType)) {
      return null;
    }

    com.google.common.reflect.TypeToken<ImmutableMap<?, ?>> betterToken =
        (com.google.common.reflect.TypeToken<ImmutableMap<?, ?>>)
            com.google.common.reflect.TypeToken.of(typeToken.getType());
    final TypeAdapter<HashMap<?, ?>> hashMapAdapter =
        (TypeAdapter<HashMap<?, ?>>)
            gson.getAdapter(
                TypeToken.get(
                    betterToken.getSupertype(Map.class).getSubtype(HashMap.class).getType()));
    return new TypeAdapter<T>() {
      @Override
      public void write(JsonWriter out, T value) throws IOException {
        HashMap<?, ?> hashMap = Maps.newHashMap((Map<?, ?>) value);
        hashMapAdapter.write(out, hashMap);
      }

      @Override
      public T read(JsonReader in) throws IOException {
        HashMap<?, ?> hashMap = hashMapAdapter.read(in);
        return (T) ImmutableMap.copyOf(hashMap);
      }
    };
  }
 @Test(
     expectedExceptions = IllegalArgumentException.class,
     expectedExceptionsMessageRegExp =
         ".* parameter 0 failed to be named by AnnotationBasedNamingStrategy requiring one of javax.inject.Named")
 public void testSerializedNameRequiredOnAllParameters() {
   parameterizedCtorFactory.create(
       gson, TypeToken.get(WithDeserializationConstructorButWithoutSerializedName.class));
 }
 public void checkSimpleComposedObject() throws IOException {
   ValidatedConstructor x = new ValidatedConstructor(Optional.of(0), 1);
   ValidatedConstructor y = new ValidatedConstructor(Optional.of(1), 2);
   TypeAdapter<ComposedObjects> adapter =
       parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class));
   assertEquals(
       new ComposedObjects(x, y),
       adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1},\"y\":{\"foo\":1,\"bar\":2}}"));
 }
Exemplo n.º 7
0
 /**
  * Configures Gson for custom serialization or deserialization. This method combines the
  * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a
  * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements
  * all the required interfaces for custom serialization with Gson. If a type adapter was
  * previously registered for the specified {@code type}, it is overwritten.
  *
  * <p>This registers the type specified and no other types: you must manually register related
  * types! For example, applications registering {@code boolean.class} should also register {@code
  * Boolean.class}.
  *
  * @param type the type definition for the type adapter being registered
  * @param typeAdapter This object must implement at least one of the {@link TypeAdapter}, {@link
  *     InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
  * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
   $Gson$Preconditions.checkArgument(
       typeAdapter instanceof JsonSerializer<?>
           || typeAdapter instanceof JsonDeserializer<?>
           || typeAdapter instanceof InstanceCreator<?>
           || typeAdapter instanceof TypeAdapter<?>);
   if (typeAdapter instanceof InstanceCreator<?>) {
     instanceCreators.put(type, (InstanceCreator) typeAdapter);
   }
   if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
     TypeToken<?> typeToken = TypeToken.get(type);
     factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
   }
   if (typeAdapter instanceof TypeAdapter<?>) {
     factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter) typeAdapter));
   }
   return this;
 }
Exemplo n.º 8
0
 public TypeAdapter create(Gson gson, TypeToken typetoken)
 {
     typetoken = typetoken.getType();
     if (!(typetoken instanceof GenericArrayType) && (!(typetoken instanceof Class) || !((Class)typetoken).isArray()))
     {
         return null;
     } else
     {
         typetoken = com.google.gson.internal.yComponentType(typetoken);
         return new ArrayTypeAdapter(gson, gson.getAdapter(TypeToken.get(typetoken)), com.google.gson.internal.ype(typetoken));
     }
 }
  private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
    Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();
    if (raw.isInterface()) {
      return result;
    }

    Type declaredType = type.getType();
    while (raw != Object.class) {
      Field[] fields = raw.getDeclaredFields();
      for (Field field : fields) {
        boolean serialize = excludeField(field, true);
        boolean deserialize = excludeField(field, false);
        if (!serialize && !deserialize) {
          continue;
        }
        field.setAccessible(true);
        Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
        List<String> fieldNames = getFieldNames(field);
        BoundField previous = null;
        for (int i = 0; i < fieldNames.size(); ++i) {
          String name = fieldNames.get(i);
          if (i != 0) serialize = false; // only serialize the default name
          BoundField boundField =
              createBoundField(
                  context, field, name, TypeToken.get(fieldType), serialize, deserialize);
          BoundField replaced = result.put(name, boundField);
          if (previous == null) previous = replaced;
        }
        if (previous != null) {
          throw new IllegalArgumentException(
              declaredType + " declares multiple JSON fields named " + previous.name);
        }
      }
      type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
      raw = type.getRawType();
    }
    return result;
  }
  public void testGenericParamsCopiedIn() throws IOException {
    TypeAdapter<GenericParamsCopiedIn> adapter =
        parameterizedCtorFactory.create(gson, TypeToken.get(GenericParamsCopiedIn.class));
    List<String> inputFoo = Lists.newArrayList();
    inputFoo.add("one");
    Map<String, String> inputBar = Maps.newHashMap();
    inputBar.put("2", "two");

    GenericParamsCopiedIn toTest =
        adapter.fromJson("{ \"foo\":[\"one\"], \"bar\":{ \"2\":\"two\"}}");
    assertEquals(inputFoo, toTest.foo);
    assertNotSame(inputFoo, toTest.foo);
    assertEquals(inputBar, toTest.bar);
  }
  @SuppressWarnings("unchecked") // Casts guarded by conditionals.
  static TypeAdapter<?> getTypeAdapter(
      ConstructorConstructor constructorConstructor,
      Gson gson,
      TypeToken<?> fieldType,
      JsonAdapter annotation) {
    Class<?> value = annotation.value();
    if (TypeAdapter.class.isAssignableFrom(value)) {
      Class<TypeAdapter<?>> typeAdapter = (Class<TypeAdapter<?>>) value;
      return constructorConstructor.get(TypeToken.get(typeAdapter)).construct();
    }
    if (TypeAdapterFactory.class.isAssignableFrom(value)) {
      Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value;
      TypeAdapterFactory factory =
          constructorConstructor.get(TypeToken.get(typeAdapterFactory)).construct();
      synchronized (createdFactories) {
        createdFactories.add(factory);
      }
      return factory.create(gson, fieldType);
    }

    throw new IllegalArgumentException(
        "@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.");
  }
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();

    Class<? super T> rawType = typeToken.getRawType();
    if (!Collection.class.isAssignableFrom(rawType)) {
      return null;
    }

    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
    ObjectConstructor<T> constructor = constructorConstructor.getConstructor(typeToken);

    @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter
    TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
    return result;
  }
Exemplo n.º 13
0
 /**
  * Writes the JSON representation of {@code src} of type {@code typeOfSrc} to {@code writer}.
  *
  * @throws JsonIOException if there was a problem writing to the writer
  */
 @SuppressWarnings("unchecked")
 public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {
   TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc));
   boolean oldLenient = writer.isLenient();
   writer.setLenient(true);
   boolean oldHtmlSafe = writer.isHtmlSafe();
   writer.setHtmlSafe(htmlSafe);
   boolean oldSerializeNulls = writer.getSerializeNulls();
   writer.setSerializeNulls(serializeNulls);
   try {
     ((TypeAdapter<Object>) adapter).write(writer, src);
   } catch (IOException e) {
     throw new JsonIOException(e);
   } finally {
     writer.setLenient(oldLenient);
     writer.setHtmlSafe(oldHtmlSafe);
     writer.setSerializeNulls(oldSerializeNulls);
   }
 }
Exemplo n.º 14
0
 public void toJson(Object obj, Type type, JsonWriter jsonWriter) throws JsonIOException {
   TypeAdapter adapter = getAdapter(TypeToken.get(type));
   boolean isLenient = jsonWriter.isLenient();
   jsonWriter.setLenient(true);
   boolean isHtmlSafe = jsonWriter.isHtmlSafe();
   jsonWriter.setHtmlSafe(this.htmlSafe);
   boolean serializeNulls = jsonWriter.getSerializeNulls();
   jsonWriter.setSerializeNulls(this.serializeNulls);
   try {
     adapter.write(jsonWriter, obj);
     jsonWriter.setLenient(isLenient);
     jsonWriter.setHtmlSafe(isHtmlSafe);
     jsonWriter.setSerializeNulls(serializeNulls);
   } catch (Throwable e) {
     throw new JsonIOException(e);
   } catch (Throwable th) {
     jsonWriter.setLenient(isLenient);
     jsonWriter.setHtmlSafe(isHtmlSafe);
     jsonWriter.setSerializeNulls(serializeNulls);
   }
 }
Exemplo n.º 15
0
 public void toJson(Object paramObject, Type paramType, JsonWriter paramJsonWriter)
     throws JsonIOException {
   paramType = getAdapter(TypeToken.get(paramType));
   boolean bool1 = paramJsonWriter.isLenient();
   paramJsonWriter.setLenient(true);
   boolean bool2 = paramJsonWriter.isHtmlSafe();
   paramJsonWriter.setHtmlSafe(this.htmlSafe);
   boolean bool3 = paramJsonWriter.getSerializeNulls();
   paramJsonWriter.setSerializeNulls(this.serializeNulls);
   try {
     paramType.write(paramJsonWriter, paramObject);
     return;
   } catch (IOException paramObject) {
     throw new JsonIOException(paramObject);
   } finally {
     paramJsonWriter.setLenient(bool1);
     paramJsonWriter.setHtmlSafe(bool2);
     paramJsonWriter.setSerializeNulls(bool3);
   }
   throw paramObject;
 }
Exemplo n.º 16
0
  @SuppressWarnings("unchecked")
  public <T> T executeCreateObject(
      final T newObject,
      final Type returnObjectType,
      final String uri,
      final Map<String, String> parameters)
      throws CloudstackRESTException {

    final PostMethod pm = (PostMethod) createMethod(POST_METHOD_TYPE, uri);
    pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    try {
      pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
    } catch (final UnsupportedEncodingException e) {
      throw new CloudstackRESTException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
      final String errorMessage = responseToErrorMessage(pm);
      pm.releaseConnection();
      s_logger.error("Failed to create object : " + errorMessage);
      throw new CloudstackRESTException("Failed to create object : " + errorMessage);
    }

    T result;
    try {
      result =
          (T)
              gson.fromJson(
                  pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
    } catch (final IOException e) {
      throw new CloudstackRESTException("Failed to decode json response body", e);
    } finally {
      pm.releaseConnection();
    }

    return result;
  }
 @Test(
     expectedExceptions = IllegalArgumentException.class,
     expectedExceptionsMessageRegExp = "Multiple entries with same key: foo.*")
 public void testNoDuplicateSerializedNamesRequiredOnAllParameters() {
   parameterizedCtorFactory.create(gson, TypeToken.get(DuplicateSerializedNames.class));
 }
 public void testRenamedFields() throws IOException {
   TypeAdapter<RenamedFields> adapter =
       parameterizedCtorFactory.create(gson, TypeToken.get(RenamedFields.class));
   assertEquals(new RenamedFields(0, 1), adapter.fromJson("{\"foo\":0,\"_bar\":1}"));
   assertEquals(adapter.toJson(new RenamedFields(0, 1)), "{\"foo\":0,\"_bar\":1}");
 }
 public void testEmptyObjectIsNull() throws IOException {
   TypeAdapter<ComposedObjects> adapter =
       parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class));
   assertNull(adapter.fromJson("{}"));
 }
 @Test(expectedExceptions = NullPointerException.class)
 public void testPartialObjectStillThrows() throws IOException {
   TypeAdapter<ComposedObjects> adapter =
       parameterizedCtorFactory.create(gson, TypeToken.get(ComposedObjects.class));
   assertNull(adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1}}"));
 }
Exemplo n.º 21
0
 public <T> TypeAdapter<T> getAdapter(Class<T> cls) {
   return getAdapter(TypeToken.get((Class) cls));
 }
 public void testNullWhenPrimitive() {
   assertNull(parameterizedCtorFactory.create(gson, TypeToken.get(int.class)));
 }
Exemplo n.º 23
0
 /**
  * Returns the type adapter for {@code} type.
  *
  * @throws IllegalArgumentException if this GSON cannot serialize and deserialize {@code type}.
  */
 public <T> TypeAdapter<T> getAdapter(Class<T> type) {
   return getAdapter(TypeToken.get(type));
 }
 public void testRejectsIfNoConstuctorMarked() throws IOException {
   TypeAdapter<DefaultConstructor> adapter =
       parameterizedCtorFactory.create(gson, TypeToken.get(DefaultConstructor.class));
   assertNull(adapter);
 }
Exemplo n.º 25
0
 @Override
 public Converter<?> get(Type type) {
   TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
   return new GsonConverter<>(adapter);
 }
Exemplo n.º 26
0
 public <T> TypeAdapter<T> getAdapter(Class<T> paramClass) {
   return getAdapter(TypeToken.get(paramClass));
 }