Example usage for com.google.common.base Defaults defaultValue

List of usage examples for com.google.common.base Defaults defaultValue

Introduction

In this page you can find the example usage for com.google.common.base Defaults defaultValue.

Prototype

@Nullable
public static <T> T defaultValue(Class<T> type) 

Source Link

Document

Returns the default value of type as defined by JLS --- 0 for numbers, false for boolean and '\0' for char .

Usage

From source file:org.akraievoy.base.proxies.Proxies.java

/**
 * @param interf interface class to create proxy for
 * @return a proxy that silently ignores all method calls
 *//*from w w w .j a  v a  2 s.c o m*/
@SuppressWarnings("unchecked")
public static <E> E noop(Class<E> interf) {
    return (E) Proxy.newProxyInstance(interf.getClassLoader(), new Class[] { interf }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Class<?> resultType = method.getReturnType();
            if (Primitives.allPrimitiveTypes().contains(resultType)) {
                return Defaults.defaultValue(resultType);
            }
            return null;
        }
    });
}

From source file:co.cask.cdap.common.lang.FieldInitializer.java

@Override
public void visit(Object instance, TypeToken<?> inspectType, TypeToken<?> declareType, Field field)
        throws Exception {
    if (Modifier.isStatic(field.getModifiers())) {
        return;/*from w  w  w . j  a  v  a 2  s  .  c  o  m*/
    }
    field.set(instance, Defaults.defaultValue(field.getType()));
}

From source file:ru.runa.wfe.commons.TypeConversionUtil.java

public static <T> T convertTo(Class<T> classConvertTo, Object object, TypeConvertor preConvertor,
        TypeConvertor postConvertor) {//from w  w w .  j  a  va 2s.  c  o  m
    try {
        Preconditions.checkNotNull(classConvertTo, "classConvertTo is null");
        if (preConvertor != null) {
            T result = preConvertor.convertTo(object, classConvertTo);
            if (result != null) {
                return result;
            }
        }
        if (object == null) {
            return Defaults.defaultValue(classConvertTo);
        }
        if (classConvertTo.isPrimitive()) {
            classConvertTo = Primitives.wrap(classConvertTo);
        }
        if (classConvertTo.isInstance(object)) {
            return classConvertTo.cast(object);
        }
        if (List.class.isAssignableFrom(classConvertTo)) {
            return (T) convertToList(Object.class, object, preConvertor, postConvertor);
        }
        if (object instanceof Actor) {
            // compatibility: client code expecting 'actorCode'
            Long actorCode = ((Actor) object).getCode();
            return convertTo(classConvertTo, actorCode, preConvertor, postConvertor);
        }
        if (object instanceof Group) {
            // compatibility: client code expecting 'groupCode'
            String groupCode = "G" + ((Group) object).getId();
            return convertTo(classConvertTo, groupCode, preConvertor, postConvertor);
        }
        if (classConvertTo == String.class) {
            if (object instanceof Date) {
                return (T) CalendarUtil.formatDateTime((Date) object);
            }
            if (object instanceof Calendar) {
                return (T) CalendarUtil.formatDateTime((Calendar) object);
            }
            if (object instanceof UserTypeMap) {
                UserTypeMap userTypeMap = (UserTypeMap) object;
                UserTypeFormat format = new UserTypeFormat(userTypeMap.getUserType());
                return (T) format.formatJSON(object);

            }
            return (T) object.toString();
        }
        if (object instanceof String) {
            String s = (String) object;
            if (s.length() == 0) {
                // treating as null
                return Defaults.defaultValue(classConvertTo);
            }
            if (classConvertTo == BigDecimal.class) {
                return (T) new BigDecimal(s);
            }
            // try to use 'valueOf(String)'
            try {
                Method valueOfMethod = classConvertTo.getMethod("valueOf", String.class);
                return (T) valueOfMethod.invoke(null, object);
            } catch (NoSuchMethodException e) {
            }
        }
        if (object instanceof Number && Number.class.isAssignableFrom(classConvertTo)) {
            Number n = (Number) object;
            if (classConvertTo == Long.class) {
                return (T) Long.valueOf(n.longValue());
            }
            if (classConvertTo == Integer.class) {
                return (T) Integer.valueOf(n.intValue());
            }
            if (classConvertTo == Byte.class) {
                return (T) Byte.valueOf(n.byteValue());
            }
            if (classConvertTo == Double.class) {
                return (T) new Double(n.doubleValue());
            }
            if (classConvertTo == Float.class) {
                return (T) new Float(n.floatValue());
            }
            if (classConvertTo == BigDecimal.class) {
                return (T) new BigDecimal(n.toString());
            }
        }
        if (classConvertTo == Long.class) {
            if (object instanceof Date) {
                return (T) (Long) ((Date) object).getTime();
            }
            if (object instanceof Calendar) {
                return (T) (Long) ((Calendar) object).getTimeInMillis();
            }
        }
        if (classConvertTo.isArray()) {
            List<?> list = convertTo(List.class, object, preConvertor, postConvertor);
            Class<?> componentType = classConvertTo.getComponentType();
            Object array = Array.newInstance(componentType, list.size());
            for (int i = 0; i < list.size(); i++) {
                Array.set(array, i, convertTo(componentType, list.get(i), preConvertor, postConvertor));
            }
            return (T) array;
        }
        if (object instanceof Date && classConvertTo == Calendar.class) {
            return (T) CalendarUtil.dateToCalendar((Date) object);
        }
        if (object instanceof Calendar && classConvertTo == Date.class) {
            return (T) ((Calendar) object).getTime();
        }
        if (object instanceof String && (classConvertTo == Calendar.class || classConvertTo == Date.class)) {
            Date date;
            String formattedDate = (String) object;
            try {
                date = CalendarUtil.convertToDate(formattedDate,
                        CalendarUtil.DATE_WITH_HOUR_MINUTES_SECONDS_FORMAT);
            } catch (Exception e1) {
                try {
                    date = CalendarUtil.convertToDate(formattedDate,
                            CalendarUtil.DATE_WITH_HOUR_MINUTES_FORMAT);
                } catch (Exception e2) {
                    try {
                        date = CalendarUtil.convertToDate(formattedDate, CalendarUtil.DATE_WITHOUT_TIME_FORMAT);
                    } catch (Exception e3) {
                        try {
                            date = CalendarUtil.convertToDate(formattedDate,
                                    CalendarUtil.HOURS_MINUTES_SECONDS_FORMAT);
                        } catch (Exception e4) {
                            try {
                                date = CalendarUtil.convertToDate(formattedDate,
                                        CalendarUtil.HOURS_MINUTES_FORMAT);
                            } catch (Exception e5) {
                                throw new InternalApplicationException(
                                        "Unable to find datetime format for '" + formattedDate + "'");
                            }
                        }
                    }
                }
            }
            if (classConvertTo == Calendar.class) {
                return (T) CalendarUtil.dateToCalendar(date);
            }
            return (T) date;
        }
        if (Executor.class.isAssignableFrom(classConvertTo)) {
            return (T) convertToExecutor(object, ApplicationContextFactory.getExecutorDAO());
        }
        if (postConvertor != null) {
            T result = postConvertor.convertTo(object, classConvertTo);
            if (result != null) {
                return result;
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    throw new InternalApplicationException(
            "No conversion found between '" + object.getClass() + "' and '" + classConvertTo + "'");
}

From source file:org.uberfire.mocks.CallerProxy.java

public Object invoke(final Object proxy, final Method m, final Object[] args) throws Throwable {
    Object result = null;/* w ww .ja v  a  2  s .  c  o  m*/
    try {
        result = m.invoke(target, args);
    } catch (Exception e) {
        if (errorCallBack != null) {
            errorCallBack.error(result, e);
        }
        if (m.getReturnType().isPrimitive()) {
            return Defaults.defaultValue(m.getReturnType());
        } else {
            return result;
        }
    }
    if (successCallBack != null) {
        successCallBack.callback(result);
    }
    return result;
}

From source file:com.comphenix.protocol.reflect.instances.PrimitiveGenerator.java

@Override
public Object create(@Nullable Class<?> type) {
    if (type == null) {
        return null;
    } else if (type.isPrimitive()) {
        return Defaults.defaultValue(type);
    } else if (Primitives.isWrapperType(type)) {
        return Defaults.defaultValue(Primitives.unwrap(type));
    } else if (type.isArray()) {
        Class<?> arrayType = type.getComponentType();
        return Array.newInstance(arrayType, 0);
    } else if (type.isEnum()) {
        Object[] values = type.getEnumConstants();
        if (values != null && values.length > 0)
            return values[0];
    } else if (type.equals(String.class)) {
        return stringDefault;
    }//from  ww  w  .  j a v  a 2  s.  co m

    // Cannot handle this type
    return null;
}

From source file:com.palantir.paxos.PaxosValue.java

public static PaxosValue hydrateFromProto(PaxosPersistence.PaxosValue message) {
    String leaderUUID = "";
    if (message.hasLeaderUUID()) {
        leaderUUID = message.getLeaderUUID();
    }/*  w w w.  j a v a  2s . c  o  m*/
    long seq = Defaults.defaultValue(long.class);
    if (message.hasSeq()) {
        seq = message.getSeq();
    }
    byte[] bytes = null;
    if (message.hasBytes()) {
        bytes = message.getBytes().toByteArray();
    }
    return new PaxosValue(leaderUUID, seq, bytes);
}

From source file:org.akraievoy.base.eventBroadcast.InvocationHandlerBroadcast.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object result = null;//  ww w .  j av a2  s  .  co m
    synchronized (parent.structuralMutex) {
        for (EventSpec eventSpec : parent.listeners) {
            try {
                result = method.invoke(eventSpec, args);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("environment is not set up properly", e);
            } catch (IllegalArgumentException e) {
                throw new IllegalStateException("should not occur", e);
            } catch (InvocationTargetException e) {
                parent.getLog().warn("failed in '" + method.toGenericString() + "': " + e.getMessage(), e);
            }
        }
    }

    Class<?> resultType = method.getReturnType();
    if (resultType.isPrimitive() && result == null) {
        return Defaults.defaultValue(resultType);
    } else {
        return result;
    }
}

From source file:com.palantir.paxos.PaxosAcceptorState.java

private PaxosAcceptorState(PaxosProposalId pid) {
    this.lastPromisedId = pid;
    this.lastAcceptedId = null;
    this.lastAcceptedValue = null;
    this.version = Defaults.defaultValue(long.class);
}

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

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

    try {//from ww w .  j  a  va 2s .co 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.apache.twill.internal.utils.Instances.java

/**
 * Creates an instance of the given using Unsafe. It also initialize all fields into default values.
 *///from   w w  w .ja  v  a 2  s .  c o m
private static <T> T unsafeCreate(Class<T> clz) throws InvocationTargetException, IllegalAccessException {
    T instance = (T) UNSAFE_NEW_INSTANCE.invoke(UNSAFE, clz);

    for (TypeToken<?> type : TypeToken.of(clz).getTypes().classes()) {
        if (Object.class.equals(type.getRawType())) {
            break;
        }
        for (Field field : type.getRawType().getDeclaredFields()) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            field.set(instance, Defaults.defaultValue(field.getType()));
        }
    }

    return instance;
}