Example usage for com.google.gson.internal Primitives isWrapperType

List of usage examples for com.google.gson.internal Primitives isWrapperType

Introduction

In this page you can find the example usage for com.google.gson.internal Primitives isWrapperType.

Prototype

public static boolean isWrapperType(Type type) 

Source Link

Document

Returns true if type is one of the nine primitive-wrapper types, such as Integer .

Usage

From source file:brooklyn.entity.java.JavaSoftwareProcessSshDriver.java

License:Apache License

/**
 * arguments to pass to the JVM; this is the config options (e.g. -Xmx1024; only the contents of
 * {@link #getCustomJavaConfigOptions()} by default) and java system properties (-Dk=v; add custom
 * properties in {@link #getCustomJavaSystemProperties()})
 * <p>// ww w. jav a  2s  . c o  m
 * See {@link #getShellEnvironment()} for discussion of quoting/escaping strategy.
 **/
public List<String> getJavaOpts() {
    Iterable<String> sysprops = Iterables.transform(getJavaSystemProperties().entrySet(),
            new Function<Map.Entry<String, ?>, String>() {
                public String apply(Map.Entry<String, ?> entry) {
                    String k = entry.getKey();
                    Object v = entry.getValue();
                    try {
                        if (v != null && Primitives.isWrapperType(v.getClass())) {
                            v = "" + v;
                        } else {
                            v = Tasks.resolveValue(v, Object.class,
                                    ((EntityInternal) entity).getExecutionContext());
                            if (v == null) {
                            } else if (v instanceof CharSequence) {
                            } else if (TypeCoercions.isPrimitiveOrBoxer(v.getClass())) {
                                v = "" + v;
                            } else {
                                // could do toString, but that's likely not what is desired;
                                // probably a type mismatch,
                                // post-processing should be specified (common types are accepted
                                // above)
                                throw new IllegalArgumentException(
                                        "cannot convert value " + v + " of type " + v.getClass()
                                                + " to string to pass as JVM property; use a post-processor");
                            }
                        }
                        return "-D" + k + (v != null ? "=" + v : "");
                    } catch (Exception e) {
                        log.warn("Error resolving java option key {}, propagating: {}", k, e);
                        throw Throwables.propagate(e);
                    }
                }
            });

    Set<String> result = MutableSet.<String>builder().addAll(getJmxJavaConfigOptions())
            .addAll(getCustomJavaConfigOptions()).addAll(sysprops).build();

    for (String customOpt : entity.getConfig(UsesJava.JAVA_OPTS)) {
        for (List<String> mutuallyExclusiveOpt : MUTUALLY_EXCLUSIVE_OPTS) {
            if (mutuallyExclusiveOpt.contains(customOpt)) {
                result.removeAll(mutuallyExclusiveOpt);
            }
        }
        for (String keyValOptPrefix : KEY_VAL_OPT_PREFIXES) {
            if (customOpt.startsWith(keyValOptPrefix)) {
                for (Iterator<String> iter = result.iterator(); iter.hasNext();) {
                    String existingOpt = iter.next();
                    if (existingOpt.startsWith(keyValOptPrefix)) {
                        iter.remove();
                    }
                }
            }
        }
        if (customOpt.contains("=")) {
            String customOptPrefix = customOpt.substring(0, customOpt.indexOf("="));

            for (Iterator<String> iter = result.iterator(); iter.hasNext();) {
                String existingOpt = iter.next();
                if (existingOpt.startsWith(customOptPrefix)) {
                    iter.remove();
                }
            }
        }
        result.add(customOpt);
    }

    return ImmutableList.copyOf(result);
}

From source file:ca.oson.json.domain.PrimitiveTypeAdapter.java

License:Apache License

@SuppressWarnings("unchecked")
public <T> T adaptType(Object from, Class<T> to) {
    Class<?> aClass = Primitives.wrap(to);
    if (Primitives.isWrapperType(aClass)) {
        if (aClass == Character.class) {
            String value = from.toString();
            if (value.length() == 1) {
                return (T) (Character) from.toString().charAt(0);
            }//from   w  w w.ja v  a2 s .  co  m
            throw new JsonParseException("The value: " + value + " contains more than a character.");
        }

        try {
            Constructor<?> constructor = aClass.getConstructor(String.class);
            return (T) constructor.newInstance(from.toString());
        } catch (NoSuchMethodException e) {
            throw new JsonParseException(e);
        } catch (IllegalAccessException e) {
            throw new JsonParseException(e);
        } catch (InvocationTargetException e) {
            throw new JsonParseException(e);
        } catch (InstantiationException e) {
            throw new JsonParseException(e);
        }
    } else if (Enum.class.isAssignableFrom(to)) {
        // Case where the type being adapted to is an Enum
        // We will try to convert from.toString() to the enum
        try {
            Method valuesMethod = to.getMethod("valueOf", String.class);
            return (T) valuesMethod.invoke(null, from.toString());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new JsonParseException("Can not adapt type " + from.getClass() + " to " + to);
    }
}

From source file:co.cask.cdap.internal.app.runtime.procedure.DefaultProcedureRequest.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from  w  ww. j a v a  2s  .c  o m
public <T> T getArgument(String key, Class<T> type) {
    Preconditions.checkNotNull(type, "Type cannnot be null.");
    Preconditions.checkArgument(!Void.class.equals(type) && !Void.TYPE.equals(type),
            "Void type not supported.");

    String value = getArgument(key);

    if (String.class.equals(type)) {
        return (T) value;
    }

    Class<T> resolvedType = type;
    if (Primitives.isPrimitive(resolvedType)) {
        resolvedType = Primitives.wrap(type);
    }
    if (Primitives.isWrapperType(resolvedType)) {
        // All wrapper has the valueOf(String) method
        try {
            return (T) resolvedType.getMethod("valueOf", String.class).invoke(null, value);
        } catch (Exception e) {
            // Should not happen
            throw Throwables.propagate(e);
        }
    }
    if (URL.class.equals(type)) {
        try {
            return (T) new URL(value);
        } catch (MalformedURLException e) {
            throw Throwables.propagate(e);
        }
    }
    if (URI.class.equals(type)) {
        return (T) URI.create(value);
    }

    // TODO: Maybe support gson decode the type??
    throw new ClassCastException("Fail to convert from String to " + type);
}

From source file:co.cask.cdap.internal.specification.PropertyFieldExtractor.java

License:Apache License

/**
 * Gets the value of the field in the given instance as String.
 * Currently only allows primitive types, boxed types, String and Enum.
 *///  www  . j  av  a 2  s  . c om
private String getStringValue(Object instance, Field field) throws IllegalAccessException {
    Class<?> fieldType = field.getType();

    // Only support primitive type, boxed type, String and Enum
    if (!fieldType.isPrimitive() && !Primitives.isWrapperType(fieldType) && !String.class.equals(fieldType)
            && !fieldType.isEnum()) {
        throw new IllegalArgumentException(
                String.format("Unsupported property type %s of field %s in class %s.", fieldType.getName(),
                        field.getName(), field.getDeclaringClass().getName()));
    }

    if (!field.isAccessible()) {
        field.setAccessible(true);
    }
    Object value = field.get(instance);
    if (value == null) {
        return null;
    }

    // Key name is "className.fieldName".
    return fieldType.isEnum() ? ((Enum<?>) value).name() : value.toString();
}

From source file:nl.colorize.util.xml.XMLConverter.java

License:Apache License

private boolean isSimpleType(Object obj) {
    if (obj == null) {
        return true;
    }// w ww  .  j a va  2  s.  c o  m
    Class<?> type = obj.getClass();
    return Primitives.isPrimitive(type) || Primitives.isWrapperType(type) || type == String.class;
}

From source file:org.apache.aurora.scheduler.storage.testing.StorageEntityUtil.java

License:Apache License

private static void validateField(String name, Object object, Field field, Set<Field> ignoredFields) {

    try {//from  ww w.  ja  va2 s  .  c  o  m
        field.setAccessible(true);
        String fullName = name + "." + field.getName();
        Object fieldValue = field.get(object);
        boolean mustBeSet = !ignoredFields.contains(field);
        if (mustBeSet) {
            assertNotNull(fullName + " is null", fieldValue);
        }
        if (fieldValue != null) {
            if (Primitives.isWrapperType(fieldValue.getClass())) {
                // Special-case the mutable hash code field.
                if (mustBeSet && !fullName.endsWith("cachedHashCode")) {
                    assertNotEquals("Primitive value must not be default: " + fullName,
                            Defaults.defaultValue(Primitives.unwrap(fieldValue.getClass())), fieldValue);
                }
            } else {
                assertFullyPopulated(fullName, fieldValue, ignoredFields);
            }
        }
    } catch (IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.eclipse.che.plugin.typescript.dto.model.FieldAttributeModel.java

License:Open Source License

/**
 * Build a new field model based on the name and Java type
 *
 * @param fieldName/*  w w w.  j a  va2 s .co  m*/
 *         the name of the field
 * @param type
 *         the Java raw type that will allow further analyzes
 */
public FieldAttributeModel(String fieldName, Type type) {
    this.fieldName = fieldName;
    this.type = type;
    this.typeName = convertType(type);

    if (typeName.startsWith("Array<") || typeName.startsWith("Map<")) {
        this.needInitialize = true;
    }

    if (this.type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) this.type;
        Type rawType = parameterizedType.getRawType();
        analyzeParametrizedType(parameterizedType, rawType);
    } else if (Primitives.isPrimitive(this.type) || Primitives.isWrapperType(this.type)
            || String.class.equals(this.type)) {
        this.isPrimitive = true;
    } else if (this.type instanceof Class && ((Class) this.type).isAnnotationPresent(DTO.class)) {
        this.isDto = true;
        dtoImpl = this.type.getTypeName() + "Impl";
    } else if (this.type instanceof Class && ((Class) this.type).isEnum()) {
        this.isEnum = true;
    }

}